Array
✅ Definition
In Java, an array is a data structure used to store multiple values of the same data type in
a single variable, instead of declaring separate variables for each value. Arrays are fixed in
size, meaning once an array is created, its size cannot be changed.
Java arrays are objects, and they can store both primitive types (like int, char, double) and
reference types (like String, custom classes, etc.).
✅ Why Use Arrays?
Arrays help organize related data together and allow you to perform operations like sorting,
searching, and looping efficiently. They make the code simpler, cleaner, and more
efficient, especially when working with large amounts of similar data.
✅ 1. Declaring Arrays
// Declaration only
int[] nums;
String[] names;
// Declaration with size
nums = new int[5]; // Initializes with default value 0
names = new String[3]; // Initializes with null
✅ 2. Initializing Arrays
// Inline initialization
int[] nums = {1, 2, 3, 4, 5};
// Dynamic assignment
String[] fruits = new String[3];
fruits[0] = "Apple";
fruits[1] = "Banana";
fruits[2] = "Mango";
✅ 3. Accessing Array Elements
[Link](nums[0]); // prints 1
[Link](fruits[2]); // prints Mango
✅ 4. Looping Through Arrays
for (int i = 0; i < [Link]; i++) {
[Link](nums[i]);
Example:
public class Main {
public static void main(String[] args) {
// Declare and initialize an array of integers
int[] numbers = {10, 20, 30, 40, 50};
// Access elements
[Link]("First element: " + numbers[0]); // Output: 10
// Change an element
numbers[2] = 99;
// Loop through the array
for (int i = 0; i < [Link]; i++) {
[Link]("Element at index " + i + ": " + numbers[i]);
1. Class and main Method
public class Main {
public static void main(String[] args) {
public class Main: Defines the class named Main.
public static void main(String[] args): The entry point of any Java application.
2. Declaring and Initializing the Array
int[] numbers = {10, 20, 30, 40, 50};
An array of integers named numbers is declared and initialized with five values.
Arrays use curly braces {} for initialization and square brackets [] for indexing.
Index positions:
numbers[0] = 10
numbers[1] = 20
numbers[2] = 30
numbers[3] = 40
numbers[4] = 50
3. Accessing an Element
[Link]("First element: " + numbers[0
✅ 1. One-Dimensional Array
Also called a single-dimensional array, it's like a simple list of elements.
� Syntax:
int[] numbers = {10, 20, 30, 40, 50};
Use Case:
Useful for storing a series of values like student marks, employee IDs, etc.
2. Two-Dimensional Array
Also called a matrix, it's an array of arrays — like a table with rows and columns.
� Syntax:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
Use Case:
Used for grid-like structures — for example, in games (chessboard), matrices, or
spreadsheets.
✅ 1. One-Dimensional Array (1D Array)
Example:
public class OneDArrayExample {
public static void main(String[] args) {
// Declare and initialize a 1D array
int[] marks = {85, 90, 78, 92, 88};
// Accessing and printing elements
[Link]("Student marks:");
for (int i = 0; i < [Link]; i++) {
[Link]("Subject " + (i + 1) + ": " + marks[i]);
Output:
Student marks:
Subject 1: 85
Subject 2: 90
Subject 3: 78
Subject 4: 92
Subject 5: 88
[Link]-Dimensional Array (2D Array)
Example:
public class TwoDArrayExample {
public static void main(String[] args) {
// Declare and initialize a 2D array (matrix)
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Printing the matrix
[Link]("2D Matrix:");
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < matrix[i].length; j++) {
[Link](matrix[i][j] + " ");
[Link](); // Move to the next row
}
}
Output:
2D Matrix:
123
456
789
explanation
// Declare and initialize a 2D array (matrix)
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Here, a two-dimensional array named matrix is declared and initialized.
It contains 3 rows and 3 columns.
Each pair of {} represents a row.
The structure looks like this:
Row 0: 1 2 3
Row 1: 4 5 6
Row 2: 7 8 9
// Printing the matrix
[Link]("2D Matrix:");
Prints a heading before displaying the matrix.
for (int i = 0; i < [Link]; i++) {
Outer for loop iterates through the rows of the matrix.
[Link] gives the number of rows (in this case, 3).
for (int j = 0; j < matrix[i].length; j++) {
Inner for loop iterates through the columns of each row.
matrix[i].length gives the number of columns in the current row.
[Link](matrix[i][j] + " ");
Prints the value at row i and column j, followed by a space.
For example, matrix[0][0] is 1, matrix[0][1] is 2, etc.
[Link](); // Move to the next row
What is an Array of Objects in Java?
An array of objects in Java is just like an array of primitive types (like int[] or double[]),
except it stores references to objects instead of primitive values.
This is useful when you need to store multiple instances of a class in a single variable.
✅ Example: Array of Objects
Let's create a class called Student and then make an array to store multiple Student objects.
� Step-by-step Code:
// Define the Student class
class Student {
String name;
int age;
// Constructor
Student(String name, int age) {
[Link] = name;
[Link] = age;
// Method to display student details
void display() {
[Link]("Name: " + name + ", Age: " + age);
// Main class
public class ArrayOfObjectsExample {
public static void main(String[] args) {
// Create an array to store 3 Student objects
Student[] students = new Student[3];
// Initialize each element with a Student object
students[0] = new Student("Alice", 20);
students[1] = new Student("Bob", 22);
students[2] = new Student("Charlie", 21);
// Loop through the array and display each student's info
[Link]("Student Details:");
for (int i = 0; i < [Link]; i++) {
students[i].display();
}
Output:
Student Details:
Name: Alice, Age: 20
Name: Bob, Age: 22
Name: Charlie, Age: 21
Explanation:
Student[] students = new Student[3];
Creates an array that can hold 3 references to Student objects.
Each element is assigned using new Student(...).
We use a loop to call the display() method for each object.
Collections:
What is a Collection in Java?
A Collection is a group of objects, often called elements, that are stored together in one
object.
Java provides the Collection Framework to store, manage, and manipulate these groups of
objects easily.
� Real-life Example:
Think of a collection like a box that can hold many things (e.g., fruits, books, etc.).
In Java, a Collection can hold things like:
A list of names
A set of numbers
A map of key-value pairs (like a dictionary)
import [Link].*;
public class Main {
public static void main(String[] args) {
List<String> fruits = new ArrayList<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Orange");
for (String fruit : fruits) {
[Link](fruit);
Step-by-Step Explanation:
1. import [Link].*;
This line imports the Java utility package, which contains useful classes like List,
ArrayList, Scanner, etc.
* means import everything from [Link].
2. public class Main { ... }
This defines a class named Main.
Every Java program must have at least one class.
This is where your program starts.
3. public static void main(String[] args) { ... }
This is the main method, where your program starts running.
Java looks for this method when you run your program.
4. List<String> fruits = new ArrayList<>();
You're creating a list of strings.
fruits is the name of the list.
ArrayList<> is one way to create a list that can grow and shrink.
The <> means you're working with String type only (no numbers, etc.).
� In short: You made an empty list to hold fruit names.
5. [Link]("Apple");
You're adding "Apple" to the list.
The list now looks like: ["Apple"]
6. [Link]("Banana");
Now the list is: ["Apple", "Banana"]
7. [Link]("Orange");
Now the list is: ["Apple", "Banana", "Orange"]
8. for (String fruit : fruits) { ... }
This is a for-each loop.
It goes through each item in the list fruits.
For each item, it gives it a temporary name fruit.
So on each loop:
First time → fruit = "Apple"
Second time → fruit = "Banana"
Third time → fruit = "Orange"
9. [Link](fruit);
This prints the current fruit name on the screen.
Key Interfaces and Classes in Java Collections Framework
Interfaces
1. Collection
Root interface for all collection types (except Map).
Defines basic operations:
add(), remove(), iterator(), size(), clear(), etc.
2. List
An ordered collection.
Allows duplicate elements.
Maintains insertion order.
Examples:
o ArrayList
o LinkedList
3. Set
A collection with no duplicate elements.
May or may not maintain order.
Examples:
o HashSet (no order)
o LinkedHashSet (insertion order)
o TreeSet (sorted order)
4. Queue
Designed for holding elements before processing.
Usually follows FIFO (First-In-First-Out).
Examples:
o PriorityQueue
o LinkedList
5. Map (Not a subtype of Collection)
Stores data as key-value pairs.
Keys must be unique, values can be duplicated.
Examples:
o HashMap (no order)
o TreeMap (sorted by keys)
o LinkedHashMap (insertion order)
Key Classes in Java Collections Framework
ArrayList
A resizable array implementation of the List interface.
Fast random access, allows duplicates, maintains insertion order.
LinkedList
A doubly-linked list implementation of both List and Deque interfaces.
Good for frequent insertions/removals, maintains insertion order.
HashSet
A hash table implementation of the Set interface.
No duplicates, no guaranteed order.
TreeSet
A Red-Black tree implementation of the Set interface.
Stores elements in sorted order, no duplicates.
HashMap
A hash table implementation of the Map interface.
Stores key-value pairs with no order guarantee.
TreeMap
A Red-Black tree implementation of the Map interface.
Stores key-value pairs in sorted order by keys.
Collections
A utility class providing static methods for operating on or returning collections (e.g.,
sort(), addAll(), reverse(), shuffle()).
Iterator Interface in Java
An Iterator allows you to traverse (loop through) a collection, element by element.
It provides methods to check for more elements, get the next element, and remove
elements safely during iteration.
import [Link];
import [Link];
public class IteratorExample {
public static void main(String[] args) {
ArrayList<String> colors = new ArrayList<>();
[Link]("Red");
[Link]("Green");
[Link]("Blue");
Iterator<String> iterator = [Link]();
while ([Link]()) {
String color = [Link]();
[Link](color);
// Remove "Green" during iteration
if ([Link]("Green")) {
[Link]();
[Link]("After removal: " + colors);
Output:
Red
Green
Blue
After removal: [Red, Blue]
List Interface in Java
List is an interface that extends Collection.
It represents an ordered collection (also called a sequence).
Allows duplicate elements.
Elements are stored and accessed based on their index (position).
Maintains the insertion order of elements.
� Key Features of List:
Ordered: Elements have a specific position (index).
Allows duplicates: Same element can appear multiple times.
Indexed access: You can get, add, or remove elements at a specific position.
Supports iteration in order.
import [Link];
import [Link];
public class ListExample {
public static void main(String[] args) {
List<String> animals = new ArrayList<>();
// Adding elements
[Link]("Cat");
[Link]("Dog");
[Link]("Elephant");
[Link]("Dog"); // duplicate allowed
// Access by index
[Link]("First animal: " + [Link](0)); // Cat
// Iterate using for loop
for (int i = 0; i < [Link](); i++) {
[Link]([Link](i));
// Remove element at index 2
[Link](2);
[Link]("After removal: " + animals);
Output:
First animal: Cat
Cat
Dog
Elephant
Dog
After removal: [Cat, Dog, Dog]
LinkedList in Java
LinkedList is a class that implements the List and Deque interfaces.
It is a doubly linked list data structure.
Elements are linked using nodes, where each node points to the previous and next
node.
Good for frequent insertions and deletions because it doesn’t require shifting
elements like an array.
Maintains insertion order.
Supports list operations (access by index) and deque operations (add/remove at both
ends).
� Key Features:
Slower random access (get(index)) compared to ArrayList because it must
traverse nodes.
Faster insertions and deletions in the middle or ends.
Can be used as a Queue or Deque (double-ended queue).
import [Link];
public class LinkedListExample {
public static void main(String[] args) {
LinkedList<String> names = new LinkedList<>();
// Adding elements
[Link]("Alice");
[Link]("Bob");
[Link]("Charlie");
// Add element at the beginning
[Link]("Zara");
// Add element at the end
[Link]("David");
[Link]("LinkedList: " + names);
// Remove first and last elements
[Link]();
[Link]();
[Link]("After removing first and last: " + names);
// Access element by index
[Link]("Element at index 1: " + [Link](1));
// Iterate using for-each
[Link]("All names:");
for (String name : names) {
[Link](name);
ArrayList Class in Java
ArrayList is a resizable array implementation of the List interface.
It provides dynamic arrays that grow as needed.
Allows duplicate elements.
Maintains insertion order.
Provides fast random access to elements via indices.
Slower than linked lists for inserting/removing elements in the middle, because
elements need to be shifted.
� Key Features:
Part of the [Link] package.
Backed by an internal array that resizes when capacity is exceeded.
Not synchronized (not thread-safe).
Implements Serializable and Cloneable.
import [Link];
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList<String> colors = new ArrayList<>();
// Adding elements
[Link]("Red");
[Link]("Green");
[Link]("Blue");
[Link]("Colors: " + colors);
// Access by index
[Link]("First color: " + [Link](0));
// Insert element at index 1
[Link](1, "Yellow");
// Remove element by index
[Link](2);
// Update element at index 0
[Link](0, "Purple");
[Link]("Updated Colors: " + colors);
[Link]("Size of list: " + [Link]());
Vector Class in Java
Vector is a resizable array implementation of the List interface, similar to
ArrayList.
It synchronizes its methods, making it thread-safe.
Maintains insertion order and allows duplicate elements.
Part of the legacy collection classes (introduced before Java 2 Collections
Framework).
Because of synchronization, it is usually slower than ArrayList in single-threaded
environments.
� Key Features:
Grows its internal array by doubling the size when capacity is exceeded (can be
customized).
Thread-safe due to synchronized methods.
Implements Serializable and Cloneable.
Suitable for multi-threaded environments where thread safety is needed without
external synchronization.
import [Link];
public class VectorExample {
public static void main(String[] args) {
Vector<String> fruits = new Vector<>();
// Adding elements
[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");
[Link]("Fruits: " + fruits);
// Access element
[Link]("First fruit: " + [Link](0));
// Remove element
[Link]("Banana");
[Link]("After removal: " + fruits);
[Link]("Size: " + [Link]());
}
}
Stack Class in Java
The Stack class represents a Last-In-First-Out (LIFO) stack of objects.
It extends the Vector class.
Provides standard stack operations like push, pop, peek, search, and empty.
Useful when you need to process elements in reverse order of insertion.
� Key Methods
import [Link];
public class StackExample {
public static void main(String[] args) {
Stack<String> stack = new Stack<>();
// Push elements onto stack
[Link]("Java");
[Link]("Python");
[Link]("C++");
[Link]("Stack: " + stack);
// Peek top element
[Link]("Top element: " + [Link]());
// Pop elements from stack
[Link]("Popped: " + [Link]());
[Link]("Stack after pop: " + stack);
// Check if stack is empty
[Link]("Is stack empty? " + [Link]());
// Search for an element
[Link]("Position of Java: " + [Link]("Java"));
Output:
Stack: [Java, Python, C++]
Top element: C++
Popped: C++
Stack after pop: [Java, Python]
Is stack empty? false
Position of Java: 2