Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors

Array in Java

ARRAY:

An array is a data structure which holds similar types of elements.
An array is an object that stores a list of items. Each slot in an array holds individual elements. Each element should be a single datatype element, such that integer, strings, char etc.

DECLARING ARRAY ELEMENTS:

It indicates the name of the array followed by empty brackets.
Int arr[ ] ;

CREATING ARRAY OBJECTS:

After declaration of array, object is created and assigned to it.

There are two methods to create the array-

  1. Initialization
int initializeArray[ ] = {  1, 2, 3, 4, 5 };

  1. Use of new keyboard.
int newArray [ ] = new int [ 5 ];

The ‘new’ keyword creates an instance of the array. The number of elements array will hold must be specify inside ‘ [ ] ‘.


Program to show creation and definition of an array.

public class Array {
int arr[] = {1,2,3,4,5,6,7};
int i;
void display(){
        System.out.println(“Displayin array elements”);
           for(i=0;ii++){
                    System.out.println(arr[i]);
        }
}
public static void main(String args[]){
        Array d = new Array();
        d.display();
}
}

OUTPUT:
Displaying array elements
1
2
3
4
5
6
7


ACCESSING ARRAY ELEMENTS:

The array subscript expressions are used to change and use the values of the array. Knowledge of array subscripts are necessary for accessing an array element.

Array subscript always with ‘0’. Array subscript also known as index number.

For example,

int arr[] = {1,2,3,4,5,6,7};

In above example array subscript (index number) is as follows:

Array subscript
Array element
0
1
1
2
2
3
3
4
4
5
5
6
6
7

All subscripts must be within the body of the array. Such that in above example number of elements are 7, so max subscript will be 6 only.

The length of an array can be tested using ‘length’ instance variable.
For example,

int totalElement = arr.length;



MULTIDIMENSIONAL ARRAY:

Java doesn’t support multidimensional array. But array of array can be created.

For example,
public class arraOfArray{
int i=0;
int j=0;
int arr[][]=new int[3][3]; // array of array created
void set(){
           arr[0][0]=1;
           arr[0][1]=0;
           arr[0][2]=0;
           arr[1][0]=0;
           arr[1][1]=1;
           arr[1][2]=0;
           arr[2][0]=0;
           arr[2][1]=0;
           arr[2][2]=1;
}
void show(){
           for(i=0;i<3 i="" span="">++){
                       for(j=0;j<3 j="" span="">++){
                    System.out.print(arr[i][j] +“”);
                   }
        System.out.println(” “);
        }
}
public static void main(String args[])
{
arrayOfArray aoa = new arrayOfArray ();
aoa.set();
aoa.show();
}
}

OUTPUT:
100
010
001