0% found this document useful (0 votes)
1 views17 pages

Unit 3 Java

Uploaded by

fowmila j
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views17 pages

Unit 3 Java

Uploaded by

fowmila j
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Unit 3

ARRAYS AND INTERFACES


ARRAYS-
An array is a linear data structure used to store a fixed-size sequential collection of elements of
the same data type.
 Arrays help reduce code duplication.
 Instead of declaring multiple variables for similar data, you can use a single array.

Key Features of Arrays in Java – Explained in Detail


1. Store Primitives and Objects

What it means: Java arrays can store both primitive data types and objects.

Data Example
Type
Primitive int[], char[], boolean[]
Object String[], Integer[], Double[]

// Primitive array
int[] numbers = {1, 2, 3};

// Object array
String[] names = {"Alice", "Bob", "Charlie"};

// Array of wrapper class objects


Integer[] marks = {90, 80, 75};
Note: Object arrays can store null values, while primitives cannot

2. Contiguous Memory Allocation


What it means:
 In arrays of primitive types, elements are stored in contiguous memory blocks.
 In arrays of objects, references (addresses) to objects are stored contiguously.
int[] arr = {10, 20, 30}; // Values stored contiguously in memory

String[] strArr = {"Java", "Python", "C++"};


 In strArr, each element stores a reference to a String object, and these references are stored
contiguously.
Why it matters: Contiguous storage allows fast indexing and efficient memory use
3. Zero-Based Indexing
What it means: In Java, array indices start at 0, not 1.
So:
 The first element is at index 0
 The second is at index 1
 The nth element is at index n-1
int[] ages = {25, 30, 35};
[Link](ages[0]); // Output: 25
[Link](ages[2]); // Output: 35
⚠️Be careful:
Accessing an invalid index (e.g., ages[3]) throws a:
[Link]

4. Fixed Length (Immutable Size)


What it means:Once an array is created, its size cannot be changed. You can't add or remove
elements dynamically like you can with ArrayList.
int[] nums = new int[3];
nums[0] = 10;
nums[1] = 20;
nums[2] = 30;

// nums[3] = 40; ❌ Error! Index out of bounds


🔄 Need dynamic resizing? Use: ArrayList <Integer> list = new ArrayList <> ();

Summary Table
Feature Description
Stores Primitives & Objects Arrays can hold either primitive types or objects
Contiguous Memory Elements or references are stored in adjacent memory
Zero-Based Indexing First element is at index 0
Fixed Size Size is defined at creation and cannot be changed
Declaring Arrays in Java

✅ 1. Preferred Declaration Style (Recommended)


🧩 Syntax:
int[] arr;
 Declares a reference variable arr that will point to an array of integers.
 The square brackets [] come after the data type, not the variable name.
int[] arr; // Declaration
arr = new int[5]; // Initialization
🔹 This is the most widely accepted and recommended syntax.

2. Alternate Style
🧩 Syntax:int arr[];
 This is legal but less preferred.
 It means the same as the first one but puts brackets after the variable.
int arr[];
arr = new int[3];
🔹 Often seen in older code or C/C++ inspired codebases.

3. Declare and Initialize in One Line (Using new)


Syntax: int[] arr = new int[5];
 Declares the array and allocates memory for 5 elements.
 All elements are initialized to default values (0 for int).

4. Declare with Array Literal


Syntax: int[] arr = {10, 20, 30};
 This is called an array literal.
 Useful when values are known at the time of declaration.
 Size is automatically determined based on the number of elements.

5. Explicit Array Literal (older Java versions)


Syntax: int[] arr = new int[]{10, 20, 30};
 Similar to the previous example but more explicit.
 Required in older Java versions when array declaration and initialization are done
separately.
6. Declare Multiple Arrays in One Line
Syntax: int[] a, b; // both are int arrays.
This declares two integer arrays: a and [Link] careful with: int a[], b; // ❌ Only a[] is an
array, b is just an int!

[Link] Array Declaration


Syntax: int[][] matrix;
 Declares a 2D array (array of arrays).
 Can also be declared as:
int matrix[][]; // Legal, but not preferred
int[] matrix[]; // Legal, not preferred
int[][] matrix = new int[3][3];

8. Array of Objects Declaration


Syntax: Student[] students;
Declares an array that will hold references to Student objects.
Student[] students = new Student[5];
students[0] = new Student(1, "Alice");

9. Array Declaration with Anonymous Array (Used in method calls)


Syntax:
sum(new int[]{1, 2, 3});
Used when passing arrays directly to methods without storing in a variable.

Declaration Description
int[] arr; Preferred single array declaration
int arr[]; Alternate syntax (less preferred)
int[] arr = new int[5]; Declaration + memory allocation
int[] arr = {1,2,3}; Array literal (shortcut initialization)
int[] arr = new int[]{1,2,3}; Explicit array creation
int[] a, b; Declares two arrays
int a[], b; a is array, b is int (⚠️be careful)
int[][] matrix; 2D array declaration
Student[] students; Array of objects
sum(new int[]{1,2,3}); Anonymous array (used in method calls)
Types of array
1. Single-Dimensional Array in Java
A single-dimensional array in Java is a linear collection of elements of the same data type,
stored in contiguous memory locations. It is the simplest form of an array and is used to store
multiple values of a single type, such as integers, strings, or objects.
Key Characteristics
 Homogeneous:
All elements in the array must be of the same data type (e.g., all int, all String).
 Fixed Size:
Once an array is declared, its size cannot be changed during runtime.
 Contiguous Memory:
Elements are stored in sequential memory locations, allowing for efficient access.
 Indexed Access:
Elements are accessed using an index, starting at 0 for the first element and ending at size -
1 for the last element.
Declaration and Initialization
1. Declaration and Allocation
dataType[] arrayName = new dataType[size];
int[] numbers = new int[5]; // Declares an array 'numbers' to hold 5 integers

2. Declaration, Allocation, and Initialization


dataType[] arrayName = {value1, value2, ..., valueN};
 This creates an array of 5 integers, each initialized to 0 by default.
String[] names = {"Alice", "Bob", "Charlie"}; // Declares and initializes an array of
Strings
 The array size is automatically determined by the number of values provided.
3. Accessing Elements
 Use the index in square brackets [] to access or modify elements.
arrayName[index];
Example:
int firstElement = numbers[0]; // Accesses the first element of the 'numbers' array
numbers[2] = 10; // Changes the third element to 10

🔄 Common Operations on Single-Dimensional Arrays


1. Iteration
 Meaning: Iteration means going through each element of the array, one by one.
 How: We use loops (like for loop or enhanced for loop) to visit every element.
 Purpose: To display values, calculate totals, or perform operations on each element.
 Example in words: If you have an array of 5 student marks, iteration means checking each
student’s mark one by one.

2. Searching
 Meaning: Searching is the process of finding whether a particular element exists in the array,
and if so, at which index (position).
 How:
o Linear Search: Start from the first element and check each one until you find the target.
o Binary Search: Faster method but requires the array to be sorted.
 Purpose: To quickly know whether an item is present or not.
 Example in words: Searching for the roll number of a specific student inside a list of roll
numbers.

3. Sorting
 Meaning: Sorting means arranging the elements of the array in a particular order.
 Types:
o Ascending order: Smallest to largest.
o Descending order: Largest to smallest.
 Purpose: Makes data easier to analyze and search.
 Example in words: Sorting student marks from highest to lowest, or arranging names in
alphabetical order.

4. Manipulation
 Meaning: Manipulation refers to modifying or updating values at specific indices in the array.
 Examples of manipulation:
o Changing a student’s mark in the array.
o Replacing an old value with a new one.
o Increasing all marks by 5 for grace marks.
 Purpose: Helps keep data up-to-date and accurate.

public class SingleDimensionalArrayExample {


public static void main(String[] args) {
// Declare and initialize an integer array
int[] scores = {85, 92, 78, 95, 88};

// Print all elements of the array


[Link]("Scores in the array:");
for (int i = 0; i < [Link]; i++) {
[Link]("Score at index " + i + ": " + scores[i]);
}

// Access and modify an element


scores[2] = 80; // Change the score at index 2

// Print the modified array using enhanced for loop


[Link]("\nScores after modification:");
for (int score : scores) {
[Link](score);
}
}
}

Output:
Scores in the array:
Score at index 0: 85
Score at index 1: 92
Score at index 2: 78
Score at index 3: 95
Score at index 4: 88

Scores after modification:


85
92
80
95
88
What is a Two-Dimensional Array?
A two-dimensional (2D) array is a special type of array that stores data in the form of a table with
rows and columns. Unlike a one-dimensional array, which stores elements in a single line, a 2D
array organizes data in a grid-like structure.
Each element in a 2D array is accessed using two indices:
 The first index represents the row number.
 The second index represents the column number.
This way, you can easily locate any element by specifying its row and column position. A 2D array
can also be thought of as an array of arrays, where each row itself is an array.
For example, if we store marks of students in different subjects, rows can represent students, and
columns can represent subjects. In this way, a 2D array becomes very useful for storing tabular
data, performing matrix operations, handling images, and designing game boards.
In short, a two-dimensional array is a structured way of storing data in rows and columns,
making it easier to manage large sets of related information.
Uses of 2D Arrays
 Storing tabular data (marks of students, sales data, etc.)
 Matrices in mathematics (addition, multiplication)
 Game boards (chess, tic-tac-toe)
 Images (pixels stored in rows and columns)
import [Link];
public class MatrixAddition {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

// Input size of matrix


[Link]("Enter number of rows: ");
int rows = [Link]();
[Link]("Enter number of columns: ");
int cols = [Link]();

// Declare matrices
int[][] A = new int[rows][cols];
int[][] B = new int[rows][cols];
int[][] C = new int[rows][cols]; // Result matrix

// Input Matrix A
[Link]("Enter elements of Matrix A:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
A[i][j] = [Link]();
}
}

// Input Matrix B
[Link]("Enter elements of Matrix B:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
B[i][j] = [Link]();
}
}

// Perform Addition (C = A + B)
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
C[i][j] = A[i][j] + B[i][j];
}
}
// Print Result
[Link]("Resultant Matrix (A + B):");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
[Link](C[i][j] + " ");
}
[Link]();
}

[Link]();
}
}
Output:
Enter number of rows: 3
Enter number of columns: 3
Enter elements of Matrix A:
123
456
789
Enter elements of Matrix B:
987
654
321
Resultant Matrix (A + B):
10 10 10
10 10 10
10 10 10
Jagged Arrays
 A Jagged Array is a two-dimensional array with rows of different lengths.
 Unlike a normal 2D array (rectangular array), where each row has the same number of
columns, in a jagged array each row can have a different number of columns.
 It is also called an “array of arrays.”
Characteristics
1. Jagged arrays are declared like normal 2D arrays but with different sizes for each row.
2. Rows can be of unequal length.
3. It provides flexibility to store non-uniform data.
4. Memory efficient – because it avoids unused cells (no need to allocate equal columns for all
rows).

Regular 2D Array (Rectangular):


1 2 3
4 5 6
7 8 9
👉 Every row has 3 columns.
Jagged Array:
1 2
3 4 5
6
7 8 9 10
👉 Rows have different column lengths.
Real-Life Examples of Jagged Arrays
 Student marks: Some students have 3 subjects, some have 5 subjects.
 Ragged tables: Data entries with different column counts.
 Pyramid or triangle patterns: Printing shapes in programs.
 Sparse data storage: When not all rows need the same number of values.
Example in Java (Conceptual)
int[][] jagged = new int[3][];
jagged[0] = new int[2]; // Row 0 → 2 elements
jagged[1] = new int[4]; // Row 1 → 4 elements
jagged[2] = new int[3]; // Row 2 → 3 elements
👉 This creates a jagged structure like:
Row 0 → [ _ _ ]
Row 1 → [ _ _ _ _ ]
Row 2 → [ _ _ _ ]
Advantages
 Saves memory space (no wasted cells).
 Flexible in handling unequal data.
 Useful for real-world applications where rows don’t have equal length.
Disadvantages
 Slightly more complex to handle compared to normal 2D arrays.
 Not suitable when data is strictly rectangular.
✨ Summary
A Jagged Array is a 2D array with rows of unequal lengths, also known as an array of arrays. It
is useful when data is not uniform, saves memory, and is widely used for handling student marks,
triangular patterns, and variable-sized data storage.
Java String
🔹 Definition
 A String is a sequence of characters enclosed within double quotes ("").
 In Java, String is a class in the [Link] package.
 Unlike primitive types (int, char, etc.), String is a reference type.
 Strings are immutable, meaning once created, their value cannot be changed.
🔹 Memory Representation
 String literals are stored in a special memory area called the String Constant Pool (SCP).
 If two string literals have the same value, they share the same object in SCP → memory efficient.
 Strings created with new keyword are stored in the heap memory (not in SCP).
Example:
String s1 = "Hello"; // Stored in SCP
String s2 = "Hello"; // Reuses same object
String s3 = new String("Hello"); // Stored in heap
🔹 Ways to Create a String
1. Using String Literal
2. String s1 = "Java";
3. Using new Keyword
4. String s2 = new String("Java");
🔹 Important Methods
 length() → returns number of characters.
 charAt(index) → returns character at given index.
 substring(start, end) → extracts a part of string.
 concat(str) → joins two strings.
 equals(str) → compares contents.
 equalsIgnoreCase(str) → compares ignoring case.
 compareTo(str) → compares lexicographically.
 toUpperCase() / toLowerCase() → converts case.
🔹 Example Program
public class StringExample {
public static void main(String[] args) {
String s1 = "Java";
String s2 = "Programming";

[Link]("Length of s1: " + [Link]());


[Link]("Character at 2: " + [Link](2));
[Link]("Concatenation: " + [Link](" " + s2));
}
}
Output:
Length of s1: 4
Character at 2: v
Concatenation: Java Programming

🔹 Uses of String
 Storing names, addresses, and textual data.
 Used in data input/output, file handling, and network communication.
 Frequently used in passwords, identifiers, tokens, etc.
Java StringBuffer
🔹 Definition
 StringBuffer is a mutable sequence of characters in Java.
 Belongs to the [Link] package.
 Unlike String (immutable), the contents of a StringBuffer object can be modified (append, insert, delete,
etc.).
 Thread-safe → All methods are synchronized, so safe to use in multi-threaded applications.
🔹 Memory Representation
 Objects of StringBuffer are stored in heap memory (not in String Constant Pool).
 Modifications are performed on the same object → No new object is created.
 This makes it efficient for frequent modifications.
🔹 Constructors
1. StringBuffer() → Creates empty buffer (capacity = 16).
2. StringBuffer(String str) → Creates buffer initialized with given string.
3. StringBuffer(int capacity) → Creates buffer with given capacity.

StringBuffer Constructors
StringBuffer provides different constructors to create mutable string objects. These constructors belong to the
[Link] package.

🔹 1. StringBuffer()
 Creates an empty StringBuffer with a default capacity of 16 characters.
 Capacity means the storage space available for characters (before memory expands).
 If characters exceed capacity, it automatically increases (newCapacity = (oldCapacity*2) + 2).
✅ Example:
StringBuffer sb1 = new StringBuffer();
[Link]("Capacity: " + [Link]()); // 16
[Link]("Length: " + [Link]()); // 0

🔹 2. StringBuffer(String str)
 Creates a StringBuffer object with the given string.
 Initial capacity = length of string + 16.
✅ Example:
StringBuffer sb2 = new StringBuffer("Hello");
[Link]("Content: " + sb2); // Hello
[Link]("Capacity: " + [Link]()); // 5 + 16 = 21

🔹 3. StringBuffer(int capacity)
 Creates an empty StringBuffer with the given custom capacity.
 Useful if you know in advance how many characters will be stored.
✅ Example:
StringBuffer sb3 = new StringBuffer(50);
[Link]("Capacity: " + [Link]()); // 50
[Link]("Length: " + [Link]()); // 0

✨ Summary
 StringBuffer() → Empty buffer with default capacity 16.
 StringBuffer(String str) → Buffer initialized with given string, capacity = string length + 16.
StringBuffer(int capacity) → Empty buffer with custom capacity. Important Methods
 append(str) → Adds string at end.
 insert(pos, str) → Inserts string at given position.
 delete(start, end) → Deletes characters from start to end.
 replace(start, end, str) → Replaces characters between start and end with new string.
 reverse() → Reverses the string.
 capacity() → Returns current capacity.
 ensureCapacity(n) → Increases buffer capacity if needed.
public class StringBufferExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");

[Link](" Java"); // Appending


[Link](5, " World"); // Insert at position
[Link](5, 11); // Delete substring
[Link](); // Reverse string

[Link](sb);
}
}

Java StringBuilder
 StringBuilder is a mutable sequence of characters in Java.
 Introduced in Java 5 (JDK 1.5).
 Like StringBuffer, but not synchronized → faster than StringBuffer.
 Belongs to the [Link] package.
 Objects of StringBuilder can be modified without creating new objects.
🔹 Memory Representation
 Stored in heap memory.
 Modifications (append, insert, delete, reverse) happen on the same object.
 Unlike String, it is mutable, so memory-efficient for frequent changes.
Constructors
1. StringBuilder() → Creates an empty object with default capacity 16.
2. StringBuilder(String str) → Creates object initialized with string; capacity = [Link]() + 16.
3. StringBuilder(int capacity) → Creates empty object with custom capacity.
✅ Example:
StringBuilder sb1 = new StringBuilder(); // Empty, capacity 16
StringBuilder sb2 = new StringBuilder("Java"); // Capacity 4+16 = 20
StringBuilder sb3 = new StringBuilder(50); // Custom capacity 50

Important Methods
 append(str) → Adds string at the end.
 insert(index, str) → Inserts string at given position.
 delete(start, end) → Deletes characters from start to end.
 replace(start, end, str) → Replaces characters between start and end.
 reverse() → Reverses the content.
 capacity() → Returns buffer capacity.
 ensureCapacity(n) → Increases capacity if required.
 charAt(index) → Returns character at given index.
 setCharAt(index, char) → Updates character at given index.
🔹 Example Program
public class StringBuilderExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Java");
[Link](" Programming"); // Add at end
[Link](4, " Language"); // Insert at index
[Link](5, 14); // Delete characters
[Link](); // Reverse string

[Link](sb);
}

}
Output:nginx
gnimmargorPavaJ
🔹 Uses
Best for frequent modifications in single-threaded [Link] than StringBuffer because it is not
[Link] in text editors, dynamic string operations, reverse operations, and building complex
strings.

Java Vectors

 A Vector in Java is a dynamic array that can grow or shrink in size automatically.
 It belongs to the [Link] package.
 Unlike normal arrays (which are fixed in size), vectors can resize themselves when elements are
added or removed.
🔹 Characteristics of Vectors
1. Dynamic Size: Automatically expands when new elements are added.
2. Indexed Storage: Elements are stored and accessed using indices (like arrays).
3. Heterogeneous Data: Technically allows different types, but usually used with Generics (e.g.,
Vector<Integer>).
4. Legacy Class: Introduced in JDK 1.0, still used but often replaced by ArrayList.
5. Thread-Safe: All methods are synchronized, which means Vectors are safe to use in multi-
threaded environments (but slower than ArrayList).
🔹 Creating a Vector
import [Link];

Vector<Integer> v = new Vector<>(); // Empty vector


Vector<String> names = new Vector<>(); // Vector of strings
🔹 Commonly Used Methods
 add(element) → Adds an element.
 add(index, element) → Inserts at specific index.
 get(index) → Retrieves element at index.
 set(index, element) → Updates element at index.
 remove(index) → Removes element at index.
 size() → Returns number of elements.
 capacity() → Returns current capacity of vector.
🔹 Example Program
import [Link];

public class VectorExample {


public static void main(String[] args) {
Vector<String> fruits = new Vector<>();

// Adding elements
[Link]("Apple");
[Link]("Banana");
[Link]("Mango");

// Insert at index
[Link](1, "Orange");

// Access elements
[Link]("First fruit: " + [Link](0));

// Modify element
[Link](2, "Grapes");

// Remove element
[Link](3);
// Display vector
[Link]("Fruits: " + fruits);
[Link]("Size: " + [Link]());
[Link]("Capacity: " + [Link]());
}
}
🔹 Output
First fruit: Apple
Fruits: [Apple, Orange, Grapes]
Size: 3
Capacity: 10
🔹 Advantages of Vectors
 Dynamic resizing (no fixed size like arrays).
 Built-in methods for easy manipulation.
 Thread-safe (synchronized).
🔹 Disadvantages
 Slower than ArrayList due to synchronization overhead.
 Considered a legacy class (modern programs often use ArrayList).
✨ Summary
A Vector in Java is a dynamic array from the [Link] package that can grow or shrink automatically. It
stores elements with indices, supports many built-in methods for adding, removing, and accessing data, and
is thread-safe but slower than ArrayList.

You might also like