12. Arrays
Saturday, August 22, 2009
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.
Some more example are given below
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:
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
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
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.
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.
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
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
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.
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
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
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:
Arrays