Given:
public class String1 {
public static void main(String[] args) {
String s = "123";
if (s.length() >2)
s.concat("456");
for(int x = 0; x <3; x++)
s += "x";
System.out.println(s);
}
}
What is the result?
A. 123
B. 123xxx
C. 123456
D. 123456xxx
E. Compilation fails
Option B.
Explanation above is wrong!
The if clause is applied (s.lengh() > 2) but the “s” String is not assigned a new value, therefore it stays like it is.
Assuming we’d add s = s.concat(“456”) instead of s.concat(“456”) we’d get 123456xxx
public class Test {
public static void main(String[] args) {
String s = “123”;
if (s.length() > 2) s = s.concat(“456”);
for (int x = 0; x < 3; x++)
s += "x";
System.out.println(s);
}
}
Ouput:
123456xxx