Showing posts with label Arrays. Show all posts
Showing posts with label Arrays. Show all posts

12.2 Java Collection Framework for Arrays

Monday, August 24, 2009 Posted by Sudarsan 0 comments
The Java collection framework gives the programmer access to prepackaged data structures as well as to algorithms for manipulating them.

A collection is an object that can hold references to other objects. The collection interfaces declare the operations that can be performed on each type of collection.

The classes and interfaces of the collections framework are in package java.util.

In this post we are going to discuss how arrays are associated with Java collection framework and also how to implement various methods of the class Arrays.

Class Arrays provides static methods for manipulating arrays, including sort for sorting an array, binarySearch for searching a sorted array, equals for comparing arrays and fill for placing items in an array.

So, have a look at the fallowing program to implement various methods of the class Arrays.

Sorting Example
// Sorting an Array

import java.util.Scanner;
import java.util.Arrays;
/**
 *
 * @author Sudarsan
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        int a[];
        a=new int[5];

        Scanner s=new Scanner(System.in);

        System.out.print("Enter Elements into the Array...");

        for(int i=0;i<a.length;i++)
        {
            a[i]=s.nextInt();
        }

        System.out.println("The Elements in the Array are...");

        for(int i=0;i<a.length;i++)
        {
            System.out.printf("%d\t", a[i]);
        }

        System.out.println();
        // passing array to the static method sort
        
        Arrays.sort(a);        

        System.out.println("After Sorting the Array...");
        
        System.out.println();

        for(int i=0;i<a.length;i++)
        {
            System.out.printf("%d\t", a[i]);
        }
    }

}

As we can see in the above example, we sorted the array by the help of a static method of Arrays class. Where we just passed an array argument to the static method sort.When we compile this program we can get the fallowing output.

Enter Elements into the Array...
78
-5
94
22
71
The Elements in the Array are...
78 -5 94 22 71

After Sorting the Array...
-5 22 71 78 94

Implementing Binary Search
// Using BinarySearch in an Array

import java.util.Scanner;
import java.util.Arrays;

/**
 *
 * @author Sudarsan
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        int a[];
        a=new int[5];

        Scanner s=new Scanner(System.in);

        System.out.println("Enter Elements into the Array....");

        for(int i=0;i<a.length;i++)
        {
            a[i]=s.nextInt();
        }

        //Sorting the Array
        //BinarySearch only works with Sorted Elements
        Arrays.sort(a);

        System.out.println("The Sorted Array is....");

        for(int i=0;i<a.length;i++)
        {
            System.out.printf("%d\t", a[i]);
        }

        System.out.println();
        
        System.out.println("Enter an Element to Search : ");
        int key=s.nextInt();

        // binarySearch returns a positive integer if element found

        int flag=Arrays.binarySearch(a, key);

        // the return value is the position of the element in the array
        
        if(flag >=0)
        {
            System.out.printf("Element Found at Location : %d", flag+1);
        }
        else
        {
            System.out.println("Element Not Found !");
        } 


    }

}

When we compile the above program we can see the fallowing output.

Enter Elements into the Array....
10
20
30
40
50
The Sorted Array is....
10 20 30 40 50
Enter an Element to Search :
40
Element Found at Location : 4

Note : Binary Search only works with Sorted Array of elements

fill, arrayCopy and equals

// Implementing fill, equals and arrayCopy

import java.util.Scanner;
import java.util.Arrays;

/**
 *
 * @author Sudarsan
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        int a[];
        int b[];

        a=new int[5];
        b=new int[5];

        Scanner s=new Scanner(System.in);

        System.out.println("Enter Elements into A ....");
        for(int i=0;i<a.length;i++)
        {
            a[i]=s.nextInt();
        }

        System.out.println("The Elements in the Array are ...");
        for(int i:a)
            System.out.println(i);


        //Filling the Array A with 5

        Arrays.fill(a, 5);

        System.out.println("After Filling the Array with 5s...");
        for(int i:a)
            System.out.println(i);

        // Copying the values of A to B

        System.arraycopy(a, 0, b, 0, 5);

        System.out.println("The Values in the Array B are ....");
        for(int i:b)
            System.out.println(i);

        // Testing wether both Arrays are equal or not
        
        if(Arrays.equals(a, b))
        {
            System.out.println("Both Array A and B are Equal");
        }
        else
        {
            System.out.println("A and B are Not Equal");
        }

    }

}

When we compile the above program we can see the fallowing output.

Enter Elements into A ....
10
20
30
40
50
The Elements in the Array are ...
10
20
30
40
50
After Filling the Array with 5s...
5
5
5
5
5
The Values in the Array B are ....
5
5
5
5
5
Both Array A and B are Equal

In Java API, various methods are available for Arrays to manipulate different types of data like int, float, double and etc. We can implement those methods whenever we want.
Labels:

12.1 Multi Dimensional Arrays

Saturday, August 22, 2009 Posted by Sudarsan 0 comments
Variable-Length Arguments

By the help of Variable-Length arguments we can create methods that can accept an unspecified number of arguments. These are a new feature in J2SE 5.0

An argument type fallowed by an ellipsis (…) in a method’s argument list indicates that the method receives a variable number of arguments of the particular type.

The usage of ellipsis can occur only once in parameter list

Have a look at the fallowing example to know more about Variable-Length Arguments (vargs)

//Using VARGS

/**
 *
 * @author Sudarsan
 */
public class Main {

    // VARGS method is used to calculate total
    public static int total(int... nums)
    {
        int tot=0;
        
        for(int i:nums)
        {
            tot=tot+i;
        }
        
        return tot;
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        int x=10;
        int y=20;
        int z=30;

        System.out.printf("Sum of x+y+z : %d\n", total(x,y,z));
        System.out.printf("Sum of x+y   : %d\n", total(x,y));
        System.out.printf("Sum of x+z   : %d\n", total(x,z));

    }

}
When we compile this we can get the fallowing output
Sum of x+y+z : 60
Sum of x+y : 30
Sum of x+z : 40

Multi Dimensional Arrays

Multi dimensional arrays with two dimensions are often used to represent tables of values consisting of information arranged in rows and columns.

Arrays that require two indices to identify a particular element are called two-dimensional arrays.

An array with p rows and q columns is called a p-by-q array.

A two dimensional array can be initialized with an array initilizer of the form

datatype variable[][]={ {row 1},{row 2}, ……};

Multidimensional arrays are maintained as arrays of separate one-dimensional arrays. As a result, the lengths of the rows in a two-dimensional array are not required to be the same.

A multidimensional array with the same number of columns in every row can be created with an array-creation expression of the form

 datatype variable[]=new datatype[rows][columns];

For example, the following declares a two-dimensional array variable called nums

int nums[][] = new int[4][5];

This allocates a 4 by 5 array and assigns it tonums internally this matrix is implemented as an array of arrays of int.

Have a look at the fallowing examples to know more about 2D Arrays

Assigning Values at Design Time to a 2D Array

// Initilizing Two dimensional Array

/**
 *
 * @author Sudarsan
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        int a[][]={{10,20,30},{40,50,60}};
        int b[][]={{10,20},{30},{40,50,60}};

        System.out.println("Values in Array A are ....");

        for(int i=0;i<a.length;i++)
        {
            for(int j=0;j<a[i].length;j++)
            {
                System.out.printf("%d ",a[i][j]);
            }

            System.out.println();
        }

        System.out.println("Values in Array B are .....");

        for(int i=0;i<b.length;i++)
        {
            for(int j=0;j<b[i].length;j++)
            {
                System.out.printf("%d ",b[i][j]);
            }
            System.out.println();
        }

    }

}

The output of the above program is given below

Values in Array A are ....
10 20 30
40 50 60
Values in Array B are .....
10 20
30
40 50 60

Assigning Values to 2D Array at Run Time

// Reading values into 2D Array at Runtime

import java.util.Scanner;

/**
 *
 * @author Sudarsan
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        int a[][];
        a=new int[2][2];

        Scanner s=new Scanner(System.in);

        System.out.println("Enter Values into 2D Array ...");

        for(int i=0;i<a.length;i++)
        {
            for(int j=0;j<a[i].length;j++)
            {
                a[i][j]=s.nextInt();

            }
        }

        System.out.println("The Values in the Array are....");

        for(int i=0;i<a.length;i++)
        {
            for(int j=0;j<a[i].length;j++)
            {
                System.out.printf("%d\t",a[i][j]);
            }

            System.out.println();
        }


    }

}

The output of the above program is given below

Enter Values into 2D Array ...
10
20
30
40
The Values in the Array are....
10 20
30 40

Passing 2D Array as a parameter to a Constructor

//Student.java

package d3;

/**
 *
 * @author Sudarsan
 */
public class Student {

    private int marks[][];

    //passing 2d array to a constructor
    
    public Student(int m[][])
    {
        marks=m;
    }

    public void stats()
    {
        System.out.printf("Minimum Marks : %d\n", min());
        System.out.printf("Maximum Marks : %d\n", max());
    }

    public int min()
    {
        int low=marks[0][0];

        for(int smarks[]:marks)
        {
           for(int mark : smarks)
           {
               if(mark<low)
                   low=mark;
           }
        }

        return low;
    }

    public int max()
    {
        int high=marks[0][0];

        for(int smarks[]:marks)
        {
            for(int mark:smarks)
            {
                if(mark>high)
                    high=mark;
            }
        }

        return high;
    }

    public int totalMarks(int groupMark[])
    {
        int tot=0;

        for(int mark: groupMark)
            tot+=mark;

        return tot;
    }

    public void outputResult()
    {
        System.out.println("The Student Report:");
        System.out.print("         ");

        for(int i=0;i<marks[0].length;i++)
            System.out.printf("Subject %d", i+1);

        System.out.println("Total");

        for(int j=0;j<marks.length;j++)
        {
            System.out.printf("Student %2d", j+1);

            for(int i:marks[j])
                System.out.printf("%8d", i);

            int tot=totalMarks(marks[j]);
            System.out.printf("%9d\n", tot);
        }
    }
}

//Constructiong Student Object

import java.util.Scanner;
/**
 *
 * @author Sudarsan
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        int m[][];
        m=new int[3][3];

        Scanner s=new Scanner(System.in);

        System.out.println("Enter Five Student Marks for Three Subjects :");

        for(int i=0;i<m.length;i++)
        {
            System.out.printf("Student %d\n", i+1);
            for(int j=0;j<m[i].length;j++)
            {
                System.out.printf("Subject %d : ", j+1);
                m[i][j]=s.nextInt();
            }
        }

        // passing 2d array as a parameter
        
        Student std=new Student(m);
        std.outputResult();
        std.stats();
    }

}

When we compile this program we can see the fallowing output

Enter Five Student Marks for Three Subjects :
Student 1
Subject 1 :
41
Subject 2 :
25
Subject 3 :
98
Student 2
Subject 1 :
14
Subject 2 :
65
Subject 3 :
33
Student 3
Subject 1 :
78
Subject 2 :
58
Subject 3 :
88
The Student Report:
Subject 1Subject 2Subject 3Total
Student 1 41 25 98 164
Student 2 14 65 33 112
Student 3 78 58 88 224
Minimum Marks : 14
Maximum Marks : 98
Labels:

12. Arrays

Posted by Sudarsan 0 comments
In this post we are going to learn, how to code One Dimensional Arrays.

Arrays are data structures consisting of related data items of the same type. Arrays are fixed length entities-they remain the same length once they are created. Although an array variable may be reassigned the reference of a new array of a different length.


An array is a group of variables containing values that all have the same type.

Arrays are objects, so they are considered reference types. The elements of an array can be either primitive types or reference types.

In order to refer a particular element in an array, we need to specify the name of the reference to the array and the index (subscript) of the element in the array.

A program refers to any one of an array array’s elements with an array-access expression that includes the name of the array fallowed by the index of the particular element in square brackets ([]) .

The first element in every array has index zero and is sometimes called the zeroth element.

An index must be a non negative integer. A program can use an expression as an index. Every array object knows its own length and maintains this information in a length field.

To create an array object the programmer specifies the of the array elements and the number of array elements as part of an array creation expression that uses new keyword.

The fallowing array creation expression creates an array of 20 int values.

int a[]=new int[20];

Some more example are given below

int[] counts; 
String[] names; 
int[][] matrix; //this is an array of arrays 

When an array is created, each element of the array receives a default value. Zero for numeric primitive type elements, false for boolen elements and null for references (any nonprimitive type).

When a Java program executes, the JVM checks array indicates to ensure that they are valid (i.e they must be greater than or equal to 0 and less than the length of the array).

If a program uses an invalid index, Java generates a so-called exception to indicate that an error occurred in the program at execution time.

It is never legal to include the size of the array in your declaration. Yes, we know you can do that in some other languages, which is why you might see a question or two that include code similar to the following:

int[5] scores;

The preceding code won’t compile. Remember, the JVM doesn’t allocate space until you actually instantiate the array object. That’s when size matters.

Implementing Array

The following figure shows the array structure in the system’s memory.


Have a look at the fallowing example, to create and initializing an array

// Creating and Initilizing an Array

/**
 *
 * @author Sudarsan
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        int a[];  // Declaring an array

        a=new int[10]; // Here the size of the array is 10

        System.out.printf("%s%10s\n","Index","Value");

        // Printing the Index as well as the initial value
        
        for(int i=0;i<a.length;i++)
        {
            System.out.printf("%5d%10d\n",i,a[i] );
        }

    }

}

When we compile this program we can see the fallowing output, here the index value is incremented and the value of the particular index is zero, means we did not assign any array location.

Index Value
0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0

Assigning Values to the Array

Have a look at the fallowing example

//Initilizing an Array

/**
 *
 * @author Sudarsan
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        // Initilizing an array with some integer values
        int a[]={10,20,30,40,50,60,70,80,90,100};

        System.out.printf("%s%10s\n","Index","Value");
        
        //Printing index as well as initial values of the array
        for(int i=0;i<a.length;i++)
        {
            System.out.printf("%5d%10d\n", i,a[i]);
        }


    }

}

The output generated by the program when we compile is given below

Index Value
0 10
1 20
2 30
3 40
4 50
5 60
6 70
7 80
8 90
9 100

Assigning Values to the Array at Runtime

We can assign values to the array at runtime by the help of Scanner class, have a look at the fallowing example to know more.

// Using Scanner class in an Array

import java.util.Scanner;
/**
 *
 * @author Sudarsan
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        Scanner s=new Scanner(System.in);

        int a[];
        a=new int[5];

        System.out.println("Enter Values into the Array...");
        
        for(int i=0;i<a.length;i++)
        {
            a[i]=s.nextInt();  // Accepting values at runtime
        }

        System.out.println("The Values in the Array are....");

        for(int i=0;i<a.length;i++)
        {
            System.out.printf("%d\t", a[i]);
        }
    }
}

If we compile this program we need to enter five values into the array, after that we can see the fallowing output

Enter the values into the Array...
10
20
30
40
50
The Values in the Array are....
10 20 30 40 50

Implementing For-Each Loop

Here we are going to discuss a new feature of J2SE 5.0, the enhanced for statement, which iterates through the elements of an array or a collection without using a counter.

The syntax of an enhanced for statement is give below.

for(parameter : arrayname)
 statemet;

Where the type of parameter must match the type of the elements in the array.
Note, however, that the for-each statement can be used only to access array elements. It cannot be used to manipulate array elements, if you want do so use traditional for loop.

Have a look at the fallowing example to implement For-Each Loop

// Using, For-Each Loop
/**
 *
 * @author Sudarsan
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        //Initilizing an array
        
        int a[]={25,10,30,34,50};

        //Printing Array elements using For-Each Loop

        for(int i:a)
            System.out.printf("%d\t", i);
    }

}

The output of the above program will be as fallows.
25 10 30 34 50

Passing Arrays to Methods

Have a look at the fallowing example, how to pass arrays to a method

//Passing array as a parameter to a method

import java.util.Scanner;

/**
 *
 * @author Sudarsan
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        int a[];
        a=new int[5];

        Scanner s=new Scanner(System.in);

        System.out.print("Enter Elements into the Array.....");

        for(int i=0;i<a.length;i++)
        {
            a[i]=s.nextInt();
        }

        //passing array as parameter to a method
        sumOfArray(a);


    }

    //Static method which is used to compute Array Sum
    
    static void sumOfArray(int a2[])
    {
        int sum=0;

        for(int i=0;i<a2.length;i++)
        {
            sum=sum+a2[i];
        }

        System.out.println("The Sum of Array Elements :"+sum);
    }

}

When we compile this we can get the fallowing output

Enter Elements into the Array.....
1
2
3
4
5
The Sum of Array Elements: 15

Passing Array as a parameter to the Constructor

We can pass an array to the constructor via a parameter; here is an example how to do so.

// To findout Maximum and Minimum Score in a class of 5 Students

/**
 *
 * @author Sudarsan
 */
 class Student {


    private int marks[];

    //Constructor having array parameter

    public Student(int m[])
    {
        marks=m;
    }

    //Method for Maximum

    public int maxMarks()
    {
        int max=marks[0];

        for(int i:marks)
        {
            if(i>max)
                max=i;
        }

        return max;
    }

    // Method for Minimum

    public int minMarks()
    {
        int min=marks[0];

        for(int i:marks)
        {
            if(i<min)
                min=i;
        }

        return min;
    }

    // Tod dispaly output
    
    void display()
    {
        System.out.println("Highest Marks :"+maxMarks());
        System.out.println("Lowest Marks : "+minMarks());
    }
}

// Constructing Student Object

import java.util.Scanner;

/**
 *
 * @author Sudarsan
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        int a[];
        a=new int[5];

        Scanner s=new Scanner(System.in);

        System.out.println("Enter Marks for Five Students ....");

        for(int i=0;i<a.length;i++)
        {
            a[i]=s.nextInt();
        }

        // Passing Array as paramemetr
        
        Student std=new Student(a);

        std.display();

    }

}

When we compile the above program we can see the fallowing output

Enter Marks for Five Students ....

25
74
98
10
99

The Maximum Marks :99
The Minimum Marks : 10

In the next post we are going to discuss Two Dimensional Arrays
Labels: