Way2Java

Java One Dimensional Arrays

Java One Dimensional Arrays

Declaring an array is the same way of declaring a variable but with an extra square brackets. To inform the compiler, that the variable represents an array, suffix or prefix (Java allows) the variable name with a pair of square brackets. Array size should be given at the time of creation itself. Depending upon the size, continuous memory locations are allocated to the elements. Array identifier follows the same rules of Java identifiers.

Syntax of Java One Dimensional Arrays

Declaring, Assigning and Accessing the Array

The following program explains the basic syntax of creating an array in Java. Let us start with one-dimensional array. First an integer array by name, marks, is created which is filled with zero values by default. Later values are given (not from keyboard for which you must wait until I/O streams). The elements are retrieved using a for loop and printed.

Example on Java One Dimensional Arrays
public class ArrayTest1
{
  public static void main(String args[])
  {
    int marks[] = new int[5];
	
    System.out.println("Elements are " + marks.length);            
    System.out.println("Default value: " + marks[0]);            
			                               // Now assign values
    marks[0] = 50;
    marks[1] = 60;
    marks[2] = 70;
    marks[3] = 80;
    marks[4] = 90;

    System.out.println("Value of 1st element: " + marks[0]);            

    System.out.println("\nPrint the values in a single row");
    for(int i = 0; i < marks.length; i++)
    {
	System.out.print(marks[i] + "\t");  // to print in a single line, ln is removed
    }

    System.out.println("\n\nOther way of printing supported from JDK 1.5");
    for(int k : marks)
    {
        System.out.print(k + "\t");
    }    
  }
}  
Output screen of ArrayTest1.java

int marks[] = new int[5];

The above style of declaration is just the same as C/C++. The couple of square brackets indicate that marks is an array. In Java, arrays are predefined objects. The marks array can store 5 elements of integer values. Following is the schematic representation of the above array.

One D Array

Java supports another style of declaration

int[] marks = new int[5];

The array variable, marks, is prefixed (not suffixed) with square brackets.

Infact, the above statement can be modified into two statements – declaration and assignment.

int marks[];
marks = new int[5];

In the first statement, array by name marks is declared and in the second statement its size is assigned. The JVM allocates memory of 5 locations of size 4 bytes each; total 20 bytes.

System.out.println("Number of elements : " + marks.length);

The length variable of array gives the number elements present in the array. Arrays are treated internally as objects by JRE.

System.out.println("Default value: " + marks[0]);

marks[0] returns the value of the first element. It prints zero as no value is assigned with still. Unassigned values are filled with default values, but not with garbage values.

          for(int k : marks)
          {
              System.out.print(k + "\t");
          }    

The above for loop is a strange one supported from JDK 1.5 onwards and works with arrays and data structures only. It is a simplified version of general for loop.

Examples of Array Declarations

Following are a few examples of array declarations Java style.

        boolean  agreements[] = new boolean[10];
        float ratings[] = new float[10];
	char  promoted[] = new char[10];
	String names[] = new String[10];
        Demo d[] = new Demo[10]; 

10 elements of an array of type boolean, float, char, String (predefined class) and Demo (an user-defined class) are created.

Programming Tip: Do not confuse with length of arrays with length() of strings. One is a variable and the other is a method; both will give the size.

Array Initialization and Accessing

The previous, ArrayTest1 program is an example of array declaration and assignment. The same program can be modified to illustrate array initialization. Declaration and assignment, put together, is known as initialization. Initialization is more appropriate when the elements values are known in advance at compile-time itself.

Program on Java One Dimensional Arrays with initialization
public class ArrayTest2
{
  public static void main(String args[])
  {
    int marks[] = { 50, 60, 70, 80, 90 };
	
    System.out.println("Elements : " + marks.length);            
    System.out.println("Value of 1st element: " + marks[0]);            

    System.out.println("\nValues in a single row");
    for(int i = 0; i < marks.length; i++)
    {
      System.out.print(marks[i] + "\t");
    }
    System.out.println("\n\nOther way of printing supported from JDK 1.5");
    for(int m : marks)
    {
      System.out.print(m + "\t");
    }    
  }
}  
Output screen of ArrayTest2.java

int marks[] = { 50, 60, 70, 80, 90 };

The above statement creates an array object marks with 5 elements. As the number of elements placed are 5, the JVM creates a 5 elements marks array and allocates 5 memory locations to store the elements.

int marks[5] = { 50, 60, 70, 80, 90 };

The above statement does not compile as Java does not allow to give the size of the array in initialization; this is supported by C/C++.

Note: Do not give the size of the array in array initialization (it is compilation error), a practice generally adopted by C/C++ programmers where it is optional.