Arrays

Creating Arrays

There are three steps to creating an array, declaring it, allocating it and initializing it.

Declaring Arrays

Like other variables in Java, an array must have a specific type like byte, int, String or double. Only variables of the appropriate type can be stored in an array. You cannot have an array that will store both ints and Strings, for instance.

Like all other variables in Java an array must be declared. When you declare an array variable you suffix the type with [] to indicate that this variable is an array. Here are some examples:

int[] k;
float[] yt;
String[] names;

In other words you declare an array like you’d declare any other variable except you append brackets to the end of the variable type.

Allocating Arrays

Declaring an array merely says what it is. It does not create the array. To actually create the array (or any other object) use the new operator. When we create an array we need to tell the compiler how many elements will be stored in it. Here’s how we’d create the variables declared above: new

k = new int[3];
yt = new float[7];
names = new String[50];

The numbers in the brackets specify the dimension of the array; i.e. how many slots it has to hold values. With the dimensions above k can hold three ints, yt can hold seven floats and names can hold fifty Strings. 

Initializing Arrays

Individual elements of the array are referenced by the array name and by an integer which represents their position in the array. The numbers we use to identify them are called subscripts or indexes into the array. Subscripts are consecutive integers beginning with 0. Thus the array k above has elements k[0], k[1], and k[2]. Since we started counting at zero there is no k[3], and trying to access it will generate an ArrayIndexOutOfBoundsException. subscripts indexes k k[0] k[1] k[2] k[3] ArrayIndexOutOfBoundsException

You can use array elements wherever you’d use a similarly typed variable that wasn’t part of an array.

Here’s how we’d store values in the arrays we’ve been working with:

k[0] = 2;
k[1] = 5;
k[2] = -2;
yt[6] = 7.5f;
names[4] = "Fred";

This step is called initializing the array or, more precisely, initializing the elements of the array. Sometimes the phrase “initializing the array” would be reserved for when we initialize all the elements of the array.

For even medium sized arrays, it’s unwieldy to specify each element individually. It is often helpful to use for loops to initialize the array. For instance here is a loop that fills an array with the squares of the numbers from 0 to 100.

float[] squares = new float[101];

for (int i=0; i <= 500; i++) {
  squares[i] = i*2;
}

Shortcuts

We can declare and allocate an array at the same time like this:

int[] k = new int[3];
float[] yt = new float[7];
String[] names = new String[50];

We can even declare, allocate, and initialize an array at the same time providing a list of the initial values inside brackets like so:

int[] k = {1, 2, 3};
float[] yt = {0.0f, 1.2f, 3.4f, -9.87f, 65.4f, 0.0f, 567.9f};

Two Dimensional Arrays

Declaring, Allocating and Initializing Two Dimensional Arrays

Two dimensional arrays are declared, allocated and initialized much like one dimensional arrays. However we have to specify two dimensions rather than one, and we typically use two nested for loops to fill the array. for

The array examples above are filled with the sum of their row and column indices. Here’s some code that would create and fill such an array:

class FillArray {

  public static void main (String args[]) {
  
    int[][] M;
    M = new int[4][5];
  
    for (int row=0; row < 4; row++) {
      for (int col=0; col < 5; col++) {
        M[row][col] = row+col;
      }
    }
    
  }
  
}

In two-dimensional arrays ArrayIndexOutOfBounds errors occur whenever you exceed the maximum column index or row index. Unlike two-dimensional C arrays, two-dimensional Java arrays are not just one-dimensional arrays indexed in a funny way.

Multidimensional Arrays

You don’t have to stop with two dimensional arrays. Java lets you have arrays of three, four or more dimensions. However chances are pretty good that if you need more than three dimensions in an array, you’re probably using the wrong data structure. Even three dimensional arrays are exceptionally rare outside of scientific and engineering applications.

The syntax for three dimensional arrays is a direct extension of that for two-dimensional arrays. Here’s a program that declares, allocates and initializes a three-dimensional array:

class Fill3DArray {

  public static void main (String args[]) {
  
    int[][][] M;
    M = new int[4][5][3];
  
    for (int row=0; row < 4; row++) {
      for (int col=0; col < 5; col++) {
        for (int ver=0; ver < 3; ver++) {
          M[row][col][ver] = row+col+ver;
        }
      }
    }
    
  }
  
}

Example 1 : declaring and initializing 1-dimensional arrays

An array groups elements of the same type. It makes it easy to manipulate the information contained in them.

class Arrays1{ 

public static void main(String args[]){

// this declares an array named x with the type “array of int” and of 
// size 10, meaning 10 elements, x[0], x[1] , … , x[9] ; the first term
// is x[0] and the last term x[9] NOT x[10].
int x[] = new int[10];

// print out the values of x[i] and they are all equal to 0.
for(int i=0; i<=9; i++)
System.out.println(“x[“+i+”] = “+x[i]);

// assign values to x[i] 
for(int i=0; i<=9; i++)
x[i] = i; // for example

// print the assigned values of x[i] : 1,2,……,9
for(int i=0; i<=9; i++)
System.out.println(“x[“+i+”] = “+x[i]);

// this declares an array named st the type “array of String”
// and initializes it
String st[]={“first”,”second”,”third”};

// print out st[i]
for(int i=0; i<=2; i++)
System.out.println(“st[“+i+”] = “+st[i]);

}
}

Example 2 : Find the sum of the numbers 2.5, 4.5, 8.9, 5.0 and 8.9

class Arrays2{ 

public static void main(String args[]){

// this declares an array named fl with the type “array of int” and
// initialize its elements

float fl[] = {2.5f, 4.5f, 8.9f, 5.0f, 8.9f};

// find the sum by adding all elements of the array fl
float sum = 0.0f;
for(int i=0; i<= 4; i++)
sum = sum + fl[i];

// displays the sum
System.out.println(“sum = “+sum);
}
}

Check that the sum displayed is 29.8.

Example 3 : declaring and initializing 2-dimensional arrays

class Arrays3{ 

public static void main(String args[]){

// this declares a 2-dimensional array named x[i][j] of size 4 (4 elements)
// its elements are x[0][0], x[0][1], x[1][0] and x[1][1].
// the first index i indicates the row and the second index indicates the
// column if you think of this array as a matrix.

int x[][] = new int[2][2];

// print out the values of x[i][j] and they are all equal to 0.0.
for(int i=0; i<=1; i++)
for(int j=0; j<=1; j++)
System.out.println(“x[“+i+”,”+j+”] = “+x[i][j]);

// assign values to x[i] 
for(int i=0; i<=1; i++)
for(int j=0; j<=1; j++)
x[i][j] = i+j; // for example

// print the assigned values to x[i][j] 
for(int i=0; i<=1; i++)
for(int j=0; j<=1; j++)
System.out.println(“x[“+i+”,”+j+”] = “+x[i][j]);

// this declares a 2-dimensional array of type String
// and initializes it
String st[][]={{“row 0 column 0″,”row 0 column 1”}, // first row 
{“row 1 column 0″,”row 1 column 1”}}; // second row 

// print out st[i]
for(int i=0; i<=1; i++)
for(int j=0; j<=1; j++)
System.out.println(“st[“+i+”,”+j+”] = “+st[i][j]);

}
}

 

// This is the Hello program in Java
class Hello {

    public static void main (String args[]) {
    
      /* Now let's say hello */
      System.out.print("Hello ");
      System.out.println(args[0]);
  }

}

If you run the program without giving it any command line arguments, then the  runtime system generates an exception something like,

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException at Hello.main(C:\javahtml\Hello.java:7)

Since we didn’t give Hello any command line arguments there wasn’t anything in args[0]. Therefore Java kicked back this not too friendly error message about an “ArrayIndexOutOfBoundsException.”

we can fix this problem by testing the length of the array before we try to access its first element (using array.length). This works well in this simple case, but this is far from the only such potential problem. 

What is an Exception ?

Let us see what happens when an exception occurs and is not handled properly

When you compile and run the following program

public class Test{ 
    public static void main(String str[]){
    int y = 0;
    int x = 1;
    // a division by 0 occurs here.
    int z = x/y;
    System.out.println(“after didvision”);
  }
}

The execution of the Test stops and this is caused by the division by zero at – x/y – an exception has been thrown but has not been handled properly.

How to handle an Exception ?

To handle an Exception, enclose the code that is likely to throw an exception in a try block and follow it immediately by a catch clause as follows

public class Test{ 
    public static void main(String str[]){
        int y = 0;
        int x = 1;
        // try block to “SEE” if an exception occurs
        try{
          int z = x/y;
          System.out.println(“after didvision”);
           // catch clause below handles the 
          // ArithmeticException generated by 
          // the division by zero.
       } catch (ArithmeticException ae) 
       {System.out.println(” attempt to divide by 0″);}
       System.out.println(” after catch “);
   } 
}

The output of the above program is as follows

attempt to divide by 0 
after catch

the statement – System.out.println(“after didvision”) – is NOT executed, once an exception is thrown, the program control moves out of the try block into the catch block.

The goal of exception handling is to be able to define the regular flow of the program in part of the code without worrying about all the special cases. Then, in a separate block of code, you cover the exceptional cases. This produces more legible code since you don’t need to interrupt the flow of the algorithm to check and respond to every possible strange condition. The runtime environment is responsible for moving from the regular program flow to the exception handlers when an exceptional condition arises.

In practice what you do is write blocks of code that may generate exceptions inside try-catch blocks. You try the statements that generate the exceptions. Within your try block you are free to act as if nothing has or can go wrong. Then, within one or more catch blocks, you write the program logic that deals with all the special cases.

To start a section of code which might fail or not follow through you start a try clause:

try
{
  // Section of code which might fail
}

The try statement is needed in case of an exception. If the read fails in some way it will throw an exception of type java.io.IOException. That exception must be caught in this method, or the method can declare that it will continue throwing that message. Exception handling is a very powerful tool, you can use it to catch and throw exceptions and thus group all your error handling code very well and make it much more readable in larger more complex applications. After the try section there must exist one or more catch statements to catch some or all of the exceptions that can happen within the try block. Exceptions that are not caught will be passed up to the next level, such as the function that called the one which threw the exception, and so on. .

try
{
  // Section of code which might fail
}
catch (Exception1ThatCanHappen E)
{
  // things to do if this exception was thrown..
}
catch (Exception2ThatCanHappen E)
{
  // things to do if this exception was thrown..
}

Here’s an example of exception handling in Java using the Hello World program above:

Source Code

// This is the Hello program in Java
class ExceptionalHello {

    public static void main (String args[]) {
    
      /* Now let's say hello */
      try {
        System.out.println("Hello " + args[0]);
      }
      catch (Exception e) {
        System.out.println("Hello whoever you are");      
      }
  }

}

You may or may not print an error message. If you write an exception handler and you don’t expect it to be called, then by all means put a

System.out.println("Error: " + e);

This has the folowing advantages over handling your errors internally:

  • You can react to an error in custom defined way. A read error does not mean that the program should crash.
  • You can write code with no worry about failure which will be handled by the users of your class.
  • You can group your error handling code much better.
  • You can make your application more transactional focused with nested try catch blocks:

A simple Java code which demonstrates the exception handling in Java

Refer to the java API document to see all exception types that can be handled in Java.

Source Code

public class excep2
{
	public static void main(String args[])
	{
		int i =0 ;
		//Declare an array of strings
		String Box [] = {"Book", "Pen", "Pencil"};
		while(i<4)
		{
			try
			{
				System.out.println(Box[i]);
				
			}
			catch(ArrayIndexOutOfBoundsException e)
			{
				System.out.println("Subscript Problem " + e);
			i++;
			}
			finally
			{
				System.out.println("This is always printed.");
			}
			i++;
		}
	}
}

Advertisements