Java Interview Questions for Fresher 2025
Prepare for your next job with top Java Interview Questions for Fresher 2025. Learn key concepts, OOPs, Java 8, and coding basics to crack your interview.
Question 1: What is Java?
Answer:
Java is a one of the most popular programming language, which is high-level, class-based, object-oriented that is designed to have as few implementation dependencies as possible. Java is a general-purpose programming language intended to let application developers write once, run anywhere (WORA), meaning that compiled Java code can run on all platforms that support Java without the need for recompilation.
Question 2: Explain the JDK, JRE, and JVM.
Answer:
- JVM (Java Virtual Machine): The JVM is an engine that provides a runtime environment to drive the Java Code or applications. It converts Java bytecode into machine language.
- JRE (Java Runtime Environment): JRE is a part of jdk which is designed to run other software. It has the set of libraries and other files that JVM uses at runtime.
- JDK (Java Development Kit): The JDK is a software development kit used for developing the many applications and applets. It physically exists. It contains JRE + development tools.
Question 3: What are variables in Java?
Answer:
Variables are containers for storing data values. The variables must be declared with a data type that tells about which type of value its holding and quantity of value it can hold. Java is a statically typed language, meaning variables need to be defined before they are used.
Question 4: What is typecasting in Java?
Answer:
Typecasting is the process of converting a variable from one type to variable of another type. There are 2 types of casting:
- Widening Casting (Implicit): In this the data automatically convert from a smaller to a larger type
- Narrowing Casting (Explicit): In this needs to be explicitly convert a larger type to a smaller type
Question 5: How do you declare an array in Java?
Answer:
An array is a unit which holds a fixed number of elements of a same data type. Array can be declare is as follows:
int[] arr_name = new int[10]; // declares an array of integers String[] arr_name = new String[50]; // declares an array of strings
Question 6: Explain the main method in Java.
Answer:
The main method is the start or an entry point for any Java program. It must define as public, static, return no value (void), and accept a String array as a parameter. It signature is:
public static void main(String[] args) {// code ,statements to execute}
Question 7: What are literals in Java?
Answer:
Literals are the fixed values assigned to variables in Java. E.g. 120, -60, 3.14F, ‘B’, and “Hi” are all literals.
Question 8: What is a constructor in Java?
Answer:
A constructor in Java it is a block of code which is similar to a method which get called when an object is created. But Unlike methods, constructors have no return type and have the same name as the class name has .
Question 9: Explain method overloading in Java.
Answer:
Method overloading is a mechanism which allows a class to have more than one method with same name, if their parameter lists are different. It is helps to achieve compile-time (or static) polymorphism.
Question 10: What is a package in Java?
Answer:
A package in Java is like a unit that organizes a set of related classes (java files) and interfaces. you can just say that packages are like different folders on your computer.
Question 11: What is Object-Oriented Programming?
Answer:
Object-oriented programming (OOP) it is a programming methodology which focus on the concept of “objects”, which can have data in which is in the form of data fields (often known as attributes or properties) and instructions or code in the form of procedures (often known as methods).
Question 12: Which are the main principles of OOP?
Answer:
- Encapsulation: It is a mechanism of wrapping of data member and member functions that operate on the data into a single unit called a ‘class’. It also means hiding data from direct access. From this we can achieve the security.
- Abstraction: It is mechanism where Hiding the complex implementation details and only show the relevant one
- Inheritance: It Allows a new class to acquire or inherit properties and methods of an another existing class.
- Polymorphism: The ability of different classes which provide a unique interface by exposing a method which can behave differently.
Question 13: What is inheritance?
Answer:
It is a mechanism where one object acquires all the properties and behaviors of a another object but there should be “is a “ relationship. It is an important part of OOPs (Object-Oriented programming systems) , which helps to achieved reusability of code.
Question 14: What is an interface?
Answer:
An interface in Java is a similar to a class, which contain only constants, method declaration, default methods, static methods, and nested types. Interfaces cannot contain instance fields. interfaces are having the abstract methods.
Question 15: which are the difference between abstract classes and interfaces.
Answer:
- Abstract Class: It Can have the abstract and as well as non-abstract methods. These classes are used to provide a base for derived classes to extend and implement the abstract methods. It used to implement abstraction partially.
- Interface: It only contains abstract methods. From java 8 version , it can also contain default and static methods. Interfaces are used to implement abstraction completely.
Question 16: What is polymorphism?
Answer:
The ability of different classes which provide a unique interface by exposing a method which can behave differently.
Question 17: Explain method overriding.
Answer:
It is process where it allows a derived class or child class to provide a specific implementation of a method that is already provided by one of its base classes or parent classes. And that method which override is called an overridden method.
Question 18: What is the “super” keyword?
Answer:
The super keyword in Java is a reference variable that is used to refer to Super class objects. This used to access the member of superclass.
Question 19: What are getters and setters in Java?
Answer:
These are method which used to change the value of private variables. For example:
public class Data {
private float num;
public float getSal() {
return sal;
}
public void setSal(float sal) {
this.sal = sal;
}
}
Question 20: What is static in Java?
Answer:
It is a keyword from java which used declare variable ,method and a block . we can only have one copy of a static variable per class, irrespective of how many objects we create. Thus, static variables are good for memory management. shared single copy to all instances of class.
Question 21: What is Exception Handling?
Answer:
Exception handling in Java is a mechanism that allows the program to handle runtime errors, maintaining the normal flow of the application. It is a process where a program responds to exceptional conditions (like errors or unusual conditions) in a controlled way, rather than crashing or abruptly terminating.
Java provides a robust mechanism to handle runtime errors using try, catch, finally, and throw keywords. Exception handling helps in dealing with errors, preventing crashes, and providing meaningful error messages to users.
Question 22: What is a try-catch block?
Answer:
A try-catch block in Java is used for exception handling. It allows you to handle runtime errors (exceptions) in a graceful manner, preventing the program from crashing unexpectedly. The try block
contains code that might throw an exception, and the catch block is used to handle the exception when it occurs.
Question 23: What is the finally block?
Answer:
The finally block in Java is a part of exception handling that ensures a set of code is always executed, regardless of whether an exception occurs or not. It is used to perform clean-up actions such as closing files, releasing resources, or any other important operations that must be performed after a block of code executes, even if an exception was thrown.
Question 24: What is an Exception?
Answer:
An exception in Java is an event that disrupts the normal flow of a program’s execution. It is an object that represents an abnormal condition or error that occurs during the execution of a program, which typically results in the program terminating or requiring special handling to continue functioning.
Exceptions are used to handle errors in a structured way, allowing programs to recover from unexpected situations without crashing.
Question 25: What are Checked Exceptions?
Answer:
In Java, checked exceptions are exceptions that are checked at compile time by the Java compiler. These are exceptions that must either be caught using a try-catch block or declared to be thrown using the throws keyword in the method signature. The compiler ensures that checked exceptions are properly handled, and if they are not, it will result in a compilation error.
Question 26: What are Unchecked Exceptions?
Answer:
In Java, unchecked exceptions are exceptions that do not require explicit handling (i.e., they do not need to be caught in a try-catch block or declared in the method signature using the throws keyword). These exceptions are not checked at compile-time but rather occur during runtime. They are typically caused by programming errors, such as logic mistakes or incorrect assumptions in the code.
Unchecked exceptions are subclasses of the RuntimeException class (or its subclasses). These exceptions generally represent conditions that the program cannot recover from, like dividing by zero, accessing an invalid index in an array, or dereferencing a null object.
Question 27: What is the throws keyword?
Answer:
The throws keyword in Java is used in a method declaration to specify that a method can throw one or more exceptions. It allows the method to delegate the responsibility of handling the exception to the calling method, rather than handling the exception within the method itself.
Question 28: What is the Difference Between throw and throws?
Answer:
In Java, both throw and throws are related to exception handling, but they serve different purposes. Understanding the difference between these two keywords is important for managing exceptions properly in your code.
Question 29: What is throw Used For?
Answer:
In Java, the throw keyword is used to explicitly throw an exception during the execution of a program. It allows you to manually trigger an exception based on specific conditions or logic within your method or block of code.
This is in contrast to exceptions that are thrown automatically by the Java runtime system (like NullPointerException or ArrayIndexOutOfBoundsException). With throw, you have control over when and where an exception occurs, which can be useful for error handling or enforcing business rules.
Question 30: Explain Custom Exceptions in Java.
Answer:
A custom exception in Java is an exception that is user-defined, meaning it is created by the programmer to handle specific errors that are not already covered by the standard Java exceptions. Custom exceptions allow developers to create more meaningful, application-specific error handling, which can make the program more readable and easier to debug.
- What is a String in Java?
Answer:
- A String in Java is a sequence of characters. In Java, strings are objects of the String class, and they are immutable, meaning once a string object is created, it cannot be modified.
- What is the difference between String, StringBuffer, and StringBuilder?
Answer:
- String: Immutable. Once created, its value cannot be changed.
- StringBuffer: Mutable and thread-safe. Suitable for use in multi threaded environments.
- StringBuilder: Mutable and not thread-safe. It is generally faster than StringBuffer when used in a single-threaded environment.
- What is the difference between == and .equals() method in Java String comparison?
Answer:
- ==: Checks if two references point to the same memory location.
- .equals(): Compares the content of two strings (i.e., checks if the strings have the same characters in the same order).
Example:
java
Copy
String str1 = “hello”;
String str2 = “hello”;
String str3 = new String(“hello”);
System.out.println(str1 == str2); // true (same reference) System.out.println(str1.equals(str3)); // true (same content)
- What is the String pool in Java?
Answer:
- The String pool (or String literal pool) is a special memory area in the heap where string literals are stored. When you create a string using a literal (e.g., “hello”), Java checks if that string already exists in the pool. If it does, it reuses the existing reference, which saves memory.
- How does String immutability work in Java?
Answer:
- A String is immutable because once a string is created, its value cannot be changed. Any operation that appears to modify a string (like concatenation) creates a new String object rather than modifying the existing one. This helps prevent unexpected behavior in multi-threaded environments.
- What is the use of StringBuilder and StringBuffer in Java?
Answer:
- Both StringBuilder and StringBuffer are used to manipulate strings when modification of the string is required. They are mutable (unlike String, which is immutable), and both allow you to modify the content of the string without creating a new object.
o StringBuffer is thread-safe (synchronized).
o StringBuilder is not thread-safe but is faster than StringBuffer in single-threaded environments.
- How do you convert a String to an integer in Java?
Answer:
- You can convert a String to an integer using Integer.parseInt() or Integer.valueOf() methods.
Example:
java
Copy
String str = “123”;
int num = Integer.parseInt(str);
System.out.println(num); // Output: 123
- How do you reverse a string in Java?
Answer:
- You can reverse a string using StringBuilder or StringBuffer’s reverse() method.
Example:
java
Copy
String str = “hello”;
StringBuilder sb = new StringBuilder(str);
System.out.println(sb.reverse()); // Output: olleh
- What are some common methods available in the String class?
Answer:
- length(): Returns the length of the string.
- charAt(int index): Returns the character at the specified index. • substring(int start, int end): Returns a substring from the string.
- indexOf(String str): Returns the index of the first occurrence of the specified substring.
- toLowerCase()/toUpperCase(): Converts all characters in the string to lowercase or uppercase.
- trim(): Removes leading and trailing spaces from the string.
- How can you concatenate two strings in Java?
Answer:
- You can use the + operator or the concat() method to concatenate strings in Java.
Example:
java
Copy
String str1 = “Hello”;
String str2 = “World”;
String result = str1 + ” ” + str2; // Using + operator
// OR
String result2 = str1.concat(” “).concat(str2); // Using concat() method
- What is File Handling in Java?
Answer:
- File handling in Java refers to reading from and writing to files in the filesystem. Java provides several classes in the java.io package, such as File, FileReader, FileWriter, BufferedReader, BufferedWriter, and others, to perform file I/O operations.
- What is the File class in Java?
Answer:
- The File class in Java is part of the java.io package and is used to represent files and directories in the filesystem. It provides methods to create, delete, and query files and directories.
- How can you read a file in Java?
Answer:
- You can read a file using classes like FileReader, BufferedReader, or Scanner. For example, using BufferedReader:
java
Copy
BufferedReader br = new BufferedReader(new FileReader(“file.txt”)); String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
- How can you write data to a file in Java?
Answer:
- You can write data to a file using FileWriter or BufferedWriter. For example:
java
Copy
BufferedWriter bw = new BufferedWriter(new FileWriter(“file.txt”));
bw.write(“Hello, World!”);
bw.newLine(); // To add a new line
bw.close();
- What is the difference between FileReader and BufferedReader?
Answer:
- FileReader is used for reading data from a file character by character.
- BufferedReader is used to read data from a file line by line and is generally more efficient because it reads larger chunks of data into memory.
- How do you check if a file exists in Java?
Answer:
- You can use the exists() method of the File class:
java
Copy
File file = new File(“file.txt”);
if (file.exists()) {
System.out.println(“File exists.”);
} else {
System.out.println(“File does not exist.”);
}
- How can you delete a file in Java?
Answer:
- You can delete a file using the delete() method of the File class: java
Copy
File file = new File(“file.txt”);
if (file.delete()) {
System.out.println(“File deleted successfully.”);
} else {
System.out.println(“File deletion failed.”);
}
- How do you create a new file in Java?
Answer:
- You can create a new file using the createNewFile() method of the File class:
java
Copy
File file = new File(“newfile.txt”);
if (file.createNewFile()) {
System.out.println(“File created: ” + file.getName()); } else {
System.out.println(“File already exists.”);
}
- What is the RandomAccessFile class used for?
Answer:
- The RandomAccessFile class is used for both reading and writing to a file. It allows you to move to a specific location in the file (random access), unlike other file handling classes which only allow sequential access.
- How do you copy a file in Java?
Answer:
- You can use Files.copy() method from the java.nio.file package: java
Copy
Path source = Paths.get(“source.txt”);
Path destination = Paths.get(“destination.txt”);
Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
- What is the Collection Framework in Java?
Answer:
- The Collection Framework in Java provides a set of interfaces and classes to store and manipulate data in the form of collections such as lists, sets, and maps. It is part of the java.util package and includes classes like ArrayList, HashSet, HashMap, etc.
- What is the difference between a List, Set, and Map in Java?
Answer:
- List: An ordered collection that allows duplicate elements (e.g., ArrayList, LinkedList).
- Set: An unordered collection that does not allow duplicates (e.g., HashSet, TreeSet).
- Map: A collection that stores key-value pairs (e.g., HashMap, TreeMap).
- What is an ArrayList in Java?
Answer:
- ArrayList is a resizable array that implements the List interface. It allows duplicates, maintains insertion order, and provides fast random access to elements.
- What is a HashSet in Java?
Answer:
- HashSet is a class that implements the Set interface. It does not allow duplicate elements and does not guarantee the order of elements. It is backed by a hash table for fast lookup.
- What is a HashMap in Java?
Answer:
- HashMap is a class that implements the Map interface. It stores key value pairs and allows null values and keys. It does not guarantee the order of elements.
- What is the difference between HashMap and TreeMap?
Answer:
- HashMap is unordered and stores elements based on the hash value of keys.
- TreeMap is ordered and stores elements in a sorted order according to the natural ordering of its keys or by a comparator.
- How does a LinkedList differ from an ArrayList?
Answer:
- ArrayList: Uses a dynamic array to store elements. It provides fast random access but slower insertions and deletions.
- LinkedList: Uses a doubly linked list to store elements. It provides faster insertions and deletions but slower random access.
- What is the Iterator interface in Java?
Answer:
- The Iterator interface provides methods for traversing elements in a collection (like next(), hasNext(), and remove()), and is commonly used to iterate through List, Set, and other collections.
- How can you convert a List to an array in Java?
Answer:
- You can use the toArray() method to convert a List to an array: java
Copy
List<String> list = new ArrayList<>();
list.add(“Java”);
list.add(“Python”);
String[] array = list.toArray(new String[0]);
- What is the difference between Iterator and ListIterator?
Answer:
- Iterator can only iterate in one direction (forward).
- ListIterator can iterate both forward and backward, and it also allows modifying the list during iteration (like adding or removing elements).
Do visit our channel to explore more: Click Here
Author:-Prajakta Desai
Call the Trainer and Book your free demo Class For Java Call now!!!
| SevenMentor Pvt Ltd.
© Copyright 2021 | SevenMentor Pvt Ltd.