Showing posts with label ArrayIndexOutOfBoundsException. Show all posts
Showing posts with label ArrayIndexOutOfBoundsException. Show all posts

Saturday, 22 February 2014

try block

Syntax
try {
   //code
}
catch and finally blocks . . .
The first step to handle the exception is enclose the error prone code in the try block. A try blcok must have at least one catch or finally block. Other wise compiler throws an error.

Example
class ExceptionEx{
 public static void main(String args[]){
  try{
   System.out.println(" I don't have any catch or finally blocks associated with me");
  }
 }
}
   
Above program, doesn't have any catch or finally block associated with it. So when you tries to compile the program, compiler throws the below error.

ExceptionEx.java:4: error: 'try' without 'catch', 'finally' or resource declarations
try{
^
1 error

try nested inside a try
class ExceptionEx{
 public static void main(String args[]){
  try{
   System.out.println("I am enclosing another try inside me");
   try{
    System.out.println(10/0);
   }
   catch(ArrayIndexOutOfBoundsException e){
    System.out.println("inside catch block " + e);
   }
  }

  catch(Exception e){
   System.out.println("Outside catch block " + e);
  }
 }
}
 
Output
I am enclosing another try inside me
Outside catch block java.lang.ArithmeticException: / by zero

As you observe the program, try has try nested in it. “10/0” is called in inside try block, which has catch block associated with it. But the catch block for the inner try block handles ArrayIndexOutOfBoundsException only. So while executing, the catch correspond to the outer block is executed.


Handling Exceptions                                                 catch block                                                 Home

Friday, 7 February 2014

One Dimensional Array

Syntax:
    dataType arrayName[] = new dataType[size];
          (OR)
    dataType arrayName[];

    arrayName = new dataType[size];

Here the dataType can be any primitive type or reference type.
Size is the How many number of elements are stored into the array.

Example
    char arr[] = new char[9];
        (OR)
    char arr[];

    arr = new char[9];

Above two declarations are syntactically correct and create an array named “arr” of type char and has the capacity to store 9 characters.

How to define an Array
You can assign elements to the array using indexes or at the time of creation. Array index starts from zero. If the array of size 'n', then the maximum index is 'n-1', since the index starts from 0.

Assigning values using indexes
    char arr[] = new char[9];

    arr[0] = 'H';
    arr[1] = 'E';
    arr[2] = 'L';
    arr[3] = 'L';
    arr[4] = 'O';
    arr[5] = 'J';
    arr[6]='A';
    arr[7] = 'V';
    arr[8] = 'A';

Assigning values At the time of creation
    char arr[] = {'H', 'E', 'L', 'L', 'O', 'J', 'A', 'V', 'A'};

Elements in the array “arr” store like following




Example 1
class ArrayEx{
 public static void main(String args[]){
  char arr[] = new char[9];
  
  arr[0] = 'H';
  arr[1] = 'E';
  arr[2] = 'L';
  arr[3] = 'L';
  arr[4] = 'O';
  arr[5] = 'J';
  arr[6] = 'A';
  arr[7] = 'V';
  arr[8] = 'A';
  System.out.println(arr);
 }
}
   
Output
HELLOJAVA

Example 2
class ArrayEx{
 public static void main(String args[]){ 
  char arr[] = {'H', 'E', 'L', 'L', 'O', 'J', 'A', 'V', 'A'};
  System.out.println(arr); 
 }
}
 
Output
HELLOJAVA

As you see, when you pass the array name as an argument to println method, it prints the entire array data to the console.

How to declare number of Arrays at a time
    Syntax
    dataType[] arr1, arr2;

    Example
class ArrayEx{
 public static void main(String args[]){
  char[] arr1, arr2;
  arr1 = new char[6];
  arr2 = new char[4];
  
  arr1[0] = 'H';
  arr1[1] = 'E';
  arr1[2] = 'L';
  arr1[3] = 'L';
  arr1[4] = 'O';
  arr1[5] = ' ';
  arr2[0] = 'J';
  arr2[1] = 'A';
  arr2[2] = 'V';
  arr2[3] = 'A';
  
  System.out.print(arr1);
  System.out.println(arr2);
 }
}
   
Output
HELLO JAVA

How to find the length of Array
java provides a property called “length” for an array to calculate the length of an array
   syntax
   arrayName.length;
      returns the size of the array.

   Example
class ArrayEx{
 public static void main(String args[]){
  char[] arr1, arr2;
  arr1 = new char[6];
  arr2 = new char[4];

  System.out.println("Length of Array1 is " +arr1.length);
  System.out.println("Length of Array2 is " +arr2.length);
 }
} 


Output
Length of Array1 is 6
Length of Array2 is 4

How to Traverse Array Elements Using Loops
Example: Calculate the sum of numbers from 1 to 10 using Arrays
class SumOfNum{
 public static void main(String args[]){
     int arr[] = {1,2,3,4,5,6,7,8,9,10};
     int sum = 0;
     /* Initialize the array */
     for(int i=0; i < 10; i++)
          sum = sum + arr[i];
     System.out.println("Sum of Numbers is " + sum);
 }
}
    
Output
Sum of Numbers is 55

Some points to remember
1. If you try to access an array with illegal index, then compiler throws “ArrayIndexOutOfBoundsException”
    Example    
class ArrayEx{
 public static void main(String args[]){
  int arr[] = new int[10];
  arr[11] = 100;
 }
}
     

When you try to compile, compiler will throw the below error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 11
            at ArrayEx.main(ArrayEx.java:5)

2.If Program defined with array of negative size, then program compiles fine, but “NegativeArraySizeException” will be thrown at run time.
    Example
class ArrayEx{
 public static void main(String args[]){
  String arr[] = new String[-10];
 }
}

Program compiles fine, but run time error come
Exception in thread "main" java.lang.NegativeArraySizeException
    at ArrayEx.main(ArrayEx.java:3)

3. Array size is always an integer, so it is correct to give array size as byte, short and int. But not long.
     Example 1
class ArrayEx{
 public static void main(String args[]){
  byte b = 10;
  short s = 11;
  int i = 5;

  String arr1[] = new String[b];
  String arr2[] = new String[s];
  String arr3[] = new String[i];

  System.out.println(arr1.length +"\t" + arr2.length + "\t" + arr3.length);

 }
}
Output
10 11 5

Example 2
class ArrayEx{
 public static void main(String args[]){
  long i = 10;
  String arr3[] = new String[i];
 } 
}

When you try to compile, you will get compiler error like below
ArrayEx.java:6: error: possible loss of precision
String arr3[] = new String[i];
^
required: int
found: long
1 error

4. The problem with Arrays is, they can't grow dynamically, once Array is initialized, you can't change the size of the array.

Arrays                                                 Multi Dimensional Array                                                 Home