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

No comments:

Post a Comment