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

Jav Array

Java arrays are objects that store multiple values of the same data type in contiguous memory locations, allowing for efficient data organization and access. They can be single-dimensional or multi-dimensional, with fixed sizes that cannot be changed after initialization. While arrays offer advantages like code optimization and random access, they also have limitations such as fixed size and type homogeneity, which can be addressed using Java's collection framework.

Uploaded by

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

Jav Array

Java arrays are objects that store multiple values of the same data type in contiguous memory locations, allowing for efficient data organization and access. They can be single-dimensional or multi-dimensional, with fixed sizes that cannot be changed after initialization. While arrays offer advantages like code optimization and random access, they also have limitations such as fixed size and type homogeneity, which can be addressed using Java's collection framework.

Uploaded by

gopogo56
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Java Arrays

Arrays are used to store multiple values in a single variable, instead of


declaring separate variables for each value.

To declare an array, define the variable type with square brackets:

String[] cars;

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.

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++.

Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
o Random access: We can get any data located at an index position.
 Efficient Access: Accessing an element by its index is fast and has constant time
complexity, O(1).
 Memory Management: Arrays have fixed size, which makes memory management
straightforward and predictable.
 Data Organization: Arrays help organize data in a structured manner, making it easier
to manage related elements.

o
Disadvantages
o 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.
o Type Homogeneity: Arrays can only store elements of the same data type, which
may require additional handling for mixed types of data.
o Insertion and Deletion: Inserting or deleting elements, especially in the middle of
an array, can be costly as it may require shifting elements.

How can we initialize an array in Java?


Arrays in Java can be initialized in several ways:
 Static Initialization: int[] arr = {1, 2, 3};
 Dynamic Initialization: int[] arr = new int[5];
 Initialization with a loop: for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1; }
Can we use an array of primitive types in Java?
Yes, Java supports arrays of primitive types such as int, char, Boolean,
etc., as well as arrays of objects.

Types of Array in java


There are two types of array.

 Single Dimensional Array


 Multidimensional Array

Single Dimensional Array in Java


Syntax to Declare an Array in Java

1. dataType[] arr; (or)


2. dataType []arr; (or)
3. dataType arr[];

Instantiation of an Array in Java


arrayRefVar=new datatype[size];

Example of Java Array


Let's see the simple example of java array, where we are going to declare, instantiate,
initialize and traverse an array.

//Java Program to illustrate how to declare, instantiate, initialize


//and 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;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}

Output
10
20
70
40
50

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

Let's see the simple example to print this array.


//Java Program to illustrate the use of declaration, instantiation
//and 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<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}

Output:

33
3
4
5

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.

//Java Program to demonstrate the way of passing an array


//to method.
class Testarray2{
//creating a method which receives an array as a parameter
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];

System.out.println(min);
}

public static void main(String args[]){


int a[]={33,3,4,5};//declaring and initializing an array
min(a);//passing array to method
}}
Output:

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<arr.length;i++)
System.out.println(arr[i]);
}

public static void main(String args[]){


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

10
22
44
66
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};
}

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<arr.length;i++)
System.out.println(arr[i]);
}}
Output:

10
30
50
90
60

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<=arr.length;i++){
System.out.println(arr[i]);
}
}}

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4


at TestArrayException.main(TestArrayException.java:5)
50
60
70
80

Array Literal in Java


In a situation where the size of the array and variables of the array are
already known, array literals can be used.
// Declaring array literal
int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };

Accessing Java Array Elements using for Loop


Each element in the array is accessed via its index. The index begins with
0 and ends at (total array size)-1. All the elements of array can be
accessed using Java for Loop.
// accessing the elements of the specified array
for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i + " : "+
arr[i]);

// Java program to illustrate creating an array

// of integers, puts some values in the array,

// and prints each value to standard output.

class GFG {

public static void main(String[] args)

// declares an Array of integers.

int[] arr;

// allocating memory for 5 integers.

arr = new int[5];


// initialize the first elements of the array

arr[0] = 10;

// initialize the second elements of the array

arr[1] = 20;

// so on...

arr[2] = 30;

arr[3] = 40;

arr[4] = 50;

// accessing the elements of the specified array

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

System.out.println("Element at index " + i

+ " : " + arr[i]);

}
Output
Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
Element at index 4 : 50

Example of Arrays of Objects


 The Student Array contains five memory spaces each of the size of
Student class in which the address of five Student objects can be
stored.
 The Student objects have to be instantiated using the constructor of
the Student class, and their references should be assigned to the array
elements in the following way.

// Java program to illustrate creating

// an array of objects

class Student {

public int roll_no;

public String name;

Student(int roll_no, String name)

this.roll_no = roll_no;

this.name = name;

// Elements of the array are objects of a class Student.

public class GFG {

public static void main(String[] args)

// declares an Array of Student

Student[] arr;

// allocating memory for 5 objects of type Student.

arr = new Student[5];

// initialize the first elements of the array

arr[0] = new Student(1, "aman");


// initialize the second elements of the array

arr[1] = new Student(2, "vaibhav");

// so on...

arr[2] = new Student(3, "shikar");

arr[3] = new Student(4, "dharmesh");

arr[4] = new Student(5, "mohit");

// accessing the elements of the specified array

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

System.out.println("Element at " + i + " : "

+ arr[i].roll_no + " "

+ arr[i].name);

OUTPUT

Output
Element at 0 : 1 aman
Element at 1 : 2 vaibhav
Element at 2 : 3 shikar
Element at 3 : 4 dharmesh
Element at 4 : 5 mohit

Example (Iterating the array):


public class GFG {

public static void main(String[] args)

int[] arr = new int[2];

arr[0] = 10;

arr[1] = 20;

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

System.out.println(arr[i]);
}

Output
10
20

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

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


2. dataType [][]arrayRefVar; (or)
3. dataType arrayRefVar[][]; (or)
4. dataType []arrayRefVar[];
Example to instantiate Multidimensional Array in Java

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

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;

Example of Multidimensional Java Array


Multi-Dimensional Arrays
Arrays with more than one dimension, such as two-dimensional arrays
(matrices).
int[][] multiDimArray = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
}; // A 2D array (matrix)

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++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}
Output:

123
245
445

Addition of 2 Matrices in Java


//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];

//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];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}}

Output:

268
6 8 10

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.
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


int c[][]=new int[3][3]; //3 rows and 3 columns

//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
System.out.print(c[i][j]+" "); //printing matrix element
}//end of j loop
System.out.println();//new line
}
}}
Output:

666
12 12 12
18 18 18

How are multidimensional arrays represented in Java?


Multidimensional arrays in Java are represented as arrays of arrays. For
example, a two-dimensional array is declared as int[][] array, and it is
effectively an array where each element is another array.

Can we change the size of an array after it is created in Java?


No, the size of an array in Java cannot be changed once it is initialized.
Arrays are fixed-size. To work with a dynamically sized collection,
consider using classes from the java.util package, such as ArrayList.

Can we specify the size of an array as long in Java?


No, we cannot specify the size of an array as long. The size of an array
must be specified as an int. If a larger size is required, it must be handled
using collections or other data structures.

Program to print the duplicate elements of an array


public class DuplicateElement {
public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {1, 2, 3, 4, 2, 7, 8, 8, 3};
System.out.println("Duplicate elements in given array: ");
//Searches for duplicate element
for(int i = 0; i < arr.length; i++) {
for(int j = i + 1; j < arr.length; j++) {
if(arr[i] == arr[j])
System.out.println(arr[j]);
}
}
}
}

OUTPUT

java -cp /tmp/ntl6HbRbN3/DuplicateElement

Duplicate elements in given array:

8
Write a program in Java to enter natural numbers in a double
dimensional array m x n (where m is the number of rows and n
is the number of columns). Display the new matrix in such a
way that the new matrix is the mirror image of the original
matrix.

8 15 9 18

1
9 7 6
0

1
8 11 13
0

12 16 17 19

Sample Input

1
9 15 8
8

1
6 7 9
0

1
13 11 8
0

19 17 16 12
Sample Output

import java.util.Scanner;

public class KboatSDAMirrorImage


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter number of rows (m): ");
int m = in.nextInt();
System.out.print("Enter number of columns (n): ");
int n = in.nextInt();

int arr[][] = new int[m][n];


int newArr[][] = new int[m][n];

System.out.println("Enter array elements");


for (int i = 0; i < m; i++) {
System.out.println("Enter Row "+ (i+1) + " :");
for (int j = 0; j < n; j++) {
arr[i][j] = in.nextInt();
}
}

System.out.println("Input Array:");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(arr[i][j] + "\t");
}
System.out.println();
}

for (int j = 0; j < n; j++) {


for (int i = 0; i < m; i++) {
newArr[i][n - 1 - j] = arr[i][j];
}
}

System.out.println("Mirror Image Array:");


for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(newArr[i][j] + "\t");
}
System.out.println();
}
}
}
OUTPUT
Write a program in Java to create a 4 x 4 matrix. Now, swap the
elements of 0th row with 3rd row correspondingly. Display the
result after swapping.
Sample Input

5 3 2 1
5 3 6 4

81 8 31 1
6 0
5 6
17 12
8 4

2 1 2 2
2 4 3 5

Sample Output

2 1 2 2
2 4 3 5

8 1
81 31
6 0

5 6
17 12
8 4

5 3 2 1
5 3 6 4

ANSWER
import java.util.Scanner;

public class KboatDDARowSwap


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int arr[][] = new int[4][4];

System.out.println("Enter elements of 4x4 array ");


for (int i = 0; i < 4; i++) {
System.out.println("Enter Row "+ (i+1) + " :");
for (int j = 0; j < 4; j++) {
arr[i][j] = in.nextInt();
}
}

System.out.println("Input Array:");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(arr[i][j] + "\t");
}
System.out.println();
}

//Swap 0th and 3rd rows


for (int j = 0; j < 4; j++) {
int t = arr[0][j];
arr[0][j] = arr[3][j];
arr[3][j] = t;
}

System.out.println("Swapped Array:");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(arr[i][j] + "\t");
}
System.out.println();
}
}
}
OUTPUT
Java Program to Rotate Matrix Elements
// Java Program to Rotate Matrix Elements

// Importing classes from java.lang package

import java.lang.*;

// Importing classes from java.util package

import java.util.*;

// main Class

class GFG {
static int r = 4;

static int c = 4;

// Method

// To rotate a matrix of

// dimension r x c. And initially,

// p = r and q = c

static void rotate_matrix(int p, int q, int matrix[][])

int rw = 0, cl = 0;

int previous, current;

// rw is the Starting row index

// p is the ending row index

// cl is the starting column index

// q is the ending column index and

// x is the iterator

while (rw < p && cl < q) {

if (rw + 1 == p || cl + 1 == q)

break;

// After storing the first element of the

// next row, this element will substitute

// the first element of the current row

previous = matrix[rw + 1][cl];

// Moving the elements of the first row

// from rest of the rows

for (int x = cl; x < q; x++) {

current = matrix[rw][x];
matrix[rw][x] = previous;

previous = current;

rw++;

// Moving the elements of the last column

// from rest of the columns

for (int x = rw; x < p; x++) {

current = matrix[x][q - 1];

matrix[x][q - 1] = previous;

previous = current;

q--;

// Moving the elements of the last row

// from rest of the rows

if (rw < p) {

for (int x = q - 1; x >= cl; x--) {

current = matrix[p - 1][x];

matrix[p - 1][x] = previous;

previous = current;

p--;

// Moving elements of the first column

// from rest of the rows

if (cl < q) {

for (int x = p - 1; x >= rw; x--) {

current = matrix[x][cl];

matrix[x][cl] = previous;
previous = current;

cl++;

// Prints the rotated matrix

for (int x = 0; x < r; x++) {

for (int y = 0; y < c; y++)

System.out.print(matrix[x][y] + " ");

System.out.print("\n");

// Method 2

// Main driver method

public static void main(String[] args)

// Custom input array

int b[][] = { { 5, 6, 7, 8 },

{ 1, 2, 3, 4 },

{ 0, 15, 6, 5 },

{ 3, 1, 2, 12 } };

// Calling function(Method1) to rotate matrix

rotate_matrix(r, c, b);

Output

java -cp /tmp/CtdHwpOXD7/GFG


1567

0 15 2 8

3634

1 2 12 5

Write a Program in Java to fill a 2D array with the first 'mxn'


prime numbers, where 'm' is the number of rows and 'n' is the
number of columns.
For example:
If rows = 4 and columns = 5, then the result should be:

2 3 5 7 11

2 2
13 17 19
3 9

3 4 4 4
31
7 1 3 7

5 5 6
61 71
3 9 7

import java.util.Scanner;

public class KboatSDAPrime


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter number of rows (m): ");
int m = in.nextInt();
System.out.print("Enter number of columns (n): ");
int n = in.nextInt();

int arr[][] = new int[m][n];


int r = 0, c = 0;
int total = m * n;
int count = 0;
for (int i = 2; count < total; i++) {
int div = 0;
for (int j = 1; j <= i; j++) {
if (i % j == 0) {
div++;
}
}

if (div == 2) {
arr[r][c++] = i;
count++;
if (c == n) {
r++;
c = 0;
}
}

System.out.println("Prime Numbers Array:");


for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(arr[i][j] + "\t");
}
System.out.println();
}
}
}

Output

Enter number of rows (m): 3

Enter number of columns (n): 3

Prime Numbers Array:

2 3 5

7 11 13

17 19 23

Program to find the frequency of each element in the


array

public class Frequency {


public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {1, 2, 8, 3, 2, 2, 2, 5, 1};
//Array fr will store frequencies of element
int [] fr = new int [arr.length];
int visited = -1;
for(int i = 0; i < arr.length; i++){
int count = 1;
for(int j = i+1; j < arr.length; j++){
if(arr[i] == arr[j]){
count++;
//To avoid counting same element again
fr[j] = visited;
}
}
if(fr[i] != visited)
fr[i] = count;
}

//Displays the frequency of each element present in array


System.out.println("---------------------------------------");
System.out.println(" Element | Frequency");
System.out.println("---------------------------------------");
for(int i = 0; i < fr.length; i++){
if(fr[i] != visited)
System.out.println(" " + arr[i] + " | " + fr[i]);
}
System.out.println("----------------------------------------");
}}
OUTPUT

java -cp /tmp/Ic6o5iu25P/Frequency

---------------------------------------

Element | Frequency

---------------------------------------

1 | 2

2 | 4

8 | 1

3 | 1

5 | 1

----------------------------------------

You might also like