Saturday, 8 February 2014

Varargs: Methods with variable number of arguments

In java we can create methods that takes variable number of arguments. This feature is called varargs or variable number of arguments. The method which accepts variable number of arguments is called varargs method.
Syntax
    returnType methodName(dataType … parameterName){

    }

"..." tells the compiler that this is a vararg.

Example
class VarargsEx{
 public void printData(int ... a){
  System.out.println("Parameters are " + a.length);
  for(int i=0; i < a.length; i++)
   System.out.print(a[i] + " ");
  System.out.println();
 }

 public static void main(String args[]){
  VarargsEx obj = new VarargsEx();
  obj.printData(1);
  obj.printData(1,2);
  obj.printData(1,2,3);
 }
}

Output
Parameters are 1
1
Parameters are 2
1 2
Parameters are 3
1 2 3

The syntax for the method printData, tells the compiler, that this method can accept zero or more arguments. So all the calls like below are valid.
      obj.printData(1);
    obj.printData(1,2);
    obj.printData(1,2,3);

The variable number of parameters (varargs) must be at last while defining a method with varargs.

There must be only one vararg parameter in method definition.

Some Points to Remember
1. The variable number of parameters (varargs) must be at last while defining a method with varargs.
    Example
class VarargsEx{
 public void printData(int ... a, float f1){ 
  System.out.println("Parameters are " + a.length);
  for(int i=0; i < a.length; i++) 
   System.out.print(a[i] + " ");
  System.out.println();
 } 
} 
           
When you try to compile the above program, compiler will generates error like below

VarargsEx.java:3: error: ')' expected
public void printData(int ... a, float f1){
 ^
VarargsEx.java:3: error: ';' expected
public void printData(int ... a, float f1){
 ^
2 errors
               

valid method definition is
    public void printData(float f1, int ... a)

2. There must be only one vararg parameter in method definition.
      Example
class VarargsEx{
 public void printData(int ... a1, int ... a2){
 }
}
     
When you try to compile the above code, compiler throws error like below             
VarargsEx.java:3: error: ')' expected
public void printData(int ... a1, int ... a2){
 ^

VarargsEx.java:3: error: <identifier> expected
public void printData(int ... a1, int ... a2){
 ^
 
VarargsEx.java:3: error: <identifier> expected
public void printData(int ... a1, int ... a2){
^
3 errors

More about methods                                                 constructore varargs                                                 Home

Friday, 7 February 2014

Multi Dimensional Arrays

Multidimensional arrays are actually arrays of arrays.

   Syntax to create two dimensional Array
      dataType arrayName[][] = new dataType[size1][size2]
         (OR)
      dataType[][] arrayName;

      arrayName = new dataType[size1][size2]

   for Example consider the array of size 5*4.
      int arr[][] = new int[5][4];

00 01 02 03
10 11 12 13
20 21 22 23
30 31 32 33
40 41 42 42

Table 1 : Array indexes
100 553 512 -9
12 32 43 56
1 3 5 7
9 -87 -98 0
-12 46 78 97

Table 2 : Values stored in Array
When you compare table1 and table 2

arr[0][0] = 100
arr[0][1] = 553
arr[0][2] = 512
arr[0][3] = -9

Example
class ArrayEx{ 
 public static void main(String args[]){
  int arr[][] = new int[5][4];

  arr[0][0] = 100;
  arr[0][1] = 553;
  arr[0][2] = 512; 
  arr[0][3] = -9;

  arr[1][0] = 12; 
  arr[1][1] = 32;
  arr[1][2] = 43; 
  arr[1][3] = 56;

  arr[2][0] = 1; 
  arr[2][1] = 3;
  arr[2][2] = 5; 
  arr[2][3] = 7;

  arr[3][0] = 9; 
  arr[3][1] = -87;
  arr[3][2] = -98; 
  arr[3][3] = 0;

  arr[4][0] = -12; 
  arr[4][1] = 46;
  arr[4][2] = 78; 
  arr[4][3] = 97;

  /*Display Elements */
  for(int i=0; i<5; i++){
   for(int j=0; j<4; j++){
    System.out.print(arr[i][j] +"\t");
   }
   System.out.println();
  }
 } 
}

Output
100 553 512 -9
12 32 43 56
1 3 5 7
9 -87 -98 0
-12 46 78 97
      

One Dimensional Array                                                 Jagged Arrays                                                 Home

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

Arrays

An array is a series of elements of the same type placed in contiguous memory locations. Elements in the array are accessed by using index positions.

Suppose if you want to calculate sum of 9 integers, you have to define 9 variables like below

    int var1, var2, var3, var4, var5, var6, var7, var8, var9;

    var1 = 5;
    var2 = -10;
    var3 = 7;
    var4 = 8
    var5 = 11;
    var6 = 12;
    var7 = 14;
    var8 = 21;
    var9 = 0;

By using new keyword we can declare like below

    int var[] = new int[9];

    var[0] = 5;
    var[1] = -10;
    var[2] = 7;
    var[3] = 8
    var[4] = 11;
    var[5] = 12;
    var[6] = 14;
    var[7] = 21;
    var[8] = 0;

As you see, Array indexes starts from 0. var[0] represents 5, var[2] represents 7 and so on.

continue                                                 One Dimensional Array                                                 Home