Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
12 views

Lecture - 4 Arrays in Java

Uploaded by

Subham Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Lecture - 4 Arrays in Java

Uploaded by

Subham Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 24

ARRAYS in JAVA

ARRAYS:
• An array is a collection of similar type of elements which has a
contiguous memory location.
• Java array is an object which contains elements of a similar data
type.
• Additionally, The elements of an array are stored in a contiguous
memory location.
• We can store only a fixed set of elements in a Java array.
• Array in Java is index-based, the first element of the array is stored
at the 0th index, 2nd element is stored on 1st index, and so on.
There are two types of arrays.
• Single Dimensional Array
• Multidimensional Array
SINGLE DIMENSIONAL ARRAY
Single Dimensional Array in Java
Declaration:
Syntax : dataType[] arr; (or) dataType []arr; (or) dataType arr[];
Ex: int[] arr; or int []arr; int arr[];
Instantiation:
Syntax: arrayRefVar=new datatype[size];
Ex: arr = new int[10];
Declaration and Instantiation :
Syntax: datatype arrayRefVar[] = new datatype[size];
Ex: int arr[] = new int[10];
Single Dimensional Array in Java
Initialization:
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
Or
int a[]={10,20,70,40,50}; //declaration, instantiation and initialization
Single Dimensional Array in Java
Example :
class program1
{
Output:
public static void main(String args[]) 10
20
{ 70
40
//declaration, instantiation and initialization
50
int a[]={10,20,70,40,50};
//printing array
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
}
}
Single Dimensional Array in Java
For-each Loop for Java Array

• We can also print the Java array using for-each loop.


• The Java for-each loop prints the array elements one by one.
• It holds an array element in a variable, then executes the body of the loop.
Syntax:
for(data_type variable:array) Example:
{ class program2
//body of the loop {
public static void main(String args[])
} {
Output: int arr[]={10,20,70,40,50};
10 for(int i:arr)
System.out.println(i);
20 }
70 }
40
50
Single Dimensional Array in Java
ArrayIndexOutOfBoundsException
• The Java Virtual Machine (JVM) throws an ArrayIndexOutOfBoundsException if the length of the array
is negative, equal to the array size, or greater than the array size while traversing the array.
Example:
public class TestArrayException
{
public static void main(String args[])
{
int arr[]={50,60,70,80};
for(int i=0;i<=arr.length;i++)
System.out.println(arr[i]);
}
}
Output:
Single Dimensional Array in Java
Passing Array to a Method in Java
• We can pass the java array to a method so that we can reuse the same logic on any array.
• Let's see the simple example to get the minimum number of an array using a method.
Example: // Smallest value among the array
class program3
{
static void min(int arr[])
{
int min=arr[0];
for(int i=1;i<arr.length;i++)
{
if(min>arr[i])
min=arr[i]; Output:
}
System.out.println("Minimum value is " + min);
Minimum value is 10
}
public static void main(String args[])
{
int a[]={40,20,10,30};
min(a);//calling min() method by passing array
}
}
Single Dimensional Array in Java
Anonymous Array in Java
• Java supports the feature of an anonymous array, so you don't need to declare the
array while passing an array to the method.
Example:
public class program4
{
//creating a method that receives an array as a parameter
static void printArray(int arr[]) Output:
{
for(int i=0;i<arr.length;i++) 10
System.out.println(arr[i]); 22
} 44
public static void main(String args[]) 66
{
//passing anonymous array to method
printArray(new int[]{10,22,44,66});
}
}
Single Dimensional Array in Java
Java Copy Array
• In Java, we can copy one array into another. There are several techniques you can use to
copy arrays in Java.

1. Copying Arrays Using Assignment Operator ( Shallow Copy )


class arrcopy1
{
public static void main(String[] args) Output:
{
int [] numbers = {1, 2, 3, 4, 5, 6}; 1,2,3,4,5,6
int [] positiveNumbers = numbers; // copying arrays

for (int number: positiveNumbers)


{
System.out.print(number + ", ");
} However, there is a problem with this technique. If
} we change elements of one array, corresponding
} elements of the other arrays also change.
Single Dimensional Array in Java

class arrcopy2
{
• Here, we can see that we have
public static void main(String[] args)
changed one value of
{
the numbers array. When we print
int [] numbers = {1, 2, 3, 4, 5, 6};
the positiveNumbers array, we can
int [] positiveNumbers = numbers; // copying arrays
see that the same value is also
changed.
numbers[0] = -1;
• It's because both arrays refer to the
for (int number: positiveNumbers)
same array object. This is because of
{
the shallow copy.
System.out.print(number + ", ");
}
• Now, to make new array objects while
}
copying the arrays, we need deep
}
copy rather than a shallow copy.

Output:

-1,2,3,4,5,6
Single Dimensional Array in Java
2. Copy Arrays Using Looping Construct (Deep Copy)

class arrcopy3
{
public static void main(String[] args)
{
int [] source = {1, 2, 3, 4, 5, 6};
int [] destination = new int[6];
Output:
// iterate and copy elements from source to destination
for (int i = 0; i < source.length; ++i) 1,2,3,4,5,6
{
destination[i] = source[i];
}
source[0]=-1; // modifying element of source array
for (int i = 0; i < destination.length; ++i)
{
System.out.println(destination[i]);
}
}
}
Single Dimensional Array in Java
3. Copying Arrays Using arraycopy() method

• In Java, the System class contains a method named arraycopy() to copy arrays.
This method is a better approach to copy arrays than the above two.
• The arraycopy() method allows you to copy a specified portion of the source array
to the destination array.

• Syntax: arraycopy(Object src, int srcPos,Object dest, int destPos, int length)

Here,
• src - source array you want to copy
• srcPos - starting position (index) in the source array
• dest - destination array where elements will be copied from the source
• destPos - starting position (index) in the destination array
• length - number of elements to copy
Single Dimensional Array in Java
import java.util.Arrays; Arrays.toString() is used to
convert an array of any type to
class arrcopy4 a human-readable string
{ representation.
public static void main(String[] args)
{ The method returns a string
int[] n1 = {2, 3, 12, 4, 12, -2}; representation of the
// Creating n2 array of having length of n1 array elements in the array,
enclosed in square brackets
int[] n2 = new int[n1.length];
([]), with each element
// Creating n3 array of having length 5 separated by commas and
int[] n3 = new int[5]; spaces.

// copying entire n1 array to n2


System.arraycopy(n1, 0, n2, 0, n1.length);
System.out.println("n2 = " + Arrays.toString(n2));

// copying elements from index 2 on n1 array - copying element to index 1 of n3 array


// 2 elements will be copied Output:
System.arraycopy(n1, 2, n3, 1, 2);
System.out.println("n3 = " + Arrays.toString(n3)); n2 = [2, 3, 12, 4, 12, -2]
} n3 = [0, 12, 4, 0, 0]
}
Programs on Single Dimensional Array

1. Write a program to read 5 numbers into an array and arrange them in ascending
order.
2. Write a program to read 6 numbers into an array and print the duplicate
numbers.
3. Write a program to find Second Largest Number in an Array.
4. Write a program to read n numbers into an array and find the sum of all the
elements.
5. Write a program to copy one array into another array.
MULTI DIMENSIONAL ARRAY
Multidimensional Array in Java
Multi-dimensional Array ( 2 – D Array) :
• Here, data is stored in a row and column-based index (also known as matrix
form)..

Syntax to Declare Multidimensional Array in Java :


dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in Java :


int[][] arr=new int[2][3];//2 rows and 3 columns

Example to initialize Multidimensional Array in Java :


int arr[][]={{10,20,30},{40,50,60}};
Multidimensional Array in Java
Multi-dimensional Array ( 2 – D Array) :

• int arr[][] = { {2,7,9},{3,6,1},{7,4,2} };


Multidimensional Array in Java
Example of Multidimensional Java Array
• Let's see the simple example to declare, instantiate, initialize and print the 2-
Dimensional array.
Example:
class program6
{
public static void main(String args[])
{
//declaring and initializing 2D array Output:
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
1 2 3
//printing 2D array 2 4 5
for(int i=0;i<3;i++) 4 4 5
{
for(int j=0;j<3;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
Multidimensional Array in Java
Addition of two matrices :
class Testarray5
{
public static void main(String args[])
{
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};

//creating another matrix to store the sum of two matrices


Output:
int c[][]=new int[2][3];
2 6 8
//adding and printing addition of 2 matrices 6 8 10
for(int i=0;i<2;i++)
{
for(int j=0;j<3;j++)
{
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}
}
Multidimensional Array in Java
Jagged Array in Java
• If we are creating odd number of columns in a 2D array, it is known as a jagged array.
• In other words, it is an array of arrays with different numbers of columns.
Example:
class TestJaggedArray
{
public static void main(String[] args)
{
//declaring a 2D array with odd columns
int arr[][] = new int[3][];

arr[0] = new int[3];


arr[1] = new int[4];
arr[2] = new int[2];
//printing the data of a jagged array
//initializing a jagged array for (int i=0; i<arr.length; i++)
int count = 0; {
for (int j=0; j<arr[i].length; j++) Output:
for (int i=0; i<arr.length; i++) {
{ System.out.print(arr[i][j]+" ");
for(int j=0; j<arr[i].length; j++) } 012
{ System.out.println(); 3456
arr[i][j] = count++; } 78
} }
} }
Multidimensional Array in Java

Advantages of Jagged Array Over Multi-dimensional Array in Java


• Jagged arrays have several advantages over multidimensional arrays with a fixed
size:
• Memory Efficiency: Jagged arrays are more memory-efficient than
multidimensional arrays because they only allocate memory for the elements they
need. In a multidimensional array with a fixed size, all the memory is allocated, even
if some elements are unused.
• Flexibility: Jagged arrays are more flexible than multidimensional arrays because
they can have different sizes for each row. Jagged arrays enable the representation
of non-rectangular or irregular data structures.
• Easy to Initialize: Jagged arrays are easy to initialize because you can specify the
size of each row individually. The suitability of jagged arrays lies in their ability to
store data that varies in size or is generated dynamically.
• Enhanced Performance: Jagged arrays can provide enhanced performance in
certain scenarios, such as when you need to perform operations on each row
independently or when you need to add or remove rows dynamically.
Thank You

You might also like