Professional Documents
Culture Documents
1.1 Array
1.1 Array
1.1 Array
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.
0 1 2 3 4 5 6 7 8 index
Length is 9
Root structure:-
java.lang.Object
|
+--java.lang.reflect.Array
48 | P a g e
Ex:-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]);
}
}
Ex:-printing the array elements by using for Ex:-printing the array elements by using for-
loop each loop(1.5 version)
class Test class Test
{ {
public static void main(String[] args) public static void main(String[] args)
{ {
int[] a={10,20,30,40}; int[] a={10,20,30,40};
for (int i=0;i<a.length;i++) for (int a1:a)
{ {
System.out.println(a[i]); System.out.println(a1);
} }
} }
} }
Ex:-
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<a.length;i++)
{
System.out.println("enter "+i+" value");
a[i]=s.nextInt();
}
for (int a1:a)
{
System.out.println(a1);
}
}
}
49 | P a g e
Ex:-
class Test
{
public static void main(String[] args)
{
int[] a=new int[100];
System.out.println(a.length);
System.out.println(a[99]);
boolean[] b=new boolean[100];
System.out.println(b[99]);
char[] ch=new char[50];
System.out.println(ch[44]);
byte[] bb=new byte[100];
System.out.println(bb[100]);//ArrayIndexOutOfBoundsException
}
}
Ex:-
class Test
{
public static void main(String[] args)
{
int[] a=new int[4];// allocates memory for 4 elements
a[0]=10;
a[1]=100;
a[2]=1000;
a[3]=10000;
System.out.println(a.length);
for (int i=0;i<a.length;i++ )
{
System.out.println(a[i]);
}
}
}
To get the class name of the array:-
getClass() method is used to get the class.
getName() method is used to print the name of the class.
class Test
{
public static void main(String[] args)
{
int[] a={10,20,30};
System.out.println(a.getClass().getName());
}
}
50 | P a g e
declaration of two dimensional array:-
int[][] a;
int [][]a;
int a[][];
int []a[];
Ex:-
class Test
{
public static void main(String[] args)
{
int[][] a={{10,20,30},{40,50,60}};
System.out.println(a[0][0]);//10
System.out.println(a[1][0]);//40
System.out.println(a[1][1]);//50
}
} 0 1
10 20 30 10 20 30
0 1 2 0 1 2
a[0][0]------10
a[0][1]------20
a[0][2]-----30
a[1][0]-----40
a[1][1]-----50
a[1][2]-----60
51 | P a g e