0% found this document useful (0 votes)
14 views47 pages

Java Arrays: Types, Usage, and Examples

The document provides a comprehensive overview of Java arrays, explaining their characteristics, advantages, and disadvantages. It covers various types of arrays, including single-dimensional, multidimensional, and jagged arrays, along with syntax for declaration, instantiation, initialization, and methods for array manipulation. Additionally, it discusses copying arrays, performing matrix addition and multiplication, and handling exceptions related to array indexing.

Uploaded by

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

Java Arrays: Types, Usage, and Examples

The document provides a comprehensive overview of Java arrays, explaining their characteristics, advantages, and disadvantages. It covers various types of arrays, including single-dimensional, multidimensional, and jagged arrays, along with syntax for declaration, instantiation, initialization, and methods for array manipulation. Additionally, it discusses copying arrays, performing matrix addition and multiplication, and handling exceptions related to array indexing.

Uploaded by

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

JAVA ARRAYS

1
JAVA ARRAYS
• Normally, an array is a collection of similar type of elements which has
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. It is a data structure where we store similar elements. 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.
• Unlike C/C++, we can get the length of the array using the length member.
• In C/C++, we need to use the sizeof operator.

2
JAVA ARRAYS
• In Java, array is an object of a dynamically generated class.
• Java array inherits the Object class, and implements the Serializable
as well as Cloneable interfaces.

• We can store primitive values or objects in an array in Java. Like C/C+


+, we can also create single dimentional or multidimentional arrays in
Java.

• Moreover, Java provides the feature of anonymous arrays which is not


available in C/C++.
3
JAVA ARRAYS

4
JAVA ARRAYS
• Advantages
• Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.

• Random access: We can get any data located at an index position.


• Disadvantages
• Size Limit: We can store only the fixed size of elements in the array. It doesn't grow
its size at runtime.

• To solve this problem, collection framework is used in Java which grows automatically.
5
JAVA ARRAYS

• Types of Array in java


• There are two types of array.
• Single Dimensional Array
• Multidimensional Array

6
JAVA ARRAYS

• Single Dimensional Array in Java


• Syntax to Declare an Array in Java
• dataType[] arr; (or)
• dataType []arr; (or)
• dataType arr[];
• Instantiation of an Array in Java
• arrayRefVar=new datatype[size];
7
JAVA ARRAYS
• Example of Java Array
• //Java Program to illustrate how to declare, instantiate,
initialize&traverse the Java array.
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40; 8

a[4]=50;
JAVA ARRAYS

//traversing array
for(int i=0;i<[Link];i++)//length is the property of array
[Link](a[i]);
}}

9
JAVA ARRAYS

Output:

10
20
70
40
50
10
JAVA ARRAYS

• Declaration, Instantiation and Initialization of Java Array


• We can declare, instantiate and initialize the java array
together by:
• int a[]={33,3,4,5};//
declaration, instantiation and initialization

11
JAVA ARRAYS
//Java Program to illustrate the use of declaration, instantiation&
initialization of Java array in a single line
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<[Link];i++)//length is the property of array
[Link](a[i]);
}}
12
JAVA ARRAYS
Output:

33
3
4
5

13
JAVA ARRAYS
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.

• The syntax of the for-each loop is given below:


for(data_type variable:array){
//body of the loop
}
14
JAVA ARRAYS
• Let us see the example of print the elements of Java array using the for-each
loop.
//Java Program to print the array elements using for-each loop
class Testarray1{
public static void main(String args[]){
int arr[]={33,3,4,5};
//printing array using for-each loop
for(int i:arr)
[Link](i);
}}
15
JAVA ARRAYS

Output:

33
3
4
5

16
JAVA ARRAYS

• Passing Array to a Method in Java


• We can pass the java array to 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.

17
JAVA ARRAYS
• //Java Program to demonstrate the way of passing an array to
method.
class Testarray2{
static void min(int arr[]){//creating a method which receives an array as
a parameter
int min=arr[0];
for(int i=1;i<[Link];i++)
if(min>arr[i])
min=arr[i];
[Link](min);}
public static void main(String args[]){
int a[]={33,3,4,5};//declaring and initializing an array 18

min(a);//passing array to method


}}
JAVA ARRAYS

Output:

19
JAVA ARRAYS
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.
//Java Program to demonstrate the way of passing an anonymous
array to method.
public class TestAnonymousArray{
//creating a method which receives an array as a parameter
static void printArray(int arr[]){
for(int i=0;i<[Link];i++)
[Link](arr[i]); 20

}
JAVA ARRAYS

public static void main(String args[]){


printArray(new int[]{10,22,44,66});//
passing anonymous array to method
}}

21
JAVA ARRAYS

Output:

10
22
44
66

22
JAVA ARRAYS
Returning Array from the Method
We can also return an array from the method in Java.
//Java Program to return an array from the method
class TestReturnArray{
//creating method which returns an array
static int[] get(){
return new int[]{10,30,50,90,60};
}
23
JAVA ARRAYS
public static void main(String args[]){
//calling method which returns an array
int arr[]=get();
//printing the values of an array
for(int i=0;i<[Link];i++)
[Link](arr[i]);
}}
24
JAVA ARRAYS

Output:
10
30
50
90
60

25
JAVA ARRAYS
ArrayIndexOutOfBoundsException
• The Java Virtual Machine (JVM) throws an ArrayIndexOutOfBoundsException if
length of the array in negative, equal to the array size or greater than the array
size while traversing the array.
//Java Program to demonstrate the case of
//ArrayIndexOutOfBoundsException in a Java Array.
public class TestArrayException{
public static void main(String args[]){
int arr[]={50,60,70,80};
for(int i=0;i<=[Link];i++){
[Link](arr[i]); 26

}
JAVA ARRAYS

Output:
Exception in thread "main" [Link]: 4
at [Link]([Link])
50
60
70
80

27
JAVA ARRAYS
Multidimensional Array in Java
• In such case, data is stored in 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
28

int[][] arr=new int[3][3];//3 row and 3 column


JAVA ARRAYS
• Example to initialize Multidimensional Array in Java
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
29
JAVA ARRAYS
Example of Multidimensional Java Array
Let's see the simple example to declare, instantiate, initialize and print the
2Dimensional array.
//Java Program to illustrate the use of multidimensional array
class Testarray3{
public static void main(String args[]){ //declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}}; //printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
30
[Link](arr[i][j]+" ");
JAVA ARRAYS

Output:
123
245
445

31
JAVA ARRAYS

• 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 number


of columns.

32
JAVA ARRAYS
//Java Program to illustrate the jagged array
class TestJaggedArray{
public static void main(String[] args){
int arr[][] = new int[3][]; //declaring a 2D array with odd columns
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[2]; //initializing a jagged array
int count = 0;
for (int i=0; i<[Link]; i++)
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++; 33
JAVA ARRAYS
//printing the data of a jagged array
for (int i=0; i<[Link]; i++){
for (int j=0; j<arr[i].length; j++){
[Link](arr[i][j]+" ");
}
[Link]();//new line
}
}
} 34
JAVA ARRAYS

• Output:
012
3456
78

35
JAVA ARRAYS
• Copying a Java Array
• We can copy an array to another by the arraycopy() method
of System class.
Syntax of arraycopy method
public static void arraycopy(
Object src, int srcPos,Object dest, int destPos, int length
)
36
JAVA ARRAYS
Example of Copying an Array in Java
//Java Program to copy a source array into a destination array in Java
class TestArrayCopyDemo {
public static void main(String[] args) {
//declaring a source array
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
'i', 'n', 'a', 't', 'e', 'd' };
//declaring a destination array
char[] copyTo = new char[7];
37
JAVA ARRAYS

//copying array using [Link]() method


[Link](copyFrom, 2, copyTo, 0, 7);
//printing the destination array
[Link]([Link](copyTo));
}
}

38
JAVA ARRAYS

• Output:
caffein

39
JAVA ARRAYS
Addition of 2 Matrices in Java
Let's see a simple example that adds two matrices.
//Java Program to demonstrate the addition of two matrices in Java
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
int c[][]=new int[2][3];
40
JAVA ARRAYS
//adding and printing addition of 2 matrices
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
[Link](c[i][j]+" ");
}
[Link]();//new line
}
}
}
41
JAVA ARRAYS

• Output:

268
6 8 10

42
JAVA ARRAYS

• Multiplication of 2 Matrices in Java


• In the case of matrix multiplication, a one-row element of the
first matrix is multiplied by all the columns of the second
matrix which can be understood by the image given below.

43
JAVA ARRAYS

44
JAVA ARRAYS
Let's see a simple example to multiply two matrices of 3 rows and 3
columns.
//Java Program to multiply two matrices
public class MatrixMultiplicationExample{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};
//creating another matrix to store the multiplication of two matrices
45
int c[][]=new int[3][3]; //3 rows and 3 columns
JAVA ARRAYS
//multiplying and printing multiplication of 2 matrices
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}//end of k loop
[Link](c[i][j]+" "); //printing matrix element
}//end of j loop
[Link]();//new line 46

}
JAVA ARRAYS

• Output:
666
12 12 12
18 18 18

47

You might also like