Java OCA OCP Practice Question 1082

Question

What will be the output of the following code?

public class StringTest { 
      public static void main(String [] a) { 
         String s1 = "test string"; 
         String s2 = "test string"; 
         if (s1 == s2) { 
            System.out.println("same"); 
         } else { 
            System.out.println("different"); 
         } //from  w w w .  j a v  a  2  s .co  m
      } 
} 
  • A. The code will compile but not run.
  • B. The code will not compile.
  • C. "different" will be printed out to the console.
  • D. "same" will be printed out to the console.
  • E. None of the above.


D.

Note

Both String variables are assigned the same string, "test string".

Because these strings are not created using the new String() method.

The strings are placed in the string pool, and a reference to those strings is stored in the String variables.

Because the reference to the string pool is the same, the == comparison will return true.

If the strings were created using the new String() method, the references would be different and the == comparison would return false.




PreviousNext

Related