Class Inheritance
1. Java Class Inheritance
Inheritance is a mechanism where one class can inherit fields and methods from another class.
2. Is-A Relationship In Java
"Is-A" is a way to establish a parent-child relationship.
Example: Dog is-a Animal, so Dog extends Animal.
3. Passing Subclass Object As Superclass Reference
You can assign a subclass object to a superclass reference.
Animal animal = new Dog(); // Subclass object as superclass reference
animal.eat();
4. Assigning Subclass Object To Superclass Reference
It allows access only to the superclass methods/fields.
Animal animal = new Dog();
// animal.bark(); // Not allowed
5. Assigning Superclass Reference To Subclass Reference
This requires explicit casting and is unsafe without a check.
Animal animal = new Animal();
Dog dog = (Dog) animal; // Will throw ClassCastException if 'animal' is not a Dog instance
6. Multilevel Inheritance In Java
A class can inherit from another class, which in turn inherits from a third class.
class Animal { void eat() {} }
class Mammal extends Animal { void walk() {} }
class Dog extends Mammal { void bark() {} }
Methods Overriding and Overloading
7. Can you override a private or static method in Java?
Private methods cannot be overridden since they are not visible to subclasses.
Static methods are associated with the class, not an instance, and cannot be overridden but can be hidden.
8. Does Java support multiple inheritances?
Java does not support multiple inheritance with classes to avoid the diamond problem.
It supports multiple inheritance through interfaces.
9. Method Overloading In Java
Overloading allows multiple methods with the same name but different parameter lists.
void add(int a, int b) {}
void add(double a, double b) {}
10. Is Java Pass by Reference or Pass by Value
Java is strictly pass by value. Object references are passed by value, not the actual object.
11. Method Overriding In Java
A subclass provides a specific implementation for a method already defined in its superclass.
class Animal {
void sound() { System.out.println("Animal makes sound"); }
}
class Dog extends Animal {
@Override
void sound() { System.out.println("Dog barks"); }
}
12. Inheritance Example Program To Remove Duplicate Code
Code reuse is achieved by placing common functionality in the parent class.
13. How A Method Can Be Overridden In Different Ways
By changing behavior, visibility, or annotations like @Override.
14. Method Overloading Vs Method Overriding
Overloading: Compile-time polymorphism (different parameter lists).
Overriding: Run-time polymorphism (same signature, subclass changes behavior).
15. Super Keyword In Java To Call Superclass Constructor
Used to call the parent class constructor or methods.
class Parent {
Parent(String name) { System.out.println(name); }
}
class Child extends Parent {
Child() { super("Parent Name"); }
}
16. Inheritance And Constructors In Java
Constructors are not inherited but can be invoked using super().
17. Dynamic Method Dispatch
Resolving method calls at runtime using overridden methods.
18. Run Time Polymorphism
Achieved using method overriding.
Animal a = new Dog();
a.sound(); // Calls Dog's sound method
Abstract Class and Methods
19. Java Abstract Class
A class declared with the abstract keyword cannot be instantiated.
20. Abstract Method In Java
Declared without a body and must be implemented by subclasses.
21. Rules For Abstract Methods and Abstract Classes
Abstract classes can have constructors and non-abstract methods.
A subclass must implement all abstract methods or itself be abstract.
Interfaces, Packages, and Access Control
22. Java Interface
A reference type containing abstract methods.
23. Difference Between Interfaces And Abstract Classes
Interfaces: No fields, multiple inheritance.
Abstract Classes: Fields and single inheritance.
24. Future Task Java Program Using Interfaces
Implement a task scheduling system using interfaces.
25. Creating Interface In Java With Example Program
Define an interface, implement it in a class.
26. Java Package
Logical grouping of classes.
27. How To Compile Classes in Package
Use javac -d to specify package structure.
28. Using private Keyword In Java For Access Control
Restricts visibility to the class.
29. Access Modifiers In Java
private, default, protected, public.
30. Java Access Modifiers With Example Program
Demonstrate modifiers with visibility.
Final, Static, and Others
31. Can you access a non-static variable in the static context?
No, static methods/blocks cannot directly access non-static members.
32. final Keyword In Java
Used for constants, methods, or classes.
33. Static Keyword In Java
Declares static variables and methods shared by all instances.
34. Creating Static Methods In Java
Shared among instances.
35. Singleton Design Pattern In Java
Ensure only one instance of a class exists.
36. Java Program To Explain Public Static Void Main
Entry point for the JVM to start program execution.
37. Static and Non-Static Variables
Static variables are shared, non-static are instance-specific.
38. Abstraction in Java
Hiding implementation details and showing only functionality. Achieved through abstract classes and interfaces.
39. Polymorphism In Java
Allows a single interface to represent different underlying forms. Achieved through method overloading (compile-tim
40. Encapsulation In Java
Restricting access to fields and methods using access modifiers. Achieved by making fields private and providing pub
41. Inheritance In Java
A mechanism where a class acquires the properties and methods of another class using the extends keyword.
42. Why Java Throws Exceptions
To handle errors and maintain normal application flow.
43. How To Handle An Exception In Java
Use try-catch blocks, finally, and exception propagation with throws.
44. Exception Handling In Java with Example Program
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
}
45. Try Catch Block In Java
Encapsulates code that might throw an exception in try and handles it in catch.
46. Java Multiple Catch Block With Example Program
try {
int[] arr = new int[2];
System.out.println(arr[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index Error");
} catch (Exception e) {
System.out.println("General Error");
}
47. Java Finally Block In Exception Handling
Executes after try or catch, used for cleanup.
48. User Defined Exception In Java
Create a custom exception by extending the Exception class.
49. Java Throw Keyword - Java Throws Keyword
throw: Used to explicitly throw an exception.
throws: Declares exceptions a method might throw.
50. Difference Between Error and Exception in Java
Errors: Critical issues, e.g., OutOfMemoryError.
Exceptions: Recoverable, e.g., IOException.
51. Checked Exception Vs Unchecked Exception In Java
Checked: Handled at compile-time (e.g., IOException).
Unchecked: Occurs at runtime (e.g., NullPointerException).
52. Java Built-In Exceptions
Includes classes like IOException, RuntimeException, ArithmeticException, etc.
53. Overriding with Exceptions
You can override a method that throws NullPointerException with a method that throws RuntimeException, as Runti
The Java Thread Model
54. Creation Of Threads In Java
Extend Thread class.
Implement Runnable interface.
55. Java Inter Thread Communication With Example
Achieved using methods like wait(), notify(), and notifyAll().
56. Synchronization
Ensures thread-safe access to resources using the synchronized keyword.
57. Thread Synchronization Using 'Synchronized'
Locks a method/block for one thread at a time.
58. static synchronized In Java
Synchronizes static methods across all instances.
59. Java Synchronized Blocks
Limits synchronization to a specific block of code.
60. Handling Thread Deadlock In Java
Avoid nested locks, use tryLock, or acquire locks in a consistent order.
61. Java Thread Group
A group of threads managed as a single unit.
Generics
62. Java Generics
Provides type safety by specifying types at compile-time.
63. A Simple Generics Example
List<String> list = new ArrayList<>();
list.add("Hello");
64. How Generics Improve Type Safety
Prevents runtime type errors by enforcing compile-time type checking.
65. A Generic Class With Two Type Parameters
class Pair<K, V> {
K key;
V value;
}
66. Java Bounded Type
Restricts types using extends.
<T extends Number> void method(T t) { }
67. Generics Wildcards
Allows flexibility with ?.
? extends T: Upper bound.
? super T: Lower bound.
68. Generics In Methods And Constructors
<T> void method(T t) { }
String
String in Java
69. What are Strings?
In Java, a string is an object that represents a sequence of characters. It is an instance of the String class, which is imm
.
70. String Heap Memory and Constant Pool Memory
Heap Memory: The heap is where objects are stored in Java. If a string is created using new (e.g., new String("Hello"))
Constant Pool: The string constant pool is a special storage area in memory where string literals (like "Hello") are sto
of each literal string.
71. Immutability in Strings
Strings in Java are immutable, meaning once a string object is created, its value cannot be changed. Any modification
s ensures thread safety and improves performance by reusing string literals from the constant pool.
72. String Creation on Heap and Constant Pool
When a string is created using a string literal (e.g., "Hello"), it is stored in the constant pool.
When a string is created using the new keyword (e.g., new String("Hello")), it is stored in the heap memory. However,
it is not already there.
73. Method APIs on String; Operations on Strings
Some commonly used String methods include:
length(): Returns the length of the string.
charAt(int index): Returns the character at the specified index.
substring(int start, int end): Returns a substring from the given range.
toLowerCase(), toUpperCase(): Converts to lowercase or uppercase.
contains(CharSequence sequence): Checks if a string contains a specified sequence of characters.
equals(), equalsIgnoreCase(): Compares strings.
split(String regex): Splits the string into an array based on a regular expression.
74. Mutability of String Objects - StringBuilder and StringBuffer
String: Immutable, meaning once a string is created, it cannot be changed.
StringBuilder: Mutable, can change the string content (e.g., append, insert, or delete). It is faster than StringBuffer in
StringBuffer: Similar to StringBuilder, but it is thread-safe, meaning it can be safely used in multithreaded environme
75. Splitting of Strings and StringTokenizer Class
split(): Splits a string into an array of substrings based on a given delimiter. Example:
Code -
String str = "apple,banana,cherry";
String[] fruits = str.split(",");
76. StringTokenizer: A legacy class used for splitting strings into tokens. It is less efficient than split() and not recomm
code -
StringTokenizer st = new StringTokenizer("apple,banana,cherry", ",");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
Serialization in Java
77. Serialization in Java
Serialization is the process of converting an object into a byte stream for storage or transmission. It is done using the
e, its objects can be written to a stream and later read back into memory.
Example:
class Person implements Serializable {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
}
public class SerializeExample {
public static void main(String[] args) throws IOException {
Person person = new Person("John", 30);
FileOutputStream fileOut = new FileOutputStream("person.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(person);
out.close();
fileOut.close();
}
}
78. Externalizable in Java with Example
The Externalizable interface allows custom serialization. It requires implementing two methods: writeExternal(Object
Example:
import java.io.*;
class Person implements Externalizable {
String name;
int age;
Person() { }
Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(name);
out.writeInt(age);
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
name = (String) in.readObject();
age = in.readInt();
}
}
public class ExternalizableExample {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Person person = new Person("John", 30);
FileOutputStream fileOut = new FileOutputStream("personExternal.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(person);
out.close();
FileInputStream fileIn = new FileInputStream("personExternal.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
Person deserializedPerson = (Person) in.readObject();
in.close();
System.out.println("Name: " + deserializedPerson.name + ", Age: " + deserializedPerson.age);
}
}
Collections Framework
79. What will happen if we put a key object in a HashMap which is already there?
If you attempt to insert a key-value pair with a key that already exists in the HashMap, the new value will replace the
Example:
Map<String, String> map = new HashMap<>();
map.put("name", "Alice");
map.put("name", "Bob"); // "Alice" will be replaced by "Bob"
System.out.println(map.get("name")); // Output: Bob
80. Java Collections Overview
The Java Collections Framework provides a set of classes and interfaces to manage data. It includes interfaces like Lis
ons like ArrayList, HashSet, and HashMap.
81. Collection Interface
The Collection interface is the root interface for all collections. It defines basic operations like add(), remove(), size(), a
82. Java List Interface
List is an ordered collection that allows duplicates and provides positional access to elements. Examples: ArrayList, L
83. Set Interface in Java
Set is a collection that does not allow duplicates. Examples: HashSet, TreeSet.
84. Java SortedSet Interface
A SortedSet is a Set that maintains its elements in ascending order. Example: TreeSet.
85. Java NavigableSet Interface
A NavigableSet extends SortedSet and provides methods for navigation, such as lower(), higher(), ceiling(), and floor()
86. Collection Classes
Classes that implement Collection and its subinterfaces include:
ArrayList, LinkedList, HashSet, TreeSet, LinkedHashSet, etc.
87. Java ArrayList
ArrayList is a dynamic array implementation of the List interface. It allows fast random access but slower insertions/d
88. Java LinkedList
LinkedList is a doubly linked list implementation of the List and Deque interfaces. It is better for frequent insertions a
89. HashSet Class in Java
HashSet implements the Set interface and does not allow duplicates. It provides constant-time performance for basi
90. Java LinkedHashSet
LinkedHashSet is a HashSet that maintains the insertion order of elements.
91. Java TreeSet - TreeSet Examples in Java
TreeSet implements the NavigableSet interface and maintains its elements in sorted order.
92. Java PriorityQueue
PriorityQueue is a queue that orders its elements according to their natural order or by a comparator.
93. Java ArrayDeque Class
ArrayDeque is a resizable array implementation of the Deque interface, allowing elements to be added or removed f
94. Java EnumSet
EnumSet is a specialized Set implementation for use with enum types. It is faster than other Set implementations wh
95. Iterator
An Iterator provides a way to access elements of a collection one at a time.
96. Java Iterator
An Iterator is used to traverse the elements of a collection. Methods include hasNext(), next(), and remove().
97. List Iterator in Java
A ListIterator is an iterator for lists that allows bidirectional traversal and modification of the list.
Map Interfaces in Java
98. Java Map Interfaces - HashMap, TreeMap, LinkedHashMap
HashMap:
A hash-based implementation of the Map interface. It does not guarantee any specific order of the elements. It allow
Example:
Map<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
TreeMap:
A Map implementation based on a Red-Black tree, which keeps keys sorted in natural order or by a custom compara
Example:
Map<String, Integer> map = new TreeMap<>();
map.put("B", 2);
map.put("A", 1); // Automatically sorted by key
LinkedHashMap:
A hash-based implementation of Map that maintains insertion order (the order in which elements were added). It all
Example:
Map<String, Integer> map = new LinkedHashMap<>();
map.put("A", 1);
map.put("B", 2); // Maintains insertion order
99. Java SortedMap Interface
SortedMap is a subinterface of Map that guarantees the order of its keys, which are sorted in natural order or by a cu
, and subMap() for range-based access to the map.
Example:
SortedMap<String, Integer> sortedMap = new TreeMap<>();
sortedMap.put("B", 2);
sortedMap.put("A", 1);
sortedMap.put("C", 3);
System.out.println(sortedMap.firstKey()); // Output: A
100. Java NavigableMap
NavigableMap is an extension of SortedMap and provides methods for navigating through keys, such as lowerEntry()
anced navigation and range-based operations.
Example:
NavigableMap<String, Integer> navigableMap = new TreeMap<>();
navigableMap.put("A", 1);
navigableMap.put("B", 2);
navigableMap.put("C", 3);
System.out.println(navigableMap.higherKey("B")); // Output: C
101. Java Map.Entry Interface
Map.Entry is an interface within Map that represents a key-value pair. It provides methods like getKey(), getValue(), a
Example:
Map<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
// Output: A = 1
// B=2
Map Classes in Java
20.6.1 Java HashMap Implementation
HashMap is a hash table-based implementation of the Map interface. It stores key-value pairs and allows for efficien
on average.
Example:
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 5);
map.put("Banana", 10);
System.out.println(map.get("Apple")); // Output: 5
102. TreeMap In Java - java.util.TreeMap
TreeMap is an implementation of the NavigableMap interface and is based on a Red-Black tree. It ensures that the ke
tom comparator.
Example:
Map<String, Integer> map = new TreeMap<>();
map.put("X", 1);
map.put("Y", 2);
map.put("Z", 3);
System.out.println(map); // Output: {X=1, Y=2, Z=3}
103. Java WeakHashMap Class
WeakHashMap is a Map implementation that stores weak references to its keys. If a key is no longer in use (i.e., there
and the corresponding entry will be removed from the map.
Example:
Map<String, String> weakMap = new WeakHashMap<>();
String key = new String("key");
weakMap.put(key, "value");
System.out.println(weakMap.get(key)); // Output: value
key = null; // The entry will be garbage collected when there are no references to "key"
104. LinkedHashMap In Java with Code Example
LinkedHashMap maintains the insertion order of its elements. It is similar to HashMap but retains the order in which
Example:
Map<String, Integer> map = new LinkedHashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
// Output: A = 1
// B=2
// C=3
Summary of Differences Between Map Implementations
HashMap: No order, allows null key/values.
TreeMap: Sorted by key, no null keys.
LinkedHashMap: Maintains insertion order.
WeakHashMap: Uses weak references for keys, allowing garbage collection.