Top 100+ Core Java Interview Questions Answers

This article contains a detailed list of most frequently asked top Core Java interview questions along with their answers. We have covered around 100+ top core java interview questions in a very easy language to help you understand the basic concepts of Java. The answers are short and simple, and are also fitted with related examples.

The article covers many JAVA topics like Java Basics, OOPs Concepts, JDBC, Spring, Hibernate, JSP, Exceptions, and Threads, etc. 

You can easily access category-wise questions directly using a section ‘quick links’. Let’s get started:

Quick Links

Core Java Interview Questions

Core Java Interview Questions

1) What is Java?

Java is a high-level, object-oriented, multithreaded, portable, and platform-independent programming language. It was originally designed by James Gosling at Sun Microsystems in June 1991. In 1995, it was released as a core component of Sun Microsystems.

Later, Sun Microsystems was acquired by Oracle and hence Java was henceforth developed by Oracle. Currently, Java is one of the most popular programming languages in the world. It is also considered as the platform because it has its own JRE and API.

2) What are the main features of Java?

The main features/ characteristics of Java are as follows:

Simple- Java is a simple programming language. The concept of pointer which is very difficult is completely eliminated from Java.
Object-oriented- Java is an object-oriented programming language. This means that Java programs use classes and objects.
Distributed- Information is distributed on different computers on a network. This is possible because Java can handle protocols such as TCP / IP and UDP.
Robust- Robust means strong. Java programs are robust and do not crash as easily as and C 'and' C ++ 'programs. There are two reasons for this. Firstly, Java has got excellent inbuilt exception handling features and secondly its memory management facility.
Most 'C' and 'C ++' programs crash midway due to not allocating enough memory. Java will not have such problems because the user does not have to allocate or deal with memory in Java. Everything will be taken care of by the JVM.
Secure- Security problems like viruses, eavesdropping, and tampering can be eliminated by Java.
System Independent- Java’s byte code is machine (system) independent. This means that these codes can be run on different machines with any processor and any operating system.
Portable- If a program produces the same result as each machine, then that program is called portable. Java programs are portable.
Multithreaded- A thread represents an individual process to execute a group of statements. JVM uses multiple threads to execute different blocks of code. Creating multiple threads is called ‘multithreading’.

3) Why pointers are eliminated from Java?

Pointers are eliminated from Java because:

Pointers lead to confusion for a program.
Pointers may crash a program easily. For example, if two pointers are added, the program crashes immediately. The same thing can also happen when we forget to free the memory allotted to a variable and reallot it to another variable.
Pointers break security. By using pointers, harmful programs such as viruses and other hacking programs can be developed.

4) What is the class? How can you access members of the class?

There may be some scenarios where some objects may have similar properties and functions. Such objects belong to the same category which is known as a 'class'. For example, Jacob, James, Smith, etc. belong to a person class. They have the same properties and actions.

We can use a class as a model for creating objects. Objects are used to access members of a class.

Class Person
String name;
int age;
void talk();    //member of class
void eat();
Person Jacob= new Person();  //Creating object 'Jacob'
Jacob. talk();    //accessing member of class
Jacob. eat();
Scroll ⇀

5) Define an object in Java. How an object is created in Java?

An object denotes an instance of a class. It is a real-world entity that contains state and behavior. An object basically consists of the following three characteristics:


To create an object, we can use ‘new’ keyword as below:

ClassName obj = new ClassName();
Scroll ⇀

6) What is the difference between an executable file and a class file?

An executable file (.exe) contains machine language instructions for the microprocessor and is system dependent. Besides, the class file contains byte code instructions for the JVM and is system independent.

7) What is the BYTE code?

The BYTE code is an intermediate-level code that is interpreted by the JVM. It is not directly executable on the machine. A BYTE code is a mediator code between Java program and machine code of operating system (OS) and is available in ‘.class’ file. A ‘.class’ file is generated when the Java program or application gets compiled. BYTE code is the same for any OS but machine code differs on each OS.

8) What is JVM? Explain its working?

The JVM (Java Virtual Machine) is an abstract machine designed to be implemented on the top of existing processors. It hides the underlying operating system (OS) from Java applications. It is actually the heart of the entire Java program execution process.

Programs written in Java are compiled into Java byte code; which is then interpreted by a particular Java interpreter for a specific platform. This Java Interpreter is referred to as 'Java Virtual Machine'. The machine language for JVM is called Java Byte Code.

First, the Java program is converted into a class file with a byte code instruction by the Java compiler. This class file is given to the JVM, it has a module called class loader subsystem, which does the following:

First of all, it loads the class file into memory.
Then, it verifies whether all byte code instructions are appropriate. If it finds any instructions suspicious, the execution is immediately rejected.
If the byte instructions are appropriate, it allocates the memory required to execute the program.
The following diagram defines how a Java source code passes through various stages before being executed by the compiler:

Core Java Interview Questions - Execution of Java Program

9) What is JRE?

JRE stands for the 'Java Runtime Environment'. It is a platform consisting of Java virtual machines, Java libraries, and all other components required to run Java applications and applets.

10) What is the Java compiler?

A Java compiler is a program that converts Java source code to Java byte code.
A basic Java compiler is already included in JDK (Java Development Kit). The Java compiler is known as 'javac'.

11) What is the JIT compiler?

A JIT (Just-In-Time) compiler is the part of JVM which increases the speed of execution of s Java program. JIT compilers interact with JVM at run time. Instead of interpreting byte code every time a method is invoked, JIT will compile the byte code into the machine code instructions of the running machine and then invoke the object code. This prevents JVM to interpret the same sequence of byte code repeatedly and leads to the increased execution speed.

12) What are the differences between JDK, JRE, and JVM? 

The most popular differences between JDK, JRE, and JVM are tabulated below:

It stands for ‘Java Development Kit’. It stands for ‘Java Runtime Environment’. It stands for ‘Java Virtual Machine’.
It is a software development environment that is used to compile, document, and package Java programs. It includes a runtime environment in which Java bytecode can be executed. It is an abstract machine that provides a runtime environment to execute Java byte code.
It exists physically. It exists physically. It is a runtime instance that is generated when you run a Java class.
It is an imple- mentation of either Standard Edition Java Platform, or Enterprise Edition Java Platform, or Micro Edition Java Platform. It is an imple- mentation of JVM. Its imple- mentation is known as JRE.

13) What gives Java it’s ‘write once and run anywhere’ nature?

The Java programs are not required to write again and again. They need to be written just once, which can be run on several platforms without making any changes in the Java program. Only the Java interpreter is changed depending on the platform.

When a Java program is written and compiled, it creates a ‘.class’ file which consists of byte code instruction understandable to JVM. This class file is system independent. Every system language has its own JVM. So, JVM converts this byte code into machine language which is understandable to that particular system. This is what gives Java ‘write once and run anywhere’ nature. The Java platform is an independent programming language.

14) What is public static void main(String args[]) in Java?

The line public static void main(String[] args) defines a method main. Conceptually, it is similar to the main() function in C/C++.

In Java, the main() is the entry point for any Java program. A Java program can have any number of classes but only one of them must include a method to initiate the execution. The line includes the following terms:

public- The term ‘public’ is an access specifier. It declares the main method as unprotected and therefore making it accessible to all other classes.

static- The term ‘static’ declares the method as one that belongs to the entire class and not a part of any object of the class. The main() should always be declared as ‘static’ because the interpreter uses this method before any object is created.

void- The type modifier 'void' states that the main method does not return any value, it simply prints the statement to the screen. 

main()- It is the method from where the interpreter starts the execution of the program. It is actually the name of the method which is searched by the Java virtual machine as an initial point for an application with a particular signature only.

String args[]- It is the parameter that is passed to the main method.

15) What happens if string args[] is not written in the main() method?

If we write a main() method without String args[], e.g., public static void main(), the code will compile but JVM will not run the code because it will not be able to recognize the main() method as the method from where it should start the execution of the Java program. Remember, JVM always looks for the main( ) method with a string array as a parameter. 

16) What happens if we write static public void instead of the public static void? 

When public static void main(String args[]) is written as the static public void main(String args[]), the program will get compiled and run normally as the order of specifiers do not matter in Java. Similarly, the subscript notation in Java array can also be used after type, before the variable or after the variable. For example:

public static void main(String[] args)  
public static void main(String []args)  
public static void main(String args[])  
Scroll ⇀

17) Explain print() and println() methods with example in Java.

Although both methods are used to display the results on the screen, they are different. The print() method displays the result and retains the cursor in the same line. Besides, the println() method displays the result and then throws the cursor to the next line.

Check out the following program:

class Myclass{
public static void main(String[] args){
System.out.println("Printed from inside of");
Scroll ⇀

Printed from inside of
Here, you can see that the cursor moved to the next after the execution of the first println( ) method. But the cursor remains in the same line after the execution of the print( ) method. This is why the last println() method has given output in the same line.

18) Do we have functions in Java?

We do not have functions in Java. Instead, we have methods. A method is a function that is written within a class. This means that whenever a function is written in Java, it should only be written inside the class.

19) Is Java 100% Object-oriented? Also, give a reason.

Java is not 100% object-oriented because it supports non-primitive data types which are not objects. Concepts like polymorphism, inheritance, abstraction, mainly OOPs concepts make Java an object-oriented language. However, it doesn’t support all the OOPs concepts such as multiple inheritances. 

20) What are the various data types used in Java?

There are eight so-called data types used in Java. The data types are namely known as "byte, short, int, long, float, double, char, and Boolean”. All these data types are called ‘Primitive Data Types’.

• The first four types (byte, short, int, long) hold integers. The four integer types are distinguished by the range of integers they can hold. These are called Integer data types. These data types are used to represent integer numbers without any fractional parts. For example, 123, 63, 225678, etc.

• The float and double data types hold real numbers. Both are distinguished by their range. These are called Float data types. These data types are used to represent numbers with a decimal point. For example, 3.14, 0.023, -123.11, etc.

• A data type ‘char’ holds a single character from the Unicode character set. It is known as the Character data type. For example, a, P, s, *, etc.

• A variable of type ‘boolean’ holds one or two logical values ‘true’ or ‘false’. It is known as the Boolean data type.

The following table shows the size, default value, minimum value, and maximum value for all data types of Java:

Core Java Interview Questions - Data Types in Java

21) What are the types of Java programs?

There are mainly two types of Java programs: (i) Internet Applets, and (ii) StandAlone Applications.

Internet Applets- Internet applets are small programs embedded in web pages and run on different machines in a secure manner by Java-enabled browsers (limited access to system resources). Internet applets cannot run on their own. These can only be run from within the web browser.

StandAlone Applications- Standalone applications are a lot more interesting than Internet applets. These are nothing but a software application that does not require a low-level operating system (OS) or hardware access. This type of Java program includes most common desktop applications such as word processors or spreadsheets, etc. Each standalone application in Java starts with the execution of the main () method. Java standalone applications can run independently on any platform.

22) How is import an efficient mechanism compared to #include?

The #include directive makes the compiler go to the C/C++ standard library and copy the code from the header files into the program. As a result, the program size increases, thus wasting memory and processor time.

The import statement makes the JVM go to the Java library, execute the code there, and substitute the result into the program. Here, no code is copied and no waste of memory or processor time.

This is how import is an efficient mechanism than #include.

23) What are the differences between Java and C++?

The difference between Java and C++ are given in the following table:

C++ Java
C++ is platform dependent language. Java is a platform-independent programming language.
It is possible to write a C++ program without using class. We cannot write a Java program without using at least one class.
Pointers are available in C++. We cannot create and use pointers in Java.
Allocating/ deallocating memory is the responsibility of the programmer. Allocation/ deallocation of memory will be taken care of by JVM.
C++ has a goto statement. Java does not support the goto statement.
Multiple Inheritance feature is available in C++. No multiple Inheritances in Java, but it can be achieved by interfaces in Java.
Operator overloading is available in C++. Operator overloading is not available in Java.
#define, typedef, and header files are available in C++. #define, typedef, and headers files are not available in Java but there are means to achieve them.
C++ supports structures and unions. Java does not support structures and unions.
There are 3 access specifiers in C++, namely private, public, and protected. Java supports 4 access specifiers, namely private, public, protected, and default.

24) What command will be typed on command prompt to compile and run a program stored in a file

To compile-
Scroll ⇀

To run-
java Myprog
Scroll ⇀

25) What is the native code?

The native code is computer programming (code) that is already been compiled to run with a specific processor or hardware platform.

26) What are the different levels of access protection (access modifiers) available in Java?

Access modifiers are the special kinds of keywords basically used to restrict the access of any class, constructor, data member, and method in another class.  There are basically four types of access modifiers in Java:

Private- Private members of a class cannot be accessed anywhere outside the class. They can only be accessed within the class by the methods of that class.

Public- Public members of a class can be accessed everywhere outside the class. Therefore, any other program can read and use them.

Protected- Protected members of a class can be accessed outside the class, but generally within the same directory.

Default- If no access modifier/specifier is written by the programmer, then the Java compiler uses a default access specifier. The 'default' members are accessible outside the class but within the same directory.

Core Java Interview Questions - Access Modifiers in Java

27) What are the popular IDE’s used in Java?

Many IDEs (Integrated Development Environment) are used in Java. These IDEs provide immense help and support in the application development process. A Java IDE is basically a software consisting of various programming tools that allow users to easily write as well as debug Java programs. Although there are many IDEs, Eclipse, IntelliJ IDEA, Codenvy, and NetBeans are widely used and the most popular Java IDEs.

28) Define ‘packages’. What are some advantages of packages?

A package represents a directory or a container that stores related group of classes and interfaces. The functionality of the objects decides how they are grouped.

Example: The statement-

Scroll ⇀

Here, we are importing classes of A ‘java’ is a directory name and ‘io’ is another subdirectory within it. Whereas ‘*’ represents all the classes and interfaces of that ‘io’ subdirectory.

Advantages of Package:

• Packages are useful for organizing related classes and interfaces in a group.
• Packages hide the classes and interfaces into a separate subdirectory so that the accidental deletion of classes and interfaces will not take place.
• Classes and interfaces of one package are isolated from classes and interfaces of another package.

29) How many types of packages are used in Java?

There are two different types of packages used in Java:

(i) Built-in Packages

These are the packages that are already available in Java language. These packages provide all the necessary classes, interfaces, and methods to a programmer to perform any task. Some important packages are:

java.lang: ‘lang’ stands for language. This package got primary classes and interfaces essential for developing a basic program.

java.util: ‘util' stands for utility. This package contains useful classes and interfaces like the stack, LinkedList, Vector, Array, etc. The classes are called collections. ‘io’ stands for ‘input and output’. This package contains streams. A stream represents the flow of data from one place to another.

(ii) User-defined Packages

Just like built-in packages, users can also create their own packages. Such packages are called user-defined packages. To create a package, a keyword ‘package’ is used. 

For example-
package packagename;  //to create package
package packagename.subpackagename;  //to create sub-package in a package
Scroll ⇀

30) What are the different types of memory areas used by JVM? 

The following are the types of memory areas allotted by JVM:

Class (Method) Area: This area contains per-class structures such as runtime constant pool, method data, field, and the code for methods.

Heap: Heap area is the runtime data area where the memory is allotted to the objects.

Stack: The Java stack stores the frame. It stores local variables and partial results. The Java stack participates in method invoke and return. Whenever a thread is created, a private JVM stack is also created for each thread. Each time a method is invoked a new frame is created and it is terminated as soon as the method invocation is finished.

Program Counter Register: Program Counter Register or PC Register stores the address of JVM instructions which are currently being executed.

Native Method Stack: It stores all the native methods that are used in the application.

31) What are the major differences between Heap and Stack Memory?

The following are the major differences between Heap and Stack memory:

Stack Heap
This is used only by one thread of execution. This is used by all the parts of the application.
It cannot be accessed by other threads. Objects saved in the heap memory can be accessed globally.
It follows the rule of LIFO (last-in, first-out) to release memory. Memory management depends on the generation linked with each object.
It remains until the end of thread execution. It exists from the start to the end of the execution of the application.
The stack memory holds only local primitive and reference variables for objects in the heap space. As soon as objects are constructed, they are always placed in the heap space.

32) What is a classloader in Java? Mention some classloaders used in Java.

Java classloader is a subset of JVM (Java Virtual Machine) which is basically used for loading the class file. Typically, it is a program used to load byte code program into memory when we want to access any class. Java has three built-in classloaders:

Bootstrap Classloader: This is the first classloader (superclass of Extension classloader) that loads JDK internal classes, usually rt.jar and other core classes.

Extension ClassLoader: This is known as the child classloader of Bootstrap and parent classloader of System classloader. It loads classes from JDK extensions directory, typically from $JAVA_HOME/jre/lib/ext directory.

System/Application ClassLoader: This is the child classloader of the Extension classloader that loads the class files from the current classpath. The classpath can be changed while invoking a program by using a "-cp” or “-classpath” switch.

We can also create a classloader by extending the ClassLoader class and overriding the loadclass(String name) method.

33) Is using an empty .java name a valid file name for Java program?

Yes, it is a valid file name. Because Java allows us to save Java program with a name ‘.java’, but we are required to compile it using javac .java and run by java classname.

For example:
class Noname{
public static void main(String args[]){  
System.out.println("Hello from TutorialsMate");  
Scroll ⇀

If you save this program by .java only, you have to compile it by javac .java and run it by java Noname.

34) What are the Wrapper classes?

As the name suggests, wrapper classes are used to wrap the primitive data type into an object of that particular class. In simple words, wrapper classes are used to convert Java primitives into the reference types (objects). They are typically the way of object representation of all eight primitive commonly used in Java. In Java, all the wrapper classes are immutable and final.

Note: Since Java 5, primitives are automatically converted into objects. This process is known as auto-boxing.

Java Interview Questions on Collections

35) What is the collection framework in Java?

In Java, a collection framework is basically an architecture consisting of classes and interfaces. It is used to store and manipulate data as objects. It includes many classes like ArrayList, Vector, Stack, HashSet, etc. and interfaces like List, Queue, Set, etc. Using collections, we can perform various functions such as searching, sorting, insertion, deletion, manipulation, etc.

In Java, a collection framework typically includes Interfaces, Classes, and Methods.

36) What is Typecasting?

Typecasting is the process of assigning one data type variable to another data type variable. However, this concept does not apply to Boolean data types. There are basically two types of typecasting:

Implicit: Implicit is the process of storing the value of a small data type in a large data type that is done automatically by the compiler.

Explicit: Explicit is the process of storing the value of a larger data type into a smaller data type.

Java Interview Questions on Array

37) What do you mean by ‘Array’?

An Array represents a collection of elements of the same data types. It can store a group of elements which means that we can store a group of int values or a group of float values or a group of strings in the Array.

In C++ by default, Arrays are created on static memory unless pointers are used to create them. In Java, Arrays are created on dynamic memory which means that the memory is allotted at runtime by JVM. There is no use of static memory in Java. Everything (i.e., variable, array, object, etc.) is created on dynamic memory only.

Typically, Arrays are categorized as:

(i) Single dimensional (or 1D Array)
(ii) Multi-dimensional (or 2D, 3D,…..Arrays)

38) How an Array is different from ArrayList in Java?

The main differences between Array and ArrayList are tabulated below:

Array ArrayList
Size should be defined at the time of the Array declaration. It does not require size as the size is changed dynamically.
It can hold primitive data types as well as objects. It can hold objects, but cannot hold primitive data types.
To add an object into an Array, we are required to specify the index. name[1] = “book” In ArrayList, there is no need to specify the index. name.add(“book”)
An Array is not type parameterized. An ArrayList is parameterized.

39) What is a Vector in Java?

A vector stores elements (objects) similar to ArrayList, but vector is synchronized. It means even if several threads act on the vector object simultaneously, the result will be reliable.

40) What are the differences between ArrayList and Vector?

The main differences between ArrayList and Vector are tabulated below:

ArrayList Vector
ArrayList is fast as it is not synchronized. The vector is slow as it is synchronized. However, it is thread-safe.
ArrayList is not a legacy class. Vector is a legacy class.
If an element is placed into ArrayList, its size increases by 50% of the Array size. In vector, the size is increased by doubling the Array size.
It does not define the increment size. It defines the increment size.
ArrayList only uses Iterator for traversing an ArrayList. Vector uses Enumeration and Iterator for traversing.

41) What are Loops in Java? Explain its types.

In Java, looping allows programmers to execute a statement or a block of statement repeatedly. It typically enables programmers to control the flow of execution by repeatedly performing a set of statements as long as the continuity condition remains true. 

There are three types of loops in Java: namely for, while, and do-while.

For Loops: used to execute statements repeatedly for a specified number of times. 

While Loops: used to execute particular statements repeatedly until a condition is satisfied. The condition is verified before the execution of statements.

Do While Loops: similar to While loop with a single difference that the condition is verified at the end. Therefore, do-while guarantees the execution of the block of statements at least once. 

42) What is an Infinite Loop?

An infinite loop is a set of instructions in Java that loops infinitely when a condition does not satisfy. This type of loop is typically a result of a programming error. An infinite loop will terminate automatically if we close the application or we can use “ctrl + c” to terminate it instantly.

public class InfiniteForLoopDemo
public static void main(String[] arg) {
System.out.println("Hello from TutorialsMate.");
Scroll ⇀

43) What is the main difference between break and continue statement? Explain with examples.

In Java, break and continue are two important statements used with Loops. Let’s understand each:


When a 'break' statement is used inside a loop, the loop is terminated instantly. It can also be used with the 'switch' statement.

Example: In this example, Loop is terminated when the value of integer ‘i’ reaches 5.

public class Breakdemo
public static void main(String[] args)
for (int i=1; i<=10; i++)
if (i==5)
System.out.println("Loop is over as i=5");
Scroll ⇀

Loop is over as i=5


When the 'continue' statement is used inside the loop, the current iteration is skipped and loop jumps to the next iteration. Unlike the 'break' statement, the 'continue' statement does not terminate the loop. A 'continue' statement can only be used with loops, not with 'switch'.

Example: In this example, when the value of ‘i' reaches 5, the loop jumps to the next iteration. Any statement written after ‘continue’ is skipped for the current iteration. 

public class Continuedemo
public static void main(String[] args)
for (int i=1; i<=10; i++)
if (i==5)
Scroll ⇀


Java Interview Questions on String

44) Explain the concept of string in Java?

Generally, a group of characters is called a 'string'. But this is not valid in Java. In Java, a string is an object that represents a sequence of characters. A class java.lang.String is used for creating a string object. An array of characters works similarly to Java strings. 

For example:
char[] ch = {'t','u','t','o','r','i','a','l','s','m','a','t','e'};  
String s = new String(ch);  
Scroll ⇀

is same as:
String s = "tutorialsmate";  
Scroll ⇀

JavaSoft people have created a class separately with the name ‘string’ in java.lang package, with all the necessary methods to work with strings.

45) How strings are created in Java?

There are three common ways used to create a string in Java:

(i) We can create a string by assigning a group of characters to a string type variable-
String s;
s = “tutorialsmate”
Scroll ⇀

The preceding two statements can be combined and can be written as:
String s = “tutorialsmate”;
Scroll ⇀

In this case, JVM creates an object and store the string “tutorialsmate” in that object.

(ii) Another way, a string can be created by using a new operator-
String s = new String(“tutorialsmate”)
Scroll ⇀

(iii) The third way of creating the strings is by converting the character array into strings-
char arr[] = {'t','u','t','o','r','i','a','l','s','m','a','t','e'};  
Scroll ⇀

Now, create a string object by passing the array name like this:
String s = new String(arr);  
Scroll ⇀

In this case, all the characters of the array are copied into the string. If we do not want to copy all the characters of the array into the string, then we can specify the characters that we need as below:
String s = new String(arr, 2, 3);
Scroll ⇀

Now, the characters will be copied from the 2nd character of the array and there will be a total of 3 characters copied into the string s. 

46) Is string a class or data type?

A string is a class in java.lang package. Since classes are also considered as data types in Java. Hence, we can assume string as a data type also. However, a string is not a primitive data type in Java. Instead, it is a class known as 'user-defined' data type. This is because a user can also create a class. 

47) What is the difference between String and StringBuffer?

String class objects are immutable and, therefore, the content cannot be modified. Whereas, the objects in the StringBuffer class are mutable, so they can be modified. In addition, methods that directly manipulate the object's data are not available in the string class. Such methods are available in the StringBuffer class.

Some other immutable classes are byte, char, int, float, double, long, etc.

48) Why Strings are immutable in Java?

The reason why a string is called immutable in Java is that once a string object is created, its state cannot be changed or modified. If we try to change the value of the object, a new string object is created by Java. Typically, the String objects are cached in the String pool. 

For example,
String str = “First Value”
Scroll ⇀

Here, reference str refers to a string object having a value “First Value”.
When a new value is given to it, a new String object gets created and the reference is changed to the new object as:
str = “New Value”
Scroll ⇀

49) What is mean by Java String Pool?

The collection of strings placed in the heap memory is known as the Java String Pool. Whenever a new object is created, it is checked whether an object is already present in the String pool or not. If there is already an object, then the current reference is returned to the variable otherwise a new object is created, and the respective reference is returned.
Core Java Interview Questions - What is Java String Pool

Java Interview Questions on Constructors

50) What are constructors in Java?

In Java, constructor is a special kind of method commonly used to initialize the state of an object. It must have the same name as that of the class where it belongs. Whenever a new object is created, a constructor corresponding to the class gets invoked. The constructor must not include an explicit return type. 

There are basically two types of the constructor: 

Default Constructor: A constructor that does not accept any input is known as the default constructor. In other words, a default constructor is created by default when we do not define any constructor in the class. This type of constructor is mainly used to initialize the instance variables with the default values. In addition, it can also be used for creating objects.

Parameterized Constructor: In Java, a parameterized constructor is referred to as the constructor which can initialize the instance variables with the defined values. In other words, a constructor that cannot take the arguments is known as a parameterized constructor. 

51) What are the differences between constructor and method?

Some important differences between constructor and method are tabulated below:

Constructor Method
It is used to initialize the instance variable of a class. It is used for any general-purpose processing or class.
A constructor’s name and class name must be the same. A method's name and class name can be the same or different.
It is called at the time of creating the object. It can be called after creating the object.
It is called only once per object. It can be called several times on the object.
It is called and executed automatically. It is executed only when we call it.

52) What is mean by constructor chaining?

In Java, we can call a constructor from another constructor with respect to the existing object. However, it is only possible via legacy where a subclass is responsible for invoking the superclass' constructor first. The process is known as 'constructor chaining’. Constructor chains can contain any number of classes. 

There are two ways that can be applied to perform constructor chaining: 

(i) Using this() within the current class
(ii) Using super() from the base class

Other Java Interview Questions

53) What are the differences between Final and Finally?

The main differences between Final and Finally are tabulated below:

Final Finally
Final is used to include restrictions on class methods and variables. It cannot be inherited. A Final method cannot be overridden and the value of the Final variable cannot be changed. 'Finally' is used to hold important code. It will be executed whether an exception is handled or not.
Final is a keyword. Finally is a block.

54) What are the differences between static and non-static methods in Java?

The main differences between static and non-static methods are tabulated below:

Static Method Non-Static Method
It must be used before the method name. It is not used before the method name.
The static method cannot access any non-static instance variable or method. The non-static method can access any static method or variable without creating an instance of the class.
The static method is called using the class (className.methodName). The non-static method is called just like any other general method.

55) Explain the final keyword in Java?

In Java, a 'final' keyword is used as a non-access modifier. In simple words, it is a special keyword that is used to include restrictions on class, methods, and variables. 

A final keyword is used in different contexts as:

final variable: Once we use the final keyword with a variable and assign a value to it, it cannot be changed. A final variable with no assigned value can only be assigned using the class constructor.

final method: Once we declare any method as the final method in Java, it cannot be overridden.

final class: Once we declare a class as final, it cannot be inherited into any of the subclasses. However, it can extend other classes.

56) What is a Map in Java?

In Java, Map is an object which maps unique keys to values. It is typically an interface but not a subset of the main collection interface and this is why it has different functionalities than other collection types. 

Some important characteristics of Map interface are listed below:

It cannot contain duplicate keys.
Each key can map to a maximum one value.

Map uses the “equal()” method to validate whether two keys are similar or different. 
There are four different types of Map in Java, namely HashMap, HashTable, LinkedHashMap, and TreeMap.

57) What is this keyword in Java?

In Java, ‘this’ is a keyword that refers to the current object in a method or constructor. In simple words, ‘this’ keyword is used to prevent the confusion between class attributes and parameters having similar names. All the methods, constructor, instance, variables can be referred by ‘this’. When an object is created for a class, a default reference is also created internally for the object. This default reference is nothing but ‘this’.

For example:
void modify(int x)
Scroll ⇀

Here, the code ‘this.x’ refers to the present class.

58) What is super in Java?

In Java, ‘super’ is a keyword that acts as a reference variable. It typically refers to the immediate parent class object. Whenever the instance of a subclass is created, an instance of the parent class is also created which is referred by a super reference variable. The compiler will implicitly call super() if there is no super() or this() in the class constructor. 

It can be used to refer to the immediate parent class instance variable.
It can be used to invoke the constructor of the immediate parent class.
It can be used to invoke the method of the immediate parent class.

59) What are the differences between this() and super()?

In Java, this() and super() both are the special keywords commonly used to call constructors. However, there are some differences between them which are tabulated below:

this() super()
this() is used to represent the current instance of a class. super() is used to represent the current instance of a parent/base class.
this() is used to access current class methods. super() is used to access base class methods.
this() is used to call the default constructor of the current class. super() is used to call the default constructor of base/parent class.
this() is used to point the current class context. super() is used to point the parent class contexts.
this() is used for differentiating local and instance variables when passed in the class constructor. super() is used for initializing the base class variables within the derived class constructor.

60) Explain the singleton class in Java?

Singleton class in Java is a class whose only one instance can be created at a time in JVM. Therefore, all the methods and variables of the singleton class belong to just one instance. To make any class singleton, we can make its constructor private. The concept of making singleton class is useful for the cases where there is a requirement of objects for a class.

61) What is the difference between equals() and == in Java?

In Java, the equal() method is defined in object class and commonly used to compare two objects defined by business logic. It returns ‘true’ if values are the same.

Besides, an equality operator or “==” is a binary operator and used for checking equality of the references of two objects.

Example: Here, equal() method returns true because the values in both strings (str 1 and str2)  are the same. Whereas, == operator returns false because both strings (str 1 and str2) objects are referencing to different objects. 

public class equalsDemo {
    public static void main(String args[]) {
        String str1 = new String("Hello from TutorialsMate");
        String str2 = new String("Hello from TutorialsMate");
        if (str1.equals(str2))
        { // when condition is true
            System.out.println("str1 & str2 are equal in terms of values.");
        if (str1 == str2) {
            //when condition is true
            System.out.println("str1 & str2 are referencing same object.");
        } else
            // when condition is NOT true
            System.out.println("str1 & str2 are referencing different objects.");
Scroll ⇀

str1 & str2 are equal in terms of values.
str1 & str2 are referencing different objects.

Java Interview Questions on OOPs

62) What is Object-Oriented Programming?

Object-oriented programming (commonly called OOP) is an approach or a programming model where programs are organized around objects rather than logic and functions. In simple terms, it is a programming paradigm that is based on the objects needed to manipulate rather than logic. The approach is particularly useful for programs with large and complex structures and where continuous maintenance and updation is required. 

Some common features of object-oriented programming are:

It follows the bottom-up approach in program design.
It focuses on data with methods to operate upon the object’s data.
It uses concepts like abstraction and encapsulation to hide complexities and display functionalities.
It includes real-time approaches such as inheritance, abstraction, etc.

63) What are the OOPs concepts in Java?

A list of various OOPs concepts is given below:


64) What is Inheritance?

In Java, Inheritance is a concept where the properties of an object of any class are acquired (inherited) by another object of another class. The concept is useful where we need new classes inside the existing class. We can reuse all the methods and fields of the parent (existing) class by inheriting the existing class. Also, we can include new methods and fields in the current class. Inheritance basically builds a relationship between different classes.

Inheritance is performed between parent class (Base class or Super class) and child class (Subclass or Derived class), which is known as the parent-child relationship in Java.

65) What are the different types of inheritance in Java?

There are four types of inheritance in Java:

Single Inheritance: When a single class inherits the properties and behavior of another class, it is known as single inheritance. It is also called single-level inheritance. There will be only one parent class and one child class in a single inheritance.

Multilevel Inheritance: In multilevel inheritance, a class is derived from a class which is also derived from another class. This means that there will be a class that has more than one parent class but at different levels. 

Hierarchical Inheritance: In hierarchical inheritance, there will be two or more child classes but with the same parent class.

Hybrid Inheritance: When there is a combination of two or more types of inheritance, it is known as hybrid inheritance.

66) Why multiple inheritance is not allowed in Java?

When a child class (a single subclass) has two parent classes, it means that a child class inherits properties from multiple classes, this is called multiple inheritance. Java does not support multiple inheritance because during runtime when there are two parent classes with the same method name, it becomes ambiguous and difficult for the compiler to determine which method to execute from the child class.

67) What is encapsulation in Java?

Encapsulation is the concept of object-oriented programming for combining data (variables) and code (methods) into one unit. Data is usually hidden from others, which means that it can only be accessed through current class methods. This is useful for protecting data from unauthorized access. This will prevent any unnecessary modifications or changes.

In Java, encapsulation is achieved using the following techniques:

We can declare the variables of a class as private.
We can provide setter and getter methods to change and view the values of the variables.

68) What is Polymorphism?

A term ‘polymorphism’ is generally referred to as “many forms”, that means “one interface, many implementations”. In simple words, polymorphism is a property of being capable to have various forms in different contexts – specifically, allowing an entity such as method, object, or variable to assume several forms. This mechanism applies only to overriding, not overloading.

There are two types of polymorphisms in Java, namely "compile-time polymorphism" and "run time polymorphism". Run time polymorphism is also known as "dynamic method dispatch".

69) What do you mean by abstraction in Java?

In Java, Abstraction is the process of hiding the implementation details from the user and showing them only the essential things. It hides internal information and enables us to focus only on the concept of what an object can do rather than how it is doing.

There are two ways to achieve abstraction in Java:

Abstract Classes

70) What is the interface in Java?

The interface is a blueprint for a class or we can say that an interface is a collection of the static constants and abstract methods. We can use interfaces to achieve full abstraction and multiple inheritance in Java. Each method in an interface is public and abstract; however, it does not include any constructor. 

A Java interface may contain only a group of the abstract method, not the method bodies. Interfaces cannot be instantiated as abstract classes. We are required to implement them to define their methods.

public interface Animal {
  public void eat();
  public void sleep();
  public void run();
Scroll ⇀

71) What are the differences between abstract class and interface?

Some of the important differences between abstract class and interface are tabulated below:

Abstract Class Interfaces
An abstract class may give complete, default code, and/or just the details required to be overridden. An interface has no ability to give any code, it can just provide a signature.
Here, a class may extend only one abstract class. Here, a class may include several interfaces.
It can contain instance variables. It cannot contain instance variables.
It can include non-abstract methods. All methods of an interface are abstract.
It can include constructors. It cannot contain constructors.
It is fast. It is slow because it uses indirection features to locate the corresponding method in the actual class.

72) What is method overloading?

In Method Overloading, methods of the same class share the same name but each method contains a different number of parameters with different types and orders. There must be a different signature for the methods. Method overloading is basically a concept of adding or extending more to the method's behavior.

Method overloading is referred to as the compile-time polymorphism. It may or may not involve inheritance.

73) What do you understand by method overriding?

In Java, method overriding allows a subclass to provide a specific implementation of a method which has already been offered with its parent class or superclass. In simple terms, the subclass retains the same method, the same name, the same type of parameter, and the same return type as a parent class. Method overriding is a concept of changing the existing behavior of the method.

Method overriding is referred to as run time polymorphism. It is necessary to have an inheritance in method overriding.

74) What are the differences between method overloading and method overriding?

The main differences between method overloading and method overriding are tabulated below:

Method Overloading Method Overriding
When two or more methods are written with the same name but with different signatures, it is called method overloading. When two or more methods are written with the same and same signature, it is called method overriding.
Method overloading happens in the same class. Method overriding happens in super and subclass.
Here, the method return type can be the same or different. Here, method return types should be the same.

75) What do you mean by association? 

Association is the relationship between two objects, where there is no ownership. This means that each object has its separate lifecycle. The relationship can be one to one, one to many, many to one, and many to many.

Example: the relationship between students and a teacher. They can associate with each other in different contexts; however, they both have their own lifecycle. There is no ownership between these two objects. 

76) What is aggregation?

In Java, aggregation can be explained as the relationship between two different classes where the aggregate class consists of a reference to the class it owns. In simple terms, all the objects have their own lifecycle but unlike the association, there is ownership. That means that child object cannot belong to any other parent object.

Example: the relationship between a teacher and the department. A teacher alone cannot belong to several departments, but the department is deleted, the teacher object will not destroy.

77) What is composition? How is it different from aggregation?

The composition is a process of holding the reference of a class within some other class. It is a specialized form of aggregation. It is also known as a death relationship. This is because child objects don't have a lifecycle. This means that if the parent object is deleted, all the associated child objects also get deleted automatically. For example, the relationship between students and the class. A student cannot exist without a class. 

The composition represents a stronger relationship between two objects. Besides, an aggregation represents the week relationship. 

For example:
Aggregation- The bike contains an indicator.
Composition- The bike contains an engine.

78) Define the marker interface.

A Marker interface can be referred to as an interface that has no data member and member functions. In other words, an empty interface is defined as the Marker interface. In Java, the most common examples of the marker interface are Serializable, Cloneable, etc.

The marker interface can be declared as:
public interface Serializable{
Scroll ⇀

79) What do you mean by object cloning in Java?

In Java, object cloning is a process that is used to create an exact copy of an object. That means that the created object will have the same state as the original object. We can use the clone() method of the object class to create a clone of the object. There must be java.lang.Cloneable marker interface to prevent any runtime exceptions. If we don’t implement Cloneable interface, a method clone() will provide CloneNotSupportedException.

Syntax of clone() method:
protected Object clone() throws CloneNotSupportedException
Scroll ⇀

Here, it should be noted that it is a protected method, therefore we are required to override it.

80) Explain constructor overloading in Java?

Constructor overloading in Java is a concept of adding any constructor to a class, but each of them has a separate parameter list. The compiler typically uses several parameters and their types in a list to separate overload constructors.

class Demo
int i;
public Demo(int a)
public Demo(int a, int b)
Scroll ⇀

81) What do you know about copy constructor?

Copy constructor is a member function commonly used to initialize an object using another object of the current class.

In Java, there is no copy constructor. It does not even need a copy constructor concept because objects are passed by reference in Java. That means that we can copy the values from one object to another. Java supports the following ways to copy the values of one object into another:

By constructor
By assigning the values of one object to another.
By using the clone() method of the object class.

Java Interview Questions on JDBC

82) What is JDBC Driver?

The JDBC driver is a software component that allows Java programs to interact with the database. There are four types of JDBC drivers, as listed below:

JDBC-ODBC bridge driver
Native-API driver (partially java driver)
Thin driver (fully java driver)
Network Protocol driver (fully java driver)

Core Java Interview Questions - JDBC Driver Diagram

83) Write down the steps to connect to a database in Java?

The following are the steps used to connect to a database in Java:

Register the driver class.
Create a connection.
Create a statement.
Execute the queries.
Close the connection.

84) Explain the JDBC API components.

The package java.sql includes classes and interfaces for JDBC API.

Classes: Driver Manager, Blob, Clob, SQLException, and Types, etc.

Interfaces: Connection, Statement, PreparedStatement, ResultSet, ResultSetMetaData, DatabaseMetaData and CallableStatement etc.

85) What do you mean by the JDBC connection interface?

The connection interface is responsible for maintaining a session with the database. It can also be used for transaction management. It offers factory methods that return instances of Statement, CallableStatement, PreparedStatement, and DatabaseMetaData.

Core Java Interview Questions - JDBC Connection Interface

86) What is batch processing in JDBC?

Batch processing is the process of grouping all related SQL statements into one batch so that they can be executed simultaneously rather than executed separately. Using this concept in JDBC, we can execute multiple queries simultaneously which will result in increased performance.

87) What are the JDBC statements?

JDBC statements are used to transmit SQL commands to the database and received the data back from it. JDBC offers different methods such as execute(), executeQuery, executeUpdate(), etc. to interact with the database.

JDBC provides three types of statements, namely Statement, PreparedStatement, and CallableStatement.

Statement: These types of statements are used to get access to the database for general purposes, and execute a static SQL query at run-time.

PreparedStatement: These are used to assign input parameters to the query in between execution.

CallableStatement: These are used to access the database stored procedures and help in accepting runtime parameters.

Java Interview Questions on Spring

88) What is Spring?

Spring is an application framework that is used for the development of enterprise applications in Java. It is a light-weight, loosely coupled, integrated, and widely used Java EE framework.

The core components of the Spring framework are “Dependency Injection” and “Aspect Oriented Programming”. The core features can be used in any Java application. It also provides extensions that can be used to develop web applications on top of the Java EE platform.

89) Mention some important modules of the Spring framework.

Some of the important Spring Framework modules are listed below:

• Spring Context: It is used for dependency injection.
• Spring AOP: It is used for aspect-oriented programming.
• Spring JDBC: It is used for JDBC and DataSource support.
• Spring ORM: It is used for ORM tools support such as Hibernate.
• Spring Web Module: It is used for creating web applications.
• Spring DAO: It is used for database operations using the DAO pattern.
• Spring MVC: It is also known as Model-View-Controller implementation. It is used for creating web applications, web services, etc.

90) What is Spring bean? Name the different Scopes of Spring bean.

Beans are the objects that are managed by the Spring IoC container. They are referred to as the backbone of Java application. In simple terms, a bean or a spring bean is an object that is instantiated, assembled, or managed by a Spring IoC container.

The different scopes of spring bean are Singleton, Prototype, Request, Session, and Global-session.

91) Explain autowiring in Spring. Name the autowiring modes.

The process of injecting the bean is known as wiring. Autowiring is the concept in the spring framework that allows us to inject the bean automatically. Therefore, we are not required to write explicit injection logic. However, it is considered as a best practice if we perform the explicit wiring of all the bean dependencies.

There are four types of autowiring modes in Spring framework:

autowiring by @Autowired and @Qualifier annotations.
autowiring byName
autowiring byType
autowiring by constructor

92) What are some important Spring annotations?

Some of the important Spring annotations are:

@Controller: It is used for controller classes in the Spring MVC project.
@RequestMapping: It is used for the configuration of URI mapping in controller handler methods. This is one of the most important annotations.
@ResponseBody: It is used for sending Objects as a response, usually for sending XML or JSON data as a response.
@PathVariable: It is used for mapping dynamic values from the URI to handler method arguments.
@Autowired: It is used for autowiring dependencies in spring beans.
@Qualifier: It is used with @Autowired annotation to avoid confusion when multiple instances of bean type are present.
@Service: It is used for service classes.
@Scope: It is used for configuring the scope of the spring bean.
@Configuration, @ComponentScan, and @Bean: They are used for java based configurations.
AspectJ annotations for configuring aspects and advice, @Aspect, @Before, @After, @Around, @Pointcut, etc.

93) What are the different types of transaction management supported in Spring?

There are two types of transaction management supported in Spring framework:

Programmatic Transaction Management: A transaction is managed with the help of programming with extreme flexibility. However, it is very difficult to manage.

Declarative Transaction Management: Here, a transaction is detached from the business code. And, then it is managed only by annotations or configurations based on XML.

Java Interview Questions on Hibernate

94) What is the Hibernate framework?

Hibernate is a lightweight and an open-source ORM (Object-Relational Mapping) tool commonly used to store, manipulate, and receive data from the database. It actually provides a framework that we can use to map application domain objects to the relational database tables and vice versa.

Hibernate provides a reference implementation of the Java Persistence API, making it a great choice as an ORM tool with the benefits of loose coupling. In addition, Hibernate Persistence API can also be used for CRUD operations. The Hibernate Framework gives us an option to map plain old Java objects to traditional database tables with the use of JPA annotations as well as XML configurations.

Likewise, Hibernate configurations are flexible and can be done programmatically in an XML configuration file as well.

95) Draw a structural view of Hibernate architecture.

The following diagram shows a structural view of Hibernate architecture:

Core Java Interview Questions - Hibernate Architecture

96) What are the advantages of using the Hibernate framework over JDBC?

Few most important advantages of using hibernate framework over JDBC are:

Hibernate helps in the removal of lots of boiler-plate code that are attached with JDBC API, which makes code clean and easy to read.
• Hibernate has features like inheritance, associations, and collections, etc., which are unavailable with JDBC API.
Hibernate query language (also called HQL) is more friendly with Java as it is more object-oriented. Besides, we are required to write native SQL queries in JDBC.
Hibernate offers caching which provides increased performance, whereas JDBC queries are not catchable.
Hibernate has options by which we can create database tables, while in JDBC, tables must exist in the database.

Java Interview Questions on JSP

97) Explain life-cycle methods for a JSP.

The following are the methods of JSP lifecycle:

jspInit(): This method is invoked only once, which is almost similar to the init method of the servlet.

_jspService(): This method is invoked at each request, which is similar to the service() method of the servlet.

jspDestroy: This method is also invoked only once. This is similar to the destroy() method of the servlet.

98) What is jspDestroy() method?

The jspDestroy() method is invoked from javax.servlet.jsp.JspPage interface whenever a JSP page is going to be destroyed. Servlets destroy method can be overridden to perform a cleanup, such as when closing a connection for a database.

99) What is servlet?

In Java, a servlet is a technology that works on the server-side. The servlet provides support for dynamic response and data persistence that helps increase the capacity of the webserver. We can also write custom servlets using the interfaces and classes of the javax.servlet and javax.servlet.http packages.

100) How to disable session in JSP?

To disable a session in JSP, we can use:

<%@ page session=“false” %>
Scroll ⇀

101) Do we need to configure JSP standard tags in web.xml?

No, we are not required to configure JSP standard tags in web.xml. This is because whenever a container loads the web application and retrieves TLD files, it automatically arranges those files. Therefore, these files are already configured and can be used with JSP pages application. We are only required to include the files on the JSP page using the taglib directive.

Java Interview Questions on Exceptions

102) How will you differentiate an error from exception?

An error is referred to as a condition that occurs at runtime and cannot be recovered or fixed. This means that these JVM errors cannot be repaired during the runtime. Although the error can be caught in the catch block, the execution of the application will stop and is not recoverable. An example of such error is OutOfMemory error. This error is the subclass of java.lang.Error and it typically occurs when JVM runs out of memory.

Besides, exceptions are the conditions that generally occur when a user provides wrong inputs during the execution. Generally, these types of issues are recovered during the runtime. For example FileNotFoundException, it occurs when there is no file in a user-specified path. It can be recovered by giving on-screen feedback which tells the user to enter a proper value or a path.

103) What are the differences between Checked and Unchecked Exception?

Some of the important differences between checked and unchecked exception are tabulated below:

Checked Exception Unchecked Exception
Checked exceptions are the classes that are used to extend Throwable class except for RuntimeException or Error. Unchecked exceptions are the classes that are used to extend RuntimeException.
These are checked during the compile-time. These are not checked during the compile-time.
Example: IOException, SQLException, etc. Example: ArithmeticException, NullPointerException, etc.

104) Explain the exception hierarchy in Java.

Exception Hierarchy: All exception classes are referred to as the subtypes of the java.lang.Exception class. The exception class is actually a subclass of the Throwable class. In simple terms, Throwable is a parent class of all the Exception classes.

Other than execution class, there is another subclass known as an ‘error’ which is derived from Throwable class. The exception class is divided into two main subclasses: IOException class and RuntimeException class. Both of these exceptions extend exception class whereas errors are further sub-divided into Virtual Machine error and Assertion error.

Core Java Interview Questions - Exception Hierarchy in Java

105) How can you create a custom Exception? 

To create a custom exception, we can extend the Exception class or any of its subclasses.

class New1Exception extends Exception { }               // creates Checked Exception
class NewException extends IOException { }             // creates Checked exception
class NewException extends NullPonterExcpetion { }  // creates UnChecked exception
Scroll ⇀

106) What is synchronization?

Synchronization is a concept of allowing only one thread to access a block of code at a time. Because Java provides the option to execute multiple threads, two or more threads may access the same fields or objects. But if multiple threads access the block of code, then there is a possibility of getting inaccurate results at the end. Therefore, synchronization is used to manage all the concurrent threads and keep them in execution to be in sync.

Synchronization prevents memory consistency errors that may have occurred because of the inconsistent view of shared memory. When a method is synchronized, the thread holds the monitor of that particular method’s object. If another thread is executing the synchronized method, the thread is blocked until the monitor is released by that thread.

Core Java Interview Questions - What is synchronization

107) What are the differences between throw and throws?

The main differences between throw and throws keywords are tabulated below:

Throw keyword Throws keyword
This keyword is used to explicitly throw an exception. This keyword is used to declare an exception.
We cannot throw multiple exceptions. We can declare multiple exceptions.
Checked exceptions cannot be propagated with throw only. Checked exceptions can be propagated with throws.
Throw keyword is followed by an instance. Throws keyword is followed by class.
Throw keyword is used within the method. Throws keyword is used with the method signature.

Java Interview Questions on Threads

108) What is a thread? 

In Java, a thread is the smallest part of the statements in the program that is executed independently by a scheduler. It actually represents a separated path of execution of a group of instructions. Whenever we write a program, the statements of the program are executed one by one by JVM. This flow of execution is called a thread. This means that there will always be at least one thread in every Java program, which is called the main thread.

The main thread is created by the JVM as soon as the execution of the program is started. The main thread is basically used to invoke the main() of the program. We can also create custom threads in Java. Threads are executed concurrently.

109) What are the differences between a process and a thread? 

The main differences between a process and a thread are tabulated below:

Process Thread
A process runs in separate virtual memory space. Two processes can run at the same time without overlapping each other. Threads are entities within a process. All threads of a process share the virtual address space and system resources of the current process; however, they use their own created stack.
Each process consists of its own data segment. All threads created by the process are allowed to use the same data segment.
Processes use techniques such as inter-process communication to interact with other processes. Threads are not allowed to have separate address space and therefore they directly communicate with other threads of the existing process.
The process is managed by an operating system (OS). Threads are managed by programmers in a program.
Processes are independent. Threads are dependent.

110) What are the two ways used to create a thread in Java? 

There are two ways commonly used to create a thread in Java:

• By implementing the Runnable interface.
• By extending the Thread.

What others reading:

Weekly Hits

Latest Tutorial

© 2024 TutorialsMate. Designed by TutorialsMate