Which is the Best Java Web Framework ?

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.



Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
comments powered by Disqus




×

Try our new Java Interview Questions Search Tool.

There are more than 1000 questions with practice tests.

It's updated daily and It's Awesome.


×

Try our new Java Practice Test tool.

There are more than 200 questions and expanding quickly. It's updated daily and It's Awesome.