All in One Java Notes
All in One Java Notes
This approach helps in building scalable and maintainable applications. For example, if we are building a
student management system, we can create a Student class and create multiple student objects from it.
In Java, a class is a blueprint or template used to define the structure and behavior of objects. It contains
variables (data) and methods (functions) that define what the object will have and do.
An object, on the other hand, is an instance of a class. It is created in memory and holds specific data.
For example, if Car is a class, then myCar and yourCar can be two different objects of that class with their own
properties like color and speed.
A constructor in Java is a special block of code that is called automatically when an object is created. It is used
to initialize the object.
The name of the constructor is always the same as the class name, and it does not have any return type, not
even void.
• A constructor is called automatically when an object is created, whereas a method must be called
manually.
• A constructor is used for initialization, while a method is used for performing operations.
1. Default Constructor – This is a constructor with no parameters. If we do not define any constructor in
our class, Java provides a default constructor automatically. It assigns default values to the object's
fields.
2. Parameterized Constructor – This constructor takes arguments so that we can assign custom values to
the object during creation.
5. What is Constructor Overloading? Give an Example.
Constructor overloading in Java means having more than one constructor in the same class with different
parameter lists. It allows us to create objects in different ways using different sets of data.
For example:
class Student {
Student() {
// default constructor
}
Student(String name) {
// constructor with one parameter
}
Student(String name, int age) {
// constructor with two parameters
}
}
In the above example, all three constructors are overloaded. Based on the number and type of parameters,
the appropriate constructor is called when the object is created.
Inheritance is one of the key features of Object-Oriented Programming. It allows a class (called the child or
subclass) to inherit properties and methods from another class (called the parent or superclass).
The main advantage of inheritance is code reusability. Instead of writing the same code again, we can extend
a class and reuse its functionality.
For example:
class Animal {
void eat() {
System.out.println("This animal eats food");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
In this example, the Dog class inherits the eat() method from the Animal class.
class A { }
class B extends A { }
class C extends B { }
The key difference is the number of levels of inheritance. Single inheritance has only one level, while multilevel
involves multiple levels.
Method overriding is a feature in Java where a child class provides its own specific implementation of a
method that is already defined in the parent class.
It occurs only in inheritance and must have the same method name, return type, and parameters.
The main purpose of overriding is to achieve runtime polymorphism and to allow a subclass to provide
specific behavior.
Example:
class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}
Method overloading means defining multiple methods in the same class with the same name but different
parameters (number, order, or type of parameters).
It is done to perform a similar task in different ways and is an example of compile-time polymorphism.
Method overriding, on the other hand, means redefining a method from the parent class in the child class with
the same method signature. It is used for runtime polymorphism.
Example of Overloading:
class Calculator {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
}
10. What is Polymorphism in Java? Explain Compile-time and Runtime Polymorphism.
Polymorphism in Java means the ability of a method, object, or class to take many forms. It allows the same
method or action to behave differently in different scenarios.
There are two types of polymorphism:
1. Compile-time Polymorphism (Static Binding)
This is achieved using method overloading. The decision of which method to call is made during
compile time.
Example:
class Demo {
void show(int a) { }
void show(String b) { }
}
2. Runtime Polymorphism (Dynamic Binding)
This is achieved using method overriding. The decision of which method to call is made at runtime
based on the object type.
Example:
class Animal {
void sound() { System.out.println("Animal sound"); }
}
class Cat extends Animal {
void sound() { System.out.println("Meow"); }
}
Animal a = new Cat();
a.sound(); // Output: Meow
In Java, the super keyword is used to refer to the immediate parent class. It is mainly used for three purposes:
1. To call the parent class constructor.
2. To access the parent class methods.
3. To access the parent class variables.
This is helpful when the child class has overridden the method or variable, and we still want to refer to the
parent class version.
Example:
class Animal {
String type = "Animal";
Animal() {
System.out.println("Animal constructor");
}
}
class Dog extends Animal {
Dog() {
super(); // calls parent constructor
System.out.println("Dog constructor");
}
void displayType() {
System.out.println(super.type); // accesses parent variable
}
}
12. Can a constructor be inherited? Why or why not?
No, constructors cannot be inherited in Java.
This is because constructors are not members of a class like methods are. They are special blocks used to
initialize objects, and each class must define its own constructor.
However, a subclass can call a constructor of the parent class using the super() keyword.
13. What is abstraction? How is it achieved in Java?
Abstraction is the process of hiding the internal implementation details and showing only the necessary
features of an object.
In Java, abstraction is achieved in two ways:
1. Abstract classes
2. Interfaces
This allows us to focus on what an object does, rather than how it does it.
Example using abstract class:
Encapsulation is the binding of data and methods that operate on that data into a single unit.
In Java, it is achieved by:
This helps in data hiding and keeps the data safe from outside interference.
Example:
class Student {
private String name;
public void setName(String n) {
name = n;
}
public String getName() {
return name;
}
}
17. Why is encapsulation important in Java?
It also makes code modular and easy to debug or upgrade without affecting other parts of the program.
18. What is the difference between private, protected, public, and default access modifiers?
These access levels control visibility and help in achieving security and encapsulation.
Java does not support multiple inheritance through classes to avoid ambiguity (like the Diamond Problem).
However, Java supports multiple inheritance using interfaces.
A class can implement multiple interfaces and thus inherit behavior from multiple sources.
Example:
interface A {
void methodA();
}
interface B {
void methodB();
}
class C implements A, B {
public void methodA() { }
public void methodB() { }
}
20. What are the real-world examples of OOPs concepts?
• Encapsulation: ATM hides the internal code and shows only options like withdraw and deposit.
• Abstraction: Using a smartphone—you interact with apps but don’t know the code behind them.
No, we cannot override static methods in Java because they belong to the class, not the object.
However, if you define a static method with the same name in a subclass, it is method hiding, not overriding.
Example:
class Parent {
static void display() {
System.out.println("Parent static method");
}
}
class Child extends Parent {
static void display() {
System.out.println("Child static method");
}
}
Calling Child.display() will call the child’s method, but it’s not runtime polymorphism.
Yes, the main() method can be overloaded like any other method in Java.
But the JVM always calls the main method with String[] args as the entry point.
Example:
Example:
Example:
class Parent {
int x = 10;
}
class Child extends Parent {
int x = 20;
void show() {
System.out.println(this.x); // 20
System.out.println(super.x); // 10
}
}
25. Can a class extend multiple classes in Java? Why not?
No, Java does not support multiple inheritance with classes to avoid ambiguity like the Diamond Problem.
Instead, Java uses interfaces to achieve multiple inheritance.
Yes, in Java, an interface can extend one or more interfaces using the extends keyword.
Example:
interface A {
void methodA();
}
interface B extends A {
void methodB();
}
This helps in creating a hierarchy of contracts.
If a subclass does not override all abstract methods, it must also be declared abstract.
Otherwise, it will cause a compile-time error.
Example:
• Upcasting: Assigning a subclass object to a parent class reference. It is safe and done automatically.
• Downcasting: Casting a parent class reference back to a subclass. Needs explicit casting and may throw
ClassCastException if not done carefully.
Example:
30. Write a code example that shows runtime polymorphism using method overriding.
class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
This is runtime polymorphism because the method call is resolved at runtime based on the object type.
String
A String in Java is an object that represents a sequence of characters. It is used to store text, like words or
sentences, and is defined in the java.lang package. Strings are widely used in Java for handling text-based data.
For example:
Strings in Java are immutable, which means once a string is created, it cannot be changed. Any operation that
seems to modify a string actually creates a new one.
This immutability is designed for security, thread safety, and performance — especially because strings are
frequently used as keys in collections and for storing sensitive information like usernames, file paths, etc.
Example:
String s = "Hello";
s.concat(" World");
System.out.println(s); // Output: Hello (not "Hello World")
3. How do you create a String object in Java?
2. String s1 = "Hello";
4. What is the difference between String str = "abc" and String str = new String("abc")?
When you use String str = "abc", the string is placed in the String Pool, and if the same literal exists, Java
reuses it.
But if you use new String("abc"), Java creates a new object in heap memory, even if the same string exists in
the pool.
This affects memory usage and object comparison.
Example:
String a = "abc";
String b = new String("abc");
System.out.println(a == b); // false (different memory)
System.out.println(a.equals(b)); // true (same content)
5. How does == differ from .equals() in string comparison?
The == operator checks if two references point to the same object in memory, while .equals() checks if the
actual content of the strings is the same.
So, use == for reference comparison, and .equals() for content comparison.
Example:
String x = "Java";
String y = new String("Java");
System.out.println(x == y); // false
System.out.println(x.equals(y)); // true
6. What is the use of the intern() method in strings?
The intern() method returns a canonical representation of the string. It tells Java to add the string to the String
Pool if it’s not already there.
This is useful when you want to ensure that all equal strings share the same memory reference.
Example:
String a = new String("Core");
String b = a.intern();
System.out.println(b == "Core"); // true
7. How is memory managed for strings in Java?
This model allows efficient memory use while also providing flexibility.
The String Pool is a special memory area in the Java heap where string literals are stored. If two strings have
the same literal value, Java uses the same object from the pool instead of creating a new one.
Example:
String a = "data";
String b = "data";
System.out.println(a == b); // true
Both a and b refer to the same object in the pool.
The substring() method is used to extract a part of a string based on a starting and optional ending index. It
returns a new string containing characters from the original string.
Example:
String str = "HelloWorld";
String sub = str.substring(0, 5); // returns "Hello"
It’s commonly used when you need only a part of a string, like extracting date, name, or code from a larger
string.
10. What is the difference between substring(int beginIndex) and substring(int beginIndex, int endIndex)?
• substring(beginIndex) returns characters from the given index to the end of the string.
Example:
The replace() method replaces all occurrences of a character or substring with another.
Example:
Example:
Example:
The trim() method removes leading and trailing white spaces from a string, but not spaces in between.
Example:
• startsWith(String prefix)
• endsWith(String suffix)
Example:
Example:
String s = "Java123";
s.contains("123"); // true
s.matches("\\w+"); // true (regex for word characters)
Use contains() for simple checks, and matches() for pattern-based validation (like email, mobile number).
The split() method breaks a string into an array based on a given delimiter.
Example:
This is useful for CSV data or user input separated by commas, spaces, etc.
You can use the toCharArray() method to convert a string into an array of characters.
Example:
Absolutely! Here are interview-level answers to your StringBuilder and StringBuffer questions — explained in
a confident, structured, and example-backed way so you can crack your Java interview with ease:
Both StringBuilder and StringBuffer are mutable classes used for creating modifiable string objects.
However, the key difference lies in thread safety.
• StringBuilder is not synchronized, hence faster and better for single-threaded applications.
Example:
In short: Use StringBuilder for speed when you don't need thread safety.
Example:
22. Can StringBuilder and StringBuffer be used for string concatenation? How?
Yes, both are commonly used for string concatenation, especially when dealing with loops or large strings, as
they avoid creating multiple immutable String objects.
The append() method adds a string (or any data type) to the end of the existing content.
Example:
It supports method chaining, so you can append multiple values in one line.
The insert() method inserts text at a specified position (index) within the string.
Example:
Example:
Example:
• capacity() returns the current storage capacity of the builder, which may be more than the actual
string length.
A palindrome reads the same forward and backward (e.g., "madam", "level").
import java.util.Scanner;
public class PalindromeCheck {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = sc.nextLine();
String reversed = new StringBuilder(str).reverse().toString();
if (str.equalsIgnoreCase(reversed)) {
System.out.println("It's a palindrome.");
} else {
System.out.println("Not a palindrome.");
}
}
}
Explanation: We use StringBuilder to reverse the string and compare it (ignoring case).
import java.util.Scanner;
public class VowelConsonantCounter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = sc.nextLine().toLowerCase();
int vowels = 0, consonants = 0;
for (char ch : str.toCharArray()) {
if (Character.isLetter(ch)) {
if ("aeiou".indexOf(ch) != -1)
vowels++;
else
consonants++;
}
}
System.out.println("Vowels: " + vowels);
System.out.println("Consonants: " + consonants);
}
}
Explanation: We loop through each character and count based on whether it is a vowel or consonant (ignoring
spaces, digits, etc.).
30. Find the first non-repeating character in a string
import java.util.*;
c class FirstNonRepeatingChar {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = sc.nextLine();
Map<Character, Integer> map = new LinkedHashMap<>();
for (char ch : str.toCharArray()) {
map.put(ch, map.getOrDefault(ch, 0) + 1);
}
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
if (entry.getValue() == 1) {
System.out.println("First non-repeating character: " +
entry.getKey());
return;
}
}
System.out.println("No non-repeating character found.");
}
}
Explanation: We use a LinkedHashMap to preserve order and track frequency. The first entry with value 1 is
our answer.
• boolean → false
class Student {
String name;
int marks;
Student(String name, int marks) {
this.name = name;
this.marks = marks;
}
void display() {
System.out.println(name + " - " + marks);
}
}
public class Test {
public static void main(String[] args) {
Student[] s = {
new Student("Gaurav", 85),
new Student("Aniket", 78)
};
for (Student stu : s) {
stu.display();
}
}
}
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
int num = 5;
Integer obj = Integer.valueOf(num);
int a = Integer.parseInt("123");
Integer b = Integer.valueOf("123");
7. What is the purpose of the xxxValue() methods in wrapper classes?
These methods convert a wrapper object back to its primitive form. For example:
Double d = 10.5;
double val = d.doubleValue(); // Unboxing manually
int a = Integer.parseInt("123");
double b = Double.parseDouble("45.6");
10. What happens if you try to parse an invalid string using Integer.parseInt()?
It throws a NumberFormatException.
int a = 10;
Integer obj = a; // autoboxing
19. Write a code snippet that shows autoboxing inside a collection like ArrayList<Integer>.
20. What are the potential pitfalls when using wrapper classes in comparisons (== vs .equals())?
Integer a = 128;
Integer b = 128;
System.out.println(a == b); // false
System.out.println(a.equals(b)); // true
Java Keyword
this.name = name;
4. What happens if you use this() and super() in the same constructor?
It leads to a compilation error because both this() and super() must be the first statement in a constructor, and
only one can occupy that position.
9. What happens if a subclass overrides a method and still wants to call the superclass version?
You can use super.methodName() to call the overridden method from the parent class.
15. Write a program to show how static members behave across multiple objects.
class Test {
static int count = 0;
Test() { count++; }
}
Test a = new Test();
Test b = new Test();
System.out.println(Test.count); // Output: 2
16. What does final mean when applied to a variable?
A final variable becomes a constant. Once assigned, its value cannot be changed.
19. Can you change the value of a final variable once assigned?
No. Attempting to change a final variable results in a compilation error.
• finalize(): A method invoked by the garbage collector before object destruction (deprecated in Java 9+).
• Interface (before Java 8) only had abstract methods. Interfaces support multiple inheritance.
28. Can a class be both abstract and final? Why or why not?
No. An abstract class needs to be extended, but a final class cannot be extended — hence, they contradict.
30. What is the effect of declaring a class final but not its methods?
The class cannot be inherited, but its methods can be invoked normally.
Exception Handling
• Error refers to serious problems that a program should not try to catch (e.g., OutOfMemoryError).
• Exception refers to conditions that a program might want to catch and handle (e.g., IOException).
• Checked exceptions must be either caught or declared using the throws keyword.
• Unchecked exceptions are not required to be caught or declared; they occur due to programming
bugs.
10. Will the finally block execute even if the program terminates using System.exit()?
No, if System.exit() is called before the finally block, it will not execute.
• throws is used in a method signature to declare that the method might throw exceptions.
• Error represents serious system failures like memory leaks or JVM crashes.
23. Can we catch multiple exceptions in a single catch block (Java 7+ feature)?
Yes, using multi-catch like:
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Arithmetic error");
} catch (Exception e) {
System.out.println("General error");
}
FileReader fr = null;
try {
fr = new FileReader("data.txt");
// Read file
} catch (IOException e) {
System.out.println("Error reading file");
} finally {
if (fr != null) fr.close();
}
• Static nested class: Does not have access to non-static members of the outer class directly.
• Non-static nested class (Inner class): Has access to all members of the outer class, including private
ones.
9. How can you access an inner class from outside the outer class?
By using the outer class object:
10. Can a static nested class access non-static members of the outer class?
No. A static nested class can only access static members of the outer class.
interface Greeting {
void sayHello();
}
public class Test {
public static void main(String[] args) {
Greeting g = new Greeting() {
public void sayHello() {
System.out.println("Hello from anonymous inner class!");
}
};
g.sayHello();
}
}
Outer.this.someMethod();
• private
• protected
• public
• protected – Accessible within the same package and by subclasses in other packages.
10. Can you restrict access to a class so it’s only visible within the same package?
Yes. Use default access (no modifier) to restrict class visibility to the same package.
11. Can you access a private variable of a class from another class?
No. Private variables are not accessible from other classes. Use getters/setters to access them if needed.
12. What happens when you try to access a private method via inheritance?
You’ll get a compilation error because private methods are not inherited.
13. Write an example to show the difference between default and protected access.
// File: package1/Base.java
package package1;
public class Base {
void defaultMethod() {
System.out.println("Default Access");
}
protected void protectedMethod() {
System.out.println("Protected Access");
}
}
// File: package2/Derived.java
package package2;
import package1.Base;
public class Derived extends Base {
public void accessMethods() {
// defaultMethod(); // Error: Not accessible outside package
protectedMethod(); // OK: Accessible via inheritance
}
}
14. What modifier would you use to make a class member accessible to all other classes?
Use the public modifier.
2. Why is the Object class considered the root of all Java classes?
It provides basic methods like equals(), toString(), hashCode(), etc., that every Java object can use or override.
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Employee e = (Employee) obj;
return id == e.id && name.equals(e.name);
}
11. How and why would you override the toString() method?
Override toString() to return a meaningful string representation of the object (used in logging, debugging).
Example:
@Override
public String toString() {
return "Employee{id=" + id + ", name='" + name + "'}";
}
12. What is the output of System.out.println(obj); if toString() is not overridden?
It prints the default output from Object class:
ClassName@HashCode
13. Can two unequal objects have the same hash code?
Yes. It’s called a hash collision, and it's allowed by the hashCode() contract.
14. Write a custom Employee class and override equals(), toString(), and hashCode().
class Employee {
int id;
String name;
Employee(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Employee e = (Employee) obj;
return id == e.id && name.equals(e.name);
}
@Override
public int hashCode() {
return id * 31 + name.hashCode();
}
@Override
public String toString() {
return "Employee{id=" + id + ", name='" + name + "'}";
}
}
15. What are some best practices when overriding equals() and hashCode()?
Java Packages
import packageName.ClassName;
• java.net – Networking
import packagename.ClassName;
OR
packagename.ClassName obj = new packagename.ClassName();
14. Can you create sub-packages in Java? How?
Yes. Use a dot . to separate sub-packages:
package mycompany.sales;
15. How does the directory structure of packages reflect the package name?
The package name maps to a folder hierarchy:
package com.example.app;
// corresponds to directory: com/example/app/
The Java Collections Framework is a set of classes and interfaces that help manage groups of objects.
It provides data structures like List, Set, and Map, along with utility classes for sorting and searching.
Collection is an interface that represents a group of elements like List and Set.
Collections is a utility class that provides static methods like sort(), reverse(), etc., to operate on collections.
It provides ready-to-use, well-tested data structures that reduce development time and improve performance.
It also promotes consistency by using standard interfaces and methods.
• Map stores key-value pairs; keys must be unique, but values can be duplicated.
• ArrayList is backed by an array and provides fast access using index but slower insertions/deletions.
• LinkedList uses a doubly-linked list, so it's better for frequent insertions and deletions but slower for
access.
10. What are the main differences between HashMap and TreeMap?
• TreeMap maintains keys in sorted order and doesn’t allow null keys.
Great! Here's the interview-style answer format for questions 11–30 on Java Collections:
• LinkedList does not have a predefined capacity; it grows dynamically as nodes are added.
19. What is the time complexity for add, remove, and search in HashSet and TreeSet?
21. What are the key differences between HashMap and TreeMap?
• TreeMap: Sorted by keys, does not allow null keys, slightly slower
• Queue: Supports insertion at the end and removal from the front
• Deque: Supports insertion and removal from both ends (Double-Ended Queue)
• LinkedList: Uses a doubly linked list, can be slower and consumes more memory
• Task scheduling
• Print job management
• Thread pool management
• BFS traversal in graphs/trees
30. What is the difference between PriorityQueue and normal Queue?
PriorityQueue arranges elements based on priority using a heap, not insertion order.
Normal queues follow simple FIFO ordering without priority handling.
• Iterator can traverse only forward and works with all collections.
• ListIterator can traverse both forward and backward but only works with List types like ArrayList and
LinkedList.
• Comparable is used to define natural ordering of objects (inside the class using compareTo()).
• Comparator is used to define custom ordering (outside the class using compare()).
37. How do you sort a list of custom objects using Comparable?
Implement the Comparable interface in the class and override the compareTo() method.
Then use Collections.sort(list);.
43. Write a program to iterate over a HashMap and print keys and values.
import java.util.*;
import java.util.*;
import java.util.*;
Collections.sort(cities, Collections.reverseOrder());
import java.util.*;
public class HashMapToTreeMap {
public static void main(String[] args) {
HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("Zebra", 1);
hashMap.put("Apple", 2);
hashMap.put("Monkey", 3);
import java.util.*;
list.add("One");
list.add("Two");
synchronized (list) {
for (String item : list) {
System.out.println(item);
}
}
}
}
48. How is fail-fast different from fail-safe iterators?
You can use LinkedHashMap with access-order enabled to implement an LRU cache.
50. What are some best practices when working with Java collections?
• Choose the right collection type based on requirements (List, Set, Map).
• Always initialize with proper capacity to avoid resizing overhead.
• Prefer interfaces (List, Set) over implementation classes (ArrayList, HashSet) for flexibility.
• Use Collections.unmodifiableXXX() to create read-only collections when needed.
• Use Concurrent collections for multi-threaded environments.
• Avoid using raw types; always use generics.
• For large datasets, prefer Streams and parallel processing where appropriate.
Thread Basics & Lifecycle (1–10)
4. What is the difference between extending Thread class and implementing Runnable?
• Runnable is preferred for flexibility (since Java doesn't support multiple inheritance).
• Use Thread when you need to override more than just run().
11. When would you use the Runnable interface over extending Thread?
When you want to extend another class or separate logic from thread management.
Synchronization (16–22)
18. What is the difference between synchronized method and synchronized block?
26. What happens if a thread calls wait() without owning the monitor?
It throws IllegalMonitorStateException.
• Lock ordering
• Timeout
Sure! Here are 5 more advanced multithreading interview questions and answers, continuing from where we
left off — focusing on concurrency utilities, thread pools, and best practices.
• execute() is used for Runnable tasks and doesn't return any result.
• submit() can accept both Runnable and Callable and returns a Future object.
6. What are the main abstract classes for byte and character streams?
For bytes: InputStream and OutputStream
For characters: Reader and Writer
All file and buffer-based classes extend from these, ensuring consistency in I/O handling.
15. What happens if the file does not exist while reading?
If we try to read a non-existent file using FileReader or BufferedReader, a FileNotFoundException is thrown.
• Absolute path includes the full location from the root (e.g., C:/Users/.../file.txt)
27. How can you copy contents from one file to another in Java?
Using streams:
Answer:
30. How can you serialize and deserialize an object to/from a file?
Serialization:
Here are detailed and interviewer-friendly answers for Serialization & Deserialization (1–10). Each answer is
crafted to show both understanding and confidence, making it easier for the interviewer to appreciate your
clarity.
Serialization & Deserialization
3. What is deserialization?
Deserialization is the reverse process of serialization. It converts the byte stream back into a Java object. This
helps in reconstructing the previously saved object state from a file, database, or network.
This tells the JVM to skip this field during serialization. It’s commonly used for sensitive data like passwords or
session tokens.
• transient fields are not serialized intentionally, even though they are part of the object.
• static fields are not serialized by nature, as they belong to the class, not the object instance.
So, both are skipped, but for different reasons.
Here, generics ensure that only String elements can be added to the list.
• Code Reusability: Write methods or classes once and use them for any type.
Example:
names.add("Alice");
• <T> defines a generic type — a placeholder for a specific type you’ll provide.
Example:
• <? extends T>: You can read subtypes of T. (Used for reading)
• <? super T>: You can write T and its subtypes. (Used for writing)
Example:
Remember:
@SuppressWarnings("unchecked")
System.out.println(element);
You can call it with any type of array — Integer[], String[], etc. — and it will work.
JDBC (Java Database Connectivity)
• Type 1 – JDBC-ODBC Bridge Driver: Translates JDBC calls into ODBC calls.
• Type 2 – Native-API Driver: Converts JDBC calls into native DB API calls.
• Type 3 – Network Protocol Driver: Sends JDBC calls to a middleware server.
• Type 4 – Thin Driver (Pure Java Driver): Converts JDBC calls directly into database-specific protocol.
Most commonly used.
3. Which JDBC driver type is platform-independent and pure Java?
Type 4 (Thin driver) is pure Java, platform-independent, and directly communicates with the database using
the database’s native protocol. It's the most widely used in production.
Class.forName("com.mysql.cj.jdbc.Driver");
In JDBC 4.0 and above, drivers are auto-registered if present in the classpath.
• Class.forName() loads and registers the driver class implicitly (via static block).
DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
com.mysql.cj.jdbc.Driver
Class.forName("oracle.jdbc.driver.OracleDriver");
For JDBC 4.0 and above, this is optional if the driver JAR is included in the classpath.
Example:
Example:
Example:
try {
// JDBC code
} catch (SQLException e) {
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
}
rs.close();
stmt.close();
con.close();
Or use try-with-resources:
con.setAutoCommit(false);
try {
// multiple SQL statements
con.commit(); // only if all successful
} catch (SQLException e) {
con.rollback(); // if error occurs
}
This gives full control over the transaction.
21. How do you perform an INSERT operation using JDBC?
Example:
String sql = "INSERT INTO student (id, name, age) VALUES (?, ?, ?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, 101);
ps.setString(2, "Gaurav");
ps.setInt(3, 22);
int rowsInserted = ps.executeUpdate();
“Using PreparedStatement avoids SQL injection and ensures the statement is compiled once and reused.”
Example:
Example:
Example:
Answer:
Use PreparedStatement. Never concatenate user inputs directly into SQL queries as it can lead to SQL
Injection.
Bad:
Good:
ps.setString(1, userInput);
Example:
String sql = "INSERT INTO student (id, name, age) VALUES (?, ?, ?)";
PreparedStatement ps = con.prepareStatement(sql);
for (int i = 0; i < 5; i++) {
ps.setInt(1, 100 + i);
ps.setString(2, "Name" + i);
ps.setInt(3, 20 + i);
ps.addBatch();
}
int[] results = ps.executeBatch();
Every executeUpdate() method returns an int which represents the number of rows affected.
Example:
ResultSet types define how you can move through the result and whether it's updatable:
Common types:
Sensitive to DB changes No No
Required settings:
• TYPE_SCROLL_SENSITIVE
• CONCUR_UPDATABLE
Example:
"Updating via ResultSet is handy when you need to fetch and modify records together."
Java Networking
"Java provides built-in libraries for handling network communication, making it easy to build distributed apps."
TCP UDP
Connection-oriented Connectionless
"Think of ServerSocket as a doorman and Socket as the client knocking on the door."
Server:
con.setRequestMethod("GET");
10. What are the advantages of using HttpURLConnection over third-party HTTP libraries?
"For basic HTTP tasks, HttpURLConnection avoids the overhead of third-party libraries."
interface MathOperation {
int operate(int a, int b);
}
public void calculate(MathOperation op) {
System.out.println(op.operate(10, 20));
}
Call:
To indicate the interface is meant to have only one abstract method. It helps catch errors at compile time.
@FunctionalInterface
interface Test {
void show();
default void log() {}
static void info() {}
}
Lambdas are often used with stream operations like filter(), map(), forEach() to process data functionally.
strList.forEach(System.out::println);
"Method references are concise and improve readability when the lambda just calls a method."
Streams API
Annotations
o @Deprecated tells developers not to use the method as it may be removed in future.
@interface MyAnnotation {
String value();
}
You can use it to add custom metadata on methods, classes, or fields.
20. What are the methods of Optional like orElse(), orElseGet(), ifPresent()?
o Period is used to measure time in days, months, and years between two dates.
o Duration is used to measure time in hours, minutes, seconds between two times.
Both help in calculating time differences in a readable way.
30. How is the new Date-Time API better than the old java.util.Date and Calendar?
The new API is immutable, thread-safe, and follows a clean design.
It avoids confusion with months (starting from 0), handles time zones better, and supports
formatting/parsing easily.
Overall, it is much easier and safer to use.