To specify array size the allowed data types are byte, short, int, char, if we are using any other type we will get compile-time error.
Example:-
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.
int[] a=new int[10.5] ; // C.E.
Array initialization:-
Whenever we are creating an array automatically every element is initialized with default values.
Example:-
int[] a=new int[3];
System.out.println(a); // [[email protected]…. System.out.println(a[0]); // 0 Note-: whenever we are trying to print any object reference internally toString() will be call which is implemented as follows- [email protected]_String_of_hashcode
The foreach Loops:
JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop, which enables you to traverse the complete array sequentially without using an index variable.
ArrayDemo.java
class ArrayDemo
{
public static void main(String[] args)
{
// declares an intArray and allocates memory for 2 int values
int[] intArray = new int[2];
int[] intArray = new int[2];
int i=0;
for (int element : intArray)
{
System.out.println("Element at Index "+ i + " : "+element);
++i;
}
}
}
Output Element at Index 0 : 0 Element at Index 1 : 0
Java Array (double array default values)
ArrayDemo.java
class ArrayDemo
{
public static void main(String[] args)
{
/*
* Declares an array of doubles and allocates memory for 5 doubles.
*/
double[] doubleArray = new double[5];
int i = 0;
for (double element : doubleArray)
{
System.out.println("Element at Index " + i + " : " + element);
++i;
}
}
}
Output :- Element at Index 0 : 0.0 Element at Index 1 : 0.0 Element at Index 2 : 0.0 Element at Index 3 : 0.0 Element at Index 4 : 0.0
Java Array (String array default values)
ArrayDemo.java
class ArrayDemo
{
public static void main(String[] args)
{
/*
* Declares an array of strings and allocates memory for 2 strings.
*/
String[] stringArray = new String[2];
int i = 0;
for (String element : stringArray)
{
System.out.println("Element at Index " + i + " : " + element);
++i;
}
}
}
Output :- Element at Index 0 : null Element at Index 1 : null
Note-
Once we created an array every element by default initialized with default values. If we are not satisfy with those default values then we can override, those with our Customized Values.