Lec 6
Lec 6
• An array in Java is a data structure that allows you to store multiple values
of the same type in a single variable. Instead of declaring individual
variables for each value, you can use an array to group them together and
access them using their index.
• Here type can be any valid java data type or object type,
array_name can be any valid java identifier that you want to use for
your array name.
• For example -
• int arr[ ];
• float numbers[ ];
• double [ ] roll;
• The first example will allocate 20 bytes (5*4 = 20) of storage for
array - 'arr'. Similarly second one will allocate 40 (10*4 = 40)
bytes and third one will allocate 40 (5*8=40) bytes.
• We can also combine the above two steps into one as follows
• int arr[] = new int[5];
• float numbers[] = new float[10];
• double[] roll = new double[5];
• Initializing array - Let us suppose that we have an array a with
5 integer elements -
int a[] = new int[5];
• It can be represent in memory like this -
• We can initialize an array in two ways -
• 1st form -
• array_name[index] = value;
• Example -
• int[0] = 2;
• int[1] = 4;
• int[2] = 6;
• int[3] = 8;
• int[4] = 10;
• 2nd form -
• type array_name[] = {list of values};
• Or
• type array_name[] = new type[]{list of values};
• Example -
• int a[] = {2,4,6,8,10};
• int a[] = new int[]{2,4,6,8,10}; // both are same
• Here array will be big enough to hold the number of elements
defined in braces { }. That is, in both the cases an array of 5 int
elements will be created and it can be represented in memory as
follows –
• In java array index always starts from 0. And also we cannot store
more values than the size of array, if we try to do that , a runtime
exception 'Array Index Out Of Bound' will occur. We can also assign
an array into another array as follows -
• int arr[] = {1,2,3,4};
• int b[];
• b = arr;
• Now array arr and b will point to the same int object and contain
same values.
• Accessing Array Elements - We can access array elements by using array index as follows
• int x = a[2];
• The above statement will take the 3rd element (element at 2nd index) of array "a" and assign to
variable x. So the value of x will be 6.
• Example –
Example -
Putting together all the above code, here is the program that create, initialize and access the array.
public class Call {
}
}
• Example 2 -
public class Call {
}
• for each loop -
• This style of for loop is added in jdk1.5. It is mainly used to iterate through the elements of
arrays and collections. It is called "for each" because it iterate through each element of
array or collection.
• Syntax -
• for(data_type:array|collection name)
• Here data_type should be of the same type as data type of elements of array or collection.
For example if array contains integer type elements then data_type should be integer and
if it contains some object type element then data_type should be of that type.
• Example -
public class Call {
public static void main(String[] args) {
• An array which has more than one dimension is called multidimensional array.
• Double Dimensional Array (2D array) - 2D Array is the most general form of
multidimensional array. It contains 2 dimensions, first dimension represents the
number of rows and second one represents number of columns in each row. It
is also called matrix or table. We can declare an array as follows -
• data_ type array_name[ ][ ];
• Here type can be any valid java data type and array_name will be any valid java
identifier. For example -
• int arr[ ][ ];
• Here we define a 2D array of integers named arr.
• A 2D Array can be declared using any of the following forms -
• 1- data_type array_name[ ][ ]; for example - int arr[ ][ ];
• 2- data_type[ ] array_name[ ]; for example - int[ ] arr[ ];
• 3- data_type[ ][ ] array_name; for example - int [ ][ ] arr;
• All the statements are equivalent; you can use any of them.
We can allocate memory to array arr as follows -
• arr = new int[3][4];
• This statement define an array arr containing 3 rows and 4
columns and will allocate 48 byte (3*4 = 12(elements)*4 = 48
bytes) of memory storage to array arr. It can be represented
as follows -
• Initializing 2D Array - We can initialize a 2D Array either one by one or by using a single statement as follows -
• Example 1 -
public class Call
{
public static void main(String[] args) {
• Note - for accessing the array elements we can either use for each loop style as we use above or we can use simple for loop style as used to initialize
array elements.
• Example 2
public class Call {
• A jagged array arr containing 3 rows, 1st row containing 3 elements, 2nd
row containing 4 elements, 3rd row containing 2 elements.
• Example -
public class Call {
}
• Practice Problems –
• Find Maximum and Minimum in an Array-
public class MaxMinArray {
public static void main(String[] args) {
int[] numbers = {12, 4, 19, 33, 7};
int max = numbers[0];
int min = numbers[0];
if (!found) {
System.out.println("Element not found");
}
}
}
• Reverse an Array –
public class ReverseArray {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
System.out.println("Original array:");
for (int num : numbers) {
System.out.print(num + " ");
}
System.out.println("\nReversed array:");
for (int i = numbers.length - 1; i >= 0; i--) {
System.out.print(numbers[i] + " ");
}
}
}
• Sort an Array (Bubble Sort) –
• Bubble Sort is a simple sorting algorithm that repeatedly steps
through the array, compares adjacent elements, and swaps them if
they are in the wrong order. This process is repeated until the array is
sorted.
• Steps of Bubble Sort:
• Start with the first element of the array.
• Compare the current element with the next one:
– If the current element is greater than the next, swap them.
– Otherwise, leave them as is.
• Move to the next pair of elements and repeat the comparison.
• Continue until the end of the array, completing one "pass."
• After each pass, the largest unsorted element "bubbles" to its correct
position.
• Repeat the process for the remaining unsorted portion of the array
until no swaps are needed (the array is sorted).
•
• Unsorted Array: {5, 3, 8, 6, 2}
• Pass 1:
• Compare 5 and 3 → Swap → {3, 5, 8, 6, 2}
• Compare 5 and 8 → No Swap → {3, 5, 8, 6, 2}
• Compare 8 and 6 → Swap → {3, 5, 6, 8, 2}
• Compare 8 and 2 → Swap → {3, 5, 6, 2, 8}
• After Pass 1: The largest element 8 is in its correct position.
• Pass 2:
• Compare 3 and 5 → No Swap → {3, 5, 6, 2, 8}
• Compare 5 and 6 → No Swap → {3, 5, 6, 2, 8}
• Compare 6 and 2 → Swap → {3, 5, 2, 6, 8}
• After Pass 2: The second largest element 6 is in its correct position.
• Pass 3:
• Compare 3 and 5 → No Swap → {3, 5, 2, 6, 8}
• Compare 5 and 2 → Swap → {3, 2, 5, 6, 8}
• After Pass 3: The third largest element 5 is in its correct position.
• Pass 4:
• Compare 3 and 2 → Swap → {2, 3, 5, 6, 8}
• After Pass 4: The array is fully sorted.
public class BubbleSortExample {
public static void main(String[] args) {
int[] numbers = {5, 3, 8, 6, 2};
System.out.println("Original Array:");
for (int num : numbers) {
System.out.print(num + " ");
}
System.out.println("\nSorted Array:");
for (int num : numbers) {
System.out.print(num + " ");
}
}
}
• Find the Second Largest Element
• Initialize two variables:
– largest to hold the largest element.
– secondLargest to hold the second largest element.
• Traverse the array:
– If the current element is greater than largest,
update secondLargest to largest and then update
largest to current element.
– If the current element is not equal to largest and
greater than secondLargest, update secondLargest.
• At the end of the traversal, secondLargest will
contain the second largest value.
public class SecondLargest {
public static void main(String[] args) {
int[] numbers = {12, 35, 1, 10, 34, 1};
// Initialize variables
int largest = Integer.MIN_VALUE;
int secondLargest = Integer.MIN_VALUE;