Java Interview Preparation
Prepare for Java placement interviews with important technical questions, output-based problems, frequently asked coding programs and a final mock interview.
Introduction to This Module
Learning Java is an important step towards becoming placement-ready. But knowing the concepts is not enough. You should also be able to explain them clearly and write programs when an interviewer asks you to do so.
In this final module, we will revise the most important Java concepts and practise questions commonly asked in fresher-level technical interviews.
The questions are arranged from basic to intermediate level so that you can build confidence step by step.
What You Will Learn
- Revise important Core Java concepts.
- Answer frequently asked OOPs interview questions.
- Practise String and Array interview questions.
- Revise Collections and Exception Handling.
- Understand output-based Java questions.
- Practise commonly asked Java coding programs.
- Learn tricky Java interview questions.
- Prepare for a basic Java mock interview.
1. Core Java Interview Questions
Core Java questions test your understanding of the basic concepts of the Java programming language. These questions are commonly asked in fresher interviews.
Q1. What is Java?
Java is a high-level, object-oriented programming language used to develop desktop applications, web applications, mobile applications and many other software systems.
Q2. What are the main features of Java?
The important features of Java include:
- Simple
- Object-oriented
- Platform-independent
- Secure
- Robust
- Multithreaded
- Portable
Q3. Why is Java platform-independent?
Java source code is compiled into bytecode. This bytecode can run on different operating systems using a compatible Java Virtual Machine (JVM).
This is why Java is commonly associated with the principle "Write Once, Run Anywhere."
Q4. What is the difference between JDK, JRE and JVM?
| Term | Meaning |
|---|---|
| JVM | Executes Java bytecode. |
| JRE | Provides the environment and libraries needed to run Java applications. |
| JDK | Provides tools needed to develop Java applications, including the compiler and runtime components. |
Q5. What is bytecode in Java?
Bytecode is the intermediate code generated by the Java compiler. It is stored in .class files and executed by the JVM.
Q6. Is Java completely object-oriented?
No. Java supports object-oriented programming, but it is not considered purely object-oriented because it also uses primitive data types such as int, char, boolean and double.
Q7. What is the main() method in Java?
The main() method is the standard entry point used by the JVM to start a traditional standalone Java application.
public static void main(String[] args) {
System.out.println("Hello Java");
}
- public: Allows the method to be accessed by the JVM.
- static: Allows it to be called without creating an object.
- void: The method does not return a value.
- String[] args: Receives command-line arguments.
Q8. What is the difference between == and equals()?
The == operator compares primitive values or, for objects, checks whether two references refer to the same object. The equals() method can be used to compare object contents when the class provides an appropriate implementation.
class Main {
public static void main(String[] args) {
String a = new String("Java");
String b = new String("Java");
System.out.println(a == b);
System.out.println(a.equals(b));
}
}
false true
Q9. What is a constructor?
A constructor is a special class member used to initialize objects. It has the same name as the class and does not have a return type.
Q10. What is the difference between a compiler and an interpreter?
A compiler translates source code into another form before execution. Java's compiler converts source code into bytecode. The JVM then executes bytecode using interpretation and just-in-time compilation techniques.
2. OOPs Interview Questions
Object-Oriented Programming is one of the most important areas of Java interviews. Make sure you understand all four major OOP principles.
Q1. What is OOP?
OOP stands for Object-Oriented Programming. It is a programming approach based on classes and objects.
Q2. What are the four pillars of OOP?
- Encapsulation
- Inheritance
- Polymorphism
- Abstraction
Q3. What is encapsulation?
Encapsulation means combining data and the methods that work on that data inside a class and controlling access to the data.
It is commonly implemented using private variables and public getter and setter methods.
Q4. What is inheritance?
Inheritance allows one class to acquire accessible properties and methods from another class.
It helps reduce code duplication and supports code reuse.
Q5. What is polymorphism?
Polymorphism means one name or interface can represent different behaviours.
Java supports two common forms:
- Compile-time polymorphism through method overloading.
- Runtime polymorphism through method overriding.
Q6. What is abstraction?
Abstraction means hiding unnecessary implementation details and showing only the important features to the user.
Java supports abstraction using abstract classes and interfaces.
Q7. What is the difference between method overloading and overriding?
| Overloading | Overriding |
|---|---|
| Methods have the same name but different parameter lists. | A subclass provides its own implementation of an inherited method. |
| Usually occurs within the same class. | Occurs between a superclass and subclass. |
| Compile-time polymorphism. | Runtime polymorphism. |
Q8. What is the difference between an abstract class and an interface?
| Abstract Class | Interface |
|---|---|
| Declared using the abstract keyword. | Declared using the interface keyword. |
| Can have constructors and instance variables. | Cannot be instantiated and does not have constructors. |
| A class can extend only one class. | A class can implement multiple interfaces. |
| Can contain abstract and concrete methods. | Can contain abstract, default, static and private methods, subject to Java language rules. |
Q9. Does Java support multiple inheritance?
Java does not support multiple inheritance through classes. However, a class can implement multiple interfaces.
Q10. What is the super keyword?
The super keyword refers to the immediate parent class. It can be used to access parent class members and call a parent class constructor.
Q11. What is the this keyword?
The this keyword refers to the current object. It is commonly used to distinguish instance variables from local variables or parameters.
Q12. Can a constructor be inherited?
No. Constructors are not inherited by subclasses. A subclass can call a superclass constructor using super().
3. Strings and Arrays Interview Questions
String Questions
Q1. What is a String in Java?
A String is an object that represents a sequence of characters. Java provides the String class to work with text.
Q2. Why are Strings immutable in Java?
Immutable means an object's value cannot be changed after it is created. String objects are immutable, which helps with security, safe sharing and efficient use of the String pool.
Q3. What is the String pool?
The String pool is a special area of the heap where Java stores and reuses string literals to reduce unnecessary duplicate objects.
Q4. What is the difference between String, StringBuilder and StringBuffer?
| String | StringBuilder | StringBuffer |
|---|---|---|
| Immutable. | Mutable. | Mutable. |
| Changes create new String objects. | Can modify the same object. | Can modify the same object. |
| Not designed for synchronized modification. | Not synchronized. | Provides synchronized methods. |
Q5. How do you find the length of a String?
String name = "Java";
System.out.println(name.length());
4
Array Questions
Q6. What is an array?
An array is a data structure used to store multiple values of the same type in a fixed-size collection.
Q7. What is the index of the first element in an array?
The first element is stored at index 0. Array indexing in Java starts from zero.
Q8. How do you find the length of an array?
Use the length property of the array.
int[] numbers = {10, 20, 30, 40};
System.out.println(numbers.length);
4
Q9. What is the difference between length and length()?
length is a property used with arrays.
length() is a method used with String
objects.
Q10. Can an array store different data types?
A primitive array stores values of one declared primitive type. An object array stores references of its declared reference type, which can include different subclass objects when the declared type allows them.
4. Collections and Exception Handling Questions
Collections Interview Questions
Q1. What is the Java Collections Framework?
It is a set of interfaces and classes used to store and manage groups of objects. It provides useful data structures such as lists, sets and maps.
Q2. What is the difference between List, Set and Map?
| List | Set | Map |
|---|---|---|
| Stores elements in a sequence. | Stores unique elements. | Stores key-value pairs. |
| Allows duplicates. | Does not allow duplicate elements. | Keys must be unique. |
| Examples: ArrayList, LinkedList. | Examples: HashSet, TreeSet. | Examples: HashMap, TreeMap. |
Q3. What is the difference between ArrayList and LinkedList?
| ArrayList | LinkedList |
|---|---|
| Uses a resizable array. | Uses a doubly linked list. |
| Fast for accessing elements by index. | Accessing an element by index requires traversal. |
| Insertion in the middle may require shifting elements. | Insertion or removal can be efficient once the required position is reached. |
Q4. What is a HashMap?
HashMap is a collection class that stores data in key-value pairs. It allows one null key and multiple null values, and it does not guarantee iteration order.
Q5. What is the difference between HashSet and HashMap?
HashSet stores unique elements, while HashMap stores key-value pairs.
Exception Handling Interview Questions
Q6. What is an exception?
An exception is an event that interrupts the normal flow of a program during execution.
Q7. What is the difference between checked and unchecked exceptions?
| Checked Exception | Unchecked Exception |
|---|---|
| Checked by the compiler. | Not checked by the compiler. |
| Must be caught or declared when required by the language rules. | Does not have to be caught or declared. |
| Example: IOException. | Example: NullPointerException. |
Q8. What is the purpose of try and catch?
The try block contains code that may throw an exception. The catch block handles a matching exception so the program can respond appropriately.
Q9. What is the finally block?
The finally block is used for cleanup code. It normally executes whether an exception occurs or not, subject to situations such as JVM termination.
Q10. What is the difference between throw and throws?
| throw | throws |
|---|---|
| Used to explicitly throw an exception. | Used in a method declaration to indicate possible exceptions. |
| Used inside a method or block. | Used in a method signature. |
5. Java Output-Based Questions
Output-based questions test whether you understand how Java code executes. Try to predict the output before checking the answer.
Question 1: Increment Operator
class Main {
public static void main(String[] args) {
int a = 5;
System.out.println(a++);
System.out.println(a);
}
}
5 6
Explanation: Post-increment first uses the current value and then increases it.
Question 2: Pre-Increment
class Main {
public static void main(String[] args) {
int a = 5;
System.out.println(++a);
System.out.println(a);
}
}
6 6
Explanation: Pre-increment increases the value before using it.
Question 3: String Comparison
class Main {
public static void main(String[] args) {
String a = "Java";
String b = "Java";
System.out.println(a == b);
System.out.println(a.equals(b));
}
}
true true
Explanation: Both string literals refer to the same pooled String object. Their contents are also equal.
Question 4: Array Index
class Main {
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40};
System.out.println(arr[2]);
}
}
30
Explanation: Array indexing starts from zero. Therefore, arr[2] represents the third element.
Question 5: Static Variable
class Test {
static int count = 0;
Test() {
count++;
}
}
class Main {
public static void main(String[] args) {
new Test();
new Test();
new Test();
System.out.println(Test.count);
}
}
3
Explanation: A static variable is shared by all objects of the class. Each constructor call increases the same variable.
Question 6: String Immutability
class Main {
public static void main(String[] args) {
String name = "Java";
name.concat(" Programming");
System.out.println(name);
}
}
Java
Explanation: concat() returns a new String. The original String remains unchanged because String objects are immutable.
Question 7: Method Overloading
class Test {
void show(int a) {
System.out.println("Integer");
}
void show(String a) {
System.out.println("String");
}
}
class Main {
public static void main(String[] args) {
Test obj = new Test();
obj.show(10);
obj.show("Hello");
}
}
Integer String
Explanation: Java selects the overloaded method based on the argument type.
Question 8: Loop Execution
class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
System.out.print(i + " ");
}
}
}
1 2 4 5
Explanation: continue skips the remaining statements in the current iteration when i equals 3.
6. Important Java Coding Programs
Coding questions are an important part of technical placement interviews. Practise writing these programs without looking at the solutions.
Program 1: Reverse a Number
Example: If the number is 1234, its reverse is 4321.
class Main {
public static void main(String[] args) {
int num = 1234;
int reverse = 0;
while (num > 0) {
int digit = num % 10;
reverse = reverse * 10 + digit;
num = num / 10;
}
System.out.println(reverse);
}
}
4321
Program 2: Check Whether a Number Is Palindrome
A palindrome number remains the same when its digits are reversed. For example, 121 is a palindrome.
class Main {
public static void main(String[] args) {
int num = 121;
int original = num;
int reverse = 0;
while (num > 0) {
int digit = num % 10;
reverse = reverse * 10 + digit;
num = num / 10;
}
if (original == reverse) {
System.out.println("Palindrome");
} else {
System.out.println("Not Palindrome");
}
}
}
Palindrome
Program 3: Check Whether a Number Is Prime
A prime number is a number greater than 1 that has exactly two positive factors: 1 and itself.
class Main {
public static void main(String[] args) {
int num = 17;
boolean isPrime = num > 1;
for (int i = 2; i <= num / i; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println("Prime Number");
} else {
System.out.println("Not Prime");
}
}
}
Prime Number
Program 4: Find Factorial of a Number
Factorial means multiplying a positive integer by all positive integers smaller than it down to 1. For example, 5! = 5 × 4 × 3 × 2 × 1 = 120.
class Main {
public static void main(String[] args) {
int num = 5;
long factorial = 1;
for (int i = 1; i <= num; i++) {
factorial = factorial * i;
}
System.out.println(factorial);
}
}
120
Program 5: Print Fibonacci Series
In the Fibonacci series, each number is the sum of the previous two numbers. The series begins with 0 and 1.
class Main {
public static void main(String[] args) {
int first = 0;
int second = 1;
for (int i = 1; i <= 7; i++) {
System.out.print(first + " ");
int next = first + second;
first = second;
second = next;
}
}
}
0 1 1 2 3 5 8
Program 6: Find the Largest Element in an Array
class Main {
public static void main(String[] args) {
int[] arr = {10, 45, 20, 80, 35};
int largest = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > largest) {
largest = arr[i];
}
}
System.out.println("Largest: " + largest);
}
}
Largest: 80
Program 7: Reverse a String
class Main {
public static void main(String[] args) {
String str = "Java";
String reverse = "";
for (int i = str.length() - 1; i >= 0; i--) {
reverse = reverse + str.charAt(i);
}
System.out.println(reverse);
}
}
avaJ
Program 8: Check Whether a String Is Palindrome
A palindrome string reads the same forward and backward. For example, "madam" is a palindrome.
class Main {
public static void main(String[] args) {
String str = "madam";
String reverse = "";
for (int i = str.length() - 1; i >= 0; i--) {
reverse = reverse + str.charAt(i);
}
if (str.equals(reverse)) {
System.out.println("Palindrome");
} else {
System.out.println("Not Palindrome");
}
}
}
Palindrome
Program 9: Count Vowels in a String
class Main {
public static void main(String[] args) {
String str = "education";
int count = 0;
str = str.toLowerCase();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch == 'a' || ch == 'e' ||
ch == 'i' || ch == 'o' ||
ch == 'u') {
count++;
}
}
System.out.println("Vowels: " + count);
}
}
Vowels: 5
Program 10: Find the Sum of Array Elements
class Main {
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40};
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum = sum + arr[i];
}
System.out.println("Sum: " + sum);
}
}
Sum: 100
7. Frequently Asked Tricky Java Questions
These questions check your understanding of small but important Java rules. Read each question carefully.
Q1. Can we overload the main() method?
Yes. We can create multiple main methods with different parameter lists. However, the JVM starts a traditional standalone application using the standard main method signature.
Q2. Can we override a static method?
No. Static methods belong to the class rather than being dynamically dispatched based on the object. A subclass can hide a static method with another static method of the same signature.
Q3. Can we create an object of an abstract class?
No. We cannot directly instantiate an abstract class. However, we can create an object of a concrete subclass that extends it.
Q4. Can a constructor be private?
Yes. A private constructor prevents other classes from directly creating objects using that constructor. It is commonly used in utility classes and singleton-style designs.
Q5. Can we use this() and super() together in a constructor?
They cannot both be used as separate constructor invocations in the same constructor because either one must be the first statement.
Q6. What happens if we divide an integer by zero?
Java throws ArithmeticException when an integer is divided by zero.
int a = 10;
System.out.println(a / 0);
ArithmeticException
Note: Floating-point division by zero follows different rules and can produce Infinity or NaN.
Q7. What is the default value of an instance int variable?
The default value of an instance variable of type int is 0. Local variables do not receive automatic default values and must be initialized before use.
Q8. Can we make a class final?
Yes. A final class cannot be extended by another class. For example, the String class is final.
Q9. Can we make a method final?
Yes. A final method cannot be overridden by a subclass.
Q10. What is garbage collection?
Garbage collection is the JVM's automatic process of identifying and reclaiming memory occupied by objects that are no longer reachable.
Q11. Is Java pass-by-value or pass-by-reference?
Java is always pass-by-value. When an object is passed to a method, the value of its reference is copied. The method can use that reference to modify the object's state, but reassigning the copied reference does not change the caller's reference.
Q12. Can we have multiple catch blocks?
Yes. A try block can be followed by multiple catch blocks to handle different exception types. More specific exception types should come before more general types.
Q13. What is the difference between break and continue?
break terminates the loop or switch statement. continue skips the remaining statements in the current loop iteration and moves to the next one.
Q14. Can an interface extend another interface?
Yes. An interface can extend one or more interfaces.
Q15. What is the difference between == and equals() for objects?
== checks whether two references refer to the same object. equals() checks logical equality according to the implementation provided by the class.
8. Java Mock Interview and Final Revision
This section gives you a small mock interview to check your preparation. Try answering each question aloud as if you were sitting in front of an interviewer.
Part A: Basic Java Questions
- Introduce Java and explain its main features.
- Why is Java platform-independent?
- Explain JDK, JRE and JVM.
- What is bytecode?
- What is the purpose of the main() method?
Part B: OOPs Questions
- Explain the four pillars of OOP.
- What is the difference between a class and an object?
- Explain method overloading and overriding.
- What is the difference between an abstract class and an interface?
- Why is inheritance useful?
Part C: Java Concepts
- Why are Strings immutable?
- What is the difference between ArrayList and LinkedList?
- What is a HashMap?
- Explain checked and unchecked exceptions.
- What is multithreading?
Part D: Coding Questions
- Write a program to reverse a number.
- Write a program to check whether a number is prime.
- Write a program to find factorial of a number.
- Write a program to reverse a String.
- Write a program to find the largest element in an array.
How to Answer in an Interview
- Listen carefully to the complete question.
- Start with a simple and clear definition.
- Explain the concept in your own words.
- Give a small real-life or programming example.
- For coding questions, explain your approach before writing code.
- Test your solution with a simple example.
- If you do not know an answer, be honest and explain what you understand.
Final Java Revision Checklist
Use this checklist before attending a placement interview.
- Java basics, data types and operators
- Conditional statements and loops
- Arrays and Strings
- Methods and recursion
- Classes and objects
- Constructors and access modifiers
- Encapsulation, inheritance, polymorphism and abstraction
- Interfaces and abstract classes
- Exception handling
- Collections Framework
- Generics, lambda expressions and Stream API basics
- File handling
- Multithreading and synchronization
- Common coding programs and output-based questions
Module Summary
- Revised important Core Java concepts.
- Covered frequently asked OOP interview questions.
- Revised String and Array concepts.
- Reviewed Collections and Exception Handling.
- Practised Java output-based questions.
- Learned common placement coding programs.
- Covered tricky Java interview questions.
- Prepared a basic mock interview and revision checklist.
Final Java Practice Assignment
Before completing this course, try to solve these questions without referring to the solutions.
- Write a program to swap two numbers.
- Write a program to check whether a number is even or odd.
- Write a program to check whether a number is prime.
- Write a program to print the Fibonacci series.
- Write a program to find the factorial of a number.
- Write a program to reverse a String.
- Write a program to check whether a String is a palindrome.
- Write a program to find the second-largest element in an array.
- Create a class with private variables and getter and setter methods.
- Demonstrate inheritance using two Java classes.
- Demonstrate method overloading and overriding.
- Write a program using ArrayList.
- Write a program to handle ArithmeticException.
- Write a program to create and read a text file.
- Create two threads using the Runnable interface.
Congratulations! You Have Completed the Java Course!
You have successfully completed all 10 modules of the Allizwell Java Programming Course.
You started with the basics of programming and gradually learned Java fundamentals, arrays, strings, methods, recursion, object-oriented programming, exception handling, collections, advanced Java concepts, file handling and multithreading.
You have also revised important interview questions and practised commonly asked Java coding programs.
Keep practising, solve coding problems regularly and prepare to explain your solutions confidently. Your next step is to apply your knowledge in placement tests and technical interviews.