Java One Dimensional Arrays


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");
    }    
  }
}  
Java One Dimensional Arrays
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.

3 thoughts on “Java One Dimensional Arrays”

  1. Sir for the above program i write this statement “System.out.println(“fifth element value is ” + pavan[5]);” it is throwing the exception as Array Index out of bound exception but i didn’t write any try catch here who trowed this exception?

Leave a Comment

Your email address will not be published.