Tutoriallearn.com

Easy Learning


Home

Search Tutoriallearn.com :



Java Array

  • An array is a collection of similar type of data.
  • For example, suppose you want to store 10 integer data and that can be accessed by one variable. Then you can create a variable using array concept that consists of 10 integer data.
  • Here is important to understand that an array can hole only similar type of data/items.
  • If you want to create an array variable that holds float data then you have to create separate array variable. You can not store integer data in float array variable.

Note:
1. There is a difference in creating an array in Java than C/C++ language.
2. Difference is:
i. Memory allocation is needed after declaring an array in Java. Java new operator is used in allocating the memory.
ii. However, memory allocation may be done by initializing the array at the time of decelerating an array. In this case, no need of new operator. We shall discuss this case later.

  • When an array is created, each element of the array is accessed using an index number.
  • Suppose an array roomno is created and it consists of 3 elements. Then the first element is accessed using array name with index no. For example, roomno [o].
  • Index no is enclosed with brackets.
  • In an array, index number is start from 0.
  • Like, first element is at 0 index, second element at 1 index, and third element is at index 2 and so on...

Now see the following example.

Example 1: Creating an array of integers

public class arraydemo1 {
	public static void main (String args[])
	{
		int roomno []; // No memory allocation
		int i;
		roomno = new int[3]; // memory is allocated to array
		
		// Following, giving values to array
		roomno[0] = 20;
		roomno[1] = 30;
		roomno[2] = 35;
		// Following, displaying value of array elements
		for (i=0;i<3;i++)
		{
			System.out.println("Room No. is "+ roomno[i]);
		}
	}
}

Output

Room No. is 20
Room No. is 30
Room No. is 35

Explanation of the program

  • This program declares an array named roomno.
  • After that, memory of 3 integers is allocated to the array roomno.
  • Here again remind that, in java, memory must be allocated after declaration of an array. It is something different from C/C++ language. Otherwise, array will not be accessible.
  • Individual element of the array is assigned with value.
  • A 'for' loop is used to display all elements of the array.
  • Here, see in the program that elements of array roomno is accessed using index number.

Example 2: Storing User Inputs to Array and Displaying Array Values
import java.util.Scanner; 
public class arraydemo2 {
	public static void main (String args[])
	{
		int roomno []; // No memory allocation
		int i;
		roomno = new int[3]; // memory is allocated to array
		
		Scanner sc = new Scanner(System.in); 
		// Taking values from user
		for(i=0;i<3;i++)
		{
			System.out.println("Enter your number: ");
			int num = sc.nextInt();
			roomno[i] = num;	
		}
		
		// Following, displaying value of array elements
		for (i=0;i<3;i++)
		{
			System.out.println("Room No. is "+ roomno[i]);
		}
	}
}

Output

Enter your number: 22
Enter your number: 34
Enter your number: 56
Room No. is 22
Room No. is 34
Room No. is 56

Explanation of the program

  • Java Scanner class is used to get inputs from the user.
  • nextInt() method of Scanner class is used to get integer value from the user.
  • One 'for' loop is used to get inputs for all elements of the array.
  • Second 'for' loop is used to display values of the array.

One Dimensional Array

  • One dimensional array consists of sequence of elements. Each element is accessed by one index. As it is shown in above two examples.
  • In both examples, an array of integers are created.

Two Dimensional Array

  • Two dimensional array consists of number of rows and columns. It is similar to matrix. It is declared in the following way:
  • int avar [][];
  • First bracket after array name 'avar' is for number of rows and second bracket is for number of columns.
  • An array can be defined in more than two dimensions in similar fashion. However, multidimensional arrays are basically arrays of arrays.

Example 3: Demonstrating two dimensional array with float datatype

import java.util.Scanner; 
public class arraydemo3 {
	public static void main (String args[])
	{
		float avar [][]; // No memory allocation
		int i,j;
		float num;
		avar = new float [2][3]; // memory is allocated to array
		Scanner sc = new Scanner(System.in); 
		// Taking values from user
		for(i=0;i<2;i++)
		{
			for (j=0;j<3;j++)
			{
				System.out.println("Enter your number: ");
				num = sc.nextFloat();
				avar[i][j] = num;	
			}
			
		}
		// Displaying value of array elements
		System.out.println("values of avar ");
		for (i=0;i<2;i++)
		{
		  for(j=0;j<3;j++)	
		  {
			System.out.print(" "+ avar[i][j]);
		  }
		  System.out.println("");
		}
	}
}

Output of the program

Enter your number:10.5
Enter your number:11.3 
Enter your number:23.0 
Enter your number:45.5 
Enter your number:22.7 
Enter your number:6.3 
values of avar 
 10.5 11.3 23.0
 45.5 22.7 6.3

Explanation of the program

  • A two dimensional array named avar with two rows and three columns has been created.
  • Array is of float data type.
  • Array is accessed using two indices (or subscripts). First index shows row number and second index shows column number.
  • Two nested 'for' loops are used to access the two dimensional array.

Array Initialization

  • Array can be initialized using following way:
  • For example: create an array of month numbers.
  • int monthnos [] = {1,2,3,4,5,6,7,8,9,10,11,12}
  • Here, an array named monthnos is declared and initialized with 12 month numbers.

Example 4: Initialization of Array

public class arraydemo4 {
	public static void main (String args[])
	{
		int monthnos [] = {1,2,3,4,5,6,7,8,9,10,11,12}; // memory is allocated according to number of elements
		int i;
		
		// Displaying value of array elements
		for (i=0;i<12;i++)
		{
			System.out.println("Month number is "+ monthnos[i]);
		}
	}
}

Output

Month number is 1
Month number is 2
Month number is 3
Month number is 4
Month number is 5
Month number is 6
Month number is 7
Month number is 8
Month number is 9
Month number is 10
Month number is 11
Month number is 12

Initialization of multidimensional array

  • A multidimensional array can be initialized by enclosing each dimension values within its own curly braces.
  • An expression can be given in the initialization.
  • Following is example of two dimensional array (3 * 3):
     
    public class arraydemo4m {
    	public static void main (String args[])
    	{
    		// Multidimensional initialization
    		int avar[][] = {
    				{2, 3, 2*3},
    				{10, 23, 7},
    				{34, 23, 18},
    			};
    		int i,j;
    		
    		// Displaying value of array elements
    		for (i=0;i<3;i++)
    		{
    			for (j=0;j<3;j++){
    			System.out.print(avar[i][j]+" ");
    			}
    			System.out.println();
    		}
    	}
    }
    
  • Output
    2 3 6 
    10 23 7 
    34 23 18 
    
  • See in the first row and third column, an expression (i.e. multiplication of two values) is used for initialization.

Second form of array declaration

  • Java provides an alternative way of declaring the array.
  • In this form, square brackets are used after type of the array. As shown in the following example:
  • int [] a = new int [3]; // one dimensional example
  • float [][] = new float [3][4]; // two dimensional example
  • This second form of declaration provides easiness when creating more array variables. Such as:
  • int [] a1, a2, a3; // Here three array variables are created.
  • It is similar to writing the following declaration for three variables:
  • int a1[], a2[], a3[];

Example 5: Demonstrating alternate way of declaring array

import java.util.Scanner; 
public class arraydemo5 {
	public static void main (String args[])
	{
		char [] avar; // No memory allocation
		int i; char symb;
		avar = new char [3]; // memory is allocated to array
		
		Scanner sc = new Scanner(System.in); 
		// Taking values from user
		for(i=0;i<3;i++)
		{
			System.out.println("Enter your character: ");
			 symb = sc.next().charAt(0);
			avar[i] = symb;	
		}
		
		// Displaying value of array elements
		for (i=0;i<3;i++)
		{
			System.out.println("Your entered character is "+ avar[i]);
		}
	}
}

Output

Enter your character: a
Enter your character: b
Enter your character: c
Your entered character is a
Your entered character is b
Your entered character is c

Different column sizes in a multidimensional array

  • During memory allocation to multidimensional array, you can specify one dimension (left most dimension) only. Other dimensions can be allocated separately.
  • This way of memory allocation gives the option to have a multidimensional array with variable other dimension sizes.
  • For example, in two dimensional array, it is possible to have 3 rows. And first row with 2 columns, second row with 3 columns and third row with 4 columns.
  • See the following code:
  • int avar[][] = new int [3][]; // 3 rows, and no value in second dimension
  • avar[0]= new int [2]; // 2 columns are allocated to first row
  • avar[1]= new int [3]; // 3 columns are allocated to second row
  • avar[2]= new int [4]; // 4 columns are allocated to third row

Example 6: Variable columns in two dimensional array

import java.util.Scanner; 
public class arraydemo6 {
	public static void main (String args[])
	{
		int avar[][] = new int [3][];  // 3 rows, and no value in second dimension
		avar[0]= new int [2];  // 2 columns are allocated to first row
		avar[1]= new int [3]; // 3 columns are allocated to second row
		avar[2]= new int [4]; // 4 columns are allocated to third row 
		int i, num;
		
		Scanner sc = new Scanner(System.in); 
		// Taking values from user
		// For first row
		for(i=0;i<2;i++)
		{
			System.out.println("Enter value of column of first row: ");
			 num = sc.nextInt();
			avar[0][i] = num;	
		}
		// For second row
		for(i=0;i<3;i++)
		{
			System.out.println("Enter value of column of second row: ");
			 num = sc.nextInt();
			avar[1][i] = num;	
		}
		// For third row
		for(i=0;i<4;i++)
		{
			System.out.println("Enter value of column of third row: ");
			 num = sc.nextInt();
			avar[2][i] = num;	
		}
		// Displaying value of array elements
		// First row
		for (i=0;i<2;i++)
		{
			System.out.println("Values of first row "+ avar[0][i]);
		}
		// Second row
		for (i=0;i<3;i++)
		{
			System.out.println("Values of second row "+ avar[1][i]);
		}
		// Third row
		for (i=0;i<4;i++)
		{
			System.out.println("Values of third row "+ avar[2][i]);
		}
	}
}

Output

Enter value of column of first row:
20
Enter value of column of first row:
12
Enter value of column of second row:
23
Enter value of column of second row:
45
Enter value of column of second row:
67
Enter value of column of third row:
27
Enter value of column of third row:
78
Enter value of column of third row:
89
Enter value of column of third row:
76
Values of first row 20
Values of first row 12
Values of second row 23
Values of second row 45
Values of second row 67
Values of third row 27
Values of third row 78
Values of third row 89
Values of third row 76


© Copyright 2016-2025 by tutoriallearn.com. All Rights Reserved.