Google News
logo
Java Arrays
Arrays
1) Arrays are used to store the multiple numbers of elements of single type.
2) The length of the array is established at the time of array creation. After creation the length is fixed.
3) The items presented in the array are classed elements. Those elements can be accessed by index values. The index is begins from (0).
Advantages of array:-
1) Length of the code will be decreased
2) We can access the element present in the any location.
3) Readability of the code will be increased.
Java Images
single dimensional array declaration
A one dimensional array or a single dimensional array represents either a row or a column of the elements.

syntax:

int[ ] a;
int [ ]a;
int a[ ]; 

declaration and  instantiation and initialization :

int a[ ]={10,20,30,40};
int[ ] a=new int[100];
a[0]=10;
a[1]=20;
a[2]=30;
a[4]=40;
printing the array elements
class Test 
{ 
public static void main(String[] args) 
{ 
int[] a={10,20,30,40}; 
System.out.println(a[0]); 
System.out.println(a[1]); 
System.out.println(a[2]); 
System.out.println(a[3]); 
} 
}
Output :
Output:10,,20,,30..40
printing the array elements by using for loop
class Test 
{ 
public static void main(String[] args) 
{ 
int[] a={10,20,30,40}; 
for (int i=0;i{ 
System.out.println(a[i]); 
} 
} 
}
Output :
output;10,,20,,30,,40
printing the array elements by using for-each loop(1.5 version)
class Test 
{ 
public static void main(String[] args) 
{ 
int[] a={10,20,30,40}; 
for (int a1:a) 
{ 
System.out.println(a1); 
} 
} 
}
Output :
output:10,,20,,30,,40
read n number of Values
import java.util.*; 
class Test 
{ public static void main(String[] args) 
{ 
int[] a=new int[5]; 
Scanner s=new Scanner(System.in); 
System.out.println("enter values"); 
for (int i=0;i{ 
System.out.println("enter "+(i+1)+" value"); 
a[i]=s.nextInt(); 
} 
for (int a1:a) 
{ 
System.out.println(a1); 
} 
} 
}
Output :
output: enter values enter 1 value 10 enter 2 value 20 enter 3 value 30 enter 4 value 60 enter 5 value 50 10 20 30 60 50