Java 03
Java 03
class Animal {
void sound() { System.out.println("Animal makes sound"); }
}
class Dog extends Animal {
@Override
void sound() { System.out.println("Dog barks"); }
}
class Parent {
Parent(String name) { System.out.println(name); }
}
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");
}
56. Synchronization
Ensures thread-safe access to resources using the synchronized keyword.
Generics
String in Java
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
Example:
import java.io.*;
Person() { }
@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();
}
}
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:
95. Iterator
An Iterator provides a way to access elements of a collection one at a time.
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
System.out.println(sortedMap.firstKey()); // Output: A
System.out.println(navigableMap.higherKey("B")); // Output: C
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
System.out.println(map.get("Apple")); // Output: 5