Java Important Notes
Java Important Notes
1|Page @shalithapraveen
Table of Contents
Table of Contents ............................................................................................................................................. 2
1.Differences between JVM,JRE,JDK ............................................................................................................ 9
1.1 JVM (Java Virtual Machine): ............................................................................................................... 9
1.2 JRE (Java Runtime Environment): ......................................................................................................... 9
1.3 JDK (Java Development Kit): .............................................................................................................. 9
1.4 How it works together: ......................................................................................................................... 9
2. Variables and Data Types in Java ........................................................................................................ 10
2.1 Variables .............................................................................................................................................. 10
2.1.1 Types of Variables in Java: ...................................................................................................... 10
2.2 Data Types ........................................................................................................................................... 11
2.2.1 Primitive Data Types ................................................................................................................... 11
2.2.2 Reference Data Types: ............................................................................................................... 11
2.2.3 Primitive vs. Reference Data Types: ......................................................................................... 12
2.3 Variable Declaration and Initialization .......................................................................................... 12
2.4 Type Casting ........................................................................................................................................ 12
2.4.1 Example of Implicit Casting: ...................................................................................................... 12
2.4.2 Example of Explicit Casting: ...................................................................................................... 13
2.5 Summary ............................................................................................................................................... 13
3. Access Modifiers......................................................................................................................................... 14
3.1 What are Access Modifiers? ............................................................................................................. 14
3.2 Analogy: Office Building Access ...................................................................................................... 14
3.3 Types of Access Modifiers ................................................................................................................. 14
3.3.1 Public: ............................................................................................................................................. 14
3.3.2 Private: .......................................................................................................................................... 14
3.3.3 Protected: ...................................................................................................................................... 14
3.3.4 Default (Package-Private): ........................................................................................................ 15
3.4 Summary of Access Modifiers: .......................................................................................................... 15
3.5 Use Cases: ............................................................................................................................................ 16
3.6 Example Combining All Modifiers:................................................................................................... 16
3.7 Conclusion: ............................................................................................................................................ 16
4. Static vs. Instance Members in Java ....................................................................................................... 17
4.1 What are they? ................................................................................................................................... 17
4.2 Analogy: Library ................................................................................................................................. 17
2|Page @shalithapraveen
4.3 Key Points: ............................................................................................................................................ 17
4.4 Example in Java: ................................................................................................................................. 17
4.5 Key Features: ....................................................................................................................................... 19
4.6 Conclusion: ............................................................................................................................................ 19
5. Constructors ................................................................................................................................................. 20
5.1 What is a Constructor? ....................................................................................................................... 20
5.2 Analogy: House Blueprints ................................................................................................................. 20
5.3 Types of Constructors ......................................................................................................................... 20
I. Default Constructor: ....................................................................................................................... 20
II. Parameterized Constructor: ......................................................................................................... 21
III. Constructor Overloading: ......................................................................................................... 22
5.4 Special Features of Constructors ...................................................................................................... 23
5.5 Conclusion: ............................................................................................................................................ 24
6. Inheritance in Java ..................................................................................................................................... 25
6.1 What is it?............................................................................................................................................. 25
6.2 Analogy: Family Traits ....................................................................................................................... 25
6.3 Key Points: ............................................................................................................................................ 25
6.4 Example: ............................................................................................................................................... 25
6.5 Important Concepts: ............................................................................................................................ 26
6.6 Conclusion: ............................................................................................................................................ 26
7. Method Overriding in Java ..................................................................................................................... 27
7.1 What is it?............................................................................................................................................. 27
7.2 Analogy: Customizing a Family Recipe ........................................................................................... 27
7.3 Key Points: ............................................................................................................................................ 27
7.4 Example in Java: ................................................................................................................................. 27
7.5 Key Features: ....................................................................................................................................... 28
7.6 Example Output:.................................................................................................................................. 28
7.8 Conclusion: ............................................................................................................................................ 28
8. Polymorphism in Java................................................................................................................................ 29
8.1 What is it?............................................................................................................................................. 29
8.2 Analogy: Remote Control for Different Devices ............................................................................ 29
8.3 Key Points: ............................................................................................................................................ 29
8.4 Example in Java: ................................................................................................................................. 29
8.5 Key Features: ....................................................................................................................................... 31
3|Page @shalithapraveen
8.6 Conclusion: ............................................................................................................................................ 31
9. Encapsulation in Java ................................................................................................................................ 32
9.1 What is it?............................................................................................................................................. 32
9.2 Analogy: Capsule or Container ........................................................................................................ 32
9.3 Key Points: ............................................................................................................................................ 32
9.4 Example in Java: ................................................................................................................................. 32
9.5 Key Features: ....................................................................................................................................... 34
9.6 Conclusion: ............................................................................................................................................ 34
10. Abstraction in Java ................................................................................................................................. 35
10.1 What is it? .......................................................................................................................................... 35
10.2 Analogy: TV Remote Control .......................................................................................................... 35
10.3 Key Points: .......................................................................................................................................... 35
10.4 Example in Java: .............................................................................................................................. 35
10.5 Key Features: ..................................................................................................................................... 36
10.6 Conclusion: .......................................................................................................................................... 36
11. Interfaces in Java .................................................................................................................................... 37
11.1 What is it? .......................................................................................................................................... 37
11.2 Analogy: Contract............................................................................................................................. 37
11.3 Key Points: .......................................................................................................................................... 37
11.4 Example in Java: .............................................................................................................................. 37
11.5 Key Features: ..................................................................................................................................... 38
11.6 Conclusion: .......................................................................................................................................... 38
12. Differences Between Interface and Abstract Class ........................................................................... 39
12.1 Purpose ............................................................................................................................................... 39
12.2 Method Definitions ............................................................................................................................ 39
12.3 Multiple Inheritance .......................................................................................................................... 39
12.4 Fields ................................................................................................................................................... 39
12.5 Constructor ......................................................................................................................................... 39
12.6 Accessibility Modifiers ..................................................................................................................... 39
12.7 Implementation .................................................................................................................................. 39
12.8 Summary Table ................................................................................................................................. 40
12.9 Example to Illustrate the Differences ............................................................................................ 40
12.10 Conclusion ........................................................................................................................................ 41
13. Method Overloading .............................................................................................................................. 42
4|Page @shalithapraveen
13.1 What is Method Overloading? ...................................................................................................... 42
13.2 Analogy: Swiss Army Knife ............................................................................................................. 42
13.3 Key Features of Method Overloading: ........................................................................................ 42
13.4 Examples: ........................................................................................................................................... 42
I. Overloading Based on Number of Parameters: ...................................................................... 42
II. Overloading Based on Parameter Types: ................................................................................ 43
III. Overloading Based on Parameter Order:............................................................................ 44
13.5 Benefits of Method Overloading: .................................................................................................. 45
13.6 Summary of Method Overloading: ............................................................................................... 45
13.7 Quick Overview: ............................................................................................................................... 45
14. Wrapper Classes .................................................................................................................................... 46
14.1 What are Wrapper Classes? ......................................................................................................... 46
14.2 Analogy: Wrapper as a Gift Box ................................................................................................. 46
14.3 Why Use Wrapper Classes? .......................................................................................................... 46
14.4 Primitive Types and Their Wrapper Classes: .............................................................................. 46
14.4.1 Example: ..................................................................................................................................... 47
14.5 Features of Wrapper Classes: ....................................................................................................... 47
14.6 Example in Practice:........................................................................................................................ 48
14.7 Benefits of Wrapper Classes: ........................................................................................................ 48
14.8 Summary of Wrapper Classes: ...................................................................................................... 49
15. Error Handling in Java ........................................................................................................................... 50
15.1 What is it? .......................................................................................................................................... 50
15.2 Analogy: Lifeguard at a Pool ........................................................................................................ 50
15.3 Key Points: .......................................................................................................................................... 50
15.4 Example in Java: .............................................................................................................................. 50
15.5 Key Features: ..................................................................................................................................... 51
15.6 Conclusion: .......................................................................................................................................... 51
16 Exception Handling in Java .................................................................................................................... 52
16.1 What is it? .......................................................................................................................................... 52
16.2 Analogy: Safety Net ........................................................................................................................ 52
16.3 Key Points: .......................................................................................................................................... 52
16.4 Example in Java: .............................................................................................................................. 52
16.5 Key Features: ..................................................................................................................................... 53
16.6 Conclusion: .......................................................................................................................................... 53
5|Page @shalithapraveen
17. Garbage Collection in Java.................................................................................................................. 54
17.1 What is it? .......................................................................................................................................... 54
17.2 Analogy: Room Cleanup After a Party ........................................................................................ 54
17.3 Key points: ......................................................................................................................................... 54
17.4 Stages of Garbage Collection:...................................................................................................... 54
18. Multithreading in Java ........................................................................................................................... 55
18.1 What is it? .......................................................................................................................................... 55
18.2 Analogy: Making a Sandwich with Multiple Tasks ..................................................................... 55
18.3 Key Points: .......................................................................................................................................... 55
18.4 Example: ............................................................................................................................................. 55
18.5 Important Concepts: ......................................................................................................................... 55
18.6 Conclusion: .......................................................................................................................................... 55
19. Concurrency in Java ................................................................................................................................ 57
19.1 What is it? .......................................................................................................................................... 57
19.2 Analogy: Busy Restaurant ............................................................................................................... 57
19.3 Key Points: .......................................................................................................................................... 57
19.4 Example in Java: .............................................................................................................................. 57
19.5 Key Features: ..................................................................................................................................... 59
19.6 Conclusion: .......................................................................................................................................... 59
20. Java Collections Framework.................................................................................................................. 60
20.1 What is it? .......................................................................................................................................... 60
20.2 Analogy: Toolbox ............................................................................................................................. 60
20.3 Key Points: .......................................................................................................................................... 60
20.4 Types of Collections: ........................................................................................................................ 60
20.5 Example in Java: .............................................................................................................................. 61
20.6 Key Features: ..................................................................................................................................... 62
20.7 Differences between their implementations ................................................................................. 62
1. List vs. Set vs. Map ............................................................................................................................ 62
2. List Implementations........................................................................................................................... 63
3. Set Implementations .......................................................................................................................... 63
4. Map Implementations........................................................................................................................ 63
5. Queue Implementations .................................................................................................................... 64
20.8 Other Important Differences: .......................................................................................................... 64
1. Synchronized vs. Non-Synchronized Collections .......................................................................... 64
6|Page @shalithapraveen
2. Sorted vs. Unsorted Collections ....................................................................................................... 64
3. Navigable Collections....................................................................................................................... 64
20.9 Conclusion: .......................................................................................................................................... 64
21. Java Generics .......................................................................................................................................... 65
21.1 What is it? .......................................................................................................................................... 65
21.2 Analogy: Universal Toolbox ........................................................................................................... 65
21.3 Key Points: .......................................................................................................................................... 65
21.4 Example in Java: .............................................................................................................................. 65
21.5 Key Features: ..................................................................................................................................... 66
21.6 Conclusion: .......................................................................................................................................... 67
22. Java Strings .............................................................................................................................................. 68
22.1 What is a String in Java? ................................................................................................................ 68
22.2 Analogy: String as a Necklace ...................................................................................................... 68
22.3 Key Characteristics of Strings: ........................................................................................................ 68
22.3.1 Creating a String: ..................................................................................................................... 68
22.4 Important String Methods: ............................................................................................................... 68
22.5 Immutability Explained: ................................................................................................................... 70
22.6 String Pool in Java: .......................................................................................................................... 70
22.6.1 How it works:.............................................................................................................................. 70
22.6.2 Example: ..................................................................................................................................... 70
22.7 Summary of Java Strings: ............................................................................................................... 70
23. String Builder............................................................................................................................................ 71
23.1 Key Features of StringBuilder ............................................................................................ 71
23.2 Basic Operations with StringBuilder ................................................................................. 71
1. Creating a StringBuilder .................................................................................................................. 71
2. append() ............................................................................................................................................. 71
3. insert(int offset, String str) ................................................................................................................ 71
4. delete(int start, int end) .................................................................................................................... 71
5. replace(int start, int end, String str) ................................................................................................ 72
6. reverse() .............................................................................................................................................. 72
7. charAt(int index) ................................................................................................................................ 72
8. toString() .............................................................................................................................................. 72
9. setCharAt(int index, char ch) ........................................................................................................... 73
10. capacity() .......................................................................................................................................... 73
7|Page @shalithapraveen
23.3 When to Use StringBuilder ................................................................................................. 73
23.4 Performance Comparison ................................................................................................................ 73
23.5 String vs. StringBuilder ..................................................................................................................... 74
23.6 Summary ............................................................................................................................................. 74
24. Differences between StringBuilder and StringBuffer ....................................................................... 75
24.1 Explanation ........................................................................................................................................ 75
1. Thread-Safety: ................................................................................................................................... 75
2. Performance: ...................................................................................................................................... 75
3. Use Case: ............................................................................................................................................ 75
24.2 Methods in StringBuilder and StringBuffer ........................................................... 76
24.3 Example: StringBuilder vs StringBuffer ......................................................................................... 76
24.4 When to Use StringBuilder or StringBuffer .......................................................... 76
24.5 Summary ............................................................................................................................................. 77
25. Java Streams............................................................................................................................................ 77
25.1 What is it? .......................................................................................................................................... 77
25.2 Analogy: River ................................................................................................................................... 77
25.3 Key Points: .......................................................................................................................................... 77
25.4 Example in Java: .............................................................................................................................. 77
25.5 Key Features: ..................................................................................................................................... 78
25.6 Conclusion: .......................................................................................................................................... 78
26. Java Lambdas .......................................................................................................................................... 79
26.1 What is it? .......................................................................................................................................... 79
26.2 Analogy: Recipe Card ..................................................................................................................... 79
26.3 Key Points: .......................................................................................................................................... 79
26.4 Syntax of a Lambda Expression: ................................................................................................... 79
26.5 Example in Java: .............................................................................................................................. 79
26.6 Key Features: ..................................................................................................................................... 80
26.7 Conclusion: .......................................................................................................................................... 80
8|Page @shalithapraveen
1.Differences between JVM,JRE,JDK
Imagine you're baking a cake, where:
JVM (Java Virtual Machine) is the oven that runs the baking process.
JRE (Java Runtime Environment) is the kitchen (with ingredients, tools, etc.) needed to
bake a cake.
JDK (Java Development Kit) is like the entire kitchen plus the recipe and tools needed
for both preparing and baking.
What it does: JRE contains everything required to run Java applications. It includes the
JVM and libraries needed to run Java programs.
Analogy: The kitchen with all the tools (ingredients, bowls, etc.) to prepare the cake, but
without the recipe or instructions to create new recipes.
What it does: The JDK is a superset of JRE, meaning it includes the JRE plus tools like
the compiler (javac) and other utilities necessary to develop Java applications.
Analogy: The kitchen (JRE) plus a cookbook and tools to create your own cake recipe.
It's what you need to both write and run Java code.
JDK: You use the JDK to write and compile Java code (writing the recipe).
JRE: Once the code is compiled into bytecode, the JRE provides the environment
(ingredients, tools) for running it.
JVM: The JVM runs the compiled bytecode, making sure the computer understands and
executes it correctly (oven baking the cake).
9|Page @shalithapraveen
2. Variables and Data Types in Java
Variables in Java are containers for storing data values. Every variable in Java must be declared
with a specific data type that determines the type and size of data it can hold.
2.1 Variables
A variable is a named memory location that can store a value. Each variable in Java has:
Name: The identifier by which the variable is referenced (e.g., age, salary).
Type: Specifies what kind of data the variable can hold (e.g., integers, floating-point
numbers, text).
Value: The data stored in the variable.
1. Local Variables:
o Declared within a method, constructor, or block.
o Scope is limited to the block where it is declared.
o Must be initialized before use.
Example:
2. Instance Variables:
10 | P a g e @shalithapraveen
Only one copy exists regardless of how many objects are created.
Example:
Data Default
Size Description Example
Type Value
2
short 0 Stores medium integer values. short s = 10000;
bytes
4
int 0 Stores standard integer values. int i = 500000;
bytes
8
long 0L Stores large integer values. long l = 100000L;
bytes
boolean isTrue =
boolean 1 bit false Stores true or false values. true;
2
char '\u0000' Stores a single character. char letter = 'A';
bytes
11 | P a g e @shalithapraveen
These data types are used to refer to objects. They include:
Example:
You declare a variable by specifying the data type and name, and optionally initializing it with a
value.
Declaration:
Type casting is used to convert a variable from one data type to another. There are two types:
Implicit Casting (Widening): Automatic conversion when the data type is widened (e.g.,
int to double).
Explicit Casting (Narrowing): Manual conversion when narrowing (e.g., double to int).
int x = 10;
double y = x; // No error, widening from int to double
12 | P a g e @shalithapraveen
2.4.2 Example of Explicit Casting:
double a = 10.5;
int b = (int) a; // Need to cast, narrowing from double to int
2.5 Summary
Variables are used to store data, and they must be declared with a specific data type.
Java has primitive and reference data types.
Primitive data types include int, double, boolean, etc.
Reference types refer to objects and arrays.
You can declare, initialize, and cast variables, converting them between data types when
needed.
13 | P a g e @shalithapraveen
3. Access Modifiers
3.1 What are Access Modifiers?
Access modifiers in Java control the visibility of classes, methods, and variables. They
define who can access a particular piece of code. Java has four types of access
modifiers: public, private, protected, and default (also called package-private).
Think of an office building with different rooms (your methods, variables, or classes). Each
room has different levels of access control based on who should be able to enter.
3.3.1 Public:
o Analogy: Lobby (Public Area). Anyone can enter the lobby of a building.
o Explanation: If something is public, it can be accessed from anywhere—inside
the same class, other classes, other packages—there are no restrictions.
Example:
3.3.2 Private:
Analogy: CEO's Office (Private Area). Only the CEO (the class itself) can access this
room; no one else in the building can.
Explanation: If something is private, it can only be accessed within the same class.
Other classes (even in the same package) cannot access it.
Example:
private String secretCode = "1234"; // Only accessible within the Office class
3.3.3 Protected:
14 | P a g e @shalithapraveen
Analogy: Employee-Only Area. Only employees and special guests (classes in the same
package or subclasses) are allowed in this area.
Explanation: If something is protected, it can be accessed by classes in the same
package and subclasses (even if they are in different packages). It's more restrictive than
public but more open than private.
Example:
Analogy: Break Room. Only employees from the same department (package) can access
this area, but people from other departments (packages) cannot.
Explanation: If no access modifier is specified, Java treats the element as package-
private. This means it is accessible by classes within the same package but not by
classes in other packages.
Example:
class Office {
Public ✅ ✅ ✅ ✅
Private ✅ ❌ ❌ ❌
Default ✅ ✅ ❌ ❌
15 | P a g e @shalithapraveen
3.5 Use Cases:
1. Public: Use it when you want your code to be available globally, like a public API or
utility method.
2. Private: Use it for sensitive data or methods that should not be exposed outside the class.
3. Protected: Use it when you want to share access with subclasses or classes within the same
package.
4. Default: Use it when you want to restrict access to the package level but don’t need
protection for subclasses.
Access modifiers are like different access levels in a building, determining who can enter
certain areas. By controlling access to your code, you protect sensitive data and maintain
clean and secure architectures.
16 | P a g e @shalithapraveen
4. Static vs. Instance Members in Java
4.1 What are they?
Static members (variables and methods) belong to the class itself rather than any specific
instance of the class. This means there is only one copy of the static member, and it is
shared across all instances of the class.
Instance members (variables and methods) belong to an individual instance (object) of a
class. Each object has its own copy of instance members, which can have different values
across different objects.
Static members represent the library's general rules and resources (like the opening hours,
membership fees, and available books). These are the same for every visitor.
Instance members represent the individual library cards and personal information of
each visitor (like the name, borrowed books, and due dates). These are unique to each
visitor.
17 | P a g e @shalithapraveen
int visitorID;
// Constructor
Library(String name, int id) {
this.visitorName = name;
this.visitorID = id;
}
// Static method
static void displayLibraryInfo() {
System.out.println("Welcome to " + libraryName);
}
// Instance method
void displayVisitorInfo() {
System.out.println("Visitor Name: " + visitorName + ", Visitor ID: " + visitorID);
}
}
18 | P a g e @shalithapraveen
visitor1.displayVisitorInfo(); // Outputs: Visitor Name: Alice, Visitor ID: 101
visitor2.displayVisitorInfo(); // Outputs: Visitor Name: Bob, Visitor ID: 102
1. Static Member: libraryName is a static variable shared among all instances of Library,
representing a common attribute of the library.
2. Instance Members: visitorName and visitorID are instance variables unique to each
Library object, allowing different visitors to have their own details.
3. Static Method: The method displayLibraryInfo() can be called without creating an
instance of Library, demonstrating how static methods can operate on class-level data.
4.6 Conclusion:
Static members are like the general rules and resources of a library that apply to all
visitors, while instance members are like the personal library cards that contain unique
information for each visitor. Understanding this distinction helps in designing classes and
managing resources effectively in Java.
19 | P a g e @shalithapraveen
5. Constructors
5.1 What is a Constructor?
Think of a constructor as the blueprint for building a house. Just like a blueprint defines how to
build a house, a constructor defines how to build and initialize an object (house). Each time you
create a new house (object), you follow the blueprint (constructor) to make sure everything is set
up properly, like the number of rooms or the type of materials used.
I. Default Constructor:
o Analogy: Standard House Blueprint: If you don't specify anything, the construction
team uses a standard blueprint with default specifications (e.g., 2 bedrooms, 1
bathroom).
o Explanation: Java provides a default constructor if you don’t define one. It
initializes the object with default values (like null for objects, 0 for integers, etc.).
Example in Java:
20 | P a g e @shalithapraveen
}
Analogy: Customized House Blueprint: When building a custom house, you specify
things like the number of bedrooms, the size of the kitchen, etc. These parameters help
you customize the house to your needs.
Explanation: A parameterized constructor allows you to pass arguments to customize
the initialization of the object. This is useful when you want to give specific initial values
to the object's properties.
Example in Java:
String type;
int rooms;
this.type = type;
this.rooms = rooms;
21 | P a g e @shalithapraveen
System.out.println(myHouse.rooms); // Output: 4
Example in Java:
// Default constructor
public House() {
this.type = "Apartment";
this.rooms = 2;
}
// Parameterized constructor
public House(String type, int rooms) {
this.type = type;
this.rooms = rooms;
}
}
22 | P a g e @shalithapraveen
House defaultHouse = new House(); // Calls default constructor
House customHouse = new House("Villa", 4); // Calls parameterized constructor
1. No Return Type:
o A constructor does not have a return type (not even void). It just initializes the
object and doesn't return any value.
2. Same Name as the Class:
o A constructor always has the same name as the class it belongs to.
3. Constructor Chaining:
o Analogy: Sometimes, you might want to use one blueprint to build the foundation,
and another one for the specifics. In Java, you can use one constructor inside
another constructor using this(), which is called constructor chaining.
Example:
// Constructor chaining
public House() {
this("Apartment", 2); // Calls the parameterized constructor
}
23 | P a g e @shalithapraveen
5.5 Conclusion:
A constructor is like a blueprint for building a house. It sets the initial state of an object
and ensures that it is properly constructed with either default or specific values. You can
have different blueprints (constructors) for various types of houses (objects), making it easy
to build and customize your objects based on different needs.
24 | P a g e @shalithapraveen
6. Inheritance in Java
6.1 What is it?
Inheritance is a key feature in Java where one class (child class) inherits properties and
behaviors (methods) from another class (parent class). It allows code reuse and makes it
easier to maintain programs.
void walk() {
System.out.println(name + " is walking.");
}
25 | P a g e @shalithapraveen
void talk() {
System.out.println(name + " is talking.");
}
}
void attendClass() {
System.out.println(name + " is attending class.");
}
}
In this example:
The Student class doesn’t need to rewrite the code for walking and talking. It inherits these
behaviors from the Person class.
The Student class can still add its own specific behavior (like attendClass()).
1. Super and Subclass: The parent is called the superclass, and the child is called the
subclass.
2. Method Overriding: If the child wants to change a trait, like how they talk, they can
override the method in the parent class.
6.6 Conclusion:
Inheritance makes it easy to create specialized classes by building on existing ones, much
like how children inherit traits from their parents but can also have their own unique
characteristics.
26 | P a g e @shalithapraveen
7. Method Overriding in Java
7.1 What is it?
Method overriding happens when a child class provides its own specific implementation of
a method that is already defined in its parent class. It allows a subclass to modify or
customize a behavior inherited from its superclass.
27 | P a g e @shalithapraveen
System.out.println("The dog barks.");
}
}
Parent Method: If you call makeSound() on an Animal, it will print "The animal makes
a sound."
Overridden Method: If you call makeSound() on a Dog, it will print "The dog barks."
7.8 Conclusion:
Method overriding allows child classes to customize or modify the behavior of methods
they inherit from their parent classes. It’s like taking an inherited family recipe and
adjusting it to fit your taste.
28 | P a g e @shalithapraveen
8. Polymorphism in Java
8.1 What is it?
3. Polymorphism in Action: Even though you are using the same remote (method), it
behaves differently depending on the device (object) you are controlling.
8.4 Example in Java:
1. Parent Class (Animal): You have a method makeSound() that is common to all animals.
2. Child Classes (Dog, Cat, Cow): Each animal makes a different sound. Polymorphism
allows you to call makeSound() on any animal object, and it will respond with its own
sound.
// Parent class
class Animal {
void makeSound() {
System.out.println("The animal makes a sound.");
}
}
29 | P a g e @shalithapraveen
@Override
void makeSound() {
System.out.println("The dog barks.");
}
}
// Main class
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal(); // Parent class object
Animal myDog = new Dog(); // Child class object - Dog
Animal myCat = new Cat(); // Child class object - Cat
Animal myCow = new Cow(); // Child class object - Cow
30 | P a g e @shalithapraveen
myAnimal.makeSound(); // Outputs: The animal makes a sound.
myDog.makeSound(); // Outputs: The dog barks.
myCat.makeSound(); // Outputs: The cat meows.
myCow.makeSound(); // Outputs: The cow moos.
}
}
8.5 Key Features:
Method Overriding: Polymorphism is achieved through method overriding. Each child
class overrides the makeSound() method to give it its own unique behavior.
Single Interface, Multiple Behaviors: The makeSound() method behaves differently
based on the object (dog, cat, or cow), even though you call the same method.
Flexible Code: Polymorphism allows you to write flexible code. You don’t need to know
which specific animal you’re working with, just that it’s an Animal. This makes your
program easier to extend or modify later.
8.6 Conclusion:
Polymorphism allows one interface (like a remote control) to handle multiple forms of
objects (different devices). In Java, it means that methods can take many forms, making
the program more dynamic and flexible. It's like using one remote for various devices, but
each responds differently depending on the type of device.
31 | P a g e @shalithapraveen
9. Encapsulation in Java
9.1 What is it?
o Private Data: Inside the capsule, ingredients are marked as private. This means
they can't be accessed directly from outside the capsule.
o Public Methods: You provide public methods (like a lid or opening) that allow
controlled access to the data.
3. Maintaining Integrity: Encapsulation ensures that the data remains valid. You can add
checks or conditions within the public methods to validate the data before using it.
9.4 Example in Java:
// Class definition
class BankAccount {
// Private data members
private String accountNumber;
private double balance;
// Constructor
public BankAccount(String accountNumber, double initialBalance) {
this.accountNumber = accountNumber;
this.balance = initialBalance;
}
32 | P a g e @shalithapraveen
// Public method to deposit money
public void deposit(double amount) {
if (amount > 0) {
balance += amount; // Add amount to balance
System.out.println("Deposited: " + amount);
} else {
System.out.println("Invalid deposit amount.");
}
}
// Main class
public class Main {
33 | P a g e @shalithapraveen
public static void main(String[] args) {
// Creating a BankAccount object
BankAccount myAccount = new BankAccount("123456789", 500.00);
Encapsulation keeps the data safe from outside interference and misuse. By using
encapsulation, you ensure that your object can maintain its internal state and provide a
clear interface for interaction. It’s like having a capsule that securely holds its contents,
allowing only controlled access to ensure everything works as intended.
34 | P a g e @shalithapraveen
10. Abstraction in Java
10.1 What is it?
35 | P a g e @shalithapraveen
// Subclass (inherits from Shape)
class Rectangle extends Shape {
// Providing implementation for the abstract method
void draw() {
System.out.println("Drawing a rectangle.");
}
}
// Main class
public class Main {
public static void main(String[] args) {
Shape myCircle = new Circle(); // Creating a Circle object
Shape myRectangle = new Rectangle(); // Creating a Rectangle object
Abstraction allows you to hide the complex implementation details of an object and
expose only the necessary functionalities, making it easier to interact with objects. It helps
to reduce complexity and enhances the usability of your code, much like a TV remote
simplifies controlling the TV.
36 | P a g e @shalithapraveen
11. Interfaces in Java
11.1 What is it?
An interface in Java is a reference type, similar to a class, that can contain only constants,
method signatures, default methods, static methods, and nested types. Interfaces cannot
contain instance fields or constructors. They are used to achieve abstraction and multiple
inheritance in Java, allowing classes to implement the same set of methods.
37 | P a g e @shalithapraveen
// Class implementing the interface
class Cat implements Animal {
// Providing implementation for the interface method
public void makeSound() {
System.out.println("The cat meows.");
}
}
// Main class
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog(); // Creating a Dog object
Animal myCat = new Cat(); // Creating a Cat object
Interfaces allow you to define a contract that multiple classes can implement, ensuring
they provide specific functionalities. This promotes flexibility and reusability in your code,
as different classes can fulfill the same contract in various ways, just like different parties
can fulfill the terms of a contract according to their unique methods.
38 | P a g e @shalithapraveen
12. Differences Between Interface and Abstract Class
12.1 Purpose
Interface: An interface defines a contract for what a class can do, without specifying how
it does it. It is primarily used to achieve abstraction and multiple inheritance.
Abstract Class: An abstract class can have both abstract methods (without implementation)
and concrete methods (with implementation). It serves as a base class that can provide
some default behavior while still enforcing that certain methods be implemented by
subclasses.
Interface: All methods in an interface are implicitly abstract (unless they are default or
static methods), meaning they do not have a body.
Abstract Class: An abstract class can have abstract methods (without implementation) as
well as fully defined methods (with implementation).
Interface: A class can implement multiple interfaces, allowing for a form of multiple
inheritance.
Abstract Class: A class can only extend one abstract class, adhering to single inheritance.
12.4 Fields
Interface: Cannot have instance variables (fields). However, it can have static final
variables (constants).
Abstract Class: Can have instance variables, providing a way to store state.
12.5 Constructor
Interface: All methods in an interface are public by default, and you cannot use access
modifiers like private or protected for methods.
Abstract Class: Can have methods with different access modifiers (public, protected, or
private).
12.7 Implementation
Interface: A class that implements an interface must provide implementations for all of its
methods.
39 | P a g e @shalithapraveen
Abstract Class: A class that extends an abstract class may implement only the abstract
methods, but it is not required to implement all the methods, as it can still inherit concrete
methods from the abstract class.
Accessibility
All methods are public Can use different access modifiers
Modifiers
Implementation Must implement all methods May implement only abstract methods
// Abstract Class
abstract class Mammal {
// Abstract method
abstract void walk();
// Concrete method
void breathe() {
40 | P a g e @shalithapraveen
System.out.println("Breathing air.");
}
}
// Main class
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.makeSound(); // Outputs: The dog barks.
myDog.walk(); // Outputs: The dog walks on four legs.
myDog.breathe(); // Outputs: Breathing air.
}
}
12.10 Conclusion
Interfaces are used when you want to define a contract that can be implemented by
multiple classes, allowing for multiple inheritance.
Abstract classes are used when you want to provide a common base with shared
behavior and enforce specific methods that subclasses must implement.
41 | P a g e @shalithapraveen
13. Method Overloading
13.1 What is Method Overloading?
Method overloading allows a class to have multiple methods with the same name but
different parameter lists (type, number, or order of parameters). This enables you to
perform similar actions in different ways.
Analogy: Imagine using a knife to cut both small and large objects. The same tool is used,
but with different effort for each size.
Explanation: Here, the methods have the same name but take different numbers of
parameters.
Example in Java:
42 | P a g e @shalithapraveen
// Overloaded method to add three numbers
public int add(int a, int b, int c) {
return a + b + c;
}
}
Analogy: The Swiss Army Knife can handle different tasks (cutting paper, cutting wood),
but the tool used depends on the material. You use scissors for paper and a blade for
wood.
Explanation: Methods have the same name but accept different types of parameters.
Example in Java:
43 | P a g e @shalithapraveen
}
}
Analogy: Using the Swiss Army Knife scissors to cut either left-handed or right-handed.
The action is the same, but the order in which you approach the task changes.
Explanation: Methods have the same name and types of parameters, but the order of the
parameters is different.
Example in Java:
44 | P a g e @shalithapraveen
public static void main(String[] args) {
Calculator calc = new Calculator();
calc.print(10, 20.5); // Output: Integer: 10, Double: 20.5
calc.print(20.5, 10); // Output: Double: 20.5, Integer: 10
}
}
13.5 Benefits of Method Overloading:
1. Cleaner Code:
o Method overloading allows you to use the same method name for similar
functionality, making the code cleaner and more readable.
2. Improves Readability:
o Having multiple methods with the same name reduces the need to remember
multiple method names, enhancing readability and ease of use.
3. Flexibility:
o Method overloading provides flexibility to call the same method with different
parameter types or numbers without having to create completely new methods.
Same name, different parameters: You can have multiple methods with the same name
but different parameter lists.
Return type doesn't matter: Method overloading is determined by the parameter list, not
the return type.
Cleaner and more readable: It improves the structure and readability of your code by
allowing similar operations to share a common method name.
Analogy: Method overloading is like a Swiss Army Knife—one tool, many functionalities.
Overloading Criteria: Differ in the number, type, or order of parameters.
45 | P a g e @shalithapraveen
14. Wrapper Classes
14.1 What are Wrapper Classes?
Wrapper classes are used to "wrap" or encapsulate primitive data types (like int, char,
etc.) into objects. Java provides wrapper classes for all primitive types. These classes
enable you to treat primitives as objects.
Imagine you have a small object, like a toy, and you want to wrap it inside a gift box to make it
presentable or easier to handle.
The toy represents the primitive data type (simple and direct, like int or char).
The gift box is the wrapper class that wraps around the toy, turning it into an object,
making it more flexible for certain situations (like storing it in collections or passing it to
methods that require objects).
1. Collections: Java collections (like ArrayList, HashMap) cannot store primitive types
directly. Instead, they store objects. Wrapper classes allow you to store primitive values in
these collections by turning them into objects.
2. Object Methods: Primitive types don't have methods. Wrapping them in objects allows
you to use methods like .toString(), .compareTo(), etc.
int Integer
char Character
double Double
boolean Boolean
float Float
long Long
byte Byte
short Short
46 | P a g e @shalithapraveen
14.4.1 Example:
Example:
Integer wrappedNum = Integer.valueOf(num); // Boxing (or wrapping) the int into an Integer
object
2. Unboxing (Unwrapping): Converting a wrapper class object back into its corresponding
primitive type.
Example:
Integer wrappedNum = 10;
int num = wrappedNum.intValue(); // Unboxing (or unwrapping) the Integer object back into a
primitive int
3. Autoboxing and Unboxing: Java automatically handles boxing and unboxing. You don’t
need to manually convert between primitives and wrapper objects.
int num = 5;
47 | P a g e @shalithapraveen
Integer wrappedNum = num; // Java automatically boxes it into an Integer object
1. Collections Compatibility: You can store primitive values in Java collections like
ArrayList, HashMap, etc.
2. Method Support: Wrapper classes come with useful methods (toString(), compareTo(),
etc.) that you can’t use with primitive types.
48 | P a g e @shalithapraveen
3. Flexibility in Coding: Wrappers provide more flexibility when passing values into
methods that require objects.
Analogy: Primitive types are like toys; wrapper classes are like gift boxes for those toys.
Boxing: Wrapping a primitive into its corresponding object (toy into gift box).
Unboxing: Unwrapping the object back into a primitive (taking the toy out of the box).
Autoboxing/Unboxing: Java’s automatic handling of boxing and unboxing.
49 | P a g e @shalithapraveen
15. Error Handling in Java
15.1 What is it?
50 | P a g e @shalithapraveen
private void rescue(String swimmer) {
System.out.println("Lifeguard is rescuing " + swimmer + "!");
}
Error handling is like having a lifeguard at a pool, ensuring that any problems are
monitored and handled effectively. It allows programs to respond gracefully to
unexpected situations, preventing crashes and ensuring user safety.
51 | P a g e @shalithapraveen
16 Exception Handling in Java
16.1 What is it?
Exception Handling is a mechanism in Java that allows developers to manage errors and
exceptional conditions in a controlled manner. It helps prevent the program from crashing
and provides a way to respond to errors gracefully.
52 | P a g e @shalithapraveen
// Method that can throw an exception
static int divide(int a, int b) {
return a / b; // This will throw ArithmeticException if b is 0
}
}
16.5 Key Features:
Try Block: The try block contains code that may throw an exception (like performing a
risky stunt). If an exception occurs, control is transferred to the catch block.
Catch Block: The catch block handles the exception (like the safety net). In this example,
if a division by zero occurs, it catches the ArithmeticException and prints an error
message.
Finally Block: The finally block executes regardless of whether an exception was
thrown or handled. It’s a place to perform cleanup tasks, similar to how a safety net is
always present, regardless of whether an acrobat falls or not.
16.6 Conclusion:
Exception handling in Java is like a safety net in a circus that catches errors and allows the
program to recover gracefully. It helps manage unexpected situations, ensuring that the program
runs smoothly without crashing.
53 | P a g e @shalithapraveen
17. Garbage Collection in Java
17.1 What is it?
Garbage Collection (GC) is Java's way of automatically finding and cleaning up unused
objects in memory, so the system doesn’t run out of space. Java automatically handles
memory management, so you don’t need to worry about deleting unused objects yourself.
Imagine you’ve just had a big party in your living room, and now there are cups, plates,
and wrappers scattered everywhere. After the party, the Garbage Collector is like a
cleaner who comes in and removes the items that are no longer in use (empty cups, dirty
plates).
1. Objects are like cups and plates left after a party. You use them while needed.
2. Garbage Collector is like the cleaner. They check the room (your program) for stuff that is
no longer being used and clean it up (remove unused objects).
3. Automatic cleanup: You don’t have to ask the cleaner to remove each cup; they
automatically know when something is no longer needed.
4. Memory management: If the cleaner didn’t show up, the room would get too cluttered
with garbage. Similarly, without garbage collection, your program would eventually run
out of memory.
Marking: The cleaner checks which items are still being used (like cups still being used by
guests) and which are not (empty plates, trash).
Sweeping: The cleaner removes all the unused items.
So, Java’s Garbage Collection is like a cleaner who ensures your room (program’s memory)
doesn’t get cluttered, making sure everything runs smoothly!
54 | P a g e @shalithapraveen
18. Multithreading in Java
18.1 What is it?
Multithreading allows a program to perform multiple tasks (threads) at the same time.
Each thread runs independently but shares the same resources, like memory. This improves
the performance of a program by allowing it to do several things at once.
Imagine you're making a sandwich, and you want to get it done faster by doing multiple tasks at
the same time instead of doing them one after another.
1. Thread: Each task, like spreading butter, cutting veggies, or toasting bread, is a thread.
Each task runs in parallel (at the same time).
2. Main Task: The overall goal (making the sandwich) is like the main thread. It controls the
process, but the smaller tasks help finish it faster.
3. Multithreading: Instead of doing each task one after another (first buttering, then cutting
veggies, etc.), you can multitask (butter the bread while the toaster is working). These are
multiple threads running simultaneously.
4. Sharing Resources: All the tasks (threads) share the same kitchen and ingredients
(memory/resources), so they must be managed carefully to avoid conflict (e.g., two tasks
trying to use the knife at the same time).
18.4 Example:
Single-threaded program: You first butter the bread, then toast it, and finally cut the
veggies. You do each task one by one. It’s slow because you’re not using all your time
efficiently.
Multithreaded program: While the bread is toasting, you can butter the second slice and
start cutting veggies. Multiple tasks run simultaneously, making the sandwich faster!
1. Synchronization: If two people are making different parts of the sandwich, they must
coordinate who uses the knife (shared resource). This is called synchronization in
multithreading, ensuring that threads don’t interfere with each other.
2. Concurrency: All tasks (threads) seem to be happening at the same time (like buttering,
toasting, cutting veggies). This is called concurrency.
18.6 Conclusion:
Multithreading helps Java programs run faster by doing several tasks at once rather than
waiting for one task to finish before starting another. Just like you save time by buttering
55 | P a g e @shalithapraveen
bread while the toaster is working, multithreading improves efficiency by managing
multiple tasks in parallel.
56 | P a g e @shalithapraveen
19. Concurrency in Java
19.1 What is it?
57 | P a g e @shalithapraveen
public void run() {
restaurant.serveCustomer(customer);
}
}
58 | P a g e @shalithapraveen
}
}
19.5 Key Features:
Multiple Threads: In the example, each Waiter represents a thread serving a different
customer concurrently.
Independent Execution: Each waiter can start serving a customer at the same time,
demonstrating concurrent execution.
Resource Sharing: All waiters share the same Restaurant object, simulating how threads
share resources.
19.6 Conclusion:
59 | P a g e @shalithapraveen
20. Java Collections Framework
20.1 What is it?
The Java Collections Framework is a set of classes and interfaces that provide various
data structures and algorithms to store, manipulate, and retrieve data efficiently. It allows
developers to work with groups of objects, making data management easier.
1. List:
o Analogy: Like a drawer with tools arranged in a specific order.
o Example: ArrayList, LinkedList
o Usage: Used for storing ordered collections that allow duplicates.
2. Set:
o Analogy: Like a container that holds only unique tools, without duplicates.
o Example: HashSet, TreeSet
o Usage: Used for storing unique elements with no duplicates.
3. Map:
o Analogy: Like a labeled organizer where each tool has a specific label (key)
associated with it.
o Example: HashMap, TreeMap
o Usage: Used for storing key-value pairs, where each key maps to a specific value.
60 | P a g e @shalithapraveen
20.5 Example in Java:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.HashMap;
// Set Example
HashSet<String> uniqueTools = new HashSet<>();
uniqueTools.add("Hammer");
uniqueTools.add("Screwdriver");
uniqueTools.add("Hammer"); // Duplicate won't be added
System.out.println("Unique Tools: " + uniqueTools);
// Map Example
HashMap<String, String> toolBox = new HashMap<>();
toolBox.put("Hammer", "Used for driving nails");
toolBox.put("Screwdriver", "Used for turning screws");
System.out.println("Tool Descriptions: " + toolBox);
}
}
61 | P a g e @shalithapraveen
20.6 Key Features:
1. ArrayList: A list that maintains the order of insertion and allows duplicates (like a drawer
where tools can be arranged in order).
2. HashSet: A set that stores unique elements and ignores duplicates (like a container that
only holds unique tools).
3. HashMap: A map that associates keys with values (like an organizer with labeled sections
for each tool).
HashSet,
ArrayList, HashMap, TreeMap,
Implementations LinkedHashSet,
LinkedList, Vector LinkedHashMap
TreeSet
62 | P a g e @shalithapraveen
2. List Implementations
Synchronized
Structure Resizable array Doubly-linked list
resizable array
Thread-safe,
Best for frequent random Best for frequent
Use Cases legacy class (use
access insertions/removals
with care)
3. Set Implementations
O(1) for add, remove, and O(1) with insertion O(log n) for add, remove,
Performance
contains order and contains
4. Map Implementations
63 | P a g e @shalithapraveen
5. Queue Implementations
3. Navigable Collections
20.9 Conclusion:
The Java Collections Framework is like a toolbox that provides various data structures
and methods for storing, managing, and retrieving collections of objects efficiently. It
offers a wide range of options to suit different needs, making data manipulation easier
and more organized.
64 | P a g e @shalithapraveen
21. Java Generics
21.1 What is it?
Java Generics is a feature that allows you to define classes, interfaces, and methods with
a placeholder for types, enabling you to create code that is type-safe and reusable
without sacrificing performance.
import java.util.ArrayList;
65 | P a g e @shalithapraveen
public T getTool(int index) {
return tools.get(index);
}
}
// Retrieving tools
System.out.println("Wrenches: " + wrenchBox.getTool(0) + ", " + wrenchBox.getTool(1));
System.out.println("Screwdrivers: " + screwdriverBox.getTool(0) + ", " +
screwdriverBox.getTool(1));
}
}
1. Generic Class: The Toolbox<T> class is defined with a type parameter <T>, allowing it to
hold any type of tool. This is similar to a universal toolbox that can hold different kinds of
tools.
2. Type Parameter: When creating instances of Toolbox, you specify the type of tool it will
hold (e.g., Toolbox<String> for string tools), ensuring type safety.
3. No Casting Needed: When retrieving tools from the toolbox, there’s no need for casting,
which simplifies the code and reduces the chance of errors.
66 | P a g e @shalithapraveen
21.6 Conclusion:
Java Generics function like a universal toolbox that can hold any type of object safely
and efficiently. By providing type safety, enhancing code reusability, and eliminating the
need for casting, generics make your Java programs cleaner and more robust.
67 | P a g e @shalithapraveen
22. Java Strings
22.1 What is a String in Java?
In Java, a String is a sequence of characters. It is one of the most commonly used data types in
programming to handle text. Strings in Java are immutable, which means once a string is
created, its value cannot be changed.
22.2 Analogy: String as a Necklace
Imagine a necklace where each bead represents a character, and the entire necklace is a string
of beads (characters).
1. Immutability: Once a string (necklace) is created, you cannot change the beads
(characters) in that string. If you try to modify it, Java creates a new string instead of
changing the existing one.
o Analogy: Imagine you have a necklace with specific beads in a certain order. If
you want to change the beads, you don't change the beads on the existing
necklace; you create a new necklace with the updated beads.
1. length(): Finds the length of the string (i.e., how many characters it has).
o Analogy: It counts the number of beads on the necklace.
68 | P a g e @shalithapraveen
2. charAt(int index): Returns the character at the specified index (position).
Analogy: It's like pointing to a specific bead on the necklace based on its position.
String str = "Hello";
char ch = str.charAt(1); // Returns 'e'
3. substring(int start, int end): Extracts a part of the string (a portion of the
necklace).
Analogy: Imagine cutting a section of the necklace to create a smaller necklace with some beads
from the original one.
String str = "Hello";
String sub = str.substring(1, 4); // Returns "ell"
Analogy: Imagine changing the color of all the beads to either bright (uppercase) or dim
(lowercase).
String str = "Hello";
String upper = str.toUpperCase(); // Returns "HELLO"
String lower = str.toLowerCase(); // Returns "hello"
Analogy: You compare two necklaces bead by bead to see if they are identical.
String str1 = "Hello";
String str2 = "Hello";
boolean isEqual = str1.equals(str2); // Returns true
69 | P a g e @shalithapraveen
22.5 Immutability Explained:
Since strings in Java are immutable, any operation that seems like it modifies the string actually
creates a new string.
String str = "Hello";
str = str.concat(" World");
System.out.println(str); // Outputs "Hello World"
Here, the original string "Hello" is not changed. Instead, a new string "Hello World" is
created, and the variable str now refers to this new string.
Analogy: If you have a necklace and want to add new beads, you can't modify the old necklace.
Instead, you create a new necklace with the old beads plus the new ones.
22.6 String Pool in Java:
Java uses a String Pool to save memory by reusing strings.
When you create a string using a literal ("Hello"), Java checks if a string with the same
value already exists in the string pool. If it does, it reuses the existing string instead of
creating a new one.
However, when you use the new keyword (new String("Hello")), Java creates a new
string even if an identical one exists in the pool.
Analogy: The string pool is like a jewelry box that holds necklaces. If you pick a necklace
(string literal) from the box, it reuses the existing necklace. If you make a new necklace
(using new), it doesn't care what's in the box—it creates a new one.
22.6.2 Example:
String str3 = new String("Hello"); // Creates a new object outside the pool
22.7 Summary of Java Strings:
70 | P a g e @shalithapraveen
23. String Builder
In Java, StringBuilder is a mutable sequence of characters, which means you can modify it
(change its contents) without creating new objects, unlike the immutable String class.
StringBuilder is more efficient when dealing with a large number of string manipulations, such as
appending, inserting, or deleting characters.
23.1 Key Features of StringBuilder
Mutable: You can modify the contents of a StringBuilder without creating new objects.
Efficient: It is more efficient than String when you have to repeatedly modify the same
string, especially in loops.
No Synchronization: Unlike StringBuffer, StringBuilder is not synchronized, making
it faster in single-threaded contexts.
1. Creating a StringBuilder
2. append()
Example:
Deletes the characters in the StringBuilder from the start index to the end index (exclusive).
71 | P a g e @shalithapraveen
Example
Replaces the characters between the start and end index with the specified string.
Example
6. reverse()
Example:
7. charAt(int index)
Example:
8. toString()
Example:
72 | P a g e @shalithapraveen
9. setCharAt(int index, char ch)
Example:
10. capacity()
Returns the current capacity of the StringBuilder. The capacity grows as the StringBuilder
needs more space.
Example:
int capacity = sb.capacity(); // capacity will be the default 16 or more if the string is larger
String concatenation in loops: If you are appending strings multiple times (e.g., in a
loop), using StringBuilder is more efficient
sb.append(i).append(" ");
System.out.println(sb.toString()); // Outputs: 0 1 2 3 4
String is immutable, so every modification creates a new object. This is inefficient when
you have many string operations.
StringBuilder is mutable, so it avoids creating unnecessary objects, leading to better
performance when modifying strings frequently.
73 | P a g e @shalithapraveen
23.5 String vs. StringBuilder
Aspect String StringBuilder
Thread-
Thread-safe (safe in multithreaded apps) Not thread-safe (use in single threads)
Safety
Use Case When the value should remain constant When string modifications are frequent
23.6 Summary
StringBuilder is used when you need to modify strings frequently, such as appending,
inserting, or deleting characters.
It provides better performance compared to String when dealing with multiple string
manipulations.
74 | P a g e @shalithapraveen
24. Differences between StringBuilder and StringBuffer
Thread-
Not thread-safe (not synchronized) Thread-safe (synchronized methods)
Safety
24.1 Explanation
1. Thread-Safety:
StringBuilder is not synchronized, which means it does not guarantee safe usage in a
multi-threaded environment. If multiple threads access a StringBuilder at the same
time, you might encounter data corruption or unexpected behavior.
StringBuffer, on the other hand, is synchronized and thread-safe. All of its methods are
synchronized, which means only one thread can access the StringBuffer object at a
time. This ensures that there are no conflicts between threads, making StringBuffer a
safer choice in multi-threaded environments.
2. Performance:
3. Use Case:
75 | P a g e @shalithapraveen
24.2 Methods in StringBuilder and StringBuffer
Both StringBuilder and StringBuffer share almost the same API and methods, including:
append()
insert()
delete()
replace()
reverse()
toString()
These methods work the same way in both classes, but the performance and thread safety aspects
differ.
24.3 Example: StringBuilder vs StringBuffer
// StringBuilder example (Single-threaded)
StringBuilder sb = new StringBuilder("Hello");
sb.append(", World!");
System.out.println(sb); // Outputs: Hello, World!
In both cases, the output is the same, but if you have multiple threads accessing sbuf,
StringBuffer ensures the correct behavior, whereas StringBuilder might not.
76 | P a g e @shalithapraveen
24.5 Summary
Java Streams are a part of the Java Collections Framework that allow you to process
sequences of elements (like collections of data) in a functional style. They enable
developers to perform operations such as filtering, mapping, and reducing in a clean and
efficient way.
1. Flowing Data:
o Just like a river carries water smoothly from one place to another, Java Streams
allow you to process data in a sequence. You can take a collection of items and
stream them through a series of operations.
2. Transformations:
o The river can split into different tributaries where it can be filtered or diverted
(e.g., a stream for fish, another for water plants). Similarly, Java Streams can be
transformed through operations like filter(), map(), and reduce(), allowing
you to shape the data as needed.
3. Lazy Evaluation:
o The flow of water in the river is continuous, but it only does work when necessary
(like eroding banks or carrying debris). Java Streams use lazy evaluation, meaning
operations are not performed until a terminal operation (like collect() or
forEach()) is invoked, which helps optimize performance.
77 | P a g e @shalithapraveen
public class StreamsExample {
public static void main(String[] args) {
// Creating a list of numbers
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
1. Stream Creation: The stream() method converts a collection into a stream, allowing you
to begin processing the data.
2. Intermediate Operations: Methods like filter() and map() are intermediate operations
that transform the data without modifying the original collection.
3. Terminal Operation: The collect() method is a terminal operation that triggers the
processing of the stream and collects the results into a new list.
25.6 Conclusion:
Java Streams are like a river flowing through a landscape, enabling the smooth and
efficient processing of data. They allow for a functional approach to data manipulation,
with transformations and lazy evaluation that optimize performance.
78 | P a g e @shalithapraveen
26. Java Lambdas
26.1 What is it?
Java Lambdas are a feature introduced in Java 8 that allows you to express instances of
single-method interfaces (functional interfaces) in a concise and readable way. They
enable you to write anonymous functions that can be treated as first-class citizens in Java,
making it easier to implement functional programming concepts.
Think of a lambda expression as a recipe card for cooking. The recipe card contains a list of
instructions (the logic) that you can follow to create a dish (the action). Just like you can use a
recipe card without formally naming the dish or writing out the entire process every time, a
lambda allows you to define a method inline without needing a separate class.
1. Concise Definition:
o A recipe card provides a quick and straightforward way to prepare a dish without
the need for an elaborate cookbook. Similarly, a lambda expression provides a
shorthand way to define a function without creating a separate method or class.
2. Parameters and Body:
o Just as a recipe card may include ingredients (parameters) and cooking steps (the
body), a lambda expression takes parameters and contains the code that defines
what to do with those parameters.
3. Anonymous:
o A recipe card can be used without needing to know who wrote it or its history. In
the same way, lambdas are anonymous functions that can be passed around
without needing a formal name or class definition.
java
Copy code
(parameters) -> { // code to execute }
Example: (int x, int y) -> x + y represents a function that takes two integers and
returns their sum.
79 | P a g e @shalithapraveen
public class LambdaExample {
public static void main(String[] args) {
// Creating a list of names
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");
1. Functional Interface: The forEach method and the filter method expect a functional
interface (like Consumer or Predicate), which is implemented by the lambda expressions.
2. Inline Logic: The lambda expression provides the implementation of the method directly,
making the code more concise and readable.
3. Readable Code: By using lambdas, the code becomes easier to read and understand,
resembling the steps on a recipe card rather than cluttered class definitions.
26.7 Conclusion:
Java Lambdas are like recipe cards that provide a simple and concise way to define and
implement functional behavior in Java. They enhance the language’s expressiveness and
enable developers to write cleaner, more maintainable code.
80 | P a g e @shalithapraveen