An array is a data structure that represents an index collection of
fixed no of homogeneous data
elements.
1.Declaring Arrays
you can type the [] before or after the name, and adding a space is
optional. This means that all four of these statements do the exact same thing:
int[] numAnimals;
int [] numAnimals2;
int numAnimals3[];
int numAnimals4 [];
The
following are the valid declarations for multidimensional arrays.
int[][] a;
int a[][];
int [][]a;
int[] a[];
int[] []a;
we can
specify the dimension before name of variable also, but this facility is
available only for the first variable.
int[] a[],b[];
int[] []a,[]b; //Wrong
2.Construction of Arrays
Single Dimension : Arrays are internally implemented
as object hence by using new operator we can construct an array.
Compulsory
at the time of construction we should specify the size otherwise compile time
error.
int[] a = new int[10]; _/
int[] a = new int[]; X C.E
It is legal
to have an error with size 0 there is no C.E or R.E
int[] a = new int[0];
If we are
specifying array size with some –ve integer, we will get R.E:NegativeArraySizeException.
int[] a = new int[-10];
The only allowed Data type to allow the size are byte,
short, char, int. if we are using any other datatype we will get a C.E.
int[] a = new int[10];
int[] a1 = new int[10l];
int[] a = new int[10L]; --> C.E possible loss of precision
found: long required: int
Multi
Dimension: In java multidimensional arrays are implemented as single
dimension arrays. This approach improves performance with respect to memory.
int[][] a = new int[3][2];
int[][] a = new int[4][]
a[0] = new int[1];
a[1] = new int[2];
a[2] = new int[4];
a[3] = new int[3];
declare an array for
the following diagram
a[][][] = new int[2][][];
a[0] = new int[3];
a[0][1] = new int[1];
a[0][2] = new int[2];
a[0][3] = new int[3];
a[1] = new int[2][2];
3.Initialization of arrays
Once we
created an array all it’s elements initialized with default values.
int[] a = new int[3];
System.out.println(a[0]); O/P: 0
System.out.println(a); O/P: [I@10b62c9
int[][] a = new int[3][2];
System.out.println(a); --> [I@10b62c9
System.out.println(a[0]); --> [[I@82ba41
System.out.println(a[0][0]); --> 0
int[][] a = new int[3][];
System.out.println(a); --> [I@10b62c9
System.out.println(a[0]); --> null
System.out.println(a[0][0]); --> NullPointerException
4.Declaration and Initialization Array in a single line
int[] a = {10,20,30};
String[] s = {“Chiru”,”Allu”,”Ram”,”Akil”}
5.length Vs length();
length: It
is the final variable applicable for array objects. It represents the size of
the array.
int [] a = new int[5];
System.out.println(a.length()); --> C.E
System.out.println(a.length); --> 6
length():It
is the final method applicable only for String Objects. Ex:
String s = "raju";
System.out.println(s.length); --> C.E
System.out.println(s.length()); --> 4




0 comments:
Post a Comment