Reputation: 1625
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
Reputation: 124265
Because in
b = q + b;
q
represents current element loop is getting from your arrayb
is result of previous concatenationswhich means you are adding new part in front of old result.
Upvotes: 5
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
Reputation: 124704
Your loop prepends each element to b
.
That is:
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