Java & SQL Interview Preparation Guide for Freshers: 25 Questions, Examples & Practice Tips
Getting ready for a software development, testing, support, or data-related interview can feel difficult when you don't know which technical topics to revise first.
For many entry-level roles, interviewers may ask about programming fundamentals, object-oriented programming, collections, exceptions, databases, SQL queries, and basic problem-solving.
This guide focuses on 25 practical Java and SQL questions that can help freshers revise important concepts before a technical interview.
The goal is not to memorize definitions word-for-word. Instead, use each question to understand the concept, study the example, and practice explaining it in your own words.
Part 1: Core Java Fundamentals
1. What are the four main principles of Object-Oriented Programming?
The four commonly discussed principles of Object-Oriented Programming (OOP) are:
Encapsulation
Encapsulation means keeping data and the methods that operate on that data together inside a class while controlling direct access to internal state.
For example:
class Employee { private String name; public void setName(String name) { this.name = name; } public String getName() { return name; } }
Here, name is private and is accessed through methods.
Abstraction
Abstraction means exposing the important behavior of an object while hiding implementation details.
For example, a user can call:
car.start();
without needing to know every internal operation involved in starting the engine.
Inheritance
Inheritance allows one class to reuse accessible properties and behavior from another class.
class Animal { void eat() { System.out.println("Eating"); } } class Dog extends Animal { void bark() { System.out.println("Barking"); } }
Dog inherits the eat() method from Animal.
Polymorphism
Polymorphism allows the same interface or method name to represent different behavior depending on the situation.
Two common examples are:
- Method overloading
- Method overriding
2. What is the difference between == and .equals() in Java?
The answer depends on what you are comparing.
For object references, == checks whether two references refer to the same object.
The .equals() method is intended to compare logical equality when a class provides an appropriate implementation.
Example:
String first = new String("Java"); String second = new String("Java"); System.out.println(first == second); System.out.println(first.equals(second));
The first comparison checks the references, while the second checks the string contents because String overrides equals().
Interview tip
A good answer is:
"
==compares primitive values directly and object references for reference equality..equals()is a method used for logical equality when the class defines it accordingly."
3. Why is String immutable in Java?
A String object cannot be changed after it has been created.
For example:
String language = "Java"; language = language + " Programming";
The original "Java" string is not modified. A new string value is produced and the variable is reassigned.
String immutability is useful for several reasons, including:
- Safe sharing of string objects
- Predictable behavior
- Use as keys in hash-based collections
- Easier handling when strings are shared between different parts of a program
Simple way to remember
String → immutable
StringBuilder → mutable
StringBuffer → mutable with synchronized methods
4. What is the difference between String, StringBuilder and StringBuffer?
| Feature | String | StringBuilder | StringBuffer |
|---|---|---|---|
| Mutable | No | Yes | Yes |
| Main use | Text that does not need modification | Frequent string modifications | Mutable text where synchronized methods are required |
| Typical performance for repeated changes | Less suitable | Generally preferred in single-threaded use | Synchronization can add overhead |
| Example | "Java" | new StringBuilder() | new StringBuffer() |
Example:
StringBuilder builder = new StringBuilder("Java"); builder.append(" Interview"); System.out.println(builder);
The StringBuilder object can be modified without creating a new immutable String for every append operation.
5. What is the difference between method overloading and method overriding?
Method Overloading
Overloading means having multiple methods with the same name but different parameter lists within a class or related context.
class Calculator { int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; } }
The compiler determines which overloaded method matches the arguments.
Method Overriding
Overriding occurs when a subclass provides its own implementation of an inherited method.
class Animal { void sound() { System.out.println("Animal sound"); } } class Dog extends Animal { @Override void sound() { System.out.println("Bark"); } }
Easy interview distinction
Overloading → same method name, different parameters
Overriding → subclass provides a new implementation
6. What is the difference between an abstract class and an interface?
Both can be used to define abstractions, but they serve different purposes.
| Feature | Abstract Class | Interface |
|---|---|---|
| Declared with | abstract class | interface |
| Constructors | Can have constructors | Cannot be instantiated and does not have constructors like a class |
| Instance state | Can contain instance fields | Fields are constants |
| Methods | Can contain abstract and concrete methods | Can declare abstract methods and also provide default/static methods |
| Inheritance | A class can extend one class | A class can implement multiple interfaces |
Example:
interface Printable { void print(); } class Report implements Printable { public void print() { System.out.println("Printing report"); } }
Interview tip
Don't simply say “interfaces are for multiple inheritance.”
A better explanation is that interfaces define a contract that classes can implement, and a class can implement multiple interfaces.
7. What are the main Java Collection types?
The Java Collections Framework provides commonly used structures for storing and working with groups of objects.
Some important interfaces include:
-
List -
Set -
Queue -
Map
Examples:
List → ArrayList, LinkedList Set → HashSet, TreeSet Queue → PriorityQueue, ArrayDeque Map → HashMap, TreeMap
One important point for interviews:
Map is part of the Java Collections Framework, but Map does not extend the Collection interface.
8. What is the difference between ArrayList and LinkedList?
| Feature | ArrayList | LinkedList |
|---|---|---|
| Basic structure | Resizable array | Doubly linked list |
| Random access | Efficient | Generally slower |
| Insertion/removal in middle | May require shifting elements | Can be efficient once the position/node is located |
| Memory overhead | Generally lower | Generally higher due to node links |
Example:
List<String> names = new ArrayList<>(); names.add("Ravi"); names.add("Priya"); names.add("Anil");
For most everyday list usage, ArrayList is a common starting choice. The correct choice still depends on the access and modification pattern of the application.
9. What is a HashMap?
HashMap stores data as key-value pairs.
Example:
Map<Integer, String> employees = new HashMap<>(); employees.put(101, "Ravi"); employees.put(102, "Priya"); System.out.println(employees.get(101));
Here:
101 → Ravi 102 → Priya
A key is used to retrieve its associated value.
Interview points
Remember these basic concepts:
- Data is stored using key-value pairs.
- Keys are unique within the map.
-
A
HashMappermits a null key and null values. - It does not guarantee iteration order.
For a fresher interview, understanding these fundamentals is more useful than memorizing internal implementation details.
10. What is the difference between checked and unchecked exceptions?
Checked exceptions
Checked exceptions are checked by the compiler.
For example:
import java.io.FileReader; import java.io.IOException; class Example { void readFile() throws IOException { FileReader file = new FileReader("data.txt"); } }
The code must deal with the checked exception through handling or declaration.
Unchecked exceptions
Unchecked exceptions are generally subclasses of `RuntimeException.
Examples include:
-
NullPointerException -
ArithmeticException -
ArrayIndexOutOfBoundsException
Interview tip
Don't say unchecked exceptions are always caused by “programming mistakes” as an absolute rule.
Instead:
Checked exceptions are subject to compile-time checking, while unchecked exceptions are subclasses of
RuntimeExceptionand are not required to be declared or caught by the compiler.
Part 2: SQL Fundamentals
11. What are DDL, DML, DCL and TCL?
These terms are commonly used to group SQL commands.
DDL — Data Definition Language
Used to define or modify database structures.
Examples:
CREATE ALTER DROP TRUNCATE
DML — Data Manipulation Language
Used to work with data.
Examples:
INSERT UPDATE DELETE
SELECT is commonly categorized separately as DQL (Data Query Language), although terminology can vary by source.
DCL — Data Control Language
Used for permissions and access control.
Examples:
GRANT REVOKE
TCL — Transaction Control Language
Used for transaction-related operations.
Examples:
COMMIT ROLLBACK SAVEPOINT
12. What is the difference between DELETE, TRUNCATE and DROP?
| Command | What it does |
|---|---|
DELETE | Removes rows from a table, optionally using a WHERE condition |
TRUNCATE | Removes all rows from a table |
DROP | Removes the table itself, including its structure |
Example:
DELETE FROM Employees WHERE department = 'HR';
This removes matching rows.
TRUNCATE TABLE Employees;
This removes all rows while retaining the table structure.
DROP TABLE Employees;
This removes the table itself.
Important
Exact transaction, identity-reset, locking, and rollback behavior can differ between database systems. In an interview, it is better to mention the general distinction rather than make a database-specific behavior sound universal.
13. What is the difference between a Primary Key, Unique Key and Foreign Key?
Primary Key
A primary key identifies a row in a table.
Example:
CREATE TABLE Employees ( employee_id INT PRIMARY KEY, name VARCHAR(100) );
Unique Key / UNIQUE constraint
A UNIQUE constraint prevents duplicate values for the constrained column or column combination, subject to the database's handling of NULL.
Example:
CREATE TABLE Employees ( employee_id INT PRIMARY KEY, email VARCHAR(150) UNIQUE );
Foreign Key
A foreign key creates a relationship between tables by referencing a key in another table.
CREATE TABLE Departments ( department_id INT PRIMARY KEY, department_name VARCHAR(100) ); CREATE TABLE Employees ( employee_id INT PRIMARY KEY, department_id INT, FOREIGN KEY (department_id) REFERENCES Departments(department_id) );
14. What are SQL JOINs?
A JOIN combines related rows from multiple tables.
INNER JOIN
Returns rows where the join condition matches in both tables.
SELECT e.name, d.department_name FROM Employees e INNER JOIN Departments d ON e.department_id = d.department_id;
LEFT JOIN
Returns all rows from the left table and matching rows from the right table.
SELECT e.name, d.department_name FROM Employees e LEFT JOIN Departments d ON e.department_id = d.department_id;
If there is no matching department, columns from the right table can contain NULL.
RIGHT JOIN
Returns all rows from the right table and matching rows from the left table.
CROSS JOIN
Produces the Cartesian product of the two tables.
For example, if one table has 3 rows and another has 4 rows, a cross join can produce 12 combinations.
Interview tip
For fresher interviews, focus especially on:
INNER JOIN + LEFT JOIN
and understand why NULL can appear in the result of a LEFT JOIN.
15. What is the difference between WHERE and HAVING?
WHERE filters individual rows before grouping.
HAVING filters groups after aggregation.
Example:
SELECT department_id, AVG(salary) AS average_salary FROM Employees WHERE status = 'Active' GROUP BY department_id HAVING AVG(salary) > 50000;
Here:
-
WHEREremoves inactive employees before grouping. -
GROUP BYcreates department groups. -
HAVINGkeeps only groups whose average salary is above 50,000.
Easy way to remember
WHERE → rows
HAVING → groups
16. What is GROUP BY used for?
GROUP BY combines rows with the same values in selected columns so aggregate functions can be applied to each group.
Example:
SELECT department_id, COUNT(*) AS employee_count FROM Employees GROUP BY department_id;
This can produce the number of employees in each department.
Common aggregate functions include:
COUNT() SUM() AVG() MIN() MAX()
17. How do you handle NULL values in SQL?
NULL means a value is missing or unknown. It should not normally be compared using:
column = NULL
Instead, use:
column IS NULL
or:
column IS NOT NULL
Example:
SELECT employee_name FROM Employees WHERE phone_number IS NULL;
You can also use functions such as COALESCE() where supported:
SELECT employee_name, COALESCE(phone_number, 'Not Provided') AS contact FROM Employees;
This replaces a NULL result with the supplied fallback value.
18. What is a subquery in SQL?
A subquery is a query placed inside another SQL statement.
Example:
SELECT employee_name, salary FROM Employees WHERE salary > ( SELECT AVG(salary) FROM Employees );
The inner query calculates the average salary.
The outer query then returns employees whose salary is above that average.
When can subqueries be useful?
They can help when one query needs the result of another query as part of its filtering or calculation.
19. How do you find duplicate records in SQL?
Suppose you want to identify duplicate email addresses.
SELECT email, COUNT(*) AS total FROM Users GROUP BY email HAVING COUNT(*) > 1;
The GROUP BY creates one group for each email.
The HAVING condition then keeps only emails appearing more than once.
Important
Finding duplicates and deleting duplicates are different tasks.
Before deleting anything from a real database, determine which record should be retained and verify the result first.
20. How do you find the second-highest salary?
One approach is:
SELECT MAX(salary) AS second_highest FROM Employees WHERE salary < ( SELECT MAX(salary) FROM Employees );
This returns the highest salary that is lower than the overall highest salary.
Another common approach is:
SELECT DISTINCT salary FROM Employees ORDER BY salary DESC LIMIT 1 OFFSET 1;
The exact syntax for limiting rows differs between database systems.
Interview tip
Always clarify whether the interviewer wants:
- second-highest distinct salary, or
- the second row after sorting salaries.
Those are not necessarily the same thing when duplicate salaries exist.
Part 3: Practical Java Interview Questions
21. What is the difference between final, finally and finalize()?
These three terms are unrelated despite their similar names.
final
A keyword used to restrict modification.
Examples:
final int age = 25;
The variable cannot be reassigned.
A final method cannot be overridden, and a final class cannot be extended.
finally
A block associated with exception handling.
try { System.out.println("Processing"); } finally { System.out.println("Cleanup"); }
The finally block is generally used for cleanup that should occur after the associated try operation.
finalize()
finalize() was an old mechanism associated with garbage collection and object cleanup.
It has been deprecated and should not be used for modern resource management.
Interview answer
final → keyword
finally → exception-handling block
finalize() → deprecated legacy method
22. What is the difference between a process and a thread?
A process is an executing program with its own process-level resources and address space.
A thread is an execution path within a process.
Multiple threads in the same process can share process resources while maintaining their own execution state, such as a stack.
Simple example
Think about a web browser:
- The browser application runs as one or more processes.
- Individual threads can perform different tasks within those processes.
Interview tip
Avoid saying:
“A thread is a small process.”
A better answer is:
“A thread is an execution unit within a process, and multiple threads can operate within the same process while sharing its resources.”
23. What are Generics in Java?
Generics allow classes, interfaces and methods to work with specified types while providing compile-time type checking.
Example:
List<String> names = new ArrayList<>(); names.add("Ravi"); names.add("Priya");
Because the list is declared as List<String>, the compiler can detect attempts to add an incompatible type.
Without generics, more explicit casting could be required when retrieving objects.
Simple interview answer
Generics improve type safety and reduce unnecessary casting when working with collections and other parameterized types.
24. What are functional interfaces and lambda expressions?
A functional interface is an interface intended to represent a single abstract method.
Example:
@FunctionalInterface interface Calculator { int add(int a, int b); }
A lambda expression can provide an implementation:
Calculator calculator = (a, b) -> a + b; System.out.println(calculator.add(10, 20));
Lambda expressions provide a concise way to represent behavior that can be passed around as a value.
Common Java functional interfaces include:
Predicate Function Consumer Supplier
25. What is the Java Stream API?
The Stream API provides a way to process sequences of data using operations such as filtering, mapping and collecting.
Example:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6); List<Integer> evenSquares = numbers.stream() .filter(n -> n % 2 == 0) .map(n -> n * n) .collect(Collectors.toList());
The result is:
[4, 16, 36]
The important concepts to understand are:
-
filter()→ selects elements -
map()→ transforms elements -
sorted()→ sorts elements -
collect()→ gathers the result
Interview tip
Don't just memorize the method names. Practice explaining the flow:
Take the numbers → keep the even ones → square them → collect the results.
How to Prepare for Java & SQL Interviews
Knowing definitions is useful, but technical interviews often require you to explain your thinking.
Use the following approach while preparing.
1. Understand before memorizing
For every concept, ask yourself:
- What does it mean?
- Why is it used?
- When would I use it?
- Can I give a simple example?
For example, don't only memorize:
“A LEFT JOIN returns all rows from the left table.”
Understand what happens when there is no matching row on the right side.
2. Write code yourself
Don't only read Java code from interview articles.
Open a Java editor or IDE and type small programs yourself.
Practice:
Loops Arrays Strings Classes Inheritance Collections Exception handling Streams
For SQL, create a small sample database and practice:
SELECT WHERE GROUP BY HAVING JOIN Subqueries Aggregate functions Duplicate detection
3. Practice explaining answers aloud
A technically correct answer can still be difficult to follow if you cannot explain it clearly.
Try this format:
Definition → Example → Practical use
For example:
“A LEFT JOIN keeps every row from the left table. If there is a matching row in the right table, its information is included. If there isn't one, the right-side columns can be NULL. It is useful when I need all records from my main table even when related data may be missing.”
That is much stronger than memorizing one sentence.
A Simple 7-Day Java & SQL Revision Plan
If your interview is approaching, you can divide preparation into seven focused days.
Day 1 — Java Basics
Revise:
- OOP
- Classes and objects
-
==vs.equals() - Strings
- Methods
- Constructors
Practice a few small Java programs.
Day 2 — Collections
Focus on:
- List
- Set
- Map
- ArrayList
- LinkedList
- HashMap
Write small programs using each.
Day 3 — Exceptions & Modern Java
Revise:
- Checked and unchecked exceptions
-
try-catch-finally - Generics
- Functional interfaces
- Lambda expressions
- Streams
Day 4 — SQL Basics
Practice:
SELECT WHERE ORDER BY GROUP BY HAVING DISTINCT NULL handling
Day 5 — SQL Joins & Subqueries
Practice:
- INNER JOIN
- LEFT JOIN
- RIGHT JOIN
- Subqueries
- Aggregate functions
Use small sample tables rather than only reading theory.
Day 6 — Query Practice
Try writing queries for:
- Maximum salary
- Second-highest salary
- Duplicate records
- Employee counts by department
- Employees above average salary
- Employees without a matching department
Day 7 — Mock Interview
Pick random questions and answer them without looking at the article.
For coding questions:
- Understand the problem.
- Explain your approach.
- Write the solution.
- Test it with an example.
- Discuss possible edge cases.
Common Mistakes Freshers Make
1. Memorizing definitions without understanding them
Interviewers may change the wording of a question. Understanding the concept makes it easier to answer.
2. Writing code without explaining the approach
Explain what you are trying to do before jumping into the code.
3. Ignoring SQL practice
Reading SQL syntax is not enough. Write queries yourself.
4. Not checking edge cases
For example, when finding the second-highest salary, ask what should happen if:
- There is only one employee.
- Multiple employees have the highest salary.
- Several employees have the second-highest salary.
-
Salary contains
NULL.
5. Trying to sound more advanced than you are
If you don't know something, don't invent an answer.
It is better to say:
“I haven't worked with that concept yet, but I understand the basics and I'm currently learning it.”
Clear and honest communication is better than giving an incorrect technical explanation.
Final Java & SQL Interview Checklist
Before your interview, make sure you can comfortably explain:
Java
☐ OOP principles
☐ == vs .equals()
☐ String immutability
☐ StringBuilder and StringBuffer
☐ Overloading vs overriding
☐ Abstract class vs interface
☐ Collections
☐ ArrayList vs LinkedList
☐ HashMap
☐ Exceptions
☐ Generics
☐ Lambda expressions
☐ Stream API
SQL
☐ SELECT and filtering
☐ GROUP BY
☐ HAVING
☐ Aggregate functions
☐ JOINs
☐ Primary and foreign keys
☐ NULL handling
☐ Subqueries
☐ Duplicate records
☐ Second-highest salary
Interview Skills
☐ Explain your approach before coding
☐ Write small programs without relying entirely on autocomplete
☐ Test your solution with sample input
☐ Explain why you selected a particular approach
☐ Ask for clarification when a question is ambiguous
☐ Be honest about concepts you haven't worked with
Final Thoughts
You do not need to memorize every possible Java or SQL interview question.
A better approach is to build a strong understanding of the fundamentals and then practice applying them to small problems.
When you can explain a concept, write a simple example, and describe when you would use it, you are much better prepared than someone who has only memorized definitions.
Use this guide as a revision checklist, then spend most of your preparation time writing Java programs and SQL queries yourself.
Good luck with your preparation.
Important Note
This guide is intended for educational and interview-preparation purposes. Java and SQL behavior can vary depending on the Java version, database system, configuration, and implementation. Always refer to the documentation for the specific technology you are using when working on a real project.
Last reviewed: September 2026
Social Plugin