Java With Us
Home   |   Tutorial   |   Programs  

Java Tutorial

Introduction to Java
Hello World Program
Variables and Data types
More about data types
Displaying text using print and println
Displaying text using printf
Java Comments
Naming conventions for Identifiers
Mathematical operations in Java
Taking input from the user

Classes and Objects
Introduction to object oriented programming
The constituents of a Class
Creating objects and calling methods
Get and Set Methods
Default constructor provided by the compiler
Access Specfiers
Scope and lifetime of Variables
Call by value and Call by Reference

A few more topics
Casting
Class as a reference data type
Constants or literals
Final variables
Increment and decrement operators
Manipulating Strings
Operators
Overloading constructors and methods
Static methods and variables
The Java API
The Math class
this keyword
Wrapper classes

Control Structures
Control Statements
Repetition statements
Nested loops
Formulating algorithms
Branching Statements

Arrays
Arrays introduction
Processing arrays using 1oops
Searching and sorting arrays
Array of objects
Multi dimensional arrays
Taking input as command line arguments
Using ellipsis to accept variable number of arguments

Inheritance
Inheritance introduction
Relation between a super class and sub class
Final classes and methods
The protected access specifier
Class Object

Polymorphism
Introduction
Interfaces
Packages
Abstract classes and methods

Exception handling
Exception handling introduction
Exception hierarchy
Nested try catch blocks
Throwing exceptions


Arrays

We have seen that variables are used to store data in a Java program. Each variable can store not more than one data item. What do we do if we wish to store a large number of data items, say 100. A quick answer from you might be to use 100 variables, one for each of the 100 data items. But coding wouldn't be as simple as the answer you have given. We need to write 100 lines of code for setting up these variables and manipulating them would be quite a difficult task. And if we do not know beforehand, the number of variables that are required, there seems to be solution from what we have studied till now. The answer to such a problem lies in arrays. Arrays are the simplest data structure inbuilt into the Java programming language. Data structures are used to store data in a more efficient way. Data here refers to a group of data items and not a single data item for the purpose of which variables are used.

An array is used to store a group of values, all of which have the same data type. All the elements stored in the arrays are accessed by simply using the variable name and the index of the element. You can think of an array as a block of cells, each having an index starting from 0, just as we had seen with Strings. Before we move further into arrays, be clear of the fact that an array is a reference data type just like a class. They are passed by reference. They may be considered as reference variables and they have a name which follows the rules of identifiers.

Here is a graphic representation of an array that contains seven elements, all having the same data type, int. The length of the array is the number of elements contained in the array. The length of this particular array, named by us as myArray is 7. The elements have indices starting from 0 and extending up to 6, which is one subtracted from the length of the array. (7-1=6). The element at index 0 is 3, the element at index 1 is 34 and so on. We refer to the elements of the array programmatically as arrayName [ index] as we will see later on. For instance myArray[0] contains the integer 3.



The data type of an array name is specified as <data type>[] where < data type > refers to the data type of the elements the array would be storing. The square brackets indicate an array. The following statements show the declaration of an array named a, which holds int values.

int [] a;

The square brackets may also be placed at the end of the array name, as shown below. It would make no difference.

int a[];

Just like variables, we may also declare more than one array in a single statement, as shown below:

int[] a, b, c;

The above statement declares three arrays, a, b and c all of int type. However, be cautious when using such a notation. In such multiple declaration statements, the square brackets are placed along with the data type. If we wish to declare a few integer variables and a few integer arrays in a single statement, we use the following form:

int a[], b, c[];

The above statement declares two integer arrays, a and c and a single integer variable b. We however recommend that you declare not more than a single array in a statement. Now that we have declared the array, we need to create an integer array and assign its reference to the array variable. Just like classes, arrays are created using the new keyword. The new keyword returns a reference to the array being created which is then assigned to an appropriate variable. The size of the arrays (or the length, which is the number of elements the array will hold) is also specified. Following statements creates an array to hold seven integers and assigns its reference to eth arrays variable a.

a = new int[7];

The size of an array may be specified using integer constants as done above or by using expression that contain variables. The following array creation statements are also valid.

int size = 7;
a = new int [ size ];
a = new int [ 3+4 ];
a = new int [ size / 3 + 5 ];

As we can specify the size of an array using a variable, arrays can be dynamically created at run time. In other words, the size of the array can be taken as an input from the user and an array can be created using the user entered value.

As with variables, the declaration and initialisation of arrays can be combined into s ingle statement as shown below:

int[] a = new int[7];

After an array is created, all the elements are set to their default values. The above array a has all the seven elements set to 0 implicitly.

Next, we need to access each element of the array and assign it with new int values. Array elements are accessed by specifying the array variable and the index of the elements. a[0] refers to the first element of the array. The following statements initialise some of the elements of the array a.

a[0]=3;
a[1]=34;
a[5]=7;

Elements accessed with the above notation ( a[index] ) may be used just like normal variables. We may print those values, use them in calculations, pass them as arguments and so on.

System.out.println( a[1] );
int sum = a[6] + a[5];
double root = Math.sqrt  ( a[5] );

When we specify an invalid index such as a negative number ora number hich is greater than or equal to the length of the array, no compilation errors occur. Rather, a run time execpetion, anmely ArrayIndexOutOfBoundsException is thrown during runtime. An exception in Java is an object which indicates an abnormal error. We shall see how to handle these errors in the chapter on exception handling.

There is one important thing to be noted here. While the array is a reference type, the elements of the array are not of reference type. a[] is a reference type while a[0] is a primitive type. For example, if we pass an element of the above array to a method and that element is modified within the method, it shows no effect on the original value stored in eth array. However, if the array itself is passed, it is passed by reference and is susceptible to changes. Look at the following program which illustrates these concepts.

public class Array {

    public static void main(String args[]) {
        int[] a = new int[7];
        a[2] = 3;
        a[5] = 7;
       System.out.println("Value of a[5] before passing it to the method changeElemnt() is " + a[5]);
       changeElement(a[5]);
        System.out.println("Value of a[5] after passing it to the method changeElemnt() is " + a[5]);
        System.out.println("Value of a[0] before passing it to the method changeArray() is " + a[0]);
       changeArray(a);
        System.out.println("Value of a[0] after passing it to the method changeArray() is " + a[0]);
    }

    public static void changeElement(int a) {
        System.out.println("In changeElement() : ");
        System.out.println("Value of a before incrementing is " + a);
        a++;
        System.out.println("Value of a after incrementing is " + a);
    }

    public static void changeArray(int[] arr) {
        System.out.println("In changeArray() :");
        System.out.println("Value of arr[0] before incrementing is " + arr[0]);
        arr[0]++;
        System.out.println("Value of arr[0] after incrementing is " + arr[0]);
    }
}

The output of this program would be

Value of a[5] before passing it to the method changeElemnt() is 7
In changeElement() : 
Value of a before incrementing is 7
Value of a after incrementing is 8
Value of a[5] after passing it to the method changeElemnt() is 7
Value of a[0] before passing it to the method changeArray() is 0
In changeArray() :
Value of arr[0] before incrementing is 0
Value of arr[0] after incrementing is 1
Value of a[0] after passing it to the method changeArray() is 1

Note that the value of the array element a[5] in main() remain changed even after it was passed as parameter to the method changeElemnt(). This is because a[5] is of type int (a primitive data type) which is passed by value. a[5] is not an array type variable.

However, when the array a[] itself was passed, the value of the event a[0] was changed. This is because a[] is of type int[] an not int. int[] is a reference type that is passed by reference and not by value.

As this program has illustrated, an array type can also be taken as an argument. Also, an array can be returned by a method. For example, a method which returns a double typed array will have the following header:

public double[] methodName ()

We will look at an example shortly in which all these concepts are explained. There is another way to initialise arrays by using an array initialiser. An array initialiser contains a pair of braces which enclose the values that are to be stored in the array separated by spaces. Following line uses an array initialise to initialise the array a[].

int[] a= { 3, 34, 7, 9};

Note that we haven't specified the length of the array in the above statement. It is automatically calculated. When using array initialisers, separating the declaration from initialisation isn't possible. The following set of statements result in a compilation error.

int [] a;
a = { 3, 34, 7, 9};

The length of an array can be determined through the length variable of the array object in the following way:

int [] a=  { 3, 34, 7, 9};
int len = a.length; //len = 4

Note that length is not a method of the array object but rather an instance variable.

Privacy Policy