Q1) Why is main() method static?
Ans) To access a static method class object is not needed. The method can be accessed directly with the help of ClassName. So when a program is started the jvm search for the class with main method and calls it without creating an object of the class.
Q2) What is the difference between static and instance methods?
Ans) instance method belongs to the instance of a class and requires an instance to be invoked, whereas static method belongs to the class itself and not to any class instance so it doesn’t need a class instance to be invoked.
Instance methods use dynamic (late) binding, whereas static methods use static (early) binding.
When the JVM invokes a class instance method, it selects the method to invoke based on the type of the object reference, which is always known at run-time. On the other hand, when the JVM invokes a static method, it selects the method to be invoked based on the actual class of the object, which may only be known at compile time.
Q) Does java supports pass by value or pass by reference?
Ans) Java supports only pass by value. The arguments passed as a parameter to a method is mainly primitive data types or objects. For the data type the actual value is passed.
Java passes the references by value just like any other parameter. The pointer to the object is passed as value. Thus, method manipulation will alter the objects but will not intialize the new object. Consider the example:
public void tricky(Point arg1, Point arg2) {
arg1.x = 100;
arg1.y = 100;
Point temp = arg1;
arg1 = arg2;
arg2 = temp;
}
public static void main(String [] args) {
Point pnt1 = new Point(0,0);
Point pnt2 = new Point(0,0);
System.out.println("X: " + pnt1.x + " Y: " +pnt1.y);
System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
System.out.println(" ");
tricky(pnt1,pnt2);
System.out.println("X: " + pnt1.x + " Y:" + pnt1.y);
System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
}
OutPut:
X: 0 Y: 0
X: 0 Y: 0
X: 100 Y: 100
X: 0 Y: 0
The method successfully alters the value of pnt1, even though it is passed by value; however, a swap of pnt1 and pnt2 fails! This is the major source of confusion. In the main() method, pnt1 and pnt2 are nothing more than object references. When you pass pnt1 and pnt2 to the tricky() method, Java passes the references by value just like any other parameter. This means the references passed to the method are actually copies of the original references.
Q3) Can static block throw exception?
Ans) Yes, static block can throw only Runtime exception or can use a try-catch block to catch checked exception.
Typically scenario will be if JDBC connection is created in static block and it fails then exception can be caught, logged and application can exit. If System.exit() is not done, then application may continue and next time if the class is referred JVM will throw NoClassDefFounderror since the class was not loaded by the Classloader.
Q) What is the difference between abstract class and interface ?
Ans) A class is called abstract when it is declared with the keywordabstract
. Abstract class contains at least one abstract method. It can also contain n numbers of concrete method. An interface can only contain abstract methods.
Q5) Explain with an example to describe when to use abstract class and interface?
Ans) Cars are meant for driving but each car has its own driving technique(4 wheel drive etc). Consider a class Drive which can have the drive method as an abstract with child class implementing the drive method.
public abstract class Drive {
public abstract void drive();
}
public class 4WD extends Drive {
public void drive() {
// 4wd drive
}
}
public class 2WD extends Drive {
public void drive() {
//2wd drive
}
}
The 4WD or 2WD can be of type Car or Truck etc. Here to define type of drive for a Car or Truck, Car and Truck are good candidate of an interface.
public interface Car {
}
public interface Truck {
}
public Car4WD extends Drive implements Car {
}
public Truck4WD extends Drive implements Truck {
}
Q6) Does java support multiple inheritance? Why?
Ans) Java doesn't support multiple inheritance but it provides a way through which it can be enacted. Consider the scenario in C++
Class A {
public void add() {
// some text
}
}
Class B {
public void add() {
// some text
}
}
Class C extends A,B {
public static void main(String arg[]){
C objC = new C();
objC.add(); // problem, compiler gets confused and cant
decide to call Class A or B method.
}
In the above code the compiler doesn't know which class add()
method should be called. This problem is called Diamond problem.
This problem in java is resolved with the use of interfaces
A Java interface is a bit like a class, except a Java interface can only contain method signatures and fields. A Java interface cannot contain an implementation of the methods(until Java8), only the signature (name, parameters and exceptions) of the method. You can use interfaces in Java as a way to achieve polymorphism.
interface A {
void add();
}
interface B {
void add();
}
class C implements A,B {
void add() {
// doesnt matter which interface it belong to
}
}
Q7) Can this keyword be assigned null value?
Ans) No
Q8) What are the different types of references in java?
Ans) Java has a more expressive system of reference than most other garbage-collected programming languages, which allows for special behavior for garbage collection. A normal reference in Java is known as a strong reference. The java.lang.ref package defines three other types of references—soft, weak and phantom references. Each type of reference is designed for a specific use.
A SoftReference can be used to implement a cache. An object that is not reachable by a strong reference (that is, not strongly reachable) but is referenced by a soft reference is called softly reachable. A softly reachable object may be garbage collected at the discretion of the garbage collector. This generally means that softly reachable objects will only be garbage collected when free memory is low, but again, it is at the discretion of the garbage collector. Semantically, a soft reference means "keep this object unless the memory is needed."
A WeakReference is used to implement weak maps. An object that is not strongly or softly reachable, but is referenced by a weak reference is called weakly reachable. A weakly reachable object will be garbage collected during the next collection cycle. This behavior is used in the class java.util.WeakHashMap. A weak map allows the programmer to put key/value pairs in the map and not worry about the objects taking up memory when the key is no longer reachable anywhere else. Another possible application of weak references is the string intern pool. Semantically, a weak reference means "get rid of this object when nothing else references it."
A PhantomReference is used to reference objects that have been marked for garbage collection and have been finalized, but have not yet been reclaimed. An object that is not strongly, softly or weakly reachable, but is referenced by a phantom reference is called phantom reachable. This allows for more flexible cleanup than is possible with the finalization mechanism alone. Semantically, a phantom reference means "this object is no longer needed and has been finalized in preparation for being collected."
Q9) How to change the heap size of a JVM?
Ans) The old generation's default heap size can be overridden by using the -Xms and -Xmx switches to specify the initial and maximum sizes respectively:
java -Xms <initial size> -Xmx <maximum size> program
For example:
java -Xms64m -Xmx128m program
Q10) What is the difference between instanceof and isInstance(Object obj)?
Ans) Differences are as follows:
1) instanceof
is a reserved word of Java, but isInstance(Object obj)
is a method of java.lang.Class.
2) instanceof is used to identify whether the object is of a particular class type or its subclass but isInstance(obj) is used to identify object of a particular class.
Q12) What is a memory leak?
Ans) A memory leak is where an unreferenced object that will never be used again still hangs around in memory and doesn't get garbage collected.
Q13) What is the difference between equals() and ==?
Ans) == operator is used to compare the references of the objects.
public boolean equals(Object o) is the method provided by the Object class. The default implementation uses == operator to compare two objects.
But since the method can be overridden like for String class. equals() method can be used to compare the values of two objects.
String str1 = "MyName";
String str2 = new String("MyName");
String str3 = str2;
if (str1 == str2) {
System.out.println("Objects are equal");
} else {
System.out.println("Objects are not equal");
}
if (str1.equals(str2)) {
System.out.println("Objects are equal");
} else {
System.out.println("Objects are not equal");
}
Output:
Objects are not equal
Objects are equal
String str2 = "MyName";
String str3 = str2;
if (str2 == str3) {
System.out.println("Objects are equal");
} else {
System.out.println("Objects are not equal");
}
if (str3.equals(str2)) {
System.out.println("Objects are equal");
} else {
System.out.println("Objects are not equal");
}
Output:
Objects are equal
Objects are equal
Don't forget to check more questions More on KeyConcepts Interview Questions
Recommend Reading