8 Java Tricky Questions, a developer must be aware off.

1. How many ways you can create a new thread ?

Ans: There is exactly one way to create a new thread in Java and that is to instantiate   java.lang.Thread .To actually run that thread you must call start().
There are two different ways to specify which code to run in that Thread:
  • Implement the interface java.lang.Runnable and pass an instance of the class implementing it to the Thread constructor.
  • Extend Thread itself and override its run() method. More details available here.

2.What is variable hiding and shadowing?

Ans: Different kinds of variables have different scopes. A variable is shadowed if there is another variable with the same name that is closer in scope. In other words, referring to the variable by name will use the one closest in scope , the one in the outer scope is shadowed.
A Local Variable Shadows An Instance Variable
Inside a class method, when a local variable have the same name as one of the instance variable, the local variable shadows the instance variable inside the method block. More details are available here.
In the following example, there is a instance variable named "a", and inside the method setA() there is a local variable "a":
class Program {
  int  a;
  int  b;
  void setA(int a) {
    a = a; //here, the local variable has closer scope than the instance 
          // variable, so the expression set parameter equal to itself
    this.a = a; // this is the correct way to set the parameter to the 
           //instance variable.
  }
  void setB(int b) {
    this.b = b;
  }
}
Let's look at another example,
class Program {
   String name = "Instance Var."; 
   void someMethod() { 
     String name ="Local Var."; 
     System.out.println(name);   //Local Var.
     System.out.println(this.name); //Instance Var. 
   } 
}
Note: Instance variables are not overridden, they are hidden.
A Class Variable Shadows the Inherited Variable from Its Parent Classes
When an instance variable in a subclass has the same name as an instance variable in a super class, then the instance variable is chosen in the class that is the reference type.
A class can declare a variable with the same name as an inherited variable from its parent class, thus "hiding" or shadowing the inherited version. (This is like overriding, but for variables.) e.g.,
public class Base {
    public  String name = "Base";
    public  String getName() { return name; }
}
public class Sub extends Base {
    public String name = "Sub";
    public String getName() { return name; }
}
The above shows two classes and Sub class is a subclass of Base class. Both of classes has a String type variable named name.
class Program {
  public static void main(String[] args) {
    Sub s  = new Sub();
    Base b = s;
    System.out.println(s.name); //Output "Sub"
    System.out.println(b.name); //Output "Base"
  }
}
In this eample :
  • Even though the variable b refers an instance of class Sub, the b.name  still evaluates to "Base". Because variables names in Java are resolved by the reference type, not the object they are referencing.
  • even though both b and s are referencing the object of type Sub, s is declared as type Sub, b is declared as type Base, Java runtime gets the s.name from the class of Sub, and b.name from the class of Base.

3 .Why does 128==128 return false but 127==127 return true when converting to Integer wrappers?

class Test {
    public static void main(String args[]) {
        Integer i=128;
        Integer j=128;
        System.out.println(i==j);
    }
}
Output: false
class Test {
    public static void main(String args[]) {
        Integer i=127;
        Integer j=127;
        System.out.println(i==j);
    }
}
Output : true
Ans : When we write "Integer i=127", compiler emits :
Integer i =Integer.valueOf(127);
and the implementation of valueof is  :
 public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
From abouve code it's clear that there exist an IntegerCache in java.lang.Integer which stores instances (for values -128 to127). This means that Integer.valueOf(127) always will return the very same instance, while Integer.of(128) will not.Why this cache exists is available here.

4. What's the differnece between nested class and inner class ?

Ans : Ther are two categoris of nested class exists in Java, static and non-static. Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes.

5. Why doesn't a static method call on null object reference generate a NullPointerException?

Ans: Static members belongs to the class rather than instance. So at compile time, instance.method() is converted to ClassName.method().
public class Player {
  private static final String type = "Human";
  private int age;
  public static String getType() {
    return type;
  }
  public int getAge() {
    return age;
  }
  public static void main(String[] args) {
    Player player = null;
    System.out.println(player.getType());      // Human
    System.out.println(player.getAge());       // throws NPE
  }
}
In the above code  player.getType() will get converted to Player.getType(), so no NPE on line 17. More details are available here.

6. What are the differences between Hashtable,SynchronizedMap and ConcurrentHashMap?

Ans:
  • Hashtable uses synchronized methods to achieve thread safety. At a time only one thread can read or write into Hashtable. In other word, thread acquires lock on entire Hashtable instance. Hence its performance is quite slow and we can not utilize the advantages of multithreaded architecture.
    Another point to note about Hashtable is that it does not allow null keys or values whereas HashMap allows one null key and any number of null values.
  • SynchronizedMap (Collections.SynchronizedMap) is a static inner class of utility class java.util.Collections. It is quite similar to Hashtable and it also acquires lock on entire Map instance. It is not a legacy class like Hashtable and  it was introduced in jdk 1.5.
    It provides functionality to convert any thread-unsafe Map implementation to thread-safe implementation using Collections.synchronizedMap(Map map) static method.
  • ConcurrentHashMap divides the Map instance into different segments. And each thread acquires lock on each segment instead of acquiring lock on entire Map object hence it has better performance compare to Hashtable ot SynchronizedMap. More details available here.

7. What is the output of below program ?

public static void main(String[] args) {
char ch = '0';
ch *= 1.1;
System.out.println(ch);
}

Ans : It's 4
char ch = '0'; // ASCII for ‘0’ is 48
ch *= 1.1; // 48 x 1.1 is 52.8 which turns to 52 when cast to char
System.out.println(ch); // 52 represents ‘4’ in ASCII

8. What is the difference between noclassdeffounderror and classnotfoundexception?

Ans : NoClassDefFoundError is thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.

The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found.
ClassNotFoundException is thrown when an application tries to load in a class through its string name using
  • The forName method in class Class.
  • The findSystemClass method in class ClassLoader .
  • The loadClass method in class ClassLoader.
but no definition for the class with the specified name could be found.

Comments

Post a Comment

Popular posts from this blog