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








Question

What is the result of the following?

public class Main{
   public static void main(String[] argv){
     List<String> one = new ArrayList<String>(); 
     one.add("abc"); 

     List<String> two = new ArrayList<>(); 
     two.add("abc"); 
     
     if (one == two)  
       System.out.println("A"); 
     else if (one.equals(two)) 
       System.out.println("B"); 
     else  
       System.out.println("C"); 
   }
}
  1. A
  2. B
  3. C
  4. An exception is thrown.
  5. The code does not compile.




Answer



B.

Note

one == two is false since the variables do not point to the same object.

one.equals(two) is true since it compares ArrayList for same elements in the same order. It is re-implemented for ArrayList.

public class Main{
   public static void main(String[] argv){
     List<String> one = new ArrayList<String>(); 
     one.add("abc"); 
//from   w w  w. ja v a2 s  .c  o m
     List<String> two = new ArrayList<>(); 
     two.add("abc"); 
     
     if (one == two)  
       System.out.println("A"); 
     else if (one.equals(two)) 
       System.out.println("B"); 
     else  
       System.out.println("C"); 
   }
}

The code above generates the following result.