Core Java
Different ways of declaration and initialization of arrays in Java
The below code shows the different ways one can declare and initialize an Array in Java:
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | import java.util.Arrays; public class ArraysDemo { public static void main(String[] args) { int [] a1 = new int []{ 1 , 2 , 3 , 4 }; print(a1); //[1,2,3,4] int [] a2 = new int [ 4 ]; a2[ 0 ] = 1 ;a2[ 2 ]= 10 ; print(a2); //[1,0,10,0] int [] a3 = { 1 , 4 , 5 , 67 , 8 }; print(a3); //[1,4,5,67,8] print(getArray()); //[3,32,6,7,5] } public static int [] getArray(){ //return {1,2,3,4}; - Invalid return new int []{ 3 , 32 , 6 , 7 , 5 }; } public static void print( int [] a){ System.out.println(Arrays.toString(a)); } } |
- Line 5: Declaration of array along with initialization of its values. Here it is not required to pass the size of the array.
- Line 8-9: Declaration of array by providing its size. The array will be initialized with 0 and we can then assign the value using the index.
- Line 12: Declaration with initialization
- Line 20: One of permissible way to return an array from the method
Published on Java Code Geeks with permission by Mohamed Sanaulla, partner at our JCG program. See the original article here: Different ways of declaration and initialization of arrays in Java Opinions expressed by Java Code Geeks contributors are their own. |