Posts

Showing posts from May, 2020

Different ways to initialize arrays in java

Different ways to initialize array's in java Array Initialization in Java Different ways to initialize array's in java Java Arrays can be populated in a number of ways following summarizes different options. One item at a time using a loop Following example we are declaring rolNumms array of size 10 and adding one item at a time using a for a loop. //Using For loops int rollNums[] = new int[10]; for (int i=0; i At the Time of Declaration We can set the content of the array while declaring the array it self. Both the syntax will result in initializing the array with 10 items. Note that when we provide the initializer while declaring the size of the array cannot be specified. int rollNums2[] = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9 ,10}; int rollNums3[] = {1, 2, 3, 4, 5, 6, 7, 8, 9 ,10}; Arrays.setAll() and Generator function We can set the content of the array using the Arrays.setAll() method as well. int rollNums4 [] = new int [10]; Arrays.setAll(rollNums4, p -> p