Panthy
Panthy

Reputation: 1625

For-each loop is iterating backwards

Given the code

String[] p = { "A", "B", "C", "D" }; 
String b = ""; 

for ( String q : p ) 
   b = q + b; 

System.out.println( b ); 

I thought the output would be "ABCD" but it is "DCBA"

Why??

Upvotes: 1

Views: 82

Answers (3)

Pshemo
Pshemo

Reputation: 124265

Because in

b = q + b;
  • q represents current element loop is getting from your array
  • b is result of previous concatenations

which means you are adding new part in front of old result.

Upvotes: 5

CDTWF
CDTWF

Reputation: 83

The expression

q + b;

means new element + old string.

For each iteration through the 4 element array, the values are

b = "A" + "" - resulting in "A"
b = "B" + "A" - resulting in "BA"
b = "C" + "BA" - resulting in "CBA"
b = "D" + "CBA" - resulting in "DCBA"

Change the assignment to b = b + q; or b += q;

Upvotes: 0

janos
janos

Reputation: 124704

Your loop prepends each element to b. That is:

  • prepend "A" -> "A"
  • prepend "B" -> "BA"
  • prepend "C" -> "CBA"
  • prepend "D" -> "DCBA"

If you want to get "ABCD", change the logic to append:

for ( String q : p ) {
   // b = q + b;  // prepend
   // b = b + q;  // append
   b += q;        // append, using the shorter `+=` notation
}

Upvotes: 10

Related Questions