0% found this document useful (0 votes)
2 views22 pages

Java Questions CampusSutraa

This document provides a comprehensive overview of core Java concepts and interview questions, covering topics such as Java's platform independence, JVM, JRE, JDK, object-oriented principles, exception handling, collections framework, multithreading, and Java 8 features like lambda expressions and the Stream API. It includes detailed explanations of key terms and concepts, along with differences between related components. The content serves as a valuable resource for preparing for Java interviews.

Uploaded by

swayamshipanda
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views22 pages

Java Questions CampusSutraa

This document provides a comprehensive overview of core Java concepts and interview questions, covering topics such as Java's platform independence, JVM, JRE, JDK, object-oriented principles, exception handling, collections framework, multithreading, and Java 8 features like lambda expressions and the Stream API. It includes detailed explanations of key terms and concepts, along with differences between related components. The content serves as a valuable resource for preparing for Java interviews.

Uploaded by

swayamshipanda
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Core Java Interview Questions — Medium Descriptive Answers

1. What is Java?

Java is a high-level, object-oriented, and platform-independent programming language designed for building secure and scalable
applications. It follows the principle of “write once, run anywhere” using bytecode executed by the JVM.

2. Why is Java platform independent?

Java code is compiled into bytecode which is executed on any system with a JVM. Since JVM implementations exist for every major
operating system, the same bytecode runs everywhere without modification.

3. What is JVM?

The JVM (Java Virtual Machine) executes Java bytecode and manages tasks like memory allocation, garbage collection, and security. It
ensures platform independence by interpreting bytecode into machine instructions.

4. What is JRE?

The JRE (Java Runtime Environment) includes the JVM and necessary libraries required to run Java applications. It does not contain
development tools like compilers.

5. What is JDK?

The JDK (Java Development Kit) contains the JRE, JVM, compilers, and tools needed for developing Java applications. Developers need
JDK, while end-users only need JRE.

6. Difference between JDK, JRE, JVM?

• JVM: Executes bytecode


• JRE: JVM + runtime libraries
• JDK: JRE + development tools

The JDK is for developers; JRE and JVM help run programs.
7. What is bytecode?

Bytecode is an intermediate machine-independent code generated by the Java compiler. It is executed by the JVM, enabling platform
independence.

8. Is Java 100% Object-Oriented?

No, because it uses primitive data types like int and boolean. These are not objects, although wrapper classes exist.

9. What are access modifiers?

Java provides public, private, protected, and default access modifiers. They define the visibility of classes, methods, and variables,
supporting encapsulation.

10. What is method overloading?

Method overloading occurs when multiple methods share the same name but have different parameters. It enables compile-time
polymorphism and improves code organization.

11. What is method overriding?

Method overriding is defining a method in a subclass with the same signature as the parent. It supports runtime polymorphism and
custom behavior.

12. What is polymorphism?

Polymorphism allows objects to behave differently based on implementation — through method overloading (compile-time) and
overriding (runtime). It enhances code flexibility.

13. What is encapsulation?

Encapsulation hides internal data using private fields and exposes controlled access through getters/setters. It enhances security and
maintainability.
14. What is abstraction?

Abstraction hides implementation details and exposes only essential features. It is implemented using abstract classes and interfaces.

15. What is an interface?

An interface defines method signatures without implementation, allowing classes to implement them. It supports multiple inheritance
and abstraction.

16. Difference between abstract class and interface?

Abstract classes allow both abstract and concrete methods, while interfaces primarily define abstract methods. A class can extend only
one abstract class but implement multiple interfaces.

17. What is inheritance?

Inheritance allows one class to acquire properties and methods of another class. It supports code reuse and hierarchical classification.

18. Types of inheritance in Java?

Java supports single, multilevel, and hierarchical inheritance. Multiple inheritance is disallowed for classes but allowed through
interfaces.

19. What is a constructor?

A constructor is a special method used to initialize objects. It has the same name as the class and is called automatically during object
creation.

20. Can constructors be inherited?

No. Constructors cannot be inherited but can be invoked using super() to call parent constructors.

21. Can constructors be overloaded?

Yes. You can define multiple constructors with different parameter lists to initialize objects in multiple ways.
22. What is the ‘this’ keyword?

this refers to the current object and is used to access instance variables or call constructors within the same class.

23. What is the ‘super’ keyword?

super refers to the parent class and is used to access parent methods, variables, or constructors.

24. Difference between == and equals()?

== compares object references, while equals() compares object values. For Strings, equals() checks content equality.

25. What is String immutability?

String objects cannot be changed after creation. Any modification results in a new object, ensuring security and memory optimization.

26. What is StringBuilder?

StringBuilder is a mutable class used for modifying strings efficiently. It is not thread-safe but performs faster than StringBuffer.

27. What is StringBuffer?

StringBuffer is similar to StringBuilder but thread-safe due to synchronized methods. It is used in multi-threaded environments.

28. What is exception handling?

Exception handling manages runtime errors using try-catch-finally blocks. It prevents application crashes and ensures smooth flow.

29. Difference between checked and unchecked exceptions?

Checked exceptions occur at compile time and must be handled. Unchecked exceptions occur at runtime due to logical errors.
30. What is throw and throws?

throw is used to explicitly throw exceptions, whereas throws declares exceptions in method signatures.

31. What is finally?

The finally block executes irrespective of exception occurrence. It is used to close resources like files and connections.

32. What is a package?

A package groups related classes and interfaces. It helps organize code and avoid naming conflicts.

33. What is the Collections Framework?

It is a set of interfaces and classes that provide data structures such as List, Set, and Map, making data manipulation easier.

34. Difference between List, Set, and Map?

• List: Ordered, allows duplicates


• Set: Unordered, no duplicates
• Map: Key-value pairs, keys unique

35. What is ArrayList?

ArrayList is a dynamic array that provides fast retrieval but slower insertions/deletions in the middle.

36. What is LinkedList?

LinkedList stores elements in a doubly linked structure. It offers faster insertion/deletion but slower access.
37. What is HashSet?

HashSet stores unique elements using hashing. It offers constant-time performance for add, remove, and search.

38. What is TreeSet?

TreeSet stores elements in sorted order. It is implemented using a Red-Black Tree and provides log(n) operations.

39. What is HashMap?

HashMap stores key-value pairs using hashing. It allows one null key and many null values with fast lookups.

40. What is LinkedHashMap?

LinkedHashMap maintains insertion order while storing key-value pairs. It is slightly slower than HashMap.

41. What is TreeMap?

TreeMap stores key-value pairs in a sorted manner using a Red-Black Tree. It does not allow null keys.

42. Difference between HashMap and Hashtable?

Hashtable is synchronized and thread-safe; HashMap is not. Hashtable does not allow nulls, while HashMap does.

43. What is ConcurrentHashMap?

ConcurrentHashMap is a thread-safe Map using lock-striping for high performance. It avoids ConcurrentModificationException.

44. What is fail-fast?

Fail-fast iterators immediately throw ConcurrentModificationException when a collection is modified while iterating.
45. What is fail-safe?

Fail-safe iterators operate on a cloned copy of the collection, preventing modification issues. Example: ConcurrentHashMap.

46. What is Generics?

Generics enable type safety and avoid ClassCastException by specifying data types at compile time.

47. What is autoboxing?

Autoboxing automatically converts primitive types into wrapper objects when needed.

48. What is unboxing?

Unboxing automatically converts wrapper objects into primitive types.

49. What is multithreading?

Multithreading allows multiple threads to run concurrently, improving performance in tasks like parallel processing.

50. What are ways to create threads?

Threads can be created by extending Thread class, implementing Runnable, or using Callable with ExecutorService.

31. What is constructor overloading in Java?

Constructor overloading means a class can have multiple constructors with different parameter lists.

It allows objects to be initialized in different ways.

The compiler determines which constructor to call based on the arguments provided.
32. What are wrapper classes in Java?

Wrapper classes convert primitive data types into objects (e.g., int → Integer, double → Double).

They are used in collections, generics, and utility classes.

They also provide useful methods like parsing and value conversion.

33. What is autoboxing and unboxing?

Autoboxing is automatic conversion of primitives to wrapper objects (int → Integer).

Unboxing is the reverse conversion (Integer → int).

These processes make working with collections and generics easier.

34. What is the difference between ArrayList and LinkedList?

ArrayList uses a dynamic array and gives fast random access but slow insert/delete in between.

LinkedList uses doubly linked nodes and provides faster insert/delete but slower access.

ArrayList is preferred when frequent access is needed; LinkedList is better for frequent updates.

35. What is an exception hierarchy?

Java exceptions form a hierarchy rooted at Throwable.

It has two branches: Error (serious system issues) and Exception (recoverable problems).

Exceptions further split into checked and unchecked exceptions.

36. What is a try-catch-finally block?

It is used for exception handling in Java.

try contains risky code, catch handles exceptions, and finally executes code regardless of exceptions.

finally is often used for closing resources like files or database connections.
37. What is method overriding?

Method overriding occurs when a subclass provides its own implementation of a method from the parent class.

The method must have the same name, parameters, and return type.

It supports runtime polymorphism in Java.

38. What is the difference between static and dynamic binding?

Static binding happens at compile time for methods like static, final, and private.

Dynamic binding occurs at runtime based on the actual object type.

Dynamic binding enables method overriding and polymorphism.

39. What is the use of the ‘super’ keyword?

super refers to the immediate parent class.

It is used to access parent class variables, methods, and constructors.

It resolves naming conflicts in inheritance.

40. What is the ‘this’ keyword?

this refers to the current object.

It is used to access instance variables, call methods, and invoke constructors within the same class.

It helps resolve naming conflicts.

41. What is a Java Bean?

A Java Bean is a reusable software component.

It must have a no-argument constructor, private fields, and getter/setter methods.


Beans are often used in frameworks and enterprise applications.

42. What is a singleton class?

A singleton ensures only one instance of a class is created.

It provides a global point of access using a private constructor and a static instance method.

Commonly used in logging, caching, or configuration.

43. What is enum in Java?

An enum represents a fixed set of constants (e.g., DAYS, COLORS).

Enums are type-safe and can have constructors, methods, and variables.

They are better alternatives to constant variables.

44. What is the difference between == and equals()?

== compares reference addresses for objects.

equals() compares values or content.

For strings, equals() checks the actual text while == checks memory location.

45. What is a marker interface?

A marker interface contains no methods (e.g., Serializable, Cloneable).

It provides metadata to the JVM or compiler.

This metadata triggers specific behavior such as enabling serialization.

46. What is the hashCode() method?

hashCode() returns an integer hash value of an object.


It is used in hashing-based collections like HashMap and HashSet.

Objects that are equal must return the same hash code.

47. What is the difference between throw and throws?

throw is used to explicitly throw an exception inside a method.

throws declares exceptions a method might throw.

throw works at runtime; throws works at compile time.

48. What is a custom exception?

A custom exception is a user-defined exception class extending Exception or RuntimeException.

Used when the built-in exceptions don’t cover specific error scenarios.

Makes code more readable and business-specific.

49. What is a thread?

A thread is the smallest independent unit of execution.

Java supports multithreading to run multiple tasks simultaneously.

Threads help improve performance in concurrent applications.

50. How do you create a thread in Java?

Threads can be created by extending the Thread class or implementing Runnable.

Runnable is preferred as it supports multiple inheritance.

The thread is started using the start() method.

51. What is thread lifecycle in Java?

A thread passes through several states: New, Runnable, Running, Blocked/Waiting, and Terminated.
The JVM controls these transitions based on thread scheduling and system resources.

Methods like start(), sleep(), wait(), and notify() affect the lifecycle.

52. What is synchronization in Java?

Synchronization ensures that only one thread accesses a shared resource at a time.

It prevents race conditions and data inconsistency.

Achieved using synchronized methods, synchronized blocks, or locks.

53. What is a deadlock?

Deadlock occurs when two or more threads are waiting on each other and none can proceed.

It typically happens when multiple locks are acquired in a circular dependency.

Proper lock ordering and avoiding nested locks helps prevent deadlocks.

54. What is volatile keyword in Java?

volatile ensures visibility of changes to a variable across multiple threads.

It prevents threads from caching the value locally.

Used for shared data that multiple threads read and update.

55. What is the difference between synchronized and volatile?

volatile ensures visibility but doesn’t guarantee atomicity.

synchronized provides both mutual exclusion and visibility.

volatile is lightweight, while synchronized is heavier but safer.


56. What is a Java memory model?

It defines how JVM handles memory areas like heap, stack, method area, and PC registers.

It governs how threads interact through shared memory.

Ensures consistent behavior across platforms.

57. What is garbage collection in Java?

Garbage collection automatically removes unused objects from memory.

It frees programmer from manual memory management.

JVM uses collectors like Serial, Parallel, CMS, and G1.

58. What are strong, weak, soft, and phantom references?

Strong: Normal references, not eligible for GC.

Soft: Cleared only when memory is low.

Weak: Cleared eagerly during GC.

Phantom: Used for cleanup before memory release.

59. What is the difference between final, finally, and finalize()?

final is a keyword for constants, final classes, or methods.

finally is a block that executes after try-catch.

finalize() is a method called before object destruction (deprecated).

60. What is a class loader?

Class loaders load .class files into JVM at runtime.

Types include Bootstrap, Extension, and Application class loaders.


They follow delegation hierarchy for security and consistency.

61. What is the Collections Framework?

A set of interfaces, classes, and algorithms for storing and manipulating data.

Includes List, Set, Map, Queue, and utility classes.

Provides reusable, efficient data structures.

62. What is the difference between List and Set?

List allows duplicates and maintains order.

Set doesn’t allow duplicates and may or may not maintain order.

Common implementations: ArrayList, LinkedList, HashSet, LinkedHashSet.

63. What is a HashMap?

HashMap stores key-value pairs using hashing.

It allows null keys and values and offers O(1) average access time.

Not synchronized and not ordered.

64. What is LinkedHashMap?

LinkedHashMap maintains insertion order while storing data like HashMap.

It uses a doubly linked list along with hashing.

Useful when predictable iteration order is needed.

65. What is TreeMap?

TreeMap stores key-value pairs in a sorted (red-black tree) structure.


It maintains natural or custom ordering.

Slower than HashMap but ordered.

66. What is HashSet?

HashSet stores unique elements using hashing.

Does not maintain insertion order.

Offers fast lookup and insertion.

67. What is LinkedHashSet?

Similar to HashSet but maintains insertion order.

Uses hashing plus a linked list.

Useful when unique + ordered behavior is required.

68. What is ConcurrentHashMap?

A thread-safe version of HashMap.

Allows concurrent read and controlled write operations without locking the entire map.

Uses segment-level or bucket-level locking.

69. What is immutable class in Java?

An immutable class cannot be changed once created (e.g., String).

Declare class final, make fields private and final, and avoid setters.

Return deep copies in getters.


70. What is the String pool?

A special memory area inside heap for storing string literals.

When a string literal is created, JVM checks the pool first to avoid duplicates.

Improves memory efficiency.

71. Difference between String, StringBuilder, and StringBuffer?

String: Immutable and thread-safe.

StringBuilder: Mutable and faster but not thread-safe.

StringBuffer: Mutable and thread-safe but slower.

72. What is method reference in Java 8?

A shorthand for lambda expressions referring to existing methods.

Types include static, instance, and constructor references.

Helps produce cleaner code.

73. What are functional interfaces?

Interfaces with exactly one abstract method (e.g., Runnable, Callable, Comparator).

Annotated with @FunctionalInterface.

Used in lambda expressions and streams.

74. What is the Stream API?

Stream API processes collections using functional programming.

Supports operations like filter, map, reduce, and collect.

Enables parallel processing and cleaner code.


75. What is Optional in Java?

Optional is a container class to avoid null values.

Provides methods like isPresent(), orElse(), orElseThrow(), etc.

Reduces NullPointerException in applications.

76. What is lambda expression in Java?

Lambda expressions provide a concise way to write anonymous methods.

They reduce boilerplate code and work with functional interfaces.

Useful in streams, sorting, iteration, and asynchronous tasks.

77. What is the difference between List and Array?

Arrays are fixed-size and store primitives or objects.

Lists are dynamic and part of the Collections Framework.

Lists support built-in functions like add(), remove(), sort(), etc.

78. What is fail-fast and fail-safe iterator?

Fail-fast iterators throw ConcurrentModificationException when structure is modified during iteration.

Example: ArrayList, HashMap iterator.

Fail-safe iterators work on a copy of the structure and don’t throw errors (e.g., ConcurrentHashMap, CopyOnWriteArrayList).

79. What is the difference between Comparator and Comparable?

Comparable provides natural ordering by implementing compareTo().

Comparator provides custom ordering using compare().

A class can have only one Comparable but multiple Comparators.


80. What is serialization?

Serialization converts an object into a byte stream for storage or network transfer.

Enabled using Serializable interface.

Deserialization reconstructs the object.

81. What is transient keyword?

transient marks fields that should not be serialized.

Used for sensitive data or derived fields.

During deserialization, transient fields get default values.

82. What is the difference between Map and HashMap?

Map is an interface of key-value pairs.

HashMap is an implementation using hashing.

HashMap allows null keys/values and gives average O(1) time.

83. Why is String immutable in Java?

For security (classloading, reflection), caching (String pool), and thread safety.

Also improves performance as immutability avoids recalculating hash codes.

String Pool relies on immutability.

84. What is equals() and hashCode() contract?

If two objects are equal, they must return the same hashCode.

If hash codes differ, objects are guaranteed not equal.


Violating this causes issues in Sets and Maps.

85. What is the difference between stack and heap memory?

Stack stores local variables and function calls; memory is small and fast.

Heap stores objects; memory is large and shared across threads.

JVM manages heap using garbage collection.

86. What is classpath?

Classpath tells JVM where to find user-defined classes and libraries.

Can be set via command line or environment variables.

Wrong classpath results in ClassNotFoundException.

87. What is method hiding?

Occurs when a subclass defines a static method with the same signature as parent.

Static methods are bound at compile time.

It does not support polymorphism.

88. What is a static block?

A static block runs when the class is loaded into memory.

Used for static initializations or configuration loading.

Runs only once per class loading.

89. What is composition in Java?

A design principle where one class contains another class.


Represents a “has-a” relationship (e.g., Car has Engine).

Improves code reusability and flexibility over inheritance.

90. What is aggregation?

A weaker form of composition where contained objects can exist independently.

Example: A university has students; destroying university doesn’t destroy students.

Defines partial ownership.

91. What is the difference between abstraction and encapsulation?

Abstraction hides implementation details and shows essential behavior.

Encapsulation bundles data and methods and restricts access using access modifiers.

Abstraction = “What” | Encapsulation = “How”.

92. What is JIT compiler?

Just-in-Time (JIT) compiler converts bytecode into native machine code at runtime.

Improves performance by optimizing frequently run code.

Part of the JVM HotSpot engine.

93. What are default, protected, and private access modifiers?

Default: Accessible within same package.

Protected: Accessible within package + subclasses.

Private: Accessible only within class.


94. What is NoClassDefFoundError?

Occurs when JVM cannot load a class at runtime even though it was present during compilation.

Often due to missing class files, wrong classpath, or deployment issues.

It is an error, not an exception.

95. What is functional programming in Java?

Uses lambda expressions and streams to write concise, declarative code.

Focuses on immutability, transformations, and pure functions.

Introduced in Java 8.

96. What is method chaining?

Calling multiple methods on the same object in a single line (e.g., builder patterns).

Each method returns the object instance (return this).

Improves readability.

97. What is polymorphism in Java?

Polymorphism allows one interface or reference to refer to multiple object types.

Achieved through method overriding (runtime) and method overloading (compile time).

Enhances flexibility and reusability.

98. What is upcasting and downcasting?

Upcasting: Parent reference pointing to child object (safe).

Downcasting: Forcing parent reference to child (requires explicit cast and may cause ClassCastException).

Used in polymorphism.
99. What is the difference between abstraction and interface?

Abstract class can have both concrete and abstract methods.

Interfaces only had abstract methods (until Java 8 added default/static).

A class can implement multiple interfaces but extend only one abstract class.

100. What is the difference between Java and JVM?

Java is a programming language and platform.

JVM executes Java bytecode, provides memory management, and ensures portability.

Java depends on JVM to run on different operating systems.

You might also like