Arrays in JAVA


arrays IN java

An array is a container object that holds fixed number of values of single type. An array is used to store collection of data of same type. A link to an array is established after an array is created after creation the link is fixed.

Syntax:

int X [];    or  int []X;  both mean the same

int []numbers =new int[10];      // declare numbers as an array that can store 10 elements, and then assign values of same types at index values 0,1,2,3…. as:

int number[0]=5; int number[1]= 10; int number[2]=15;…and so on

position  or index for array are from 0,1,2… up till 9, making size of array as 10. So we cannot write the value at index 10 because that is 11th position and will out of range for this array.

Declaring Multiple arrays

If we declare more than one array as:

int [] arr1, arr2, arr3;     // here all variables arr1, arr2, arr3 are declared as arrays

and

int numbers1[], numbers2, numbers3 ;   // But in his case only numbers1 is array and rest all are not.

If we wish declare all three as arrays then we will have to write them as:

int numbers1[], numbers2[], numbers3[] ;

Throughout our explanation we shall use the following syntax for creation of array.

int []array1 = new int [10];

Another shortcut method of assigning values to all elements is:

int [] array1 = {5,10,15,20,25,30,35,40};

Example-1 Use of array:

To print all values of an array we can use loop with index values starting from the begining. See the example below:

package com.example;
public class arrays
{
public static void main(String[] args)
{

int [] Numbers={5,10,15,20,30,35, 40, 45};
for(int i=0; i<Numbers.length;i ++)

{

System.out.println(Numbers[i]);

}

}

}

The loop runs from index i= 0 to index <array1.length which is 9 and we get the correct print of all elements.

Enhanced for Loop for printing array values

Another enhanced for loop to get array values is presented below. We declare a variable as initial value inside the array, and then give second argment as array name. When the loop runs, it assigns array1 elements to var1. This way we can print all values, notice no index is used here with array name.

package com.example;
public class arrays
{

public static void main(String[] args)
{

int [] array1={5,10,15,20,30,35, 40, 45};
System.out.println(“Enhanced loop to get array value”);
for (int val : array1)

{

System.out.println(val);

}

}

}

error: Content is protected !!