OCA Java SE 8 Mock Exam - OCA Mock Question 18








Question

What is the result of the following code?

public class Main{
  public static void main(String[] argv){
     String s1 = "Java"; 
     String s2 = "Java"; 
     StringBuilder sb1 = new StringBuilder(); 
     sb1.append("Ja").append("va"); 
     System.out.println(s1 == s2); 
     System.out.println(s1.equals(s2)); 
     System.out.println(sb1.toString() == s1); 
     System.out.println(sb1.toString().equals(s1)); 
  
  }
}

  1. true is printed out exactly once.
  2. true is printed out exactly twice.
  3. true is printed out exactly three times.
  4. true is printed out exactly four times.
  5. The code does not compile.




Answer



C.

Note

JVM has a string pool for storing the string constants.

String literals are used from the string pool.

s1 and s2 define string with the same value which is Java.

s1 and s2 refer to the same object and s1== s2 are equal.

Therefore, the first two print statements print true.

     System.out.println(s1 == s2);  // true
     System.out.println(s1.equals(s2));  //true 

The third print statement prints false since toString() computes and returns the value and it is not from the string pool even if toString() returns the same literal value.

     
System.out.println(sb1.toString() == s1); //false

The final print statement prints true since equals() looks at the values of String objects.

public class Main{
  public static void main(String[] argv){
     String s1 = "Java"; 
     String s2 = "Java"; 
     StringBuilder sb1 = new StringBuilder(); 
     sb1.append("Ja").append("va"); 
     System.out.println(s1 == s2); /*ww w. j  a v a2s  .  com*/
     System.out.println(s1.equals(s2)); 
     System.out.println(sb1.toString() == s1); 
     System.out.println(sb1.toString().equals(s1)); 
  
  }
}

The code above generates the following result.