Key Concepts in Java

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 therefore it requires an instance before it can be invoked, whereas static method belongs to the class itself and not to any class instance so it doesn’t need an 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 invoke based on the actual class of the object, which may only be known at compile time.

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.

Q4) What is difference between abstract class and interface?

Ans) A class is called abstract when it is declared with keyword abstract. Abstract class may contain abstract method. It can also contain n numbers of concrete method. Interface can only contain abstract methods.

  • Interface can have only abstract methods. Abstract class can have concerete and abstract methods.
  • The abstract class can have public, private, protected or default variables and also constants. In interface the variable is by default public final. In nutshell the interface doesnt have any variables it only has constants.
  • A class can extend only one abstract class but a class can implement multiple interfaces. Abstract class doesn't support multiple inheritance whereas abstract class does.
  • If an interface is implemented its mandatory to implement all of its methods but if an abstract class is extended its mandatory to implement all abstract methods.
  • The problem with an interface is, if you want to add a new feature (method) in its contract, then you MUST implement those method in all of the classes which implement that interface. However, in the case of an abstract class, the method can be simply implemented in the abstract class and the same can be called by its subclass.

Q5) Explain with example to describe when to use abstract class and interface?

Ans) Consider a scenario where all Cars will have 4 tyres and other features can be different.
In this case any subclass of Car has to have 4 tyres. This is a case where abstract class will be used and a default implementaion for tyres will be provided.

public abstract class Car {
	private final static TOTAL_TYRES = 4;
	public abstract String getCarName();  
	public final int getNoOfTyres() {
		return TOTAL_TYRES;
	} 
}
Consider a scenario where Cars can have any number of tyres and other features can also be different. In this case interface will be created.
public interface Car {
	public abstract String getCarName();
	public abstract int getNoOfTyres();
}

Q6) Does java support multiple interitance? 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.
	}

As, on can see the problem in 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. An 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.

In Java similar problem would look like:

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 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 of identify whether the object is type of a particular class or its subclass but isInstance(obj) is used to identify object of a particular class.

Q11) 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, since the references point to the original object 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.

Q12) What is memory leak?

Ans) A memory leak is where an unreferenced object that will never be used again still hangs around in memory and doesnt get garbage collected.

Q13) What is the difference between equals() and ==?

Ans) == operator is used to compare the references of the objects.
public bollean 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 overriden 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