OCA Java SE 8 Core Java APIs - OCA Mock Question Core Java APIs 1-8








Question

What is the result of the following code? (Choose all that apply)

     3: String a = ""; 
     4: a += 2; 
     5: a += 'c'; 
     6: a += false;             
     7: if ( a == "2cfalse") System.out.println("=="); 
     8: if ( a.equals("2cfalse")) System.out.println("equals"); 
  1. Compile error on line 4.
  2. Compile error on line 5.
  3. Compile error on line 6.
  4. Compile error on another line.
  5. ==
  6. equals
  7. An exception is thrown.




Answer



F.

Note

a += 2 expands to a = a + 2.

A String concatenated with any other type gives a String.

Lines 4, 5, and 6 results as "2cfalse".

The if statement on line 7 returns false because the two String objects are not the same in memory. The one in the if statement is from string pool. The calculated one is not.

The if statement on line 8 returns true because the values of the two String objects are the same using object equality.

public class Main{
   public static void main(String[] argv){
     String a = ""; 
     System.out.println(a); //from ww w.  j  a  v  a  2s  . c  o m
     a += 2; 
     System.out.println(a); 
     a += 'c'; 
     System.out.println(a); 
     a += false;            
     System.out.println(a);  
     if ( a == "2cfalse") 
        System.out.println("=="); 
     if ( a.equals("2cfalse")) 
        System.out.println("equals"); 
   }
}