In previous post, we learned more about Array Declarations. In this blog post, I will discuss Array Creation.
Array in java is an object hence we can create by using new keyword.
int[] arr = new int[5];
For every array type corresponding classes are available but these classes are part of java language and not available to the programmer level.
Rule 1: At the time of array creation compulsory we should specify the size otherwise we will get compile time error.
Example:
int[] a=new int[3];
int[] a=new int[]; //C.E:array dimension missing
Rule 2: It is legal to have an array with size zero in java.
Example:
int[] a=new int[0];
System.out.println(a.length); //0
Rule 3: If we are taking array size with -ve int value then we will get runtime exception saying NegativeArraySizeException.
Example:
int[] a=new int[-3];//R.E:NegativeArraySizeException
Rule 4: The allowed data types to specify array size are byte, short, char, int. By mistake if we are using any other type we will get compile time error.
Examples:
int[] a=new int['a'];//(valid)
byte b=10;
int[] a=new int[b];//(valid)
short s=20;
int[] a=new int[s];//(valid)
int[] a=new int[10l];//C.E:possible loss of precision//(invalid)
int[] a=new int[10.5];//C.E:possible loss of precision//(invalid)
Rule 5: The maximum allowed array size in java is maximum value of int size [2147483647].
Examples:
int[] a1=new int[2147483647];(valid)
int[] a2=new int[2147483648]; //C.E:integer number too large: 2147483648(invalid)
Array in java is an object hence we can create by using new keyword.
int[] arr = new int[5];
For every array type corresponding classes are available but these classes are part of java language and not available to the programmer level.
Rule 1: At the time of array creation compulsory we should specify the size otherwise we will get compile time error.
Example:
int[] a=new int[3];
int[] a=new int[]; //C.E:array dimension missing
Rule 2: It is legal to have an array with size zero in java.
Example:
int[] a=new int[0];
System.out.println(a.length); //0
Rule 3: If we are taking array size with -ve int value then we will get runtime exception saying NegativeArraySizeException.
Example:
int[] a=new int[-3];//R.E:NegativeArraySizeException
Rule 4: The allowed data types to specify array size are byte, short, char, int. By mistake if we are using any other type we will get compile time error.
Examples:
int[] a=new int['a'];//(valid)
byte b=10;
int[] a=new int[b];//(valid)
short s=20;
int[] a=new int[s];//(valid)
int[] a=new int[10l];//C.E:possible loss of precision//(invalid)
int[] a=new int[10.5];//C.E:possible loss of precision//(invalid)
Rule 5: The maximum allowed array size in java is maximum value of int size [2147483647].
Examples:
int[] a1=new int[2147483647];(valid)
int[] a2=new int[2147483648]; //C.E:integer number too large: 2147483648(invalid)
good article
ReplyDeletekissanime alternatives