Core Java

What will happen to the Exception object after exception handling ?

The Exception object will be garbage collected in the next garbage collection.

What is the contract between equals() and hashCode() ?

Whenever an object overrides equals() method it must override also the hashCode() method.

Multiple invocations of the hashCode() method in Java application must consistently produce the same integer results, provided no information used in equals() comparisons on the object is modified.

For same objects hashCode values must be same but not necessarily for two different objects hashCode values must be different. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.

You can check and example on hashCode() and equals() method.

Give the list of methods in Object class of Java.

getClass() – Returns the runtime class of this object.
hashCode() – Returns a hash code value for the object.
equals() – Indicates whether some other object is “equal to” this one.
clone() – Creates and returns a copy of this object.
toString() – Returns a string representation of the object.
notify() – Wakes up a single thread that is waiting on this object’s monitor.
notifyAll() – Wakes up all threads that are waiting on this object’s monitor.
wait() – Causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object, or some other thread interrupts the current thread, or a specified amount of time has elapsed.
finalize() – Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

Can we override static method ?

If a subclass defines a static method with the same signature as a static method in the superclass, then the method in the subclass hides the one in the superclass.

The distinction between hiding a static method and overriding an instance method has important implications:

The version of the overridden instance method that gets invoked is the one in the subclass.
The version of the hidden static method that gets invoked depends on whether it is invoked from the superclass or the subclass

Consider an example,

package com.roytuts.staticmethod;
public class Vehicle {
	public static void classMethod() {
		System.out.println("Super : inside classMethod");
	}
	public void instanceMethod() {
		System.out.println("Super : inside instanceMethod");
	}
}
package com.roytuts.staticmethod;
public class Car extends Vehicle {
	public static void classMethod() {
		System.out.println("Child : inside classMethod");
	}
	public void instanceMethod() {
		System.out.println("Child : inside instanceMethod");
	}
}
package com.roytuts.staticmethod;
public class TestMethodOverride {
	public static void main(String[] args) {
		Car car = new Car();
		car.instanceMethod();
		car.classMethod();
		Vehicle vehicle = new Vehicle();
		vehicle.instanceMethod();
		vehicle.classMethod();
		vehicle = car;
		vehicle.instanceMethod();
		vehicle.classMethod();
	}
}

Output

Child : inside instanceMethod
Child : inside classMethod
Super : inside instanceMethod
Super : inside classMethod
Child : inside instanceMethod
Super : inside classMethod

The Car class overrides the instance method in Vehicle and hides the static method in Vehicle. The main method in this class creates an instance of Car and invokes classMethod() on the class and instanceMethod() on the instance.

From the above output it is clear that the version of the hidden static method that gets invoked is the one in the superclass, and the version of the overridden instance method that gets invoked is the one in the subclass.

Can you list serialization methods ?

Serializable interface does not have any methods, that’s why iIt is called a marker interface. It just tells JVM to serialize a class.

What is the difference between super() and this() ?

super() is invoked for calling the super class’s constructor and this() is invoked for calling the same class’s constructor.

How to prevent a method from being overridden ?

Make the method final.

For example,

<access modifier><return type><final><method name>(<arguments>) {}

public void final methodName() {
}

Can we create abstract classes without any abstract methods ?

Yes. We can have abstract class without abstract method in it.

For example,

package com.roytuts.java.abstractclass;
public abstract class AbstractClass {
	public void display() {
		System.out.println("Abstract Class");
	}
}

Can we have static methods in interface ?

Methods in interface are by default public and abstract up to Java 7. From Java 8 we can have static and default methods in interfaces.

For more information please read Java 8 default and static methods example

What is transient variable ?

Transient variables cannot be persisted during serialization. A transient variable is a variable that can not be serialized. the transient keyword can be used to indicate the Java Virtual Machine (JVM) that the variable is not part of the persistent state of the object.

This can be used in a scenario where only some of the fields in a class are required to be saved and others are actually derived from the existing.

For more information please read https://roytuts.com/java-transient-modifier/

In case, there is a return at the end of try block, will execute finally block ?

Yes. The finally block will be executed even there is a return statement at the end of try block. It returns after executing the finally block.

What is abstract class or abstract method ?

By specifying abstract keyword just before class, we can make a class as abstract class. This class cannot be instantiated or we cannot create any instance from the abstract class.

public abstract class AbstractClass{ }

The method is one that has to be implemented in the child class. An abstract class may or may not contain abstract method. Abstract method contains abstract in its method signature and does not contain any implementation. Abstract methods are looks like as given below:

public abstract String getMessage();

What is default value of a boolean ?

false.

Does System.exit() in try block executes finally block ?

No. Besides a System.exit(), the finally block will not run if the JVM crashes for some reason (e.g. infinite loop in the try block).

public class TestFinally {
	public static void main(String[] args) {
		try {
			System.out.println("Inside the try block");
			System.exit(1);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			System.out.println("Inside the finally block!!!");
		}
	}
}

Output:

Inside the try block

What is final, finally and finalize ?

final

It is a keyword.
The variable declared as final can be initialized only once and cannot be changed later.
Java classes declared as final cannot be extended or overridden by its subclass.
Methods declared as final cannot be overridden in the subclass.

finally

finally is a block that follows the try block.
The finally block gets always executed when the try block exits even if an unexpected exception occurs.
finally bock is useful for more than just exception handling – it allows the programmer to avoid having clean up code accidentally bypassed by a return, continue, or break statement.

finalize

finalize is a method.
This method is called by the garbage collector on an object when garbage collection determines that there are no more references to the object.
Also, the garbage collector is not guaranteed to run at any specific time. In general, finalize() is probably not the best method to use in general unless there is something specific you need it for.

In Java, are true and false keywords ?

There are two boolean literals

true represents a true boolean value
false represents a false boolean value

How to get current time in milliseconds ?

System.currentTimeMillis()

What is the purpose of garbage collection ?

The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused later. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects from the memory. Every class inherits finalize() method from java.lang.Object, the finalize() method is called by the garbage collector when it determines no more reference to the object exists. In Java, it is a good idea to explicitly assign null value into a variable when the variable is no longer in use. In Java, calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected. Garbage collection is an automatic process and cannot be forced. There is no guarantee that Garbage collection will start immediately upon request of System.gc().

You can read more about Garbage Collection in Java.

What happens if one of the members in a class does not implement Serializable interface ?

When a class implements Serializable interface and if the class includes an object of a class that does not implement Serializable interface then a NotSerializableException will be thrown at the run time.