Most Frequently Asked Java Interview Questions
- What is Java, and how is it platform-independent?
- What is JDK, JRE and JVM in Java?
- What are Instance, Local, and Class Variables in Java?
- Is Java a pure object-oriented programming language?
- Explain the memory areas of JVM in Java?
- What is a JIT compiler?
- What is the difference between Java and C++?
- Why Java doesn’t support pointers like C++?
- Explain the data types of Java.
- What is the default value of byte, float, double, and char data type in Java?
Basic Java Interview Questions for Freshers
1. What is Java?
Java is a high-level object-oriented programming language developed by Sun Microsystems. Java has some unique features, making it popular among developers. Features like platform independence, automatic memory and pointer management, object-oriented design, multithreading, and other features have made it extremely popular among developers and software companies.
2. Why is Java platform independent?
It is platform independent because java has the ability to run the same code on any operating system without modification. It compiles the java code (.java files) into an intermediate form called bytecode(.class file). The bytecode is not specific to any hardware or OS, it can run on any machine.
The bytecode is then processed by a component called JVM, which translates the bytecode into machine specific instructions at run time. JVM has to be installed separately for different OS(Mac, Linux and Windows).
3. What is JDK, JRE and JVM in Java?
JDK |
JRE |
JVM |
- It includes the full suite of tools required for developing Java applications.
- Includes JRE, JVM, java compiler, java debugger and javadoc.
|
- It is a software layer that provides the necessary environment to run java programs.
- It consists of the JVM, java libraries like .util and .lang, and runtime tools like java collector.
|
- JVM converts Java Code into Bytecode.
- It is platform dependent i.e it has different version of Mac, Linux and Windows.
|
4. What are Instance, Local, and Class Variables in Java?
Instance variables are declared inside the class but outside the methods. So basically these are accessible by all the methods of that class. The default value for numeric types is 0, for boolean false and null for object references.
Example:
class Sample {
// Instance Variables
public String s1;
public int m1;
// main method
public static void main(String[] args) {
// Creating an instance of the Sample class
Sample obj = new Sample();
// Initializing instance variables
obj.s1 = "Intellipaat";
obj.m1 = 100;
// Displaying the values of instance variables
System.out.println("The value of s1 is: " + obj.s1);
System.out.println("The value of m1 is: " + obj.m1);
// Modifying instance variables
obj.s1 = "Updated Intellipaat";
obj.m1 = 200;
// Displaying updated values
System.out.println("The updated value of s1 is: " + obj.s1);
System.out.println("The updated value of m1 is: " + obj.m1);
}
}
Output:
The value of s1 is: Intellipaat
The value of m1 is: 100
The updated value of s1 is: Updated Intellipaat
The updated value of m1 is: 200
Local variables’s scope is limited to the function, constructor, or block of code, so no other function can access those variables. These variables don’t have any default value.
Example:
class Sample {
// main method
public static void main(String[] args) {
// local variable
int m1 = 50;
// Displaying the value of the local variable
System.out.println("The value of m1 is: " + m1);
// Perform some operations on m1
m1 = m1 + 25; // Add 25 to m1
System.out.println("The updated value of m1 is: " + m1);
// Further operation
m1 = m1 * 2; // Multiply m1 by 2
System.out.println("The value of m1 after multiplying by 2 is: " + m1);
}
}
Output:
The value of m1 is: 50
The updated value of m1 is: 75
The value of m1 after multiplying by 2 is: 150
Class variables are also known as static variables in Java, defined in a class using static keywords. These variables are stored in static memory and can be called in a program using the class name. The default values are the same as the instance variables.
Example:
class Sample {
// Static or class variable
public static String s1 = "Intellipaat";
public static void main(String[] args) {
// Accessing and printing the static variable
System.out.println("The value of s1 is: " + s1);
// You can also modify the static variable if needed
s1 = "Updated Intellipaat";
System.out.println("The updated value of s1 is: " + s1);
}
}
Output:
The value of s1 is: Intellipaat
The updated value of s1 is: Updated Intellipaat
The main difference between Instance variables and Class Variables is that the instance variables belong to only a specified class in which they are declared. While the class variables belong to classes and subclasses.
5. Is Java a pure object-oriented programming language?
No, Java is not a pure object-oriented programming language because it provides primitive data types like char, boolean, int, short, long, double etc. and also supports the concepts of static methods and variables, which can be directly accessed with class name. So there is no need of an objects toaccess some specific entity Java that’s why Java is not a pure object-oriented programming language.
6. Explain the memory areas of JVM in Java?
- Class Memory Area – This is also known as the method area that stores the class-level data such as method data, variable code, runtime constant pool, constructor, etc.
- Heap Memory Area – It is used to assign the memory to objects. So basically, it is responsible for object creation and storage. After java, static methods and variables are stored in the Heap area, not the Class Area.
- Stack Area – A JVM stack area is used to store the partial data or partial results. Programs generally use this data for dynamic linking and returning value for the method.
- Program Counter Register Area – This is used to store the address of the following JVM instructions that need to be executed further.
- Native Method Stack – It is used to store the native methods and get allocated to a created thread that might be dynamic. These native methods are not written in Java programming language and never compiled to bytecode.
7. What is a JIT compiler?
JIT stands for Just-In-Time compiler in Java. It is a part of JVM that converts the bytecode into machine code for better performance of Java applications during execution.
As you know, that bytecode takes more time to execute than the machine code. So when JVM executes the bytecode it maintains a record of a function execution. In simpler terms, you can consider a Java application with so many functions, and it might be possible that some functions are repetitively used in a large Java application. If JVM executes the bytecode every time, it will create a worse effect on performance. So here, our hero JIT compiler takes an entry. It converts that bytecode into machine code that can be directly executed by hardware rather than interpreting that bytecode line by line.
So basically, JVM gives a signal for the entry of the JIT compiler, and JIT converts that red flag bytecode (provided by JVM) into machine code for better performance.
8. What is the difference between Java and C++?
- Memory Management – C++ provides more control over memory allocation and deallocation using pointers concepts. But Java doesn’t give the idea of pointers.
- Platform – Java is platform-independent, supporting the Write Once and Run Anywhere concept. While C++ is platform-dependent.
- Compiled/Interpreted – Java is compiled and interpreted while C++ is only compiled language.
- Multiple Inheritance – C++ supports various inheritance while Java language does not support this due to ambiguity problems.
- Root Hierarchy – Java programming language has a single root hierarchy due to Java. Lang. object class but C++ is not a single root hierarchy language.
9. Why Java doesn’t support pointers like C++?
Java doesn’t support the pointers concept due to safety, performance and multiple complication issues. As you know, you can directly access the memory address using the pointers in C++.
Comparing Java to C++ in terms of object-oriented programming, then Java wins here and obviously, pointers generally breach the abstraction concept of the programming language at a developer level. So to boost the performance and overall abstraction, Java provides the garbage collection and reference features which are automated.
10. Explain the data types of Java.
In Java, we have 2 types of data types i.e.
- Primitive or Pre-Defined Data Types
- Non-Primitive or Object Data Types
Primitive Data Types – Numeric data like integers and floating points are considered as primitive data types.
Example – byte, short, int, long, float, double, boolean, and char.
Non-Primitive or Object Data Types – These are generally reference types as they store the address of the variable’s values, not the variable’s value.
Example – String, Array, Objects, etc.
11. What is the default value of byte, float, double, and char data type in Java?
Here are the default value of the data types:
- Byte: 0
- Float: 0.0f
- Double: 0.0d
- Char: ‘\u0000’
12. What is the difference between Java, Python, and C++?
Here’s a comparison table highlighting the key differences between Java, Python, and C++:
Java |
Python |
C++ |
Verbose, requires semicolons |
Concise, indentation-based |
Complex requires semicolons |
Statically typed |
Dynamically typed |
Statically typed |
Moderate, managed by JVM |
Generally slower than Java |
High performance, compiled code |
Automatic garbage collection |
Automatic garbage collection |
Manual memory management |
Rich standard libraries |
Extensive libraries (e.g., NumPy, pandas) |
Standard Template Library (STL) |
Built-in support with threads |
GIL limits thread performance |
Powerful threading capabilities |
Large, strong enterprise focus |
Rapidly growing, diverse |
Established, strong in systems |
13. Explain the difference between StringBuffer and StringBuilder in Java programming.
StringBuffer |
StringBuilder |
StringBuffer methods are synchronized. |
StringBuilder is non-synchronized. |
StringBuffer is thread-safe. |
StringBuilder is not thread-safe. |
The performance is very slow. |
The performance is very fast. |
14. Define inheritance.
Inheritance is an object-oriented programming concept that allows one class to inherit the properties and methods from another class. Inheritance promotes the reusability of the code and establishes the hierarchy between the classes. The class from where we are deriving or inheriting the properties or methods is called a superclass and the class from where we are deriving is known as a subclass.
For instance, we have a class named car that includes attributes like number of tiers, mileage, and so on. Let’s now consider another class, car, which will also possess all of the vehicle’s properties. In this case, the car is a subclass that inherits the parent class’s properties, while the vehicle is a superclass.
15. Explain method overloading.
When a Java program contains more than one method with the same name but with different properties, then it is called method overloading.
Example
class Display {
// Method to display an integer
void show(int a) {
System.out.println("Integer: " + a);
}
// Method to display a string
void show(String b) {
System.out.println("String: " + b);
}
public static void main(String[] args) {
Display display = new Display();
// Calling overloaded methods
display.show(10); // Calls show(int a)
display.show("Intellipaat"); // Calls show(String b)
}
}
Here when we call the function based on the argument passed, the method will be called, so if we pass 10, it will call the method that prints integer, and if we pass a string, it will call a method that prints a string.
Watch this Java Interview Questions video:
16. Compare overloading with overriding.
Overloading refers to the case of having two methods of the same name but different properties; whereas, overriding occurs when there are two methods of the same name and properties, but one is in the child class and the other is in the parent class.
17. Explain the creation of a thread-safe singleton in Java using double-checked locking.
Singleton is created with the double-checked locking as before Java 5 acts as a broker and it’s been possible to have multiple instances of singleton when multiple threads create an instance of the singleton at the same time. Java 5 made it easy to create thread-safe singleton using Enum. Using a volatile variable is necessary for the same.
18. Differentiate between an ArrayList and a Vector.
ArrayList |
Vector |
An ArrayList is not synchronized. |
A vector is synchronized. |
An ArrayList is fast. |
A vector is slow as it is thread-safe. |
If an element is inserted into an ArrayList, it increases its array size by 50 percent. |
A vector defaults to doubling the size of its array. |
An ArrayList does not define the increment size. |
A vector defines the increment size. |
An ArrayList uses an Iterator for traversing. |
Except for the hashtable, a vector is the only other class using Enumeration and Iterator. |
19. Mention the difference between Iterator and Enumeration.
Iterator |
Enumeration |
Iterator is an interface found in the java.util package. |
Enumeration is a special data type that allows you to define a fixed set of constants. |
Uses three methods to interface:
- hasNext()
- next()
- remove()
|
Uses two methods:
- hasMoreElements()
- nextElement()
|
Iterator method names have been improved. |
The traversing of elements can only be done once per creation. |
20. Explain the difference between the inner class and the subclass.
Inner Class |
Subclass |
An inner class is a class that is defined within another class. |
A subclass is a class that inherits properties from another class called the superclass. |
It provides access rights for the class, which is nesting it, which can access all variables and methods defined in the outer class. |
It provides access to all public and protected methods and fields of its superclass. |
21. Can we execute any code, even before the main method? Explain.
Yes, we can execute any code, even before the main method. We can use a static block of code in the class when creating the objects at the load time of the class. Any statements within this static block of code will get executed at once while loading the class, even before the creation of objects in the main method.
Example
class Intellipaat {
// Static block
static {
System.out.println("Static block executed!");
}
public static void main(String[] args) {
System.out.println("Main method executed!");
}
}
Output
Static block executed!
Main method executed!
A static block runs when the class is loaded before any objects are created or the main method is invoked.
22. How can we restrict inheritance for a class?
We can restrict the class from getting inherited by using the following way:
- By using the final keyword
- If we make all methods final, then we cannot override it.
- By using private constructors
23. Java doesn’t support multiple inheritance. Why?
Java doesn’t support multiple inheritance because we cannot use different methods in one class; it creates ambiguity.
Example:
interface Intellipaat1 {
default void test() {
System.out.println("test() method from Intellipaat1");
}
}
interface Intellipaat2 {
default void test() {
System.out.println("test() method from Intellipaat2");
}
}
// Implementing multiple interfaces
class C implements Intellipaat1, Intellipaat2 {
// Resolving ambiguity
@Override
public void test() {
Intellipaat1.super.test(); // Call test from Intellipaat1
Intellipaat2.super.test(); // Call test from Intellipaat2
System.out.println("test() method from class C");
}
}
class Main {
public static void main(String[] args) {
C obj = new C();
obj.test();
}
}
Output:
test() method from Intellipaat1
test() method from Intellipaat2
test() method from class C
Intellipaat1 and Intellipaat2 test() methods are inheriting to class C. So, which test() method class C will take?
As Intellipaat1 and Intellipaat2 class test () methods are different, here we would face ambiguity.
24. Are constructors inherited? Can a subclass call the parent’s class constructor?
We cannot inherit a constructor in Java, However, a subclass can call the parent constructor using the super keyword. We do this to initialise inherited fields in the parents class by creating an instance of a subclass. By calling the parent constructor, we ensure that the parent class is initialised correctly.
25. Define JSON.
JSON stands for ‘JavaScript Object Notation.’ It is a much lighter and more readable alternative to XML. It is independent and primarily used for client-server and server-server communication.
26. What are the advantages of JSON over XML?
The advantages of JSON over XML are:
- JSON is lighter and faster than XML.
- It is easy to understand.
- It is easy to parse and convert to objects.
- JSON supports multiple data types—string, number, array, or Boolean—but XML only accepts strings.
27. Outline the major Java features.
The significant features of Java programming language are:
- Platform Independent: Java provides a “write once run anywhere” feature. This means you can write Java code once and can use the same code in any operating system. This is possible because the Javacode is converted to bytecode, which can be run on any system which has JDK installed.
- Object Oriented: Java follows the concept of object-oriented programming, which allows us to reuse the code through principles like inheritance. Encapsulation and polymorphism.
- Automatic Memory Management: Java offers built-in garbage collection, which helps you manage the memory efficiently by preventing memory leaks.
- Multithreading: Java supports multithreading, allowing concurrent execution of multiple threads.
- Security: Java provides a secure environment with features like the Java security manager.
Get 100% Hike!
Master Most in Demand Skills Now!
28. What do you mean by an object?
An object consists of methods and classes that depict its state and perform operations. Objects are the instances of a class that are created to use the attributes and methods of a parent class.
29. What is a Classloader?
It is a part of the Java Runtime Environment which is used to dynamically load the class files into the Java Virtual Machine(JVM). The classloader triggers whenever a Java file is executed.
There are three types of classloaders in Java:
- Bootstrap Classloader: The bootstrap loader is the superclass of extension classloader, which loads the standard JDK files from rt.jar and other core classes. The rt.jar file contains all the package classes of java.net, java.lang, java.util, java.io, java.sql, etc.
- Extension Classloader: The extension classloader is known as the parent of the System classloaders and the child of the Bootstrap classloader. It only loads the files available in the extension classpath, which includes ‘dirs/JRE/lib/ext directory. If the file is unavailable in the mentioned directory, the extension classloader will delegate it to the System classloader.
- System/Application Classloader: It loads the classes of application type available in the environment variable such as -classpath, or -cp command-line option. The application classloader generates a ClassNotFoundException if the class is unavailable in the application classpath.
30. How does the == operator function in Java?
Java uses the == operator to compare the reference equality of two objects, which means that it determines if the two objects refer to the same memory location or not.
31. What is the purpose of static in Java? Mention an example.
The static keyword in Java is intended to indicate that a certain variable or method belongs to the class and not its instances. For this reason, even without instantiating an object of the class, such a variable or method can be accessed.
class MathUtils {
public static int add(int a, int b) {
return a + b;
}
public static double square(double num) {
return num * num;
}
public static void main(String[] args){
System.out.println(""+square(2));
}
}
Output: 4.0
32. What is a try-catch in Java?
A try-catch block in Java is used to implement exceptional handling. The code that may throw exceptions has to be written inside the try block, and if any exception occurs, catch it and work on it in the corresponding catch block.
33. Differentiate between checked and unchecked.
The compiler checks checked exceptions at compile time, meaning that programmers have to handle such exceptions with try-catch blocks or declare them using the method signature. Unlike checked exceptions, unchecked exceptions are not checked at compile-time, hence they do not require explicit handling by a programmer.
34. What is the meaning of ‘final’ in Java? Give example
Java uses the final keyword to declare constants, prevent method overriding, and create immutable classes. For example, final int MAX_SIZE = 100; declares a constant MAX_SIZE whose value is 100.
35. Is multithreading part of Java?
Yes, multithreading is part of Java. It provides built-in support for creating and managing threads, thereby enabling multiple tasks to be executed concurrently within one program.
36. What is the purpose of the ‘super’ keyword in Java?
Super is used in the Java programming language to refer to the superclass of an object being manipulated. It can also be used as a bridge between superclass methods/constructors and subclass methods/constructors. For instance, super.methodName() invokes the method defined by the superclass.
37. What is an abstraction in Java? Give an example.
Java Abstraction refers to encapsulating only the function ability and behavior of methods while not exposing their implementation details to the user. The object design used here focuses on what an object does rather than on how it performs that function. For instance, the List interface in Java is an example of abstraction because it describes general operations for lists without defining how they are implemented by specific list classes such as LinkedList and ArrayList.
Java Developer Interview Questions for Experienced
38. Is an empty .java file name a valid source file name in java?
Yes, we can save a java file with an empty .java file name. You can compile it in the command prompt by ‘javac .java’ and run it by typing ‘java classname’. Here is an example of such a program:
import java.util.*;
class A
{
public static void main(String args[])
{
System.out.println("Hello World");
}
}
Output: Hello World
Once the code has been saved, you need to launch the command prompt and navigate to the file’s directory. After that, you need to write “javac .java” to compile the program and “java A” to execute it.
39. What is the difference between Object-oriented and object-based programming language?
Following are the key differences between the object-oriented and object-based programming languages:
Object-oriented programming language |
Object-based programming language |
Object-oriented programming languages support all the features of OOPS, including polymorphism and inheritance |
Object-based programming language does not support inheritance or polymorphism |
Doesn’t support built-in objects |
Support built-in objects like JavaScript has the window object |
Example: C#, C++, Java, Python, etc. |
JavaScript and Visual Basic are examples of object-based programming language |
40. Why is the main method static in Java?
The main method is static in Java because to call the static methods, there is no need for the object. The Java Virtual Machine(JVM) has to create an object to call the non-static main() method, which will result in extra memory allocation to avoid that we craete a main method with static keyword.
41. Can we declare the static variables and methods in an abstract class?
Yes, we can declare the static variables and methods in an abstract class by inheriting the abstract class. In java, the static variables and methods can be accessed without creating an object. You can simply extend the abstract class and use the static context as mentioned below:
// Parent class A
class A {
static int x = 110; // Static variable
// Static method
static void method1() {
System.out.println("Class A static function called");
}
}
// Child class prog1 inheriting from A
class prog1 extends A {
public static void main(String[] args) {
// Accessing the static method and variable of class A
A.method1();
System.out.println("Value of x = " + A.x);
}
}
The output of the above program will be:
Class A static function called
Value of x=110
42. What is Aggregation?
Aggregation in Java represents a relationship where one class contains the reference of another class. In other words, it refers to a one-way relationship between two classes where the aggregate class has the instance of another class it owns.
For example, in the program below the aggregate class student have a one-way relationship with the class Address. Here each student having an address makes sense, but address having the student doesn’t make any sense. So, instead of inheritance, the aggregation is based on the usage of the classes.
import java.util.*;
class Address
{
String street, city, state, country;
public Address(String street, String city, String state, String country)
{
this.street=street;
this.city=city;
this.state=state;
this.country=country;
}
}
class student
{
int reg_no;
String name;
Address address;
public student(int id,String name,Address address)
{
this.reg_no=id;
this.name=name;
this.address=address;
}
public void display()
{
System.out.println("Student details: ");
System.out.println("Name: "+name);
System.out.println("Reg_no: "+reg_no);
System.out.println("Address: "+address.street+", "+address.city+", "+address.state+", "+address.country);
}
public static void main(String args[])
{
Address address1=new Address("Paper Mill Road","SRE","UP","India");
Address address2=new Address("Service Road","BNG","KA","India");
student ob1=new student(111,"Sam",address1);
student ob2=new student(112,"Alex",address2);
ob1.display();
ob2.display();
}
}
The output of the above program will be:
Student details:
Name: Sam
Reg_no: 111
Address: Paper Mill Road, SRE, UP, India
Student details:
Name: Alex
Reg_no: 112
Address: Service Road, BNG, KA, India
43. What is composition?
Composition refers to a relationship between two objects. If an object contains another object and the contained object can’t exist without the existence of that particular object, then it’s known as the composition.
In simple words, the composition is a kind of aggregation used to describe the reference between two classes using the reference variable.
For example, a class student contains another class named address. So, if the class address cannot exist without the class student, then there exists a composition between them.
44. Can we overload the main method in Java?
Yes, you can overload the main() method in Java using the concept of method overloading.
Below is an example of main() method overloading:
import java.util.*;
class main_overloading
{
public static void main(String args)
{
System.out.println("Main with String");
}
public static void main(String args[])
{
System.out.println("Main with the String args[]");
}
public static void main()
{
System.out.println("main without String");
}
}
The output of the above code will be:
Main with the String args[]
This happens because the JVM only reconize the main method with (String args[]). If you need to call other overloaded main methods you have to call them explicitly.
Here the code if you want to do so,
import java.util.*;
class MainOverloading {
public static void main(String[] args) {
System.out.println("Main with the String args[]");
// Explicitly calling other overloaded main methods
main("Single String");
main();
}
public static void main(String args) {
System.out.println("Main with String");
}
public static void main() {
System.out.println("Main without String");
}
}
Output :
Main with the String args[]
Main with String
Main without String
45. Explain public static void main(String argos[]) in Java?
The main() method is the entry point for any java program. In the expression public static void main(String argos[]), each keyword has significance as mentioned below:
- Public: It’s an access specifier which is used to specify the accessibility of a method in java. Here, Public means anyone can access the method or the class.
- static: the static keyword in java identifies the main method as class-based, which means it can be accessed without creating an object/instance. Static methods can b3e directly called by the Java Virtual Machine(JVM), which in turn saves extra memory allocation.
- void: void is a return type in java, which means the main method will not return any value back.
- String args[]: String argos[] or String[] args is an array of String objects which stores the command line arguments. Here the argument is of array type. Therefore, it’s passed as the parameter in the main() method.
46. What is the difference between a constructor and a destructor?
Below is the difference between a constructor and a destructor based on various parameters:
Constructor |
Destructor |
A constructor is used to allocate the memory. |
A destructor is used to deallocate or free up the memory. |
Mayor may not accept the arguments. |
Destructors don’t accept any arguments. |
class_name(arguments){
} |
~class_name(){
}; |
The constructor is called as soon as the object is created. |
Called at the time of program termination or when the block is exited. |
Constructors are executed in successive order, meaning from parent to child class. |
Destructors are called in the reverse order, meaning from child to parent class. |
Can be overloaded. |
Cannot be overloaded. |
47. Can a Java interface have static methods?
Yes, a Java interface can have static methods, but we cannot override them as they’re static. So, we have to define the static methods in the interface and only perform the calling party in the class.
Below is an example of a static method in the
Java interface:
import java.util.*;
interface A
{
static void staticmethod()
{
System.out.println("Static method of interface A called");
}
default void display()
{
System.out.println("Default function of interface A called");
}
}
Output :
spoj: The program compiled successfully, but main class was not found.
Main class should contain
The above interface has a static method and a default method that can be executed without affecting the class that implements it. However, there is no use in creating the static methods in the Java interface as we cannot override the function by redefining it in the main() method.
import java.util.*;
// Interface A with a static and a default method
public interface A {
// Static method in the interface
static void staticMethod() {
System.out.println("Static method of interface A called");
}
// Default method in the interface
default void display() {
System.out.println("Default function of interface A called");
}
}
// Class B implementing the interface A
class B implements A {
// No need to override static methods; they belong to the interface
// Default methods can be optionally overridden
@Override
public void display() {
System.out.println("Default function overridden in class B");
}
}
// Main class
class Main {
public static void main(String[] args) {
// Calling the static method of interface A
A.staticMethod();
// Creating an object of class B
B obj = new B();
// Calling the overridden default method
obj.display();
}
}
So, the output of the above program would be:
Static method of interface A called
Default function of interface A called
48. What are JAR files?
Java Archive(JAR) is a file format that aggregates many files into a single file similar in a format similar to a ZIP file. In other words, the JAR is a zipped file comprised of java lass files, metadata, and resources like text, images, audio files, directories, .class files, and more.
Following is the syntax to create a JAR file:
Jar cf file_name input files
49. What is the difference between method overloading and method overriding in Java? Provide examples to illustrate.
Method overloading is using a single class that has two or more methods with the same name but different parameters. It is solved at compile-time based on the number and types of arguments given. One more instance exists when a subclass provides the specific implementation for some method already defined in its superclass, this is called method overriding, which is used to achieve runtime polymorphism.
For example
class Parent {
void display() {
System.out.println("Parent's display method");
}
}
class Child extends Parent {
void display() {
System.out.println("Child's display method");
}
}
class Main {
public static void main(String[ ] args) {
Parent p = new Parent( );
p.display( ); // Output: Parent's display method
Child child = new Child();
child.display(); // Output: Child's display method
}
}
50. Explain the concept of encapsulation in Java. How does it help in achieving data hiding and abstraction?
Encapsulation in Java is the act of keeping together data and methods that are part of a class to hide the internal state from direct access. The reason behind this approach is to ensure data integrity and promote abstraction by exposing only essential details of the class’s behavior through public methods.
To achieve data hiding, encapsulation restricts direct access to an object’s internal state, thus ensuring data integrity. By doing this, it makes abstraction possible as it only exposes some critical behaviors about the object via public methods, thereby enabling simpler interaction and decreased complexity.
51. What is the purpose of the final keyword in Java? How is it used in variables, methods, and classes?
The final keyword can be added before a variable declaration, any method header, or preceding the class keyword so as not to allow changing their value, to prevent them from being overridden, or before words like “extends” in order not to let inheritance happen.
public final class Circle {
private final double PI = 3.14;
public final void calculateArea(final double radius) {
final double area = PI * radius * radius;
System.out.println("Area of circle: " + area);
}
}
52. What is the difference between ArrayList and LinkedList in Java? When would you choose one over the other for storing data?
ArrayList is a dynamic array that stores elements and supports fast random access. It is better suited for element traversal and frequent access. Conversely, LinkedList is a linked list that stores its elements in the form of nodes, making it very suitable for high-speed insertion and deletion operations. Therefore, it can be useful where there are many additions or removals.
If you want fast access and traversal through elements, then use an ArrayList; otherwise, for fast insertion or deletion of elements, use LinkedList.
53. How many types of constructors are there in the Java programming language?
There are two types of constructors in the Java programming language:
- Parameterized Constructor: A constructor that accepts arguments or parameters is known as the parameterized constructor. It initializes the instance variables will the values passed while creating an object.
Below is an example of the parameterized constructor:
import java.util.*;
class A
{
int roll_no;
String name;
A()
{
System.out.println("Constructor called");
}
public void fun()
{
System.out.println("Class A function called");
}
}
class parameterized_constructor
{
public static void main(String args[])
{
A obj=new A();
obj.fun();
System.out.println("The value of instance variables are: ");
System.out.println("Name: "+obj.name);
System.out.println("Roll No: " +obj.roll_no);
}
}
The output of the above program would be:
Constructor called
Class A function called
The value of instance variables are:
Name: null
Roll No: 0
- Non-parameterized/Default constructor: The constructors with no parameters or arguments are known and non-parameterized constructors. In case you don’t define a constructor of any type, the compiler itself creates a default constructor which will be called when the object is created.
Below is an example of a non-parameterized constructor:
import java.util.*;
class A
{
int roll_no;
String name;
A(int x,String y)
{
this.roll_no=x;
this.name=y;
System.out.println("Constructor called");
}
public void fun()
{
System.out.println("Class A function called");
}
}
class non_parameterized_constructor
{
public static void main(String args[])
{
A obj=new A(10,"Harry Williams");
System.out.println("The value of instance variables");
System.out.println("Name: "+obj.name);
System.out.println("Roll No: "+obj.roll_no);
}
}
The output of the above program will be:
Constructor called
The value of instance variables
Name: Harry Williams
Roll No: 10
54. What is the purpose of a Default constructor in Java?
If no constructor is available in the class, the Java compiler creates a default constructor and assigns the default value to the instance variables.
For example:
import java.util.*;
class A
{
String name;
int id;
void display()
{
System.out.println("Name: "+this.name);
System.out.println("Id: "+this.id);
}
}
class B
{
public static void main(String args[])
{
A object=new A();
System.out.println("The values of the instance variables are:");
System.out.println("Name: "+object.name);
System.out.println("Name: "+object.id);
}
}
The output of the above program:
The values of the instance variables are:
Name: null
Name: 0
55. What is the use of a copy constructor in Java?
Java does not support a copy constructor. However, you can copy the values of one instance to another by copying the instance variables of one object to another. Below is an example of such a method:
import java.util.*;
class demo
{
String name;
int roll_no;
//constructor to initialize the name and roll number
demo(int x, String y)
{
name=y;
roll_no=x;
}
//constructor to initialize another object variables
demo(demo ob)
{
roll_no=ob.roll_no;
name=ob.name;
}
void display()
{
System.out.println("Name: "+name);
System.out.println("Roll Number:"+roll_no);
}
}
class copy_constructor
{
public static void main(String args[])
{
demo obj=new demo(10,"Alice Williams");
demo obj2=new demo(obj);
obj.display();
obj2.display();
}
}
The output of the following code is:
Name: Alice Williams
Roll Number:10
Name: Alice Williams
Roll Number:10
56. What is the difference between aggregation and composition?
Below are the key differences between aggregation and composition in Java:
Aggregation |
Composition |
The parent class has a one-way relationship with the child class. |
In composition, the parent class owns the child class |
Aggregation is denoted by an empty diamond in UML (Unified Modeling Language) notation |
Denoted by a filled diamond in the UML notation |
Child class has its own life cycle |
Child class doesn’t have a lifetime |
Aggregation is a weak relationship. For example, a bike with an indicator is aggregation |
Composition is a stronger relationship. For example, a bike with an engine is a composition |
57. What is object cloning?
Object cloning means creating the exact copy of an existing object. In java programming, object cloning can be done using the clone() method. To create the object clone, you should implement the java.lang.Cloneable interface, otherwise the clone() method generates a CloneNotSupportException.
The syntax for the clone method is:
protected Object clone() throws CloneNotSupportedException
58. What are various exception-handling keywords in Java?
Java language has three exception handling keywords:
- try: whenever a code segment has a chance of an error or any abnormality, it can be placed inside the try block. In case of any error, the try block will send the exception to the catch block.
- catch: catch handles the exception generated in the try block. It comes after the try block.
- final: The final keyword ensures that the segments execute despite the errors and exceptions processed by the try & catch block. The final keyword comes either after the try block or both the try and the catch block.
59. Differentiate between this() and super() in Java.
this() |
super() |
Represents the present instance of a class |
Represents the current instance of the parent class |
Calls the default constructor |
Calls the base class constructor |
Used to point to the current class instance |
Used to point to the instance of the superclass |
60. Can we import the same package/class twice? Will the JVM load the package twice at runtime?
A package or class can be inherited multiple times in a program code. JVM and compiler will not create any issue. Moreover, JVM automatically loads the class internally once, regardless of times it is called in the program.
61. Define an abstract class.
A class that contains the abstract keyword in its declaration is known as an abstract class. It can have abstract and non-abstract methods (method with a body).
- This class can have public, private, protected, or constants and default variables.
- It needs to be extended and its method needs to be implemented. It cannot be instantiated.
- If a class has at least one abstract method, then the class must be declared abstract.
62. Describe annotations.
- Java annotation is a tag that symbolizes the metadata associated with class, interface, methods, fields, etc.
- Annotations do not directly influence operations.
- The additional information carried by annotations is utilized by Java compiler and JVM.
63. What is the difference between HashMap and HashTable in Java? When would you choose one over the other for storing key-value pairs?
These two are used to save key/value pairs, but with some differences:
- HashMap does not have a synchronization feature, making it not thread-safe, while HashTable does.
- HashMap allows null keys as well as values, but HashTable does not allow any null key or value.
Generally, HashMap is preferred in non-thread-safe scenarios where performance is important; on the other hand, HashTable is recommended for multi-threaded environments where thread safety is required.
64. What are the different access modifiers in Java? Describe their visibility scopes and when to use each one.
Public, protected, default (no modifier), and private are four access modifiers in Java.
- Public: access from anywhere
- Protected: access to the same package or other packages (subclasses)
- Default (no modifier): Only access in the created package.
- Private: No one else but the declaring class will be able to obtain it.
Use public if you want your member to be accessed from anywhere, protected when you wish to restrict access to subclasses and classes within the same package, default when you want access at the package level, and private when you only want access within the declaring class.
65. How does Java handle memory management and garbage collection? Explain the role of the JVM in managing memory resources.
Garbage collection is Java’s automatic memory management system. It runs as a process that recovers memory from objects that will never be used again. Memory resources management is done by JVM like allocating memory for objects, garbage collecting unused objects, and optimizing memory usage for performance enhancement. Various types of memory areas are used by JVM such as heap, stack method area, and native method stacks to help keep its memory efficient.
Advanced Java Interview Questions for Senior Developers
66. Distinguish between static loading and dynamic class loading.
- Static loading: In static loading, classes are loaded statically with the operator ‘new.’
- Dynamic class loading: It is a technique for programmatically invoking the functions of a class loader at runtime. The syntax for this is as follows:
Class.forName (Test className);
67. Struts 1 classes are not thread-safe, whereas Struts 2 classes are thread-safe. Why?
Struts 1 actions are singleton. So, all threads operate on the single action object and hence make it thread-unsafe.
Struts 2 actions are not singleton, and a new action object copy is created each time a new action request is made and hence it is thread-safe.
68. Define JAXP and JAXB.
JAXP: It stands for Java API for XML Processing. This provides a common interface for creating and using DOM, SAX, and XSLT APIs in Java regardless of which vendor’s implementation is actually being used.
JAXB: It stands for Java API for XML Binding. This standard defines a system for a script out of Java objects as XML and for creating Java objects from XML structures.
69. Define an enumeration?
The term “enum” is commonly used to refer to an enumeration. An enumeration represents an interface that encompasses methods facilitating access to the underlying data structure from which the enumeration is derived. It enables a systematic, sequential retrieval of all the elements stored within the collection.
70. How can we find the actual size of an object on the heap?
In the Java programming language, you cannot accurately determine the exact size of an object located in the heap.
71. What’s the base class of all exception classes?
Java.Lang.throwable: It is the superclass of all exception classes, and all exception classes are derived from this base class.
72. Why do we use a vector class?
A vector class provides the ability to execute a growable array of objects. A vector proves to be very useful if you don’t know the size of the array in advance or if we need one that can change the size over the lifetime of a program.
73. What is the difference between transient and volatile variables in Java?
Transient: In Java, it is used to specify whether a variable is not being serialized. Serialization is a process of saving an object’s state in Java. When we want to persist the object’s state by default, all instance variables in the object are stored. In some cases, we want to avoid persisting a few variables because we don’t have the necessity to transfer across the network. So, we declare those variables as transient.
If the variable is confirmed as transient, then it will not be persisted. The transient keyword is used with the instance variable that will not participate in the serialization process. We cannot use static with a transient variable as they are part of the instance variable.
Volatile: The volatile keyword is used with only one variable in Java, and it guarantees that the value of the volatile variable will always be read from the main memory and not from the thread’s local cache; it can be static.
74. Why Map interface does not extend the Collection interface in the Java Collections Framework?
The Map interface is not compatible with the Collection interface, because Map requires a key as well as a value, for example, if we want to add a key–value pair, we will use put(Object key, Object value).
There are two parameters required to add an element to HashMap object. In Collection interface, add(Object o) has only one parameter.
The other reasons are: Map supports valueSet, keySet, and other suitable methods that have just different views from the Collection interface.
75. Mention the uses of the synchronized block.
We use the synchronized block because:
- It helps lock an object for every shared resource.
- The scope of the synchronised block is smaller than the method.
76. Difference between Stack and Heap Memory in Java?
The key differences between Heap and Stack memory in Java are:
Stack Memory |
Heap Memory |
Smaller in size. |
Larger in size. |
Exists until the end of the thread. |
Lives from the start till the end of application execution. |
Objects stored in Stack can’t be accessed by other threads. |
Globally accessible. |
Follows LIFO(Last In First Out) order. |
Dynamic memory allocation. |
The variables in Stack memory are only visible to the owner thread. |
Heap memory is visible to all the threads. |
Continuous memory allocation. |
Random order memory allocation. |
Less flexible, one cannot alter the allocation memory. |
Users can alter the allocated memory. |
Fast access, allocation, and deallocation. |
Slow access, allocation, and deallocation. |
77. What do you mean by the interface in Java?
Java interface is a completely abstract class referred to as a collection of abstract methods, static methods, and constants. It acts as a blueprint of a class that groups related methods or functions with empty bodies.
Below is an example of a java interface:
import java.io.*;
interface x
{
int p=10;
void pr();
default void show()
{
System.out.println("A default method in interface");
}
}
class impx implements x
{
public void pr()
{
System.out.println("Hello World");
}
public static void main(String args[])
{
x ob=new impx();
ob.pr();
ob.show();
}
}
Output:
Hello World
A default method in interface
78. What is the difference between abstract class and interfaces?
Below are the major differences between the abstract class and an interface:
Abstract Class |
Interface |
Can provide complete, default, or only the details in method overriding |
Doesn’t provide any code, the user can only have the signature of the interface. |
Have instance variables. |
No instance variables. |
An abstract class can be public, private, or protected. |
The interface must be public. |
An abstract class can have constructors. |
No constructors are available in the interface. |
A class can inherit only a single abstract class. |
A class can implement one or more interfaces. |
Abstract classes are fast. |
Interfaces are slower as they have to locate the corresponding methods in the class. |
79. What is a servlet in java?
It’s a server-side technology used to create web servers and application servers. We can understand Servlets as the java programs that handle the request from the web servers, process the request, and reverts to the web servers after the response is generated.
Several packages like javax.servlet and javax.servlet. HTTP provides the appropriate interfaces and classes that help the user to create their servlet. All the servlets should implement the javax.servlet.Servlet interface, plus other interfaces and classes like the HttpServlet, Java Servlet API, and more.
The execution of a servlet involves six distinct steps:
- The clients initiate the request by sending it to the web server or application server.
- The web server receives the request from the clients.
- The servlet processes the request, carrying out the necessary computations, and generates the corresponding output.
- Subsequently, the servlet sends the processed request back to the web server.
- Finally, the web server dispatches the request to the clients, and the resulting output is displayed on the client’s screen or any other designated device.
80. What is a Request Dispatcher?
The request dispatcher serves as an interface utilized to effectively redirect requests to various resources within the application itself. These resources may include Java Server Pages (JSP), images, HTML files, or other servlets. Moreover, it facilitates the integration of responses from one servlet into another, guaranteeing that the client receives output from both servlets. Additionally, it allows for the seamless forwarding of client requests to the next servlet in the specified sequence.
There are two methods defined in a Requestdispatcher interface:
- void include(): It includes the content of the resource before sending the response.
- void forward(): the method forwards the request from one servlet to another resource like the JSP, image, etc on the server.
81. How do cookies work in Servlets?
Cookies are the text files sent by the server and get stored in the client system to keep the information on the local machine and use it for tracking purposes. Java Servlet supports HTTP cookies through javax.servlet.http.Cookie class that implements cleanable and serializable interfaces.
The server sends a set of cookies to the client computer, for example, name, age, etc. Then, the browser stores the information in the local machine and sends these cookies to the server, if any request is sent to the webserver. This information can then be used to identify the user.
82. What is the difference between ServletContext vs. ServletConfig?
The difference between ServletContext and ServletConfig is as follows:
ServletContext |
ServletConfig |
Common for all the servlets and generally represents the whole web application. |
represents a single servlet. |
Similar to global parameters linked to the whole application. |
Similar to local parameters associated with a particular servlet. |
The ServletContext has an application-wide scope. |
ServletConfig has the servlet wide scope. |
To get the context object, getServletContext() method is used. |
To get the config object, getServletConfig() is used. |
Mainly used to get a MIME type of file or application. |
Mainly used for specific users or tasks like the shopping card. |
83. Explain the thread lifecycle in Java?
There are 5 states in a thread lifecycle and java can be at any one of them. The thread lies in any one of these states:
- New: The thread lies in the new state after it has been created. It remains in the new state until you start the execution process.
- Running: At runnable state, the thread is ready to run at any point in time or it might have started running already.
- Running: The scheduler picks up the thread and changes its state to running, the CPU starts executing the thread in the running state.
- Waiting: While being ready to execute, another thread might be running in the system. So, the thread goes to the waiting state.
- Dead: Once the execution of the thread is finished, its state is changed to the dead state, which means it’s not considered active anymore.
84. Explain the types of Exceptions in Java.
There are two types of Exceptions in Java Programming:
- Built-in Exception: These exceptions are the exceptions available in the standard package of java lang. They are used for certain errors with specific Exceptions as mentioned below:
- AriththmeticException: thrown for the errors related to the arithmetic operations.
- IOException: thrown for failed input-output operations.
- FileNotFourndException: raised when the file is not accessible or does not exist.
- ClassNotFoundException: exception is raised when the compiler is unable to find the class definition.
- InterruptedEException: raised when a thread is interrupted.
- NoSuchFieldException: raised when a class or method doesn’t have a variable specified.
- NullPointerException: thrown while referring to the variable or values of a null object.
- RuntimeException: raised for the errors occurring during the runtime. For example, performing invalid type conversion.
- IndexOutOfBoundsException: raised when the index of the collection like an array, string, or vector is out of the range or invalid.
- User-defined Exceptions: User-defined exceptions are the exceptions thrown by the user with custom messages. These are used for cases where the in-built Exception might not be able to define the error.
85. How to write multiple catch statements under a single try block?
In Java, we can include multiple catch statements for a single try block. This is done, to handle different exceptions separately for a single try block.
Below is the program for multiple catch statements:
import java.util.*;
class multiple_catch
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
int x,y,z;
try{
System.out.println("Enter the elements for division: ");
x=s.nextInt();
y=s.nextInt();
z=x/y;
System.out.println("Value of z: "+z);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occured");
}
catch(IllegalArgumentException e)
{
System.out.println("Illegal argument");
}
catch(Exception e)
{
System.out.println("Any Exception in the try block");
}
System.out.println("End of the program");
}
}
The output of the following program in different cases will be:
Case 1: Dividing an integer by zero
Enter the elements for division:
30
0
Arithmetic Exception occurred
End of the program
Case 2: Execution successful
Enter the elements for division:
15
3
Value of z: 5
End of the program
Case 3: Value entered is invalid
Enter the elements for division:
23
t
Any Exception in the try block
End of the program
86. Difference between the throw and throws keyword?
Following are the key differences between the throw and throws keyword:
throw |
throws |
The throw keyword is used to explicitly throw an exception inside a program or a block of code. |
Throws keyword is used to declare an exception in the method signature that might occur during the compilation or execution of a program. |
Can throw only unchecked exceptions. |
Can be used for both checked and unchecked exceptions. |
throw keyword followed by an instance variable. |
throws keyword followed by the exception class names. |
throw keyword is used to throw only a single exception. |
throws can be used to throw multiple exceptions. |
87. Write the string reversal program without using the in-built function?
There are two ways we can reverse a string in java without using the in-built function:
- Using the loop by printing string backward, one character each time.
- Using the recursive function and printing the string backward.
In the following program, you can see both ways to print the string in reverse order:
import java.util.*;
class string_reversal
{
public void method1(String str)
{
for(int i=str.length()-1;i>=0;i--)
{
System.out.print(str.charAt(i));
}
System.out.println();
}
public void reverse(String str)
{
if(str.isEmpty())
{
return;
}
else
reverse(str.substring(1));
System.out.print(str.charAt(0));
}
public static void main(String args[])
{
String str="Intellipaat";
System.out.println("The original string is "+str);
System.out.println("String reversal using the loop: ");
string_reversal obj=new string_reversal();
obj.method1(str);
System.out.println("String reversal using recursion: ");
obj.reverse(str);
}
}
The output of the above program will be:
The original string is Intellipaat
String reversal using the loop:
taapilletnI
String reversal using recursion:
taapilletnI
That is all in the section of intermediate core Java interview questions. Let’s move on to the next section of advanced Java interview questions for experienced professionals.
88. What is HTTP Tunneling?
HTTP tunneling refers to encapsulating of non HTTP data into HTTP/HTTPS. This is generally done to bypass firewalls, network restrictions or proxies where only HTTP or HTTPS traffic is allowed.
It works in a client-server setup:
- The client encapsulates the non-HTTP data into HTTP/HTTPS data and sends it through the firewall to the server.
- The server decrypts the encapsulated data, and forwards it to the destination. Once the response is received from the destination, the server again packs the data into HTTP/HTTPS and sends it to the client.
89. Define a StringJoiner and write a sample code.
StringJoiner is a class in Java that is used to join multiple strings together, optionally adding a delimiter between them. Here’s an example code that demonstrates the usage of StringJoiner:
import java.util.StringJoiner;
class Main {
public static void main(String[] args) {
// Create a StringJoiner with a delimiter "."
StringJoiner strJoiner = new StringJoiner(".");
// Add strings to the StringJoiner
strJoiner.add("AAA").add("BBB");
// Print the joined string
System.out.println(strJoiner); // Output: AAA.BBB
}
}
OutPut:
AAA.BBB
90. What is a collection in Java?
A collection is a framework that is used to store and manipulate a container of objects in Java.
Java Collections can be used for performing a variety of operations such as:
- Search
- Sort
- Manipulate
- Delete
Below is the chart that represents the hierarchy of collections in Java: