Java Interview Questions and Answers
Java is high level, simple and object oriented programming language.
Java is not 100% object-oriented because it supports primitive data types (int, float, char, etc.), which are not objects.
Pointers are Unsafe, Java does not use pointers to avoid security risks and memory corruption, ensuring robust memory management with garbage collection.
JIT stands for (Just-in-Time) compiler is a part of JRE(Java Runtime Environment), it is used for better performance of the Java applications during run-time.
String is immutable in Java for security, synchronization, and performance reasons. This helps in optimizing memory usage by using the String pool.
A marker interface is an empty interface with no methods, used to indicate metadata to the JVM (e.g., Serializable, Cloneable).
Private methods cannot be overridden as they are not inherited.
Static methods cannot be overridden but can be redefined in subclasses (method hiding).
JDK (Java Development Kit): Includes JRE and development tools.
JRE (Java Runtime Environment): Runs Java applications.
JVM (Java Virtual Machine): Converts bytecode to machine code.
public: Accessible everywhere.
static: Called without creating an object.
void: Returns nothing.
main: Entry point of Java programs.
Java uses JVM, which allows bytecode to run on any operating system.
Heap Memory: Stores objects, shared across threads.
Stack Memory: Stores method-specific variables, thread-specific.
=
is an assignment operator.
==
compares primitive values or object references.
Local variables: Declared inside methods, scope limited to the method.
Instance variables: Declared in a class but outside methods, scope tied to object instances.
Use the final
keyword: final int MAX = 100;
break
: Terminates loop execution.
continue
: Skips current iteration and continues loop execution.
A ClassLoader loads classes into memory at runtime.
Overloading: Same method name, different parameters (compile-time polymorphism).
Overriding: Redefining parent class method in child class (runtime polymorphism).
Java is platform-independent, C++ is not.
Java has garbage collection, C++ uses manual memory management.
final
: Prevents modification (class, method, variable).
finally
: Executes code after try-catch
.
finalize
: Used for garbage collection.
Type casting converts one data type into another.
Types: Implicit (automatic) and Explicit (manual).
Mechanism to handle runtime errors using try
, catch
, finally
, throw
, and throws
.
No, static methods belong to the class, not instances.
Compiled Java code executed by the JVM (.class file).
Used for iteration: for
, while
, do-while
.
private
, default
, protected
, public
.
Public: Accessible to everyone without any restrictions
Private: Only code declared in the same class or struct can access this member
Protected: Only code in the same class or in a derived class can access this type or member
Internal: Only code in the same assembly can access this type or member
Object-Oriented Programming System (OOPS) principles: Encapsulation, Inheritance, Polymorphism, Abstraction. In detail
Threads are small units of a computer program that can run independently. They allow a program to perform multiple tasks at the same time, like having different parts of the program run simultaneously. This makes programs more efficient and responsive, especially for tasks that can be divided into smaller parts.
Lightweight process for multitasking (Thread
class, Runnable
interface).
String
: Immutable, StringBuffer
: Mutable.
Serialization in Java is the mechanism of converting the state of an object into a byte stream. This byte stream can then be saved into a file, transferred over a network, or stored in a database. The reverse process, called deserialization, reconstructs the object from the byte stream.
ArrayList
: Ordered, allows duplicates.
HashSet
: Unordered, no duplicates.
Interface: Fully abstract, no constructors.
Abstract Class: Can have methods with implementation.
A superclass is the class from which many subclasses can be created. The subclasses inherit the characteristics of a superclass. The superclass is also known as the parent class or base class.
Ensures a method overrides a superclass method.
The primary purposes of using @Override
are:
Error Prevention:
It helps catch errors during compile time if a method is not actually overriding a superclass method due to a typo or incorrect signature.
Code Readability:
It makes the code more readable and understandable by explicitly stating the intent of method overriding.
Maintainability:
It simplifies code maintenance by clearly marking overridden methods, making it easier to track changes and understand inheritance relationships.
Provides data structures like List
, Set
, Map
.
Running multiple threads simultaneously for concurrent execution.
A static
method can be accessed without creating an object of the class.
The static
keyword is a non-access modifier used for methods and attributes. Static methods/attributes can be accessed without creating an object of a class.
Stack (method execution), Heap (objects), Method Area, PC Register, Native Stack.
Stack:
It is used for static memory allocation and stores local variables, method calls, and references to objects. The stack operates in a Last-In-First-Out (LIFO) manner, meaning that the last variable stored is the first one removed.
Heap:
It is used for dynamic memory allocation and stores objects. The heap is a larger memory pool compared to the stack, and memory allocation and deallocation are managed by the garbage collector.
No default value; must be initialized before use.
Constructor that creates a new object by copying another object.
Creating a copy of an object (clone()
method).
A wrapper class in Java converts primitive data types into objects. Example: Integer
, Double
, Boolean
.
A singleton class allows only one instance of itself to be created.
A package in Java is a group of related classes and interfaces.
Example: import java.util.*;
It is a special memory area in the heap where Java stores string literals to optimize memory.
A Java String Pool is a place in heap memory where all the strings defined in the program are stored. JVM checks for the presence of the object in the String pool, If String is available in the pool, the same object reference is shared with the variable, else a new object is created.
The JVM cannot call it without an instance, so it results in a NoSuchMethodError
.
Refers to the current instance of a class.
class Demo {
int x;
Demo(int x) { this.x = x; }
}
No, because static methods belong to the class, not an instance.
Also called dynamic binding, it occurs at runtime when method calls are resolved dynamically.
Example: Method overriding.
Allows type safety in collections and classes.
Generics means parameterized types. The idea is to allow a type (like Integer
, String
, etc., or user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types. An entity such as a class, interface, or method that operates on a parameterized type is a generic entity.
Java Server Pages (JSP) is a technology for creating dynamic web pages using Java.
Java Database Connectivity (JDBC) allows Java programs to interact with databases.
A Java framework for building enterprise applications, providing dependency injection, MVC, AOP, etc.
A framework that simplifies Spring-based applications by providing embedded servers, auto-configuration, and minimal setup.
Spring Boot is a Java framework that helps developers quickly create web applications and microservices. It's an open-source project that's built on the Spring Framework.
Faster development
Easy deployment
Embedded servers
Java Cryptography Architecture, used for security and encryption.
Java Cryptography Architecture (JCA)
A framework for working with cryptography in the Java programming language
Part of the Java security API
Includes APIs for encryption, key management, and certificate validation
Helps developers integrate security into their applications
Java Persistence API (JPA) is a framework that allows Java applications to access and manage relational databases. It's based on the Java programming model and is part of the Java Enterprise Edition (Java EE).
A Java program that runs on a server and handles web requests.
A servlet is a Java program that runs on a web server to handle requests from web clients. Servlets are used to extend the functionality of web servers by providing dynamic content.
A fixed-size data structure storing elements of the same type.
An array is a data structure that stores multiple values of the same type under a single variable name. Arrays are used in programming and computing to organize and manage data.
int[] arr = {1, 2, 3};
A linked list in Java is a dynamic data structure whose size increases as you add the elements and decreases as you remove the elements from the list. The elements in the linked list are stored in containers. The list holds the link to the first container.
Each element in a linked list is called a node.
Each node contains data and a reference to the next node.
The order of the elements is not determined by their physical location in memory.
Nodes can be stored wherever there is free space in memory.
Types of linked lists
Singly linked list: Each node points to the next node.
Doubly linked list: Each node points to both the next and previous node.
Circular linked list: The last node points back to the first node, forming a circle.
Recursion is a method of solving problems by breaking them down into smaller, similar problems.
A function calls itself, either directly or indirectly.
The function breaks down the problem into smaller parts.
The function solves the smaller parts, and then uses the solutions to solve the larger problem.
Dynamic binding is a programming technique that determines which method to call at runtime, rather than at compile time. It's also known as late binding.
Method binding at runtime (polymorphism).
An immutable class representing character sequences.
StringBuffer
is synchronized, StringBuilder
is faster but not thread-safe.
Automatically removes unused objects to free memory.
Serialization: Converts an object into a byte stream.
Deserialization: Converts a byte stream back into an object.
A contract defining methods without implementations.
An interface is a fully abstract class. It includes a group of abstract methods (methods without a body).
We use the interface
keyword to create an interface in Java.
Used to access and modify private variables.
Spring Boot is a framework that simplifies Java application development by providing auto-configuration, embedded servers, and minimal setup.
Database Connection File:
We configure the database connection in the application.properties
or application.yml
file.
Example (application.properties
for MySQL):
spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase
spring.datasource.username=root
spring.datasource.password=yourpassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
Encryption: Converts plain text into an unreadable format (ciphertext).
Decryption: Converts encrypted text back into readable text
More Question and Answers - Here
Join Kiran on Peerlist!
Join amazing folks like Kiran and thousands of other people in tech.
Create ProfileJoin with Kiran’s personal invite link.
0
5
1