Java - Tricky Code Examples


1. String Comparison and String Pool

Concepts
  • .equals() compares the content of object whereas == checks if it's the same object.
  • When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object and returning its reference.
Code

class BuggyBread { 
  public static void main(String[] args)
  {
  String s2 = "I am unique!"; 
  String s5 = "I am unique!";
      
  System.out.println(s2 == s5); 
 
}

Output: true

Explanation

String comparison is a famous interview question where interviewee is asked to tell the difference about  "==" and .equal method. When we evaluate two objects relation using "==", it turns out to be true if both references are referring to same object. Yes, They both are pointing to same String object. Please read String Pool.

2. Default Constructor and Constructor Declaration.

Concepts
  • Java doesn't creates  no argument Default Constructor if any constructor is defined by the programmer. 
  • If we add any return type to the name of the constructor, Java treats it as a new method instead of giving any error.
Code

class BuggyBread2 { 
 
  private static int counter = 0;
void BuggyBread2() {
counter = 5;
}
BuggyBread2(int x){
counter = x;
}
 
    public static void main(String[] args) {
       BuggyBread2 bg = new BuggyBread2();
       System.out.println(counter);
   } 
}


Output: Compile time error as it won't find the constructor matching BuggyBread2()


3. Overloading and Overridding

Code

class BuggyBread1 {
     public String method() {
          return "Base Class - BuggyBread1";
     }
}

class BuggyBread2 extends BuggyBread1{ 
 
     private static int counter = 0;
     public String method(int x) {
         return "Derived Class - BuggyBread2";
     }
      
     public static void main(String[] args) {
          BuggyBread1 bg = new BuggyBread2();  
          System.out.println(bg.method());
     } 
}

Output: Base Class - BuggyBread1

Explanation

Though Base Class handler is having the object of Derived Class but its not overriding as now with a definition having an argument ,derived class will have both method () and method (int) and hence its overloading.