Go to Top

Thursday, 29 September 2011

Utilities 7 - Printing arrays

Having problems while printing arrays ? Use this simple program to print an array with a single statement.

Java Program : 

class array
{
 static void display(int a[])
 {
     for(int i=0;i<a.length;i++)
     System.out.print(a[i]+" ");
    }
    static void display(short a[])
 {
     for(int i=0;i<a.length;i++)
     System.out.print(a[i]+" ");
    }static void display(byte a[])
 {
     for(int i=0;i<a.length;i++)
     System.out.print(a[i]+" ");
    }static void display(long a[])
 {
     for(int i=0;i<a.length;i++)
     System.out.print(a[i]+" ");
    }static void display(float a[])
 {
     for(int i=0;i<a.length;i++)
     System.out.print(a[i]+" ");
    }static void display(double a[])
 {
     for(int i=0;i<a.length;i++)
     System.out.print(a[i]+" ");
    }static void display(char a[])
 {
     for(int i=0;i<a.length;i++)
     System.out.print(a[i]+" ");
    }static void display(boolean a[])
 {
     for(int i=0;i<a.length;i++)
     System.out.print(a[i]+" ");
    }
    static void display(String a[])
 {
     for(int i=0;i<a.length;i++)
     System.out.print(a[i]+" ");
    }
}

Next time you have to print an array, just type array.display(array_name); and you are done. No more annoying for and while loops now.

Syntax : array.display(array_name);

For example :

//Rest part is omitted. 
int[] my_array=new int[10];
array.display(my_array);


No comments:

Post a Comment

ShareThis