For the latest Java Interview Questions Refer to the Following Article – Java Interview Questions – Fresher and Experienced (2025)
Java is one of the most popular and widely used programming languages and a platform that was developed by James Gosling in the year 1995. It is based on the concept of object-oriented Programming. A platform is an environment in that develops and runs programs written in any programming language. Java is a high-level, object-oriented, secure, robust, platform-independent, multithreaded, and portable programming language. It is mainly used for programming, Windows, web-based, enterprise, and mobile applications.
Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and performance. To get into these companies and other software companies, you need to master some important Core Java interview questions to crack their Java Online Assessment round and Java Technical interview.
This Core Java programming interview questions article is written under the guidance of the masters of Java and by getting ideas through the experience of students' recent Java interviews.
Core Java Interview Questions For Freshers
Q1. Explain JVM, JRE, and JDK.
JVM (Java Virtual Machine): JVM(Java Virtual Machine) acts as a run-time engine to run Java applications. JVM is the one that calls the main method present in Java code. JVM is a part of JRE(Java Runtime Environment).
JRE (Java Runtime Environment): JRE refers to a runtime environment in which Java bytecode can be executed. It implements the JVM (Java Virtual Machine) and provides all the class libraries and other support files that JVM uses at runtime. So JRE is a software package that contains what is required to run a Java program. It’s an implementation of the JVM which physically exists.
JDK(Java Development Kit): It is the tool necessary to compile, document, and package Java programs. The JDK completely includes JRE which contains tools for Java programmers. The Java Development Kit is provided free of charge. Along with JRE, it includes an interpreter/loader, a compiler (javac), an archiver (jar), a documentation generator (Javadoc), and other tools needed in Java development. In short, it contains JRE + development tools.
Q2. Explain public static void main(String args[]).
- Public: Public is an access modifier. Public means that this Method will be accessible by any Class.
- static: It is a keyword in Java that identifies it as class-based i.e it can be accessed without creating the instance of a Class. Since we want the main method to be executed without any instance also, we use static.
- Void: It is the return type of the method. Void defines the method which will not return any value.
- main: This is the first method executed by JVM. The signature of the method must be the same.
Q3. Why Java is platform independent?
Platform independence practically means “write once run anywhere”. Java is called so because of its byte codes which can run on any system irrespective of its underlying operating system.
Q4. Why is Java not purely Object-oriented?
Java is not considered pure Object-oriented because it supports primitive data types such as boolean, byte, char, int, float, double, long, and short.
Q5. Define class and object. Explain them with an example using Java.
- Class: A class is a user-defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type. In general, class declarations can include these components, in order.
- Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.
- Interfaces: A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.
- Object: It is a basic unit of Object Oriented Programming and represents real-life entities. A typical Java program creates many objects, which as you know, interact by invoking methods. An object consists of :
- State: It is represented by attributes of an object. It also reflects the properties of an object.
- Behavior: It is represented by the methods of an object. It also reflects the response of an object to other objects.
- Identity: It gives a unique name to an object and enables one object to interact with other objects.
For Example, an Employee is an example of a class. A specific employee with unique identification is an example of an object.
class Employee
{
// instance variables declaration
// Methods definition
}
An object of an employee is a specific employee
Employee empObj = new Employee();
One of the objects of Employee is referred to by ‘empObj’
Q6. What is a method? Provide several signatures of the methods.
- A Java method is a set of statements to perform a task. A method is placed in a class.
- Signatures of methods: The method's name and the parameters(type and order) comprise the method signature.
- A method can have the following elements in its signature:
- Access specifier – public, private, protected, etc. (Not mandatory)
- Access modifier – static, synchronized, etc. (Not mandatory)
- Return type - void, int, String, etc. (Mandatory)
- Method name – show() (Mandatory)
- With or without parameters – (int number, String name); (parenthesis are mandatory)
Example:
Java
class Test {
void fun1() {}
public double fun2(double x) {}
public static void fun3() {}
public static void fun4(String x) {}
}
Q7. Explain the difference between an instance variable and a class variable.
An instance variable is a variable that has one copy per object/instance. That means every object will have one copy of it. A class variable is a variable that has one copy per class. The class variables will not have a copy in the object.
Example:
Java
class Employee {
int empNo;
String empName, department;
double salary;
static int officePhone;
}
An object referred to by empObj1 is created by using the following:
Employee empObj1 = new Employee();
The objects referred by instance variables empObj1 and empObj2 have separate copies empNo, empName, department, and salary. However, the officePhone belongs to the class(Class Variable) and can be accessed as Employee.officePhone.
Q8. Which class is the superclass of all classes?
java.lang.Object is the root class for all the Java classes and we don’t need to extend it.
Q9. What are constructors in Java?
In Java, a constructor refers to a block of code that is used to initialize an object. It must have the same name as that of the class. Also, it has no return type and is automatically called when an object is created.
If a class does not explicitly declare any, the Java compiler automatically provides a no-argument constructor, also called the default constructor.
This default constructor calls the class parent’s no-argument constructor (as it contains only one statement i.e. super();), or the Object class constructor if the class has no other parent (as the Object class is a parent of all classes either directly or indirectly).
There are two types of constructors:
- Default constructor
- Parameterized constructor
Q10. What are the different ways to create objects in Java?
There are many different ways to create objects in Java.
1 Using new keyword
2 Using new instance
3 Using clone() method
4 Using deserialization
5 Using newInstance() method of Constructor class
Please refer to this article - 5 Different ways to create objects in Java
Q11. What’s the purpose of Static methods and static variables?
When there is a requirement to share a method or a variable between multiple objects of a class instead of creating separate copies for each object, we use static keywords to make a method or variable shared for all objects.
Static variable: Static variables are also known as Class variables.
- These variables are declared similarly to instance variables, the difference is that static variables are declared using the static keyword within a class outside any method constructor or block.
- Unlike instance variables, we can only have one copy of a static variable per class irrespective of how many objects we create.
- Static variables are created at the start of program execution and destroyed automatically when execution ends.
- To access static variables, we need not create an object of that class.
Static methods: A static method can be accessed without creating objects. Just by using the Class name, the method can be accessed. The static method can only access static variables, not local or global non-static variables.
For Example:
Java
class StaticMethod {
public static void printMe()
{
System.out.println("Static Method access directly by class name!");
}
}
class MainClass {
public static void main(String args[])
{
StaticMethod.printMe();
}
}
OutputStatic Method access directly by class name!
Q12. Why can static methods not access non-static variables or methods?
A static method cannot access non-static variables or methods because static methods can be accessed without instantiating the class, so if the class is not instantiated the variables are not initialized and thus cannot be accessed from a static method.
Q13. What is a static class?
A class can be said to be a static class if all the variables and methods of the class are static and the constructor is private. Making the constructor private will prevent the class to be instantiated. So the only possibility to access is using the Class name only.
Q14. Explain How many types of variables are in Java?
There are three types of variables in Java:
- Local Variables
- Instance Variables
- Static Variables
Local Variables: A variable defined within a block or method or constructor is called a local variable. These variables are created when the block is entered or the function is called and destroyed after exiting from the block or when the call returns from the function. The scope of these variables exists only within the block in which the variable is declared. i.e. we can access these variables only within that block.
Java
// Java program to demonstrate local variables
public class LocalVariable
{
public void getLocalVarValue()
{
// local variable age
int localVar = 0;
localVar = localVar + 11;
System.out.println("value of local variable" +
" is: " + localVar);
}
public static void main(String args[])
{
LocalVariable obj = new LocalVariable();
obj.getLocalVarValue();
}
}
Output:
value of local variable is: 11
In the above program, the variable localVar is the local variable to the function getLocalVarValue(). If we use the variable localVar outside getLocalVarValue() function, the compiler will produce an error as "Cannot find the symbol localVar".
Instance Variables: Instance variables are non-static variables and are declared in a class outside any method, constructor, or block. As instance variables are declared in a class, these variables are created when an object of the class is created and destroyed when the object is destroyed. Unlike local variables, we may use access specifiers for instance variables. If we do not specify any access specifier then the default access specifier will be used.
Java
// Java program to demonstrate instance variables
public class InstanceVariable {
int instanceVarId;
String instanceVarName;
public static void main(String args[])
{
InstanceVariable obj = new InstanceVariable();
obj.instanceVarId = 0001;
obj.instanceVarName = "InstanceVariable1";
System.out.println("Displaying first Object:");
System.out.println("instanceVarId==" + obj.instanceVarId);
System.out.println("instanceVarName==" + obj.instanceVarName);
InstanceVariable obj1 = new InstanceVariable();
obj1.instanceVarId = 0002;
obj1.instanceVarName = "InstanceVariable2";
System.out.println("Displaying Second Object:");
System.out.println("instanceVarId==" + obj1.instanceVarId);
System.out.println("instanceVarName==" + obj1.instanceVarName);
}
}
OutputDisplaying first Object:
instanceVarId==1
instanceVarName==InstanceVariable1
Displaying Second Object:
instanceVarId==2
instanceVarName==InstanceVariable2
In the above program the variables i.e. instanceVarId, instanceVarName are instance variables. In case we have multiple objects as in the above program, each object will have its own copies of instance variables. It is clear from the above output that each object will have its own copy of the instance variable.
Static variable: Static variables are also known as Class variables.
- These variables are declared similarly to instance variables, the difference is that static variables are declared using the static keyword within a class outside any method constructor or block.
- Unlike instance variables, we can only have one copy of a static variable per class irrespective of how many objects we create.
- Static variables are created at the start of program execution and destroyed automatically when execution ends.
To access static variables, we need not create an object of that class, we can simply access the variable as:
Java
// Java program to demonstrate static variables
public class StaticVar {
private static int count = 0;
private int nonStaticCount = 0;
public void incrementCounter()
{
count++;
nonStaticCount++;
}
public static int getStaticCount()
{
return count;
}
public int getNonStaticCount()
{
return nonStaticCount;
}
public static void main(String args[])
{
StaticVar stVarObj1 = new StaticVar();
StaticVar stVarObj2 = new StaticVar();
stVarObj1.incrementCounter();
stVarObj2.incrementCounter();
System.out.println("Static count for stVarObj1: " +
stVarObj1.getStaticCount());
System.out.println("NonStatic count for stVarObj1: " +
stVarObj1.getNonStaticCount());
System.out.println("Static count for stVarObj2: " +
stVarObj2.getStaticCount());
System.out.println("NonStatic count for stVarObj2: " +
stVarObj2.getNonStaticCount());
}
}
OutputStatic count for stVarObj1: 2
NonStatic count for stVarObj1: 1
Static count for stVarObj2: 2
NonStatic count for stVarObj2: 1
In the above program, stVarObj1 and stVarObj2 share the same instance of static variable count hence if the value is incremented by one object, the incremented value will be reflected for stVarObj1 and stVarObj2.
Q14. What is the difference between the Set and List interface?
Set and List are both child interfaces of the Collection interface. There are following two main differences between them
- List can hold duplicate values but Set doesn’t allow this.
- In List interface data is present in the order you inserted but in the case of Set, the insertion order is not preserved.
Q15. What is the difference between StringBuffer and String?
The String class is an Immutable class, i.e. you can not modify its content once created. While StringBuffer is a mutable class, which means you can change its content later. Whenever we alter the content of a String object, it creates a new string and refers to that, it does not modify the existing one. This is the reason that the performance with StringBuffer is better than with String.
Please see String vs StringBuilder vs StringBuffer for more details.
Q16. When is the super keyword used?
The super keyword is used to refer to:
- immediate parent class constructor,
- immediate parent class variable,
- immediate parent class method.
Refer to super for details.
Q17. Differences between HashMap and HashTable in Java.
- HashMap is non-synchronized. It is not thread-safe and can’t be shared between many threads without proper synchronization code whereas Hashtable is synchronized. It is thread-safe and can be shared with many threads.
- HashMap allows one null key and multiple null values whereas Hashtable doesn’t allow any null key or value.
- HashMap is generally preferred over HashTable if thread synchronization is not needed.
Refer to HashMap and HashTable for more details.
Q18. What happens if you remove the static modifier from the main method?
Program compiles successfully. But at runtime throws an error “NoSuchMethodError”.
Q19. Can we overload the main() method?
The main method in Java is no extra-terrestrial method. Apart from the fact that main() is just like any other method & can be overloaded similarly, JVM always looks for the method signature to launch the program.
- The normal main method acts as an entry point for the JVM to start the execution of the program.
- We can overload the main method in Java. But the program doesn’t execute the overloaded main method when we run your program, we need to call the overloaded main method from the actual main method only.
Q20. What are wrapper classes in Java?
Wrapper classes convert the Java primitives into reference types (objects). Every primitive data type has a class dedicated to it. These are known as wrapper classes because they “wrap” the primitive data type into an object of that class.
Q21. Why pointers are not used in Java?
Java doesn’t use pointers because they are unsafe and increase the complexity of the program. Since, Java is known for its simplicity of code, adding the concept of pointers will be contradicting. Moreover, since JVM is responsible for implicit memory allocation, thus to avoid direct access to memory by the user, pointers are discouraged in Java.
Q22. What is the meaning of Collections in Java?
The collection is a framework that is designed to store the objects and manipulate the design to store the objects.
Collections are used to perform the following operations:
- Searching
- Sorting
- Manipulation
- Insertion
- Deletion
A group of objects is known as a collection. All the classes and interfaces for collecting are available in the Java util package.
Q23. What is Synchronization?
Synchronization makes only one thread access a block of code at a time. If multiple threads access the block of code, then there is a chance for inaccurate results at the end. To avoid this issue, we can provide synchronization for the sensitive block of codes.
The synchronized keyword means that a thread needs a key to access the synchronized code.
Every Java object has a lock. A lock has only one key. A thread can access a synchronized method only if the thread can get the key to the objects to lock. Locks are per object.
Refer to Synchronization for more details.
Q24. What is the disadvantage of Synchronization?
Synchronization is not recommended to implement all the methods. Because if one thread accesses the synchronized code then the next thread should have to wait. So it makes a slow performance on the other end.
Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. Known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Syntax and s
10 min read
Basics
Introduction to JavaJava is a high-level, object-oriented programming language developed by Sun Microsystems in 1995. It is platform-independent, which means we can write code once and run it anywhere using the Java Virtual Machine (JVM). Java is mostly used for building desktop applications, web applications, Android
4 min read
Java Programming BasicsJava is one of the most popular and widely used programming language and platform. A platform is an environment that helps to develop and run programs written in any programming language. Java is fast, reliable and secure. From desktop to web applications, scientific supercomputers to gaming console
4 min read
Java MethodsJava Methods are blocks of code that perform a specific task. A method allows us to reuse code, improving both efficiency and organization. All methods in Java must belong to a class. Methods are similar to functions and expose the behavior of objects.Example: Java program to demonstrate how to crea
7 min read
Access Modifiers in JavaIn Java, access modifiers are essential tools that define how the members of a class, like variables, methods, and even the class itself, can be accessed from other parts of our program. They are an important part of building secure and modular code when designing large applications. In this article
6 min read
Arrays in JavaIn Java, an array is an important linear data structure that allows us to store multiple values of the same type. Arrays in Java are objects, like all other objects in Java, arrays implicitly inherit from the java.lang.Object class. This allows you to invoke methods defined in Object (such as toStri
9 min read
Java StringsIn Java, a String is the type of object that can store a sequence of characters enclosed by double quotes and every character is stored in 16 bits, i.e., using UTF 16-bit encoding. A string acts the same as an array of characters. Java provides a robust and flexible API for handling strings, allowin
8 min read
Regular Expressions in JavaIn Java, Regular Expressions or Regex (in short) in Java is an API for defining String patterns that can be used for searching, manipulating, and editing a string in Java. Email validation and passwords are a few areas of strings where Regex is widely used to define the constraints. Regular Expressi
7 min read
OOPs & Interfaces
Classes and Objects in JavaIn Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are used to represent real-world concepts and entities. A class is a template to create objects having similar properties and behavior, or in other words, we can say that a class is a blueprint for objects.An
10 min read
Java ConstructorsIn Java, constructors play an important role in object creation. A constructor is a special block of code that is called when an object is created. Its main job is to initialize the object, to set up its internal state, or to assign default values to its attributes. This process happens automaticall
10 min read
Java OOP(Object Oriented Programming) ConceptsBefore Object-Oriented Programming (OOPs), most programs used a procedural approach, where the focus was on writing step-by-step functions. This made it harder to manage and reuse code in large applications.To overcome these limitations, Object-Oriented Programming was introduced. Java is built arou
10 min read
Java PackagesPackages in Java are a mechanism that encapsulates a group of classes, sub-packages and interfaces. Packages are used for: Prevent naming conflicts by allowing classes with the same name to exist in different packages, like college.staff.cse.Employee and college.staff.ee.Employee.They make it easier
8 min read
Java InterfaceAn Interface in Java programming language is defined as an abstract type used to specify the behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static constants and abstract methods. Key Properties of Interface:The interface in Java is a mechanism to
11 min read
Collections
Exception Handling
Java Exception HandlingException handling in Java is an effective mechanism for managing runtime errors to ensure the application's regular flow is maintained. Some Common examples of exceptions include ClassNotFoundException, IOException, SQLException, RemoteException, etc. By handling these exceptions, Java enables deve
8 min read
Java Try Catch BlockA try-catch block in Java is a mechanism to handle exceptions. This make sure that the application continues to run even if an error occurs. The code inside the try block is executed, and if any exception occurs, it is then caught by the catch block.Example: Here, we are going to handle the Arithmet
4 min read
Java final, finally and finalizeIn Java, the keywords "final", "finally" and "finalize" have distinct roles. final enforces immutability and prevents changes to variables, methods, or classes. finally ensures a block of code runs after a try-catch, regardless of exceptions. finalize is a method used for cleanup before an object is
4 min read
Chained Exceptions in JavaChained Exceptions in Java allow associating one exception with another, i.e. one exception describes the cause of another exception. For example, consider a situation in which a method throws an ArithmeticException because of an attempt to divide by zero.But the root cause of the error was an I/O f
3 min read
Null Pointer Exception in JavaA NullPointerException in Java is a RuntimeException. It occurs when a program attempts to use an object reference that has the null value. In Java, "null" is a special value that can be assigned to object references to indicate the absence of a value.Reasons for Null Pointer ExceptionA NullPointerE
5 min read
Exception Handling with Method Overriding in JavaException handling with method overriding in Java refers to the rules and behavior that apply when a subclass overrides a method from its superclass and both methods involve exceptions. It ensures that the overridden method in the subclass does not declare broader or new checked exceptions than thos
4 min read
Java Advanced
Java Multithreading TutorialThreads are the backbone of multithreading. We are living in the real world which in itself is caught on the web surrounded by lots of applications. With the advancement in technologies, we cannot achieve the speed required to run them simultaneously unless we introduce the concept of multi-tasking
15+ min read
Synchronization in JavaIn multithreading, synchronization is important to make sure multiple threads safely work on shared resources. Without synchronization, data can become inconsistent or corrupted if multiple threads access and modify shared variables at the same time. In Java, it is a mechanism that ensures that only
10 min read
File Handling in JavaIn Java, with the help of File Class, we can work with files. This File Class is inside the java.io package. The File class can be used to create an object of the class and then specifying the name of the file.Why File Handling is Required?File Handling is an integral part of any programming languag
6 min read
Java Method ReferencesIn Java, a method is a collection of statements that perform some specific task and return the result to the caller. A method reference is the shorthand syntax for a lambda expression that contains just one method call. In general, one does not have to pass arguments to method references.Why Use Met
9 min read
Java 8 Stream TutorialJava 8 introduces Stream, which is a new abstract layer, and some new additional packages in Java 8 called java.util.stream. A Stream is a sequence of components that can be processed sequentially. These packages include classes, interfaces, and enum to allow functional-style operations on the eleme
15+ min read
Java NetworkingWhen computing devices such as laptops, desktops, servers, smartphones, and tablets and an eternally-expanding arrangement of IoT gadgets such as cameras, door locks, doorbells, refrigerators, audio/visual systems, thermostats, and various sensors are sharing information and data with each other is
15+ min read
JDBC TutorialJDBC stands for Java Database Connectivity. JDBC is a Java API or tool used in Java applications to interact with the database. It is a specification from Sun Microsystems that provides APIs for Java applications to communicate with different databases. Interfaces and Classes for JDBC API comes unde
12 min read
Java Memory ManagementJava memory management is the process by which the Java Virtual Machine (JVM) automatically handles the allocation and deallocation of memory. It uses a garbage collector to reclaim memory by removing unused objects, eliminating the need for manual memory managementJVM Memory StructureJVM defines va
4 min read
Garbage Collection in JavaGarbage collection in Java is an automatic memory management process that helps Java programs run efficiently. Java programs compile to bytecode that can be run on a Java Virtual Machine (JVM). When Java programs run on the JVM, objects in the heap are created, which is a portion of memory dedicated
7 min read
Memory Leaks in JavaIn programming, a memory leak happens when a program keeps using memory but does not give it back when it's done. It simply means the program slowly uses more and more memory, which can make things slow and even stop working. Working of Memory Management in JavaJava has automatic garbage collection,
3 min read
Practice Java
Java Interview Questions and AnswersJava is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Java Programs - Java Programming ExamplesIn this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read
Java Exercises - Basic to Advanced Java Practice Programs with SolutionsLooking for Java exercises to test your Java skills, then explore our topic-wise Java practice exercises? Here you will get 25 plus practice problems that help to upscale your Java skills. As we know Java is one of the most popular languages because of its robust and secure nature. But, programmers
7 min read
Java Quiz | Level Up Your Java SkillsThe best way to scale up your coding skills is by practicing the exercise. And if you are a Java programmer looking to test your Java skills and knowledge? Then, this Java quiz is designed to challenge your understanding of Java programming concepts and assess your excellence in the language. In thi
1 min read
Top 50 Java Project Ideas For Beginners and Advanced [Update 2025]Java is one of the most popular and versatile programming languages, known for its reliability, security, and platform independence. Developed by James Gosling in 1982, Java is widely used across industries like big data, mobile development, finance, and e-commerce.Building Java projects is an excel
15+ min read