Core Java Interview Question and Answers
Core Java Interview Question and Answers
Java 8 has been one of the biggest release after Java 5 annotations and generics.
Some of the important features of Java 8 are:
JDK provides all the tools, executables and binaries required to compile, debug and
execute a Java Program. The execution part is handled by JVM to provide machine
independence.
main method is public and static so that java can access it without initializing the class.
The input parameter is an array of String through which we can pass runtime arguments
to the java program.
Overriding concept comes in picture with inheritance when we have two methods with
same signature, one in parent class and another in child class. We can use @Override
annotation in the child class overridden method to make sure if parent class method is
changed, so as child class.
9.What is method signature? What are the things it
consists of?
Method signature is used by the compiler to differentiate the methods. Method
signature consists of three things.
a) Method name
b) Number of arguments
c) Types of arguments
None of them. It is neither constructor overloaded nor method overloaded. First one is a
constructor and second one is a method.
For every method call there should be proper method definition. This is a rule in java. If
compiler does not see the proper method definition for every method call, it throws
error.
Static binding is a binding which happens during compilation. It is also called early
binding because binding happens before a program actually runs. Static binding can be
demonstrated like in the below picture.
In this picture, ‘a1’ is a reference variable of type Class A pointing to object of class
A. ‘a2’ is also reference variable of type class A but pointing to object of Class B.
During compilation, while binding, compiler does not check the type of object to which a
particular reference variable is pointing. It just checks the type of reference variable
through which a method is called and checks whether there exist a method definition for
it in that type.
For example, for “a1.method()” method call in the above picture, compiler checks
whether there exist method definition for method() in Class A. Because ‘a1′ is Class A
type. Similarly, for“a2.method()” method call, it checks whether there exist method
definition for method() in Class A. Because ‘a2′ is also Class A type. It does not check
to which object, ‘a1’ and ‘a2’ are pointing. This type of binding is called static binding.
Dynamic Binding In Java :Dynamic binding is a binding which happens during run
time. It is also called late binding because binding happens when program actually is
running. During run time actual objects are used for binding. For example,
for “a1.method()” call in the above picture, method() of actual object to which ‘a1’ is
pointing will be called. For“a2.method()” call, method() of actual object to which ‘a2’ is
pointing will be called. This type of binding is called dynamic binding.
The dynamic binding of above example can be d
Actual object is not used for binding. Actual object is used for binding.
It is also called early binding because It is also called late binding because
binding happens during compilation. binding happens at run time.
Method overloading is the best example of Method overriding is the best example of
static binding. dynamic binding.
Private, static and final methods Other than private, static and final
show static binding. Because, they cannot methods show dynamic binding. Because,
be overridden. they can be overridden.
We can use final keyword with methods to make sure child classes can’t override it.
final keyword can be used with variables to make sure that it can be assigned only
once.
finalize() is a special method in Object class that we can override in our classes. This
method get’s called by garbage collector when the object is getting garbage collected.
This method is usually overridden to release system resources when object is garbage
collected.
Declaration
Following is the declaration for java.lang.Object.finalize() method
protected void finalize()
Parameters
NA
Return Value
This method does not return a value.
Exception
Throwable -- the Exception raised by this method
Example
The following example shows the usage of lang.Object.finalize() method.
package com.tutorialspoint;
import java.util.*;
// finalize cal
System.out.println("Finalizing...");
cal.finalize();
System.out.println("Finalized.");
}
}
25. Can we declare a class as static?
We can’t declare a top-level class as static however an inner class can be declared as
static. If inner class is declared as static, it’s called static nested class.
Static nested class is same as any other top-level class and is nested for only
packaging convenience.
import java.lang.Math;
//inside class
We can do the same thing by importing the static method or variable only and then use
it in the class as if it belongs to it.
double test = PI * 5;
Use of static import can cause confusion, so it’s better to avoid it. Overuse of static
import can make your program unreadable and unmaintainable.
27. What is try-with-resources in java?
One of the Java 7 features is try-with-resources statement for automatic resource
management. Before Java 7, there was no auto resource management and we should
explicitly close the resource. Usually, it was done in the finally block of a try-catch
statement. This approach used to cause memory leaks when we forgot to close the
resource.
From Java 7, we can create resources inside try block and use it. Java takes care of
closing it as soon as try-catch block gets finished.
Before Java 7:
try{
} catch (FileNotFoundException e) {
}finally{
// close resources
}
Java 7 try with resources implementation:
// use resources
} catch (FileNotFoundException e) {
// exception handling
package com.journaldev.util;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
"C:\\journaldev.txt"))) {
System.out.println(br.readLine());
} catch (IOException e) {
e.printStackTrace();
If a catch block handles multiple exception, you can separate them using a pipe (|) and
in this case exception parameter (ex) is final, so you can’t change it.
Before Java 7:
1
2 catch (IOException ex) {
logger.error(ex);
3 throw new MyException(ex.getMessage());
4 catch (SQLException ex) {
5 logger.error(ex);
6 throw new MyException(ex.getMessage());
7 }catch (Exception ex) {
logger.error(ex);
8 throw new MyException(ex.getMessage());
9 }
10
In Java 7, we can catch all these exceptions in a single catch block as:
Interfaces are good for starting point to define Type and create top level hierarchy in our
code. Since a java class can implements multiple interfaces, it’s better to use interfaces
as super class in most of the cases.
A class can extend only one abstract class but it can implement multiple interfaces.
We can run abstract class if it has main() method whereas we can’t run an interface.
enum is the keyword to create an enum type and similar to class. Enum constants are
implicitly static and final.
Even though we don’t use Reflection API in normal programming, it’s very important to
have. We can’t have any frameworks such as Spring, Hibernate or servers such as
Tomcat, JBoss without Reflection API. They invoke the appropriate methods and
instantiate classes through reflection API and use it a lot for other processing.
Even though we don’t use Reflection API in normal programming, it’s very important to
have. We can’t have any frameworks such as Spring, Hibernate or servers such as
Tomcat, JBoss without Reflection API. They invoke the appropriate methods and
instantiate classes through reflection API and use it a lot for other processing.
Java composition is achieved by using instance variables that refers to other objects.
Benefit of using composition is that we can control the visibility of other object to client
classes and reuse only what we need.
Any change in the superclass might affect subclass even though we might not be using
the superclass methods. For example, if we have a method test() in subclass and
suddenly somebody introduces a method test() in superclass, we will get compilation
errors in subclass. Composition will never face this issue because we are using only what
methods we need.
Inheritance exposes all the super class methods and variables to client and if we have no
control in designing superclass, it can lead to security holes. Composition allows us to
provide restricted access to the methods and hence more secure.
We can get runtime binding in composition where inheritance binds the classes at compile
time. So composition provides flexibility in invocation of methods.
However, if you want to sort based on different criteria, such as sorting an Employees
collection based on salary or age, then we can create Comparator instances and pass it
as sorting methodology.
We can have local inner class or anonymous inner class inside a class.
Since an anonymous class has no name, it is not possible to define a constructor for an
anonymous class. Anonymous inner classes are accessible only at the point where it is
defined.
1. Bootstrap Class Loader – It loads JDK internal classes, typically loads rt.jar and
other core classes.
2. Extensions Class Loader – It loads classes from the JDK extensions directory,
usually $JAVA_HOME/lib/ext directory.
3. System Class Loader – It loads classes from the current classpath that can be set
while invoking a program using -cp or -classpath command line options.
package com.journaldev.access;
public SuperClass(){
package com.journaldev.access;
super();
test();
super.test();
@Override
//constructor
this.x = x;
this.y = y;
We can also use this keyword to invoke other constructors from a constructor.
public Rectangle() {
this(0, 0, 0, 0);
this.x = x;
this.y = y;
this.width = width;
this.height = height;
The process of converting stream data created through serialization to Object is called
deserialization.
System class is final so that we can’t subclass and override it’s behavior through
inheritance. System class doesn’t provide any public constructors, so we can’t
instantiate this class and that’s why all of it’s methods are static.
Some of the utility methods of System class are for array copy, get current time, reading
environment variables.
System.out.println("String value:"+str);
System.out.println("Integer value:"+str);
Since str is of type String at runtime, first if statement evaluates to true and second one
to false.
Heap memory is used by all the parts of the application whereas stack memory is
used only by one thread of execution.
Whenever an object is created, it’s always stored in the Heap space and stack
memory contains the reference to it. Stack memory only contains local primitive
variables and reference variables to objects in heap space.
Memory management in stack is done in LIFO manner whereas it’s more complex
in Heap memory because it’s used globally.
60. Java Compiler is stored in JDK, JRE or JVM?
The task of java compiler is to convert java program into bytecode, we
have javac executable for that. So it must be stored in JDK, we don’t need it in JRE
and JVM is just the specs.
2. package com.journaldev.util;
3.
5.
8. return "";
9. }
10.
12. System.out.println(toString());
13. }
Answer: The code won’t compile because we can’t have an Object class
method with static keyword. You will get compile time error as “This static
method cannot hide the instance method from Object”. The reason is that
static method belongs to class and since every class base is Object, we
can’t have same method in instance as well as in class.
16.
18.
22. }
23.
26. System.out.println(obj.foo());
27. }
I must admit that it’s a very tricky question and if you are interviewing
o Thread is lightweight.
Under preemptive scheduling, the highest priority task executes until it enters the waiting or
dead states or a higher priority task comes into existence. Under time slicing, a task
executes for a predefined slice of time and then reenters the pool of ready tasks. The
scheduler then determines which task should execute next, based on priority and other
factors.
wait() sleep()
1) The wait() method is defined in Object class. The sleep() method is defined in Thread class.
2) wait() method releases the lock. The sleep() method doesn't releases the lock.
yes, but it will not work as a thread rather it will work as a normal object so there will not
be context-switching between the threads.
69. Daemon thread in java is a service provider thread that provides services to the user
thread. Its life depend on the mercy of user threads i.e. when all the user threads dies, JVM
terminates this thread automatically. It is a low priority thread.
There are many java daemon threads running automatically e.g. gc, finalizer etc.
You can see all the detail by typing the jconsole in the command prompt. The jconsole tool
provides information about the loaded classes, memory usage, running threads etc.
The sole purpose of the daemon thread is that it provides services to user thread for
background supporting task. If there is no user thread, why should JVM keep running this
thread. That is why JVM terminates the daemon thread if there is no user thread.
The java.lang.Thread class provides two methods for java daemon thread.
1) public void setDaemon(boolean status) is used to mark the current thread as daemon threa
Note: If you want to make a user thread as Daemon, it must not be started otherwise it will throw
IllegalThreadStateException.
The shutdown hook can be used to perform cleanup resource or save the state when JVM
shuts down normally or abruptly. Performing clean resource means closing log file, sending
some alerts or something else. So if you want to execute some code before JVM shuts
down, use shutdown hook.
The addShutdownHook() method of Runtime class is used to register the thread with the
Virtual Machine. Syntax:
The object of Runtime class can be obtained by calling the static factory method
getRuntime(). For example:
Runtime r = Runtime.getRuntime();
Factory method
The method that returns the instance of a class is known as factory method.
Note: The shutdown sequence can be stopped by invoking the halt(int) method of Runtime class.
Interrupting a Thread:
If any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the
interrupt() method on the thread, breaks out the sleeping or waiting state throwing
InterruptedException. If the thread is not in the sleeping or waiting state, calling the
interrupt() method performs normal behaviour and doesn't interrupt the thread but sets
the interrupt flag to true. Let's first see the methods provided by the Thread class for
thread interruption.
Synchronization in Java
Synchronization in java is the capability to control the access of multiple threads to
any shared resource.
Java Synchronization is better option where we want to allow only one thread to access the
shared resource.
Why use Synchronization
The synchronization is mainly used to
Types of Synchronization
There are two types of synchronization
1. Process Synchronization
2. Thread Synchronization
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread
communication.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. static synchronization.
Yes. You can lock an object by putting it in a "synchronized" block. The locked object is
inaccessible to any thread other than the one that explicitly claimed it.
If you make any static method as synchronized, the lock will be on the class not on object.
The notify() is used to unblock one waiting thread whereas notifyAll() method is used to
unblock all the threads in waiting state.
77.What is deadlock?
Deadlock is a situation when two threads are waiting on each other to release a resource.
Each thread waiting for a resource which is held by the other waiting thread.