← Back to Interview Questions

Interview Preparation

💼 Backend & Java

Explore core Java, OOPs, system design principles, and database management challenges.

Loading questions... ⭐ View Bookmarked Questions
Question 1 of 40

No questions match your search. Try a different keyword.

All Backend & Java Interview Questions (42 total)

Here's the full list of backend and Java interview questions from the practice tool above, spanning core Java, OOP, databases, and system design fundamentals. Expand any question to read the detailed answer.

1. What is Java and what does 'platform independent' mean for it? (Easy)

Java is a general-purpose, object-oriented programming language. It is platform independent because Java source code is compiled into an intermediate format called bytecode, which can run unchanged on any device with a Java Virtual Machine (JVM), following the principle of 'write once, run anywhere'.

2. What is the JVM, JRE, and JDK, and how do they relate? (Easy)

The JVM (Java Virtual Machine) executes Java bytecode and provides platform independence. The JRE (Java Runtime Environment) bundles the JVM with core class libraries needed to run Java applications. The JDK (Java Development Kit) includes the JRE plus development tools like the compiler (javac) and debugger, needed to write and build Java programs.

3. What is the difference between primitive data types and reference data types in Java? (Easy)

Primitive types, such as int, char, boolean, and double, store actual values directly in memory and have fixed sizes defined by the language. Reference types, such as objects, arrays, and Strings, store a reference (memory address) pointing to the actual object data stored on the heap.

4. What is the difference between == and .equals() in Java? (Medium)

== compares references for objects, checking whether two variables point to the exact same memory location, while for primitives it compares actual values. .equals() is a method that can be overridden to compare the logical content of two objects, such as String.equals() comparing character sequences rather than memory addresses.

5. What is the difference between String, StringBuilder, and StringBuffer in Java? (Medium)

String is immutable, so every modification creates a new object, which can be inefficient for heavy text manipulation. StringBuilder is mutable and designed for building strings efficiently but is not thread-safe. StringBuffer is also mutable and functionally similar to StringBuilder, but its methods are synchronized, making it thread-safe at the cost of some performance.

6. What is method overloading versus method overriding in Java? (Medium)

Method overloading occurs when multiple methods in the same class share a name but differ in parameter type, number, or order; it is resolved at compile time. Method overriding occurs when a subclass provides a new implementation of a method inherited from its superclass with the same signature; it is resolved at runtime through dynamic dispatch.

7. What is the 'static' keyword used for in Java? (Easy)

The static keyword marks a member as belonging to the class itself rather than to any individual instance. Static variables are shared across all objects of a class, and static methods can be called directly on the class without creating an instance, commonly used for utility methods and constants.

8. What is the difference between an interface and an abstract class in Java? (Medium)

An abstract class can have both abstract methods (without implementation) and concrete methods, along with instance fields and constructors, but a class can only extend one abstract class. An interface traditionally only declares method signatures (though Java 8+ allows default and static methods), has no instance state, and a class can implement multiple interfaces, enabling a form of multiple inheritance.

9. What are the four main pillars of Object-Oriented Programming? (Easy)

The four pillars are encapsulation, which bundles data and methods together while restricting direct access to internal state; abstraction, which hides implementation details and exposes only essential features; inheritance, which allows a class to acquire properties and behavior from a parent class; and polymorphism, which allows the same interface or method call to behave differently depending on the object it acts upon.

10. What is encapsulation and how is it implemented in Java? (Easy)

Encapsulation is the practice of bundling an object's data and the methods that operate on it into a single unit while restricting direct access to internal state. In Java it is implemented by declaring fields as private and providing public getter and setter methods to control how that data is read or modified.

11. What is polymorphism, and what is the difference between compile-time and runtime polymorphism? (Medium)

Polymorphism allows objects of different classes to be treated through a common interface while behaving according to their actual type. Compile-time (static) polymorphism is achieved through method overloading, resolved during compilation. Runtime (dynamic) polymorphism is achieved through method overriding, resolved during execution based on the actual object type via virtual method dispatch.

12. What is inheritance in OOP and what problem does it solve? (Easy)

Inheritance allows a class (subclass) to acquire the fields and methods of another class (superclass), promoting code reuse and establishing an 'is-a' relationship between classes. It solves the problem of duplicating common logic across related classes by letting shared behavior live in a single base class.

13. What is the difference between composition and inheritance? (Medium)

Inheritance models an 'is-a' relationship where a subclass extends a superclass and inherits its implementation, which can lead to tight coupling. Composition models a 'has-a' relationship where a class contains references to other objects to reuse their functionality, generally offering more flexibility and looser coupling, which is why 'favor composition over inheritance' is a common design principle.

14. What is abstraction in OOP? (Easy)

Abstraction means exposing only the essential features of an object while hiding the internal implementation complexity. In Java it's achieved through abstract classes and interfaces, letting client code depend on what an object does rather than how it does it, which reduces coupling and makes systems easier to extend.

15. What is the Java Collections Framework? (Easy)

The Java Collections Framework is a unified architecture of interfaces, implementations, and algorithms for storing and manipulating groups of objects. Core interfaces include List, Set, Queue, and Map, with common implementations like ArrayList, HashSet, LinkedList, and HashMap, providing standardized, reusable data structures.

16. What is the difference between ArrayList and LinkedList in Java? (Medium)

ArrayList is backed by a dynamic array, offering fast O(1) random access by index but slower O(n) insertions or deletions in the middle since elements must shift. LinkedList is backed by a doubly linked list, offering fast O(1) insertions and deletions at known positions but slower O(n) random access since it must traverse nodes sequentially.

17. What is the difference between HashMap, LinkedHashMap, and TreeMap? (Medium)

HashMap stores key-value pairs with no guaranteed ordering and offers average O(1) access time. LinkedHashMap maintains insertion order while offering similar performance. TreeMap stores entries in sorted order based on the keys' natural ordering or a custom comparator, backed by a red-black tree, giving O(log n) access time.

18. What is the difference between a Set and a List in Java? (Easy)

A List is an ordered collection that allows duplicate elements and supports index-based access. A Set is a collection that does not allow duplicate elements and, in most implementations, does not guarantee a specific iteration order (though LinkedHashSet and TreeSet do provide ordering).

19. What is the difference between HashMap and Hashtable in Java? (Medium)

HashMap is not synchronized and allows one null key and multiple null values, making it faster in single-threaded contexts. Hashtable is a legacy class whose methods are synchronized, making it thread-safe but slower, and it does not allow any null keys or values.

20. What is an Iterator in Java and why is it used instead of a regular loop for collections? (Medium)

An Iterator is an object that provides a standard way to traverse a collection using hasNext() and next() methods, without exposing the collection's underlying structure. It is preferred when elements need to be removed safely during traversal via iterator.remove(), since directly modifying a collection with a for-each loop throws a ConcurrentModificationException.

21. What is exception handling in Java and what keywords are used? (Easy)

Exception handling is a mechanism for responding to runtime errors in a controlled way instead of letting the program crash. Java uses try to wrap risky code, catch to handle specific exception types, finally to run cleanup code regardless of outcome, and throw/throws to raise or declare exceptions explicitly.

22. What is the difference between checked and unchecked exceptions in Java? (Medium)

Checked exceptions, such as IOException, are checked at compile time, and a method must either handle them with try-catch or declare them with throws. Unchecked exceptions, such as NullPointerException or ArithmeticException, extend RuntimeException and are not required to be declared or caught, typically representing programming errors.

23. What is the purpose of the 'finally' block in Java? (Easy)

The finally block contains code that always executes after a try-catch block, whether or not an exception was thrown or caught, except in cases like System.exit() being called. It is typically used for cleanup tasks such as closing files, releasing database connections, or freeing other resources.

24. What is a custom exception in Java and how do you create one? (Medium)

A custom exception is a user-defined exception class created by extending Exception (for a checked exception) or RuntimeException (for an unchecked exception). It is used to represent application-specific error conditions with meaningful names and messages, improving code readability and error handling precision.

25. What is JDBC and what is it used for? (Easy)

JDBC (Java Database Connectivity) is a Java API that provides a standard way for Java applications to connect to and interact with relational databases. It allows executing SQL statements, retrieving results, and managing transactions regardless of which specific database vendor is used, as long as a compatible JDBC driver is available.

26. What are the main steps involved in connecting to a database using JDBC? (Medium)

The typical steps are: load the JDBC driver, establish a connection using DriverManager.getConnection() with a connection URL, credentials, and driver, create a Statement or PreparedStatement, execute the SQL query, process the ResultSet if applicable, and finally close the connection and related resources to free them.

27. What is the difference between Statement and PreparedStatement in JDBC? (Medium)

Statement executes static SQL queries built as plain strings, which recompiles the query each time and is vulnerable to SQL injection if user input is concatenated directly. PreparedStatement precompiles a parameterized SQL query with placeholders, improving performance for repeated execution and protecting against SQL injection by safely binding parameter values.

28. What is a ResultSet in JDBC? (Easy)

A ResultSet is an object that represents the tabular result of executing a SQL query through JDBC. It maintains a cursor pointing to the current row, and methods like next() move the cursor forward while getter methods such as getString() or getInt() retrieve column values from the current row.

29. What is the difference between SQL's WHERE and HAVING clauses? (Medium)

WHERE filters individual rows before any grouping or aggregation occurs and cannot reference aggregate functions like SUM or COUNT. HAVING filters groups after a GROUP BY clause has been applied and is specifically designed to filter based on aggregate function results.

30. What is the difference between INNER JOIN, LEFT JOIN, and RIGHT JOIN in SQL? (Medium)

INNER JOIN returns only rows that have matching values in both joined tables. LEFT JOIN returns all rows from the left table plus matched rows from the right table, filling unmatched columns with NULL. RIGHT JOIN does the reverse, returning all rows from the right table plus matched rows from the left table.

31. What is a primary key versus a foreign key in SQL? (Easy)

A primary key uniquely identifies each row in a table and cannot contain NULL or duplicate values. A foreign key is a column (or set of columns) in one table that references the primary key of another table, used to enforce referential integrity between related tables.

32. What is the difference between DELETE, TRUNCATE, and DROP in SQL? (Medium)

DELETE removes specific rows from a table based on a WHERE condition, is logged row by row, and can be rolled back. TRUNCATE removes all rows from a table quickly with minimal logging and typically resets identity counters, but generally cannot be selectively filtered. DROP removes the entire table structure, including its schema, indexes, and data, permanently.

33. What is SQL injection and how can it be prevented? (Medium)

SQL injection is a security vulnerability where an attacker inserts malicious SQL code into an input field that gets concatenated directly into a query, potentially exposing or corrupting data. It is prevented primarily by using parameterized queries or prepared statements instead of string concatenation, along with input validation and the principle of least privilege for database accounts.

34. What is database normalization? (Medium)

Normalization is the process of organizing a relational database's tables and columns to reduce data redundancy and improve data integrity. It involves dividing large tables into smaller related ones and defining relationships between them, typically following a series of rules called normal forms (1NF, 2NF, 3NF, and beyond).

35. What is the difference between a relational database and a NoSQL database? (Medium)

A relational database stores data in structured tables with predefined schemas and relationships enforced through foreign keys, using SQL for queries, examples being MySQL and PostgreSQL. A NoSQL database stores data in flexible formats such as documents, key-value pairs, or graphs without a rigid schema, often prioritizing horizontal scalability, examples being MongoDB and Redis.

36. What is an index in a database and why is it useful? (Medium)

An index is a data structure, typically a B-tree, that a database maintains on one or more columns to speed up data retrieval. Instead of scanning every row (a full table scan) to find matching data, the database can use the index to quickly locate relevant rows, though indexes add some overhead to write operations.

37. What does ACID stand for in the context of databases? (Medium)

ACID stands for Atomicity, Consistency, Isolation, and Durability, the four properties that guarantee reliable transaction processing. Atomicity ensures a transaction fully completes or fully fails, Consistency ensures data remains valid according to constraints, Isolation ensures concurrent transactions don't interfere with each other, and Durability ensures committed changes survive system failures.

38. What is a database transaction? (Easy)

A transaction is a sequence of one or more database operations that are executed as a single logical unit of work, following the all-or-nothing principle. If any operation within the transaction fails, the entire transaction is rolled back, ensuring the database remains in a consistent state.

39. What is the Spring Framework? (Easy)

Spring is a widely used Java framework that simplifies enterprise application development by providing infrastructure support such as dependency injection, transaction management, and integration with data access and web technologies. It promotes building loosely coupled, testable applications through inversion of control.

40. What is dependency injection and how does Spring implement it? (Medium)

Dependency injection is a design pattern where an object's dependencies are supplied by an external source rather than the object creating them itself, reducing tight coupling. Spring implements this through its IoC (Inversion of Control) container, which creates and wires beans together automatically based on annotations like @Autowired or XML configuration.

41. What is a Spring Bean? (Easy)

A Spring Bean is an object that is instantiated, configured, and managed by the Spring IoC container. Beans are typically defined using annotations such as @Component, @Service, or @Repository, or through explicit configuration classes, and the container handles their entire lifecycle, including dependency injection.

42. What is Spring Boot and how does it differ from the core Spring Framework? (Medium)

Spring Boot is built on top of the core Spring Framework and is designed to simplify application setup through auto-configuration, embedded servers like Tomcat, and opinionated default settings, minimizing the amount of boilerplate configuration required. Core Spring, by contrast, typically requires more manual configuration of beans, servers, and dependencies.