Hi Friends here I am providing the most important java interview questions that are frequently asked in interviews. If you want to submit any core java or advance java interview questions or if you find any mistake in below questions than please notify us by the Contact Me page.
Table of Contents
- Basic Questions
- OOPs interview Questions
- Exception handling interview Questions
- Java Multithreading interview Questions
- Serialization interview Questions
- String Interview Questions
- Java Collections interview Questions
- Applet interview Questions
Basic Questions
Yes. Java is a platform independent language. We can write java code on one platform and run it on another platform. For e.g. we can write and compile the code on windows and can run it on Linux or any other supported platform. This is one of the main features of java.
Heap, Stack, Program Counter Register and Native Method Stack
The following features of java make it different from the C++:
- Simple
- Multi-threaded
- Distributed Application
- Robust
- Security
- Complexities are removed (Pointers, Operator overloading, Multiple inheritance).
It produces the java byte code from *.java file. It is the intermediate representation of your source code that contains instructions.
Class is nothing but a template that describes the data and behavior associated with instances of that class
java.lang.ObjectPath specifies the location of .exe files while classpath is used for specifying the location of .class files.
- byte – 8 bit (are esp. useful when working with a stream of data from a network or a file).
- short – 16 bit
- char – 16 bit Unicode
- int – 32 bit (whole number)
- float – 32 bit (real number)
- long – 64 bit (Single precision)
- double – 64 bit (double precision)
Java uses Unicode to represent the characters. Unicode defines a fully international character set that can represent all of the characters found in human languages.
A literal is a value that may be assigned to a primitive or string variable or passed as an argument to a method.
Java allows variables to be initialized dynamically, using any expression valid at the time the variable is declared.
To create a conversion between two incompatible types, we must use a cast. There are two types of casting in java: automatic casting (done automatically) and explicit casting (done by programmer).
An array is a group of fixed number of same type values. Read more about Arrays here.
It is also referred as terminator. In Java, the break statement can be used in following two cases:
- It terminates a statement sequence in a switch-case statement.
- It can be used to come out of a loop
Yes, the specification says that arrays are object references just like classes are. You can even invoke the methods of Object such as toString () and hashCode () on an array. However, length is a data item of an array and not a method. So you have to use myArray.length.
Use a JAR file. Put all the files in a JAR, then run the app like this:
Java -jar [-options] jarfile [args...]Any Data type declaration should not be inside the loop.
Jdk1.1 release consists of Java Unicode character to support the multiple language fonts, along with Event Handling, Java security, Java Beans, RMI, SQL are the major feature provided.
- Object class
- Data type wrapper classes
- Math class
- String class
- System and Runtime classes
- Thread classes
- Exception classes
- Process classes
- Class classes
int arr[] = null; int arr[][] = new int arr[][]; int [][] arr = new arr [][]; int [] arr [] = new arr[][];
OOPs Interview Questions
- Inheritance
- Polymorphism
- Data Encapsulation
- Abstraction
The process by which one class acquires the properties and functionalities of another class. Inheritance brings reusability of code in a java application.
When a class extends more than one classes then it is called multiple inheritance. Java doesn’t support multiple inheritance whereas C++ supports it, this is one of the difference between java and C++.
Polymorphism is the ability of an object to take many forms. The most common use of polymorphism in OOPs is to have more than one method with the same name in a single class. There are two types of polymorphism: static polymorphism and dynamic polymorphism.
It is a feature using which a child class overrides the method of parent class. It is only applicable when the method in child class has the signature same as parent class. Read more about method overriding here.
No, we cannot override a static method.
Having more than one method with the same name but different number, sequence or types of arguments is known is method overloading.
Operator overloading is not supported in Java.
No, We cannot do this.
Yes, we can overload main() method as well.
There are several differences; You can read them here: Overloading Vs Overriding.
Binding refers to the linking of method call to its body. A binding that happens at compile time is known as static binding while binding at runtime is known as dynamic binding.
Encapsulation means the localization of the information or knowledge within an object.
Encapsulation is also called as “Information Hiding”.
An abstract class is a class which can’t be instantiated (we cannot create the object of abstract class), we can only extend such classes. It provides the generalized form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details. We can achieve partial abstraction using abstract classes, to achieve full abstraction we use interfaces.
An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface.
1) abstract class can have abstract and non-abstract methods. An interface can only have abstract methods.
2) An abstract class can have static methods but an interface cannot have static methods.
3) abstract class can have constructors but an interface cannot have constructors.
public ,private , abstract, final, protected.
Constructors are used for creating an instance of a class, they are invoked when an instance of class gets created. Constructor name and class name should be same and it doesn’t have a return type. Read more about constructors here.
No, we cannot inherit constructors.
No, Constructor cannot be declared final.
Default: Constructors with no arguments are known as default constructors, when you don’t declare any constructor in a class, compiler creates a default one automatically.
Yes. A constructor can call the another constructor of same class using this keyword. For e.g. this() calls the default constructor.
Note: this() must be the first statement in the calling constructor.
Yes. In fact it happens by default. A child class constructor always calls the parent class constructor. However we can still call it using super keyword. For e.g. super() can be used for calling super class default constructor.
The THIS keyword is a reference to the current object.
No, this keyword cannot have null values assigned to it.
In java, arguments can be passed in 2 ways,
Pass by reference – Changes made to the parameter will affect the argument used to call the subroutine.
Static variables are also known as class level variables. A static variable is same for all the objects of that particular class in which it is declared.
A static block gets executed at the time of class loading. They are used for initializing static variables.
Static methods can be called directly without creating the instance (Object) of the class. A static method can access all the static variables of a class directly but it cannot access non-static variables without creating instance of class.
super keyword references to the parent class. There are several uses of super keyword:
- It can be used to call the superclass(Parent class) constructor.
- It can be used to access a method of the superclass that has been hidden by subclass (Calling parent class version, In case of method overriding).
- To call the constructor of parent class.
Final methods – These methods cannot be overridden by any other method.
Final variable – Constants, the value of these variable can’t be changed, its fixed.
Final class – Such classes cannot be inherited by other classes. These type of classes will be used when application required security or someone don’t want that particular class.More details.
This is a special class defined by java; all other classes are subclasses of object class. Object class is superclass of all other classes. Object class has the following methods
- objectClone () – to creates a new object that is same as the object being cloned.
- boolean equals(Object obj) – determines whether one object is equal to another.
- finalize() – Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. A subclass overrides the finalize method to dispose of system resources or to perform other cleanup.
- toString () – Returns a string representation of the object.
A Package can be defined as a grouping of related types (classes, interfaces, enumerations and annotations )
The star form (java.util.* ) includes all the classes of that package and that may increase the compilation time – especially if you import several packages. However it doesn’t have any effect run-time performance.
Since objects are dynamically allocated by using the new operator, java handles the de-allocation of the memory automatically when no references to an object exist for a long time is called garbage collection. The whole purpose of Garbage collection is efficient memory management.
finalize() method is used to free the allocated resource.
The garbage collector calls the finalize() method Only once for an object.
System.gc() OR Runtime.getRuntime().gc().No, its not possible. you cannot force garbage collection. you can call system.gc() methods for garbage collection but it does not guarantee that garbage collection would be done.
Exception handling Interview Questions
Exceptions are abnormal conditions that arise during execution of the program. It may occur due to wrong user input or wrong logic written by programmer.
Java.lang.ExceptionThis package contains definitions for Exceptions.
There are two types of exceptions: checked and unchecked exceptions.
Checked exceptions: These exceptions must be handled by programmer otherwise the program would throw a compilation error.
Unchecked exceptions: It is up to the programmer to write the code in such a way to avoid unchecked exceptions. You would not get a compilation error if you do not handle these exceptions. These exceptions occur at runtime.
Error: Mostly a system issue. It always occur at run time and must be resolved in order to proceed further.
Exception: Mostly an input data issue or wrong logic in code. Can occur at compile time or run time.
The throw keyword is used for throwing user defined or pre-defined exception.
If a method does not handle a checked exception, the method must declare it using the throwskeyword. The throws keyword appears at the end of a method’s signature.
Read the difference here: Java – throw vs throws.
Yes, A static block can throw exceptions. It has its own limitations: It can throw only Runtime exception (Unchecked exceptions), In order to throw checked exceptions you can use a try-catch block inside it.
Finally block is a block of code that always executes, whether an exception occurs or not. Finally block follows try block or try-catch block.
1) ClassNotFoundException occurs when loader could not find the required class in class path.
2) NoClassDefFoundError occurs when class is loaded in classpath, but one or more of the class which are required by other class, are removed or failed to load by compiler.
No, we cannot have a try block without catch or finally block. We must have either one of them or both.
Yes we can have multiple catch blocks in order to handle more than one exception.
Yes, we can have try block followed by finally block without even using catch blocks in between.
The only time finally won’t be called is if you call System.exit() or if the JVM crashes first.
Yes we can do that using if-else statement but it is not considered as a good practice. We should have one catch block for one exception.
A JavaBean is a Java class that follows some simple conventions including conventions on the names of certain methods to get and set state called Introspection. Because it follows conventions, it can easily be processed by a software tool that connects Beans together at runtime. JavaBeans are reusable software components.
Java Multithreading Interview Questions
It is a process of executing two or more part of a program simultaneously. Each of these parts is known as threads. In short the process of executing multiple threads simultaneously is known as multithreading.
Maximizing CPU usage and reducing CPU idle time
1) One process can have multiple threads. A thread is a smaller part of a process.
2) Every process has its own memory space, executable code and a unique process identifier (PID) while every thread has its own stack in Java but it uses process main memory and shares it with other threads.
3) Threads of same process can communicate with each other using keyword like wait and notify etc. This process is known as inter process communication.
There are following two ways of creating a thread:
1) By Implementing Runnable interface.
2) By Extending Thread class.
yield() – It causes the currently executing thread object to temporarily pause and allow other threads to execute.
sleep() – It causes the current thread to suspend execution for a specified period. When a thread goes into sleep state it doesn’t release the lock
A daemon thread is a thread, that does not prevent the JVM from exiting when the program finishes but the thread is still running. An example for a daemon thread is the garbage collection.
if you use join() ,it makes sure that as soon as a thread calls join,the current thread(yes,currently running thread) will not execute unless the thread you have called join is finished.
1) The preemptive scheduling is prioritized. The highest priority process should always be the process that is currently utilized.
2) Time slicing means task executes for a defined slice/ period of time and then enter in the pool of ready state. The scheduler then determines which task execute next based on priority or other factor.
Yes, we can call run() method of a Thread class but then it will behave like a normal method. To actually execute it in a Thread, you should call Thread.start() method to start it.
Starvation describes a situation where a thread is unable to gain regular access to shared resources and is unable to make progress. This happens when shared resources are made unavailable for long periods by “greedy” threads. For example, suppose an object provides a synchronized method that often takes a long time to return. If one thread invokes this method frequently, other threads that also need frequent synchronized access to the same object will often be blocked.
Deadlock describes a situation where two or more threads are blocked forever, waiting for each other.
Serialization interview Questions
Serialization is a process of converting an object and its attributes to the stream of bytes. De-serialization is recreating the object from stream of bytes; it is just a reverse process of serialization. To know more about serialization with example program.
No. In order to make an object serializable we just need to implement the interface Serializable. We don’t need to implement any methods.
1) transient variables are not included in the process of serialization.
2) They are not the part of the object’s serialized state.
3) Variables which we don’t want to include in serialization are declared as transient.
String interview questions
String class is immutable that’s the reason once its object gets created, it cannot be changed further.
1) StringBuffer is thread-safe but StringBuilder is not thread safe.
2) StringBuilder is faster than StringBuffer.
3) StringBuffer is synchronized whereas StringBuilder is not synchronized.
The toString() method returns the string representation of any object.
Java collections interview questions
Elements can be inserted or accessed by their position in the list, using a zero-based index.
A list may contain duplicate elements.
Map interface maps unique keys to values. A key is an object that we use to retrieve a value later. A map cannot contain duplicate keys: Each key can map to at most one value.
A Set is a Collection that cannot contain duplicate elements.
Array can hold fixed number of elements. ArrayList can grow dynamically.
1) LinkedList store elements within a doubly-linked list data structure. ArrayList store elements within a dynamically resizing array.
2) LinkedList is preferred for add and update operations while ArrayList is a good choice for search operations.
LinkedList. Because deleting or adding a node in LinkedList is faster than ArrayList.
ArrayList. Searching an element is faster in ArrayList compared to LinkedList.
1) Vector is synchronized while ArrayList is not synchronized.
2) By default, Vector doubles the size of its array when it is re-sized internally. ArrayList increases by half of its size when it is re-sized.
Following are the major differences between them:
1) Iterator can be used for traversing Set, List and Map. ListIterator can only be used for traversing a List.
2) We can traverse only in forward direction using Iterator. ListIterator can be used for traversing in both the directions(forward and backward).
TreeSet implements SortedSet interface.
1) Hashtable is synchronized. HashMap is not synchronized.
2) Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.
1) Iterator allows to remove elements from the underlying collection during the iteration using its remove() method. We cannot add/remove elements from a collection when using enumerator.
2) Iterator has improved method names.
Enumeration.hasMoreElement() -> Iterator.hasNext()
Enumeration.nextElement() -> Iterator.next().
Read More »


