0% found this document useful (0 votes)
3 views

Java Arrays

This document provides a comprehensive overview of arrays in Java, including how to declare, initialize, and manipulate both one-dimensional and multidimensional arrays. It covers various methods for copying arrays, such as using assignment, loops, the arraycopy() method, and the copyOfRange() method. Additionally, it includes examples demonstrating the concepts discussed, ensuring a clear understanding of array operations in Java.

Uploaded by

Supriya Nevewani
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Java Arrays

This document provides a comprehensive overview of arrays in Java, including how to declare, initialize, and manipulate both one-dimensional and multidimensional arrays. It covers various methods for copying arrays, such as using assignment, loops, the arraycopy() method, and the copyOfRange() method. Additionally, it includes examples demonstrating the concepts discussed, ensuring a clear understanding of array operations in Java.

Uploaded by

Supriya Nevewani
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 47

Session 5: Arrays Lecture: •

Java Initialize array


Java initialize array is basically a term
used for initializing an array in Java. We
know that an array is a collection of
similar types of data. The array is a very
important data structure used for
solving programming problems.
The word element is used for the
values stored in different positions of
the array. In order to use the Array data
structure in our code, we first declare it,
and after that, we initialize it.
Declaration of an Array
The syntax of declaring an array in Java
is given below.

datatype [] arrayName;

Here, the datatype is the type of


element that will be stored in the
array, square bracket[] is for the size
of the array, and arrayName is the
name of the array.
Initializing an Array
Only the declaration of the array is not
sufficient. In order to store values in the
array, it is required to initialize it after
declaration. The syntax of initializing an
array is given below.

1. datatype [] arrayName = new dataty


pe [ size ]
In Java, there is more than one way of
initializing an array which is as follows:
1. Without assigning values
In this way, we pass the size to
the square braces[], and the default
value of each element present in the
array is 0. Let's take an example and
understand how we initialize an array
without assigning values.
ArrayExample1.java
public class ArrayExample1 {

public static void main( String args[]


){

//initializing array without passing val


ues
int[] array = {1,2,3,4,5};

//print each element of the array


for (int i = 0; i < 5; i++)
{
System.out.println(array[i]);
}
}

Java Multidimensional Arrays


In this tutorial, we will learn about the Java
multidimensional array using 2-dimensional
arrays and 3-dimensional arrays with the help
of examples.
Before we learn about the multidimensional
array, make sure you know about Java array.
A multidimensional array is an array of arrays.
Each element of a multidimensional array is
an array itself. For example,

int[][] a = new int[3][4];


Here, we have created a multidimensional
array named a. It is a 2-dimensional array,
that can hold a maximum of 12 elements,

Remember, Java uses zero-based indexing,


that is, indexing of arrays in Java starts with 0
and not 1.
Let's take another example of the
multidimensional array. This time we will be
creating a 3-dimensional array. For example,
String[][][] data = new String[3]
[4][2];
Here, data is a 3d array that can hold a
maximum of 24 (3*4*2) elements of
type String.

How to initialize a 2d array in Java?


Here is how we can initialize a 2-dimensional
array in Java.

int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
};
As we can see, each element of the
multidimensional array is an array itself. And
also, unlike C/C++, each row of the
multidimensional array in Java can be of
different lengths.
Initialization of
2-dimensional Array
Example: 2-dimensional Array
class MultidimensionalArray {
public static void
main(String[] args) {

// create a 2d array
int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
};
// calculate the length of
each row
System.out.println("Length
of row 1: " + a[0].length);
System.out.println("Length
of row 2: " + a[1].length);
System.out.println("Length
of row 3: " + a[2].length);
}
}
Run Code
Output:
Length of row 1: 3
Length of row 2: 4
Length of row 3: 1
In the above example, we are creating a
multidimensional array named a. Since each
component of a multidimensional array is also
an array (a[0], a[1] and a[2] are also
arrays).

Here, we are using the length attribute to


calculate the length of each row.

Example: Print all elements of 2d array


Using Loop
class MultidimensionalArray {
public static void
main(String[] args) {

int[][] a = {
{1, -2, 3},
{-4, -5, 6, 9},
{7},
};
for (int i = 0; i < a.length; +
+i) {
for(int j = 0; j < a[i].length; +
+j) {
System.out.println(a[i][j]);
}
}
}
}
Run Code
Output:
1
-2
3
-4
-5
6
9
7
We can also use the for...each loop to access
elements of the multidimensional array. For
example,
class MultidimensionalArray {
public static void
main(String[] args) {

// create a 2d array
int[][] a = {
{1, -2, 3},
{-4, -5, 6, 9},
{7},
};
// first for...each loop
access the individual array
// inside the 2d array
for (int[] innerArray: a)
{
// second for...each
loop access each element inside
the row
for(int data:
innerArray) {
System.out.println(data);
}
}
}
}
Run Code
Output:
1
-2
3
-4
-5
6
9
7

In the above example, we are have created a


2d array named a. We then used for loop
and for...each loop to access each
element of the array.
How to initialize a 3d array in Java?
Let's see how we can use a 3d array in Java.
We can initialize a 3d array similar to the 2d
array. For example,

// test is a 3d array
int[][][] test = {
{
{1, -2, 3},
{2, 3, 4}
},
{
{-4, -5, 6, 9},
{1},
{2, 3}
}
};
Basically, a 3d array is an array of 2d arrays.
The rows of a 3d array can also vary in length
just like in a 2d array.
Example: 3-dimensional Array
class ThreeArray {
public static void
main(String[] args) {

// create a 3d array
int[][][] test = {
{
{1, -2, 3},
{2, 3, 4}
},
{
{-4, -5, 6, 9},
{1},
{2, 3}
}
};

// for..each loop to
iterate through elements of 3d
array
for (int[][] array2D:
test) {
for (int[] array1D:
array2D) {
for(int item:
array1D) {
System.out.println(item);
}
}
}
}
}
Run Code
Output:
1
-2
3
2
3
4
-4
-5
6
9
1
2
3

Java Copy Arrays


In this tutorial, you will learn about different
ways you can use to copy arrays (both one
dimensional and two-dimensional) in Java
with the help of examples.
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


Let's take an example,
class Main {
public static void
main(String[] args) {
int [] numbers = {1, 2, 3,
4, 5, 6};
int [] positiveNumbers =
numbers; // copying arrays

for (int number:


positiveNumbers) {
System.out.print(number + ", ");
}
}
}
Run Code
Output:
1, 2, 3, 4, 5, 6
In the above example, we have used the
assignment operator (=) to copy an array
named numbers to another array
named positiveNumbers.
This technique is the easiest one and it works
as well. However, there is a problem with this
technique. If we change elements of one
array, corresponding elements of the other
arrays also change. For example,
class Main {
public static void
main(String[] args) {
int [] numbers = {1, 2, 3,
4, 5, 6};
int [] positiveNumbers =
numbers; // copying arrays
// change value of first
array
numbers[0] = -1;
// printing the second
array
for (int number:
positiveNumbers) {
System.out.print(number + ", ");
}
}
}
Run Code
Output:
-1, 2, 3, 4, 5, 6
Here, we can see that we have changed one
value of the numbers array. When we print
the positiveNumbers array, we can see
that the same value is also changed.
It's because both arrays refer to the same
array object. This is because of the shallow
copy. To learn more about shallow copy,
visit shallow copy.
Now, to make new array objects while copying
the arrays, we need deep copy rather than a
shallow copy.
2. Using Looping Construct to Copy Arrays
Let's take an example:
import java.util.Arrays;

class Main {
public static void
main(String[] args) {
int [] source = {1, 2, 3,
4, 5, 6};
int [] destination = new
int[6];

// iterate and copy


elements from source to
destination
for (int i = 0; i <
source.length; ++i) {
destination[i] =
source[i];
}
// converting array to
string
System.out.println(Arrays.toString
(destination));
}
}
Run Code
Output:
[1, 2, 3, 4, 5, 6]

In the above example, we have used


the for loop to iterate through each element
of the source array. In each iteration, we are
copying elements from the source array to
the destination array.
Here, the source and destination array refer to
different objects (deep copy). Hence, if
elements of one array are changed,
corresponding elements of another array is
unchanged.
Notice the statement,

System.out.println(Arrays.toString
(destination));
Here, the toString() method is used to convert
an array into a string. To learn more, visit
the toString() method (official Java
documentation).

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. For example,
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
Let's take an example:
// To use Arrays.toString() method
import java.util.Arrays;

class Main {
public static void
main(String[] args) {
int[] n1 = {2, 3, 12, 4,
12, -2};
int[] n3 = new int[5];

// Creating n2 array of
having length of n1 array
int[] n2 = new
int[n1.length];
// 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
System.arraycopy(n1, 2,
n3, 1, 2);
System.out.println("n3 = "
+ Arrays.toString(n3));
}
}
Run Code
Output:
n2 = [2, 3, 12, 4, 12, -2]
n3 = [0, 12, 4, 0, 0]
In the above example, we have used
the arraycopy() method,
 System.arraycopy(n1, 0, n2, 0,
n1.length) - entire elements from
the n1 array are copied to n2 array
 System.arraycopy(n1, 2, n3, 1,
2) - 2 elements of the n1 array starting from
index 2 are copied to the index starting
from 1 of the n3 array
As you can see, the default initial value of
elements of an int type array is 0.
4. Copying Arrays Using copyOfRange()
method
We can also use the copyOfRange() method
defined in Java Arrays class to copy arrays.
For example,
// To use toString() and
copyOfRange() method
import java.util.Arrays;

class ArraysCopy {
public static void
main(String[] args) {
int[] source = {2, 3, 12,
4, 12, -2};
// copying entire source
array to destination
int[] destination1 =
Arrays.copyOfRange(source, 0,
source.length);
System.out.println("destination1 =
" +
Arrays.toString(destination1));
// copying from index 2 to
5 (5 is not included)
int[] destination2 =
Arrays.copyOfRange(source, 2, 5);
System.out.println("destination2 =
" +
Arrays.toString(destination2));
}
}
Run Code
Output
destination1 = [2, 3, 12, 4, 12, -
2]
destination2 = [12, 4, 12]
In the above example, notice the line,

int[] destination1 =
Arrays.copyOfRange(source, 0,
source.length);
Here, we can see that we are creating
the destination1 array and copying
the source array to it at the same time. We
are not creating the destination1 array
before calling the copyOfRange() method.
To learn more about the method, visit Java
copyOfRange.

5. Copying 2d Arrays Using Loop


Similar to the single-dimensional array, we
can also copy the 2-dimensional array using
the for loop. For example,
import java.util.Arrays;

class Main {
public static void
main(String[] args) {
int[][] source = {
{1, 2, 3, 4},
{5, 6},
{0, 2, 42, -4, 5}
};

int[][] destination = new


int[source.length][];

for (int i = 0; i <


destination.length; ++i) {
// allocating space
for each row of destination array
destination[i] = new
int[source[i].length];

for (int j = 0; j <


destination[i].length; ++j) {
destination[i][j]
= source[i][j];
}
}
// displaying destination
array
System.out.println(Arrays.deepToSt
ring(destination));
}
}
Run Code
Output:
[[1, 2, 3, 4], [5, 6], [0, 2, 42,
-4, 5]]
In the above program, notice the line,
System.out.println(Arrays.deepToSt
ring(destination);
Here, the deepToString() method is used
to provide a better representation of the 2-
dimensional array. To learn more, visit Java
deepToString().

Copying 2d Arrays using arraycopy()


To make the above code more simpler, we
can replace the inner loop
with System.arraycopy() as in the case
of a single-dimensional array. For example,
import java.util.Arrays;

class Main {
public static void
main(String[] args) {
int[][] source = {
{1, 2, 3, 4},
{5, 6},
{0, 2, 42, -4, 5}
};
int[][] destination = new
int[source.length][];

for (int i = 0; i <


source.length; ++i) {

// allocating space
for each row of destination array
destination[i] = new
int[source[i].length];
System.arraycopy(source[i], 0,
destination[i], 0,
destination[i].length);
}
// displaying destination
array
System.out.println(Arrays.deepToSt
ring(destination));
}
}
Run Code
Output:
[[1, 2, 3, 4], [5, 6], [0, 2, 42,
-4, 5]]
Here, we can see that we get the same output
by replacing the inner for loop with
the arraycopy() method.

Example 2 to find the average from user


inputted numbers
Next, let us read the input array
numbers from the user using
the Scanner class.
Scanner Example to add two
numbers
0 import java.util.Scanner;
1
0
2 public class ArrayAverageUserInput
{
0
3
0 public static void main(String[]
4 args) {
0
5
0 // reading the array size.
6
Scanner s
0
= new Scanner(System.in);
7
0
8 System.out.println("Enter
0 array size: ");
9
int size = s.nextInt();
1
0 // create an array
1 int[] array = new int[size];
1
1
// reading values from user
2
keyboard
1
3 System.out.println("Enter
1 array values : ");
4
for (int i = 0; i < size; i++) {
1
5 int value = s.nextInt();

1 array[i] = value;
6
1
7 }
1
8
1 // getting array length
9 int length = array.length;
2
0
// default sium value.
2
1 int sum = 0;
2
2
// sum of all values in array
2 using for loop
3
for (int i = 0; i < array.length;
2
4 i++) {
2 sum += array[i];
5
}
2
6
2 double average = sum /
7
2 length;
8
2
9 System.out.println("Average of
array : " + average);
3
0
3 }
1
3
2 }
3
3
3
4
3
5
3
6
3
7
3
8
3
9
4
0
Output:
1 Enter array size:
2 5
3
Enter array values :
4
12
5
6 23
7 34
8 45
9
56
Average of array : 34.0

// Basic Java program that reverses an


array
public class reverseArray {

• Reverse an array

// function that reverses array and


stores it
// in another array
static void reverse(int a[], int n)
{
int[] b = new int[n];
int j = n;
for (int i = 0; i < n; i++) {
b[j - 1] = a[i];
j = j - 1;
}

// printing the reversed array


System.out.println("Reversed array
is: \n");
for (int k = 0; k < n; k++) {
System.out.println(b[k]);
}
}

public static void main(String[] args)


{
int [] arr = {10, 20, 30, 40, 50};
reverse(arr, arr.length);
}
}

Java Program to sort the elements of an


array in ascending order
In this program, we need to sort the
given array in ascending order such that
elements will be arranged from smallest
to largest. This can be achieved through
two loops. The outer loop will select an
element, and inner loop allows us to
compare selected element with rest of
the elements.
Elements will be sorted in such a way
that the smallest element will appear on
extreme left which in this case is 1. The
largest element will appear on extreme
right which in this case is 8.
Algorithm
o STEP 1: START
o STEP 2: INITIALIZE arr[] ={5, 2, 8, 7,
1 }.
o STEP 3: SET temp =0
o STEP 4: PRINT "Elements of Original
Array"
o STEP 5: REPEAT STEP 6 UNTIL
i<arr.length
//for(i=0; i<arr.length; i++)
o STEP 6: PRINT arr[i]
o STEP 7: REPEAT STEP 8 to STEP 9
UNTIL i<arr.length
//for(i=0; i<arr.length; i++ )
o STEP 8: REPEAT STEP 9 UNTIL
j<arr.length
//for(j=i+1;j<arr.length;j++)
o STEP 9: if(arr[i]>arr[j]) then
temp = arr[i]
arr[i]=arr[j]
arr[j]=temp
o STEP 10: PRINT new line
o STEP 11: PRINT "Elements of array
sorted in ascending order"
o STEP 12: REPEAT STEP 13 UNTIL
i<arr.length
//for(i=0;i<arr.length;i++)
o STEP 13: PRINT arr[i]
o STEP 14: END

Program:
public class SortAsc {
public static void main(String[] args)
{

//Initialize array
int [] arr = new int [] {5, 2, 8, 7, 1};

int temp = 0;

//Displaying elements of original arra


y
System.out.println("Elements of origi
nal array: ");
for (int i = 0; i < arr.length; i++) {

System.out.print(arr[i] + " ");


}

//Sort the array in ascending order


for (int i = 0; i < arr.length; i++) {

for (int j = i+1; j < arr.length; j+


+) {
if(arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}

System.out.println();

//Displaying elements of array after s


orting
System.out.println("Elements of arra
y sorted in ascending order: ");
for (int i = 0; i < arr.length; i++) {

System.out.print(arr[i] + " ");


}
}
}
Output:
Elements of original array:
5 2 8 7 1
Elements of array sorted in
ascending order:
1 2 5 7 8

• Convert char Array to String

// Java Program to Convert Character Array to


String
// Using copyOf() method ofArrays() Class

// Importing required classes


import java.util.*;

// Main class
class GFG {
1 public static String toString(char[] a)
{
// Creating object of String class
String string = new String(a);
return string;
}
public static void main(String args[])
{

// Declaring and initializing a character


array
char s[] = { 'g', 'e', 'e', 'k', 's', 'f', 'o',
'r', 'g', 'e', 'e', 'k', 's' };

// Printing converted string from


character array
System.out.println(toString(s));
}
}

• Add two Matrix using Multi-dimensional Arrays

public class AddMatrices {

public static void


main(String[] args) {
int rows = 2, columns = 3;
int[][] firstMatrix =
{ {2, 3, 4}, {5, 2, 3} };
int[][] secondMatrix =
{ {-4, 5, 3}, {5, 6, 3} };

// Adding Two matrices


int[][] sum = new
int[rows][columns];
for(int i = 0; i < rows;
i++) {
for (int j = 0; j <
columns; j++) {
sum[i][j] =
firstMatrix[i][j] +
secondMatrix[i][j];
}
}

// Displaying the result


System.out.println("Sum of
two matrices is: ");
for(int[] row : sum) {
for (int column : row)
{
System.out.print(column + " ");
}
System.out.println();
}
}
}
Output
Sum of two matrices is:
-2 8 7
10 8 6

• Concatenate two arrays


Example 1: Concatenate Two Arrays using
arraycopy

import java.util.Arrays;

public class Concat {

public static void


main(String[] args) {
int[] array1 = {1, 2, 3};
int[] array2 = {4, 5, 6};

int aLen = array1.length;


int bLen = array2.length;
int[] result = new
int[aLen + bLen];

System.arraycopy(array1,
0, result, 0, aLen);
System.arraycopy(array2,
0, result, aLen, bLen);

System.out.println(Arrays.toString
(result));
}
}
Output
[1, 2, 3, 4, 5, 6]
In the above program, we've two integer
arrays array1 and array2.
In order to combine (concatenate) two arrays,
we find its length stored
in aLen and bLen respectively. Then, we
create a new integer array result with
length aLen + bLen.
Now, in order to combine both, we copy each
element in both arrays to result by
using arraycopy() function.
The arraycopy(array1, 0, result,
0, aLen) function, in simple terms, tells the
program to copy array1 starting from
index 0 to result from index 0 to aLen.
Likewise, for arraycopy(array2, 0,
result, aLen, bLen) tells the program to
copy array2 starting from
index 0 to result from index aLen to bLen.
Example 2: Concatenate Two Arrays without
using arraycopy

import java.util.Arrays;

public class Concat {

public static void


main(String[] args) {
int[] array1 = {1, 2, 3};
int[] array2 = {4, 5, 6};

int length = array1.length


+ array2.length;

int[] result = new


int[length];
int pos = 0;
for (int element : array1)
{
result[pos] = element;
pos++;
}

for (int element : array2)


{
result[pos] = element;
pos++;
}

System.out.println(Arrays.toString
(result));
}
}
Output
[1, 2, 3, 4, 5, 6]
In the above program, instead of
using arraycopy, we manually copy each
element of both
arrays array1 and array2 to result.
We store the total length required
for result, i.e. array1.length +
array2. length. Then, we create a new
array result of the length.
Now, we use the for-each loop to iterate
through each element of array1 and store it
in the result. After assigning it, we increase
the position pos by 1, pos++.
Likewise, we do the same for array2 and
store each element in result starting from
the position after array1.

• Two dimensional array in java • Java Variable


Arguments explained • Add, update, read array
elements • Sorting and searching in array • Java
String Array to String • How to copy arrays in Java

You might also like