Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
43 views

Arrays in Java

Java has a true array type with protective features to prevent your program from writing outside the memory bounds of the array. Arrays are treated as true objects In Java. You must declare an array before you can use it. Memory to contain the array data must be allocated from dynamic memory using statements such as the following. You can execute one statement to declare the array and another statement to cause the memory to be allocated.

Uploaded by

Jorge Ortiz
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

Arrays in Java

Java has a true array type with protective features to prevent your program from writing outside the memory bounds of the array. Arrays are treated as true objects In Java. You must declare an array before you can use it. Memory to contain the array data must be allocated from dynamic memory using statements such as the following. You can execute one statement to declare the array and another statement to cause the memory to be allocated.

Uploaded by

Jorge Ortiz
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Handout 32 Programming - 2

Umair Javed BTE

Arrays
Please note that this topic is not discussed in the lecture. Please cover it by yourself. Any queries are warmly welcomed.

The first step


The first step in learning to use a new programming language is usually to learn the foundation concepts such as variables, types, expressions, flow-of-control, arrays, strings, etc. This handout concentrates on arrays.

Arrays in Java
Java does have a true array type with protective features to prevent your program from writing outside the memory bounds of the array. Arrays are treated as true objects in Java.

Declaring an array
In Java, you must declare an array before you can use it. In declaring the array, you must provide two important pieces of information:

the name of the array the type of data to be stored in it.

Different declaration formats


Arrays may be declared in Java using either of two different formats as illustrated below:

int[] myArray; int myArray[];

Declaration does not allocate memory


Note that as with other objects in Java, the declaration does not allocate memory to contain the array data. Rather it simply allocates memory to contain a reference to the array.

Umair 2006, All Rights Reserved

-1-

TA: Munawar Nadeem

Handout 32 Programming - 2

Umair Javed BTE

How do I allocate memory for the data?


Memory to contain the array data must be allocated from dynamic memory using statements such as the following.
int[] myArray = new int[15]; int myArray[] = new int[25];

These two statements simultaneously declare the name of the array and cause memory to be allocated to contain the array. However there is another way of doing that. The initialization list is used for allocating memory as well as assigning values to elements of the array
int[] intArray = {3, 4, 2, 10, 7}; char[] charArray[] = {w, d, e};

In the above case, the java will determine the size of the array from the number of values provided in the initialization list. So, size of intArray would be 5 and charArray would be 3.

Can declaration and allocation be separated?


However, it is not necessary to combine these two processes. You can execute one statement to declare the array and another statement to cause the memory to be allocated as shown below. Causing memory to be set aside to contain the array data is commonly referred to as instantiating the array object (creating an instance of the array object).

Separating declaration from instantiation


If you prefer to declare and instantiate the array at different points in your program, you can use the following syntax. This pattern is very similar to the declaration and instantiation of all objects in Java.
int[] myArray; . . . myArray = new int[25];

Umair 2006, All Rights Reserved

-2-

TA: Munawar Nadeem

Handout 32 Programming - 2

Umair Javed BTE

Combining declaration and instantiation


The general syntax for declaring and instantiating an array is as shown below.
// general syntax typeOfElements[] nameOfArray = new typeOfElements[sizeOfArray]; // declaring an double array double arr[] = new double[10];

From which value first index start?


As in C++, array indices in Java always begin with 0 (zero).

Accessing array elements


Having instantiated an array in Java, you can access the elements of the array using index syntax similar to C++ and many other languages as shown below.

//assigning 6 to array 3rd element myArray[2] = 6; //retrieving value of array 3rd element myVar = myArray[2];

The length property of an array


The following code fragment illustrates another interesting aspect of arrays in Java. Note the use of length in the following code.
int a[] = new int[5]; // this will print 5 System.out.println(a.length);

All array objects in Java have a length property that can be accessed to determine the number of elements stored in the array. Remember: length is an property not a function, so no set of parentheses [ () ] are add.

Umair 2006, All Rights Reserved

-3-

TA: Munawar Nadeem

Handout 32 Programming - 2

Umair Javed BTE

What types can you store in a Java array?


Arrays can contain any Java data type including reference types such as objects, or other primitive types.

Constructing multi-dimensional arrays


Causing an array to contain elements that are also arrays is a good way to construct multidimensional arrays in Java.

Odd-shaped multi-dimensional arrays


The following program illustrates an interesting aspect of the use of arrays in Java. Java can be used to produce multi-dimensional arrays, which can be viewed as an array of arrays. However, the secondary arrays need not all be of the same size. In this program, a two-dimensional array of integers is declared and instantiated with the primary size (size of the first dimension) being three. The sizes of the secondary dimensions (sizes of each of the sub-arrays) are 2, 3, and 4 respectively.

Can declare the size of secondary dimension later


When declaring a two-dimensional array, it is not necessary to declare the size of the secondary dimension when the array is declared. Declaration of the size of each sub-array can be deferred until later as illustrated in this program.

Accessing an array out-of-bounds in Java


This program also illustrates the result of attempting to access an element that is out-ofbounds in Java. Java protects you from such programming errors.

ArrayIndexOutOfBoundsException
In Java, an exception occurs if you attempt to access out-of-bounds, as shown in the given below sample program. In this case, the exception was simply allowed to cause the program to terminate. The exception could have been caught and processed by an exception handler, a concept that will be explored in depth later. To know more about Exceptions, see handout on it.

Umair 2006, All Rights Reserved

-4-

TA: Munawar Nadeem

Handout 32 Programming - 2

Umair Javed BTE

The sample program


class ArrayTest { public static void main(String[] args){ //main method // Declare a two-dimensional array with a size of 3 on // the primary dimension but with different sizes on // the secondary dimension. // Note that Secondary size not specified initially int[][] myArray = new int[3][]; myArray[0] = new int[2];//secondary size is 2 myArray[1] = new int[3];//secondary size is 3 myArray[2] = new int[4];//secondary size is 4 //Fill the array with data for(int i = 0; i < 3; i++){ for(int j = 0; j < myArray[i].length; j++){ myArray[i][j] = i * j; }//end inner loop }//end outer loop

//Display data in the array for(int i = 0; i < 3; i++){ for(int j = 0; j < myArray[i].length; j++){ System.out.print(myArray[i][j]); }//end inner loop System.out.println(); // moving cursor to new line }//end outer loop //Attempt to access an out-of-bounds array element System.out.println( "Attempt to access array out of bounds"); myArray[4][0] = 7; //The above statement produces an ArrayIndexOutOfBounds // exception. }//end main }//End ArrayTest class.

Umair 2006, All Rights Reserved

-5-

TA: Munawar Nadeem

Handout 32 Programming - 2

Umair Javed BTE

Output
File ArrayTest.java Illustrates creation and manipulation of two-dimensional array with the sub arrays being of different lengths. Also illustrates detection of exception when an attempt Is made to store a value out of the array bounds. This program produces the following output:

00 012 0246 Attempt to access array out of bounds java.lang.ArrayIndexOutOfBoundsException: at array01.main(array01.java: 47)

Assigning one array to another array -- be careful


Java also allows you to assign one array to another. You must be aware, however, that when you do this, you are simply making another copy of the reference to the same data in memory.

Sample program to illustrate assignment of arrays


If you assign one array reference then actually you have two references to the same data in memory, which is often not a good idea. This is illustrated in the following diagram as well as in the program.

//creating two arrays using initialization lists int int firstArray[] = {10, 20, 30}; secondArray[] = {40, 50, 60}; 0F32
10 20 30

firstArray

0F32
secondArray

0 9E21
40

1
50

2
60

9E21

Umair 2006, All Rights Reserved

-6-

TA: Munawar Nadeem

Handout 32 Programming - 2 //assigning firstArray referenc to secondArray secondArray = firstArray;

Umair Javed BTE

firstArray

0F32
10 20 30

0F32
secondArray

0 9E21
40

1
50

2
60

0F32

// as you have clearly seen, secondArray is now also Pointing to the firstArray elements

The Sample Program


Class ArrayTest2 { public static void main(String[] args){//main method int[] firstArray; int[] secondArray; firstArray = new int[3]; for(int i = 0; i < firstArray.lenght; i++){ firstArray[i] = i; } secondArray = new int[3]; //assigning firstArray reference to secondArray

secondArray = firstArray;

System.out.println( "firstArray contents" ); for(int i = 0; i < firstArray.lenght; i++) { System.out.print(firstArray[i] + " " ); } //moving cursor to new line System.out.println(); System.out.println( "secondArray contents" ); for(int i = 0; i < secondArray.lenght; i++)

Umair 2006, All Rights Reserved

-7-

TA: Munawar Nadeem

Handout 32 Programming - 2 System.out.print(secondArray[i] + " " ); //moving cursor to new line System.out.println();

Umair Javed BTE

System.out.println( "Change value in firstArray and display both again");

firstArray[1] = 10;
System.out.println( "firstArray contents" ); for(int i = 0; i < firstArray.lenght; i++) { System.out.print(firstArray[i] + " " ); } //moving cursor to new line System.out.println(); System.out.println( "secondArray contents" ); for(int i = 0; i < secondArray.lenght; i++) System.out.print(secondArray[i] + " " ); }//end main }//End ArrayTest class.

Output
File ArrayTest2.java Illustrates that when you assign one array to another array, you end up with two references to the same array. The output from running this program is:

firstArray contents 0 1 2 secondArray contents 0 1 2 Change a value in firstArray and display both again firstArray contents 0 10 2 secondArray contents 0 10 2

---------------------------------Umair 2006, All Rights Reserved -8TA: Munawar Nadeem

You might also like