forum

Home / DeveloperSection / Forums / Array in Java

Array in Java

Nitin Kushwaha 680 10-Jul-2019

Java Arrays:-

  • Arrays mean that to store the homogenous (similar data type) data value.
  • Arrays stored the element in a contiguous memory location.
  • Array in Java is index-based, the first element of the array is stored at the 0th index, and the second element is stored on the first index and so on.
  • In Java, we can also generate single dimensional or multidimensional array in java.
  • The main disadvantages of arrays are, we can store the only fixed size of data.

Types of Array in java:-

There are two types of array:-

  •  Single Dimensional Array.
  •  Multidimensional Array.

Declaration of arrays:-

data_type array_name[array_size];

Example:-

float mark [5];

Access the Elements of an Array

We can access an array element by referring to the index number. This statement accesses the value of the first element in cars:

Example

String [] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars[0]);
// Outputs Volvo.

Array Length:-

To find out how many elements an array by using the length property:

Example

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars.length);
// Outputs 4.

Example of Java Array

Single Dimension

class Studentarray
{  
public static void main(String args[])
{  
int a[]=new int[5] 
a[0]=450; 
a[1]=320;  
a[2]=75;  
a[3]=43;  
a[4]=502;  
for(int i=0;i<a.length;i++) 
System.out.println(a[i]);  
}
}
Output:-
450
320
75
43
502

Multidimensional Array

class Studentarray
{
public static void main(String args [])
{
int a[][]={{1,2,3},{4,5,6},{7,8,9}};
for(i=0; i<=2; i++)
{
for(j=0; j<=2; j++)
{
System.out.println(arr[i][j]+" ");  
 }  
 System.out.println();  
}  
}
}  
Output:-
1 2 3
4 5 6
7 8 9



Updated on 10-Jul-2019

Can you answer this question?


Answer

0 Answers

Liked By