Java OCA OCP Practice Question 892

Question

What is the result of the following code?

3: String s = "abcd"; 
4: s.toUpperCase(); 
5: s.trim(); 
6: s.substring(1, 3); 
7: s += " two"; 
8: System.out.println(s.length()); 
  • A. 2
  • B. 4
  • C. 8
  • D. 10
  • E. An exception is thrown.
  • F. The code does not compile.


C.

Note

This question is trying to see if you know that String objects are immutable.

Line 4 returns ABCD but the result is ignored and not stored in s.

Line 5 returns abcd since there is no whitespace present but the result is again ignored.

Line 6 returns "bc" because it starts with index 1 and ends before index 3 using zero-based indexes.

The result is ignored again.

We concatenate four new characters to s and now have a String of length 8.




PreviousNext

Related