[Most Asked] Java Interview Questions and Answers FAQs

Java Interview Questions

1. What is Java?

Java is a high-level, object-oriented programming language. It is a general-purpose language that is class-based and designed to have as few implementation dependencies as possible.

2. What are the main features of Java?

Some key features of Java are:

  • Object-oriented – Everything in Java is an object. Java supports all concepts of OOPs like Abstraction, Encapsulation, Inheritance, and Polymorphism.
  • Platform independent – Java code can run on any platform like Windows, Linux, Mac etc.
  • Simple – Java syntax is simple, clean and easy to understand.
  • Secure – Java provides security features like (i) No explicit pointer (ii) Exception handling (iii) Automatic garbage collection etc.
  • Robust – Java makes an effort to eliminate error-prone situations by emphasizing mainly on compile-time error checking and runtime checking.

3. What are arrays in Java?

Arrays in Java are dynamically allocated collections of homogeneous data elements. Each element in an array is accessed via its index.

Arrays have the following properties:

  • Fixed size at declaration
  • Can contain primitives or object references
  • Elements can be accessed and updated using index
  • Stores elements in contiguous/adjacent memory locations

4. What is JVM and why is Java called a platform independent language?

JVM stands for Java Virtual Machine. It is a runtime environment that converts Java bytecode into machine language and executes it.

Java is called platform independent because its compiled bytecode can run on all platforms/OS that have JVM without recompilation.

5. What are the differences between JDK, JRE and JVM?

  • JDK – Java Development Kit used to develop Java programs. Includes JRE + development tools like javac, java docs etc.
  • JRE – Java Runtime Environment provides runtime environment to execute Java code. Includes set of libraries + other files that JVM uses at runtime.
  • JVM – Java Virtual Machine executes the Java bytecode. Provides runtime environment to run Java code. Part of JRE.

Java Interview Questions

6. What is the purpose of garbage collection in Java?

The purpose of garbage collection in Java is to:

  • Free up memory by deleting unused objects
  • Avoid memory leaks
  • Ensure there are no dangling references to unused objects
  • Improve efficiency by reusing memory allocated to discarded objects

This helps programmers focus on application logic rather than worrying about memory management.

7. What is method overloading and overriding in Java?

Method overloading – When two or more methods in the same class have the same name but different parameters.

Method overriding – When a sub class provides a specific implementation of a method already defined in its super class. The method must have the same name, parameters and return type.

8. What is an abstract class in Java?

An abstract class in Java is a class that cannot be instantiated and is only to be subclassed. An abstract class may contain abstract methods that must be implemented by subclasses. Abstract classes allow related classes to share common code.

Key properties:

  • Cannot be instantiated directly
  • May contain abstract methods without body
  • Regular non-abstract methods can also be there
  • Constructors can be there

9. What is the difference between abstract classes and interfaces in Java?

Abstract Classes Interfaces
Can have constructors Cannot have constructors
Can have non-abstract and abstract methods Can only have public abstract methods
Can have instance variables Cannot have instance variables
Can extend only one abstract or regular class Can extend multiple interfaces using “implements” keyword

10. What are the access modifiers in Java?

The access modifiers in Java are:

  • public – accessible from any class
  • protected – accessible within package and subclasses
  • default (no modifier) – accessible within package only
  • private – accessible within the declaring class only

11. What is encapsulation in Java?

Encapsulation in Java refers to the bundling of related data and associated methods into a single class. Getter and setter methods are used to access and update the data indirectly.

The key benefit is that class internals are protected from unintended access and modification. This improves flexibility, reusability and maintainability of code.

12. What is inheritance in Java?

Inheritance in Java allows a derived class (subclass) to inherit visible attributes and methods from a base class (superclass). The subclass can then add its own methods and attributes in addition to the inherited ones.

This enables reuse of common logic and promotes abstraction by establishing hierarchical relationships between classes.

13. What is method overriding in Java?

Method overriding in Java occurs when a subclass has a method with same name, parameters and return type as a method in its superclass.

When the method is called from a subclass object, the version in the subclass is executed, instead of the superclass version.

14. What is exception handling in Java?

Exception handling in Java provides a robust mechanism to handle runtime errors and anomalous situations in your program. The key components involved in exception handling are:

  • try block – code that may throw exception
  • catch block – handles the exception thrown in try block
  • throw keyword – explicitly throws an exception
  • throws keyword – specifies exceptions thrown by a method
  • finally block – executes code after try/catch regardless of exception

This enables graceful recovery from errors and continuation of program execution.

15. What are the differences between checked and unchecked exceptions?

Checked Exceptions Unchecked Exceptions
Extend Exception class (compile-time exceptions) Extend RuntimeException
Must be caught or declared with throws clause Need not be caught or declared
Examples – IOException, SQLException etc Examples – NullPointerException, ArithmeticException etc

16. What is the purpose of finally block in Java?

The finally block in Java executes always, after try and catch blocks, regardless of whether an exception was thrown or not.

The key purposes of finally block are:

  • Release resources like file handles used in try block
  • Execute clean up code like closing connections
  • Execute critical code that needs to run even after exceptions

17. What is multithreading in Java?

Multithreading in Java allows concurrently executing multiple threads sharing the same JVM and process resources.

Threads represent independent paths of execution sharing common computing resources. This improves utilization of available CPU time.

18. How do you create a thread in Java?

There are two ways to create a thread in Java:

  1. By extending Thread class
    • Create a class that extends Thread class
    • Override run() method with thread task code
    • Create instance and invoke start()
  2. By implementing Runnable interface
    • Create a class that implements Runnable interface
    • Implement run() method with thread task code
    • Pass instance to Thread constructor and invoke start()

19. What is the difference between sleep() and wait() methods?

sleep() wait()
Static method of Thread class Instance method of Object class
Puts thread in sleep for specified interval Puts thread in waiting state for notification
Does not release lock Releases lock held by thread

20. What are JAR files in Java?

JAR stands for Java ARchive. It is used to bundle multiple Java class files, associated metadata and resources into one file.

JAR files allow:

  • Compression – Reduces file size
  • Aggregation – Combines multiple files
  • Deployment – Distribute Java apps as single JAR file
  • Faster download – Only single file to be downloaded

21. What is the difference between ArrayList and LinkedList?

ArrayList LinkedList
Implements List interface Implements List and Deque interfaces
Backed by array data structure Backed by doubly linked list data structure
Better performance for random access Better performance for add/remove operations
Stores elements contiguously Elements stored as nodes connected by pointers

22. What is the difference between HashMap and HashTable in Java?

HashMap Hashtable
Non synchronized Synchronized
Permits null keys and values Does not permit null keys or values
Faster performance Slower performance due to thread safety
Introduced in JDK 1.2 Legacy class from JDK 1.0
Backed by linked list chaining Backed by array
Default capacity 16, load factor 0.75 Default capacity 11, load factor 0.75

23. What are the differences between Heap and Stack memory in Java?

Heap Stack
Larger memory Smaller memory
Stores objects and reference variables Stores local variables and call stack
Access is slower Access is faster
Memory allocated during runtime Fixed memory allocated at compile time
Controlled by JVM through garbage collector Controlled by thread calls in LIFO manner

24. What is serialization and deserialization in Java?

Serialization is the process of converting an object into a stream of bytes in order to store it into memory, file or database.

Deserialization is the reverse process of creating an object from a stream of bytes.

Key classes involved are:

  • ObjectOutputStream and ObjectInputStream
  • Serializable interface

25. What is the difference between final, finally and finalize in Java?

  • final – modifier, can be applied to class, method or variable. Declares class cannot be inherited, method cannot be overridden and value of variable cannot change.
  • finally – block always executes after a try/catch block completes execution. Used to release resources.
  • finalize – method called by garbage collector on object before being garbage collected. Used to perform cleanup.

26. What are some Java Collections Framework interfaces and classes?

Some commonly used Java Collections Framework interfaces and classes are:

Interfaces

  • Collection – Root interface
  • List – Ordered collection of elements
  • Set – Unique elements
  • Queue – Specifically for holding elements prior to processing
  • Deque – Double ended queue
  • Map – Key-value pairs

Classes

  • ArrayList, LinkedList
  • HashSet, LinkedHashSet, TreeSet
  • PriorityQueue
  • ArrayDeque
  • HashMap, LinkedHashMap, TreeMap

27. What are anonymous inner classes in Java?

Anonymous inner classes enable you to instantiate an interface or abstract class, and define its methods right inline without having to explicitly create a class file.

These provide a way to implement simple lightweight classes needed only locally within a single method.

28. What is Object class in Java and why is it special?

Object class in Java is the parent class of all classes. When a class does not extend any other class then it implicitly extends Object.

It defines common behaviors like equals(), hashCode(), toString() etc that all objects need to have. Since it is a base class, its methods can be called on any Java object.

29. What is Marker interface in Java?

A marker interface is an empty interface in Java used to provide metadata to inform the compiler or JVM about some special behavior. Some marker interfaces are:

  • Serializable – Enables an object to be converted to bytes for storage
  • Cloneable – Permits object to be cloned
  • Remote – Indicating object can be serialized for remote method calls

30. What is difference between throw and throws in Java?

throw throws
Used within method body to explicitly throw exception Declared in method signature to indicate exceptions that may be thrown by the method
Followed by instance creation e.g. throw new IOException() Followed by class names e.g. public void method() throws IOException
Transfers control out of the method Does not explicitly throw exception

31. What are the differences between Heap and Stack memory in Java?

Heap Stack
Larger memory Smaller memory
Stores objects and reference variables Stores local variables and call stack
Access is slower Access is faster
Memory allocated during runtime Fixed memory allocated at compile time
Controlled by JVM through garbage collector Controlled by thread calls in LIFO manner

32. What is Autoboxing and Unboxing in Java?

Autoboxing is automatic conversion of primitive data types into their corresponding object wrapper classes.

For example, int to Integer, long to Long, float to Float etc. This happens when a primitive is passed as parameter to a method that expects an object.

Unboxing is the reverse process of automatic conversion from wrapper object to primitive data type. This occurs when an object is passed to a method that expects a primitive data type.

33. What are Java annotations and some common annotations?

Java annotations provide metadata about code that is not part of the program itself. They have no direct effect on operation.

Some common annotations are:

  • @Override – Indicates current method overrides superclass method
  • @Deprecated – Indicates method is outdated and should not be used
  • @SuppressWarnings – Disables compile time warnings
  • @FunctionalInterface – Indicates interface has exactly one abstract method

34. What is reflection in Java?

Reflection in Java is the ability to inspect and dynamically call classes, methods, attributes etc at runtime. No compile time knowledge is required.

Key classes that enable this are Class, Field, Method and Constructor. Using reflection improves flexibility but lowers performance.

35. What are generics in Java?

Java generics enable types (classes and interfaces) to be parameters when defining classes, methods, interfaces, and variables. The key benefit is reusability and type safety of code.

For example, ArrayList<String> accepts only Strings while ArrayList<Integer> accepts only Integers.

36. What are the advantages of packages in Java?

Advantages of packages in Java are:

  • Modularization – Logical grouping of related classes and interfaces
  • Manage namespace – Avoid name collisions between classes in different modules
  • Access control – Can restrict access using access modifiers
  • Reusability – Classes packaged for reuse without modification

37. What is JDBC in Java?

JDBC (Java Database Connectivity) is the Java API to connect and execute queries to a database from a Java program.

The key components involved are:

  • JDBC driver – Enables connection to database
  • Connection object – Represents connection
  • Statement and PreparedStatement – Execute queries
  • ResultSet – Represents query result set

38. What is Java building block?

The building blocks of Java are:

  • Class – Blueprint that defines attributes and behaviors
  • Object – Instance of a class created at runtime
  • Method – Block of code representing behavior
  • Variable – Stores data/state in an object
  • Constructor – Special method that initializes new objects

39. What is a Java package and why is it used?

A Java package is a namespace that organizes Java classes and interfaces into logical groups. Packages are declared using the package keyword.

Some key uses of packages are:

  • Modularization – Logical grouping of related classes
  • Avoid naming collisions – Classes in different packages can have same names
  • Access control – Control class and interface visibility
  • Reusability – Package once for reuse across projects

40. What are access specifiers in Java?

Access specifiers in Java control accessibility of classes, interfaces, constructors, methods and field members. The four access specifiers are:

  • public – Accessible from any class
  • protected – Accessible within package and subclasses
  • default – When no specifier, accessible within package only
  • private – Accessible within declaring class only

41. What is static in Java?

The static keyword in Java is used to denote a fixed value or attribute shared across all instances of a class. They can be used on variables, methods, blocks and nested classes.

Static attributes exist only once per class. Static methods can be invoked without an object.

42. What is final in Java?

The final keyword in Java is used to restrict changes to classes, methods and variables.

A final class cannot be inherited, final method cannot be overridden and value of final variable cannot change once assigned.

Final attributes are useful for constants e.g. final float PI = 3.14F;

43. What is a constructor in Java?

A constructor in Java is a special method that is invoked automatically when an object of a class is instantiated.

It initializes the state of the object using available data. Every class has a constructor, if not explicitly defined a default one is provided.

44. What is singleton class in Java and how can we make a class singleton?

A singleton class in Java allows only one instance of the class to be created and gives global point of access. A class can be made singleton by:

  • Making constructor private
  • Providing a static method that returns the instance
  • Providing a global access point to the static instance

45. How can you achieve thread safety in Java?

Some ways to achieve thread safety in Java are:

  • Synchronized keyword on critical sections
  • Volatile keyword for thread visibility of field
  • Atomic classes for thread safe operations
  • Lock interface to explicitly lock critical section
  • Concurrent data structures that internally handle synchronization

46. What is Java Virtual Machine (JVM)?

The Java Virtual Machine (JVM) is the abstract computing machine that enables portability of Java programs. It converts Java bytecode into machine language and executes them at runtime.

JVMs are available for many hardware and software platforms. Since JVM sits between platform and Java code, Java programs can run on any platform.

47. What is the difference between path and classpath variables?

  • PATH is an operating system environment variable that specifies locations of executable programs.
  • CLASSPATH is specific to Java and specifies locations of folders and JAR files containing Java class libraries and packages. JVM uses it to find user classes as well as Java core classes.

48. What are some Java keywords?

Some commonly used Java keywords are:

  • abstract – Abstract class or method
  • final – Final class, method or variable
  • import – Imports packages into current file
  • interface – Defines a Java interface
  • package – Specifies Java package for classes
  • private – Private access modifier
  • protected – Protected access modifier
  • public – Public access modifier
  • static – Static member of a class
  • try – Try block for exception handling

49. How is exception propagation implemented in Java?

Exception propagation in Java refers to the sequential process of re-throwing an exception from where it occurred up the call stack until it is handled.

It enables tracing exception origin and handling it at suitable level. Steps involved are:

  • Method throws exception to caller
  • Caller can handle or rethrow it further
  • Exception propagates up call stack
  • If uncaught, default exception handler terminates program

Leave a Reply

Your email address will not be published. Required fields are marked *