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

Introduction to Java_chapter6

Chapter 6 discusses single-dimensional arrays in Java, highlighting their properties, such as fixed size, uniform data type, and the ability to reference multiple data items. It covers array declaration, initialization, and accessing elements using indices, as well as the use of for-each loops and array bounds. Additionally, it explains passing arrays to methods and returning arrays from methods, emphasizing that arrays in Java are treated as objects.

Uploaded by

Mohammed Breka
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Introduction to Java_chapter6

Chapter 6 discusses single-dimensional arrays in Java, highlighting their properties, such as fixed size, uniform data type, and the ability to reference multiple data items. It covers array declaration, initialization, and accessing elements using indices, as well as the use of for-each loops and array bounds. Additionally, it explains passing arrays to methods and returning arrays from methods, emphasizing that arrays in Java are treated as objects.

Uploaded by

Mohammed Breka
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Chapter 6

SINGLE-DIMENSIONAL ARRAYS

Lecture notes for computer programming 1


Faculty of Engineering and Information Technology
Prepared by: Iyad Albayouk
What is an Array?

• A single array variable can reference a large


collection of data.
• Arrays have three important properties:
– arrays represent a group of related data (for
example, temperature for the last five days, or
stock prices for the last 30 days.)
– all data within a single array must share the
same data type (for example, you can create an
array of ints or an array of floats, but you
cannot mix and match ints with floats.)
– The size of an array is fixed once it is created.
What exactly are we talking about?!

• Let’s say you have ten students and you want to


save the grades for each of them for use
throughout your program (i.e. we need to
remember every grade not just loop and count
them or average them, etc.)
• Could do it the hard way:
• Set up ten variables called
studentOneGrade,
studentTwoGrade,
studentThreeGrade, etc.
• Very difficult to use and manipulate
• Instead, could use an array to do it the easy way…
Using an array variable

• Create an array variable called studentGrades[10]


• Declared as follows:
• int studentGrades[] = new int[10];
• This sets up a location in memory for 10 integers which
can be referenced using
studentGrades[ # ] where # is the particular
student you want to look at.
Array Naming Considerations

• The rules for naming variables apply when


selecting array variable names
– Composed of letters, digits, dollar signs and
underscore characters
– Cannot start with a digit
• Follow all the good programming hints
recommended for variable names
– i.e. just think of it as an ordinary variable when
making up the name
• In addition it is bad style to end an array name
with a digit
– ie. array3[5]
Parts of the array

• The array has some terminology we haven’t seen


yet
– Elements
– Index
• Position Number
• Subscript
– Zeroth element
– Keyword “new”
Elements

• Refers to the individual items represented by the


array. For example,
– an array of 10 integers is said to have 10
elements
– an array of 15 floats has 15 elements
– an array of 5 characters has 5 elements
– and so on…
Index (Position Number or Subscript)

• Refers to one particular element in the array


• Also known as position number or, more formally,
as a subscript
• The first element in an array is represented by an
index or subscript of 0 (zero). For example,
– studentGrades[ 0 ]
• This first position is known as the zeroth element
• The second position is referred to by
– studentGrades[ 1 ]
Figuring out the array positions

• In Java, an arrays’ elements start out at index 0


and go up to (the number of elements – 1)
• For example, our array of 10 student grades filled
in with grades might look like:

Index 0 1 2 3 4 5 6 7 8 9
Value 85 76 99 38 78 98 89 90 82 88
Array positions (cont’d)

• We can access them by specifying the array name


followed by square brackets with the index
number between them. For example,
System.out.println ("The third student’s grade is "
+ studentGrades[ 2 ] );

• Would print only the third integer spot in the array


(remember 0 is the first, 1 is the second, and 2 is
the third element’s index / subscript)
• The output would look like the following:
The third student’s grade is 99
Array positions (cont’d)

• The index scheme starting at 0 may be initially


confusing.
• This is the cause of many off-by-one errors so
study the concept carefully
• The element in the array’s first position is
sometimes referred to as the zeroth element.
• Notice the difference between "position" and
"element number"
subscript terminology

• From this point forward, for this class, all


references to array elements will refer to the
subscript of the array.
• In the event that we want to discuss the position of
an element in an array, we will refer to it’s
position.
• In other words, we will not use i'th element or
element i notation unless we are referring to the
zeroth element.
Keyword new

• As we will see, the keyword new is used in Java


when you wish to create a new object.
• In Java, arrays are objects.
• As with all data members of objects, the elements
of the each position in a new array will
automatically be initialized to the default value for
the array’s type.
Some powerful features of arrays

• Can use expressions as the subscript


– E.g. if variables a = 1 and b = 2
• studentGrades[ a + b ] would be the same as writing
studentGrades[ 3 ]
• Can use array elements in expressions
– E.g.
int gradeTotal = 0 ;
gradeTotal = studentGrades[ 0 ] +
studentGrades[ 1 ] +
studentGrades[ 2 ] + …etc…
studentGrades[ 9 ] ;
– Would add up all the array elements and store them in gradeTotal.
Powerful features (cont’d)

• Can set array elements equal to other values or


expressions. For example,
studentGrades[ 1 ] = 100 ;
• This would set the array element with a subscript
of 1 to a grade of 100. That is, the second student
would have a grade of 100.

• Java allows us to access an array’s length by using


the following notation:
– studentGrades.length would evaluate to 10
So how do we use arrays?

• Same concepts as other variables apply


– Must declare the array
– Must initialize the array (unlike regular
variables, Java will automatically initialize
arrays with default values)
• Arrays variables are actually reference variables.
– Can use arrays in expressions and methods,
setting elements’ values or using their values,
similar to the use of ordinary variables
Declaring an array
• First you can declare an array reference variable (you must
specify the type of the elements in the array) :
– int [] myFirstArray; //declares an array
//variable for ints
– Note: the line above does not allocate memory for the array (it
cannot since we have not said the size of the array yet). It only sets
aside enough memory to reference the array. Until we create an
array, the reference is to null.
• Next, we create the array and “point” the reference to it:
– myFirstArray = new int [10];
– To create the array, we need the number of elements in the array so
the computer can set aside adequate memory for the array.
• We can combine the declaration and allocation lines into
one line as follows:
– int [] myFirstArray = new int [10];
Initializing array with a for loop

• After declaring an array, you can initialize it in the


body of your program by using a for loop:
int [] myFirstArray = new int [ 5 ];

for (int i = 0 ; i <= 4 ; i++ )


{
myFirstArray[ i ] = 1 ;
} // end for

• Note the upper bound is 4, not 5! That is, you loop


through 0 to 4 to initialize an array with 5
elements
• Note: Array elements are initialized with default
values. Numeric types get 0, boolean get false and
char gets the null character (ascii code 0).
Declaring arrays (cont)

• You can use a constant to set the size of the array


final int NUM_STUDENTS_IN_CLASS = 8
int [] exams = new int [NUM_STUDENTS_IN_CLASS ];

• In Java, you do not need to know the size of the array at


COMPILE time. Instead you can know the size at RUN
time. For example, the following is legal:
inputString = JOptionPane.showInputDialog ("How
many students ?");
int students = Integer.parseInt (inputString);
int [] myFirstArray = new int [students];
Initializing an Array
• You can initialize an array when you declare it, as
you do with other variables
• Syntax is slightly different, as you are now
initializing more than one element at a time
• One way at declaration, using initializers:

int myFirstArray[ ] = { 0, 0, 0, 0, 0 };

• Note the braces around the initial zeroes which


themselves are separated by commas.
• Also note that creating arrays in this way eliminates
the need for the keyword new.
Accessing elements with for loop

• Can use a for loop to print the contents of an array

int [] myFirstArray = new int [ 5 ];


for (int i = 0 ; i <= myFirstArray.length – 1; i++ )
{
System.out.println ("array element " + i +
" is equal to " + myFirstArray [i]);
} // end for
– For an array of the char[ ] type, it can be printed using one print
statement. For example, the following code displays IYAD :
char[ ] name = {‘I’ , ‘Y’, ‘A’, ‘D’ };
System.out.println(name);
Outline
for-each Loops

• In general, the syntax for a for-each loop is


for (elementType element: arrayRefVar) {
// Process the element
}

• For example, the following code displays all the


elements in the array myList :

for(double u: myList) {
System.out.println(u);
}

 2003 Prentice Hall, Inc.


All rights reserved.
Array Bounds

• Very Important: Java does not provide array


bounds checking at compile time.
• This means that your program will crash at run
time of you try to access memory outside of an
array’s bounds.
• For example, suppose you have:
int [] myFirstArray = new int [ 10 ];
myFirstArray[100] = 45;

• 100 is very far outside your defined size (0..9)


• However, the compiler will not indicate an error.
Outline

Example Using Arrays

• Using histograms do display array data graphically


– Histogram
• Plot each numeric value as bar of asterisks (*)

 2003 Prentice Hall, Inc.


All rights reserved.
1 // Histogram.java Outline
2 // Histogram printing program.
3 import javax.swing.*;
javax.swing.*; Declare array with
4 initializer list Histogram.java
5 public class Histogram {
6
7 public static void main( String args[]
args[] ) Line 9
8 { Declare array with
9 int array[] = { 19,
19, 3, 15,
15, 7, 11,
11, 9, 13,
13, 5, 17,
17, 1 }; initializer list
10
11 String output = "Element\
"Element\tValue\
tValue\tHistogram"
tHistogram";
12
Line 19
13 // for each array element, output a bar in histogram For each array
14 for ( int counter = 0; counter < array.length;
array.length; counter++ ) { element, print
15 output += "\n" + counter + "\t" + array[ counter ] + "\t";
t"; associated number of
16
asterisks
17 // print bar of asterisks
18 for ( int stars = 0; stars < array[ counter ]; stars++ )
19 output += "*";
"*";
20
21 } // end outer for
For each array element, print
22 associated number of asterisks
23 JTextArea outputArea = new JTextArea();
JTextArea();
24 outputArea.setText(
outputArea.setText( output );
25

 2003 Prentice Hall, Inc.


All rights reserved.
26 JOptionPane.showMessageDialog( null, outputArea, Outline
27 "Histogram Printing Program", JOptionPane.INFORMATION_MESSAGE );
28
29 System.exit( 0 ); Histogram.java
30
31 } // end main
32
33 } // end class Histogram

 2003 Prentice Hall, Inc.


All rights reserved.
References and Reference Outline
Parameters

• Two ways to pass arguments to methods


– Pass-by-value
• Copy of argument’s value is passed to called method
• In Java, every primitive is pass-by-value
– Pass-by-reference
• Caller gives called method direct access to caller’s data
• Called method can manipulate this data
• Improved performance over pass-by-value
• In Java, every object is simulated pass-by-reference
– In Java, arrays are objects
• Therefore, arrays are passed to methods by reference
– Technically, we are using pass by value but the “value”
we are passing is a reference to the array.

 2003 Prentice Hall, Inc.


All rights reserved.
Outline
Passing Arrays to Methods

• To pass array argument to a method


– Specify array name without brackets
• Array hourlyTemperatures is declared as
int [ ] mylist ={1,2,3,4};

• The method call


printArray( mylist );

Or

printArray( new int[]{1,2,3,4} );

 2003 Prentice Hall, Inc.


All rights reserved.
Passing arrays to methods (cont)

• In the method header, use similar syntax as that


for array declaration:
public static void printArray (int array [] )

or
public static void ptintArray (int [] array )

• For example, the following method displays the


elements in an int array:
Public static void printArray(int [] array){
for(int i=0 ; i < array.length ; ++i)
system.out.println( array[i] + ” “);
}
Outline
Example for pass by sharing
Public class Test{
public static void main (String [ ] args){
int x=1;
int [ ] y = new int [10];
m( x , y );
System.out.println(“x is “ + x);
System.out.println(“y[0] is “ + y[0] );
}
public static void m( int number, int [ ] numbers){
number = 1001;
numbers[0] = 5555;
}
}

X is 1
Y[0] is 5555  2003 Prentice Hall, Inc.
All rights reserved.
Outline
Example for pass by sharing, cont.
•The primitive type value in x is passed to number, and
the reference value in y is passed to numbers.

 2003 Prentice Hall, Inc.


All rights reserved.
Returning arrays from methods

• We have seen examples of methods that modify an


array. Since the array is passed by reference, it is
modified in the original method as well.
• Another way to return information in an array is to
explicitly return the array.
• For example, a method with the header:
public static int [] makeArray ()
• Returns an integer array.
Returning arrays (cont)
• In order to return an array, the method creates the array
first.

public static int [] makeArray ()


{
int [] myArray = new int [10];
for (int i; i < myArray.length;
i++)
Myarray [i] = i;
return myArray;
}
• The method above creates a new array called myArray,
initializes each element and returns the reference to
myArray.
Outline
Returning arrays (cont)
•For example, the following method returns an array that
is the reversal of another array.

•For example, the following statement returns a new array list2 with
elements 6,5,4,3,2,1
Int [ ] list1={1,2,3,4,5,6};
Int [ ] list2= reverse(list1);  2003 Prentice Hall, Inc.
All rights reserved.
Outline
Variable-Length Argument Lists
•A variable number of arguments of the same type can be passed to a method and treated as
an array.
•You can pass a variable number of arguments of the same type to a method. The
parameter in the method is declared as follows:
typeName... parameterName
Example:

 2003 Prentice Hall, Inc.


All rights reserved.
Example of Copying Arrays

In this example, you will see that a simple


assignment cannot copy arrays in the following
program. The program simply creates two arrays
and attempts to copy one to the other, using an
assignment statement.
Copying Arrays

Before the assignment After the assignment


list2 = list1; list2 = list1;

list1 list1
Contents Contents
of list1 of list1

list2 list2
Contents Contents
of list2 of list2
Garbage
Copying Arrays

Using a loop:
int[] sourceArray = {2, 3, 1, 5, 10};
int[] targetArray = new int[sourceArray.length];

for (int i = 0; i < sourceArrays.length; i++)


targetArray[i] = sourceArray[i];
The arraycopy Utility

arraycopy(sourceArray, src_pos,
targetArray, tar_pos, length);

Example:
System.arraycopy(sourceArray, 0, targetArray,
0, sourceArray.length);
Outline
The Arrays Class

• The java.util.Arrays class contains useful methods


for common array operations such as sorting and
searching.
• For example, the following code sorts an array of
numbers and an array of characters.
double[ ] numbers = {6.0 ,4.4 ,1.9 ,2.9 ,3.4 ,3.5 };
java.util.Arrays.sort(numbers); // Sort the whole array

char[ ] chars = {‘a’ ,’A’ ,’4’ ,’F’ ,’D’ ,’P’ };


java.util.Arrays.sort(chars,1 , 3);// Sort part of the
array from chars[1] to chars[3-1].

 2003 Prentice Hall, Inc.


All rights reserved.
Outline
The Arrays Class, cont.

• For example, the following code searches the keys in


an array of integers and an array of characters.
int [ ] list = {2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79};
System.out.println(“(1) Index is “ +java.util.Arrays.binarySearch(list,11 ));
System.out.println(“(2) Index is “ +java.util.Arrays.binarySearch(list,12 ));

char [ ] chars = {‘a’, ‘c’, ‘g’, ‘x’, ‘y’, ‘z’};


System.out.println(“(3) Index is “ +java.util.Arrays.binarySearch(chars,’a’ ));
System.out.println(“(3) Index is “ +java.util.Arrays.binarySearch(chars,’t’ ));
The output of the preceding code is
1. Index is 4
2. Index is –6
3. Index is 0
4. Index is –4  2003 Prentice Hall, Inc.
All rights reserved.

You might also like