Java Arrays

Arrays are used to store multiple values in a single variable instead of declaring separate variables for each value.

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.
 

Syntax :

String[] fruits;

OR 

String fruits[];

You can insert value in array as below,

String[] fruits = {"Apple","Orange", "Banana", "Grapes"};

Types of Array in java
 

There are two types of array.

  1. Single Dimensional Array
  2. Multidimensional Array

Single Dimensional Array can be inistantiated,defined and declared as below.

arrayVar=new datatype[size];  

Example ,

int i[]=new int[3];//declaration and instantiation  
i[0]=30;//initialization  
i[1]=40;
i[2]=50;  

 

Multidimensional Array can be defined and declared as below.

dataType[][] arrayVar; 
OR  
dataType [][]arrayVar;
OR 
dataType arrayVar[][]; 
OR
dataType []arrayVar[];   

Multidimensional Array can be inistantiated as below.

dataType[][] arrayVar = new dataType[][];

Example,

int[][] arrayVar=new int[2][2];//2 row and 2 column  

arrayVar[0][0] =1;

arrayVar[0][1] =2;

arrayVar[1][0] =3;

arrayVar[1][1] =4;

 


 

 

Example :

import java.util.*;

public class Main {
public static void main(String[] args) {
System.out.println("Learn Array!");
String[] fruits = {"Apple","Orange", "Banana", "Grapes"};

for(int i =0 ; i < fruits.length;i++){
System.out.println("Fruit Name : "+fruits[i]);
}
System.out.println("Learn Single Dimensional Array!");
int p[]=new int[3];//declaration and instantiation  
p[0]=60; //initialization  
p[1]=70;
p[2]=80;
for(int j=0;j<p.length;j++){
System.out.println("Number is : "+p[j]);
}

System.out.println("Learn Multidimensional Dimensional Array!");
//declaring and initializing 2D array
int arrval[][]={{11,22,33},{12,14,15},{54,44,35}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(" "+arrval[i][j]);
}
System.out.println();
}

}
}

Output :

Learn Array!
Fruit Name : Apple
Fruit Name : Orange
Fruit Name : Banana
Fruit Name : Grapes
Learn Single Dimensional Array!
Number is : 60
Number is : 70
Number is : 80
Learn Multidimensional Dimensional Array!
11 22 33
12 14 15
54 44 35

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

31124