CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 3 GEORGE KOUTSOGIANNAKIS Copyright: 2015- Illinois...

38
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 3 GEORGE KOUTSOGIANNAKIS ight: 2015- Illinois Institute of Technology/George Koutsogiannakis 1

Transcript of CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 3 GEORGE KOUTSOGIANNAKIS Copyright: 2015- Illinois...

CS 116

OBJECT ORIENTED PROGRAMMING IILECTURE 3

GEORGE KOUTSOGIANNAKIS

Copyright: 2015- Illinois Institute of Technology/George Koutsogiannakis1

OOP Review• In previous lecture we discussed:

– Service classes versus Client classes.– Packaging of classes using Command Line.– Input using Command Line arguments.– How to read text files with scanner object.– The scope of a variable.– Enumerations.– Using the StringTokenizer object.– Formatting of Numbers.

2

Arrays – Single DimensionTopics in Today’s Lecture

• Review Material– Declaring and Instantiating Arrays– Entering Array Elements– Accessing Array Elements– Aggregate Array Operations– Arrays of Objects.– Using Arrays in classes.

• New Material not covered in CS115– Creating packages– Creating Documentation with javadocs command

(optional- not responsible for it in exams or labs).

3

Arrays• An array is a sequence of variables of the same data type.• Arrays are useful for many applications, including calculating statistics or

representing the state of a game. • The data type can be any of Java's primitive types (int, short, byte, long,

float, double, boolean, char), an array, or a class. • Each variable in the array is an element.• We use an index to specify the position of each element in the array.• An array is an Object by itself.

• Remember that we can also have arrays of objects. The objects can be representative of pre defined classes (library classes) or user defined classes

4

Declaring and Instantiating Arrays

Arrays are objects, so creating an array requires two steps:1. declaring a reference to the array2. instantiating the array

To declare a reference to the array, use this syntax: datatype [] arrayName;

To instantiate an array, use this syntax: arrayName = new datatype[ size ]; where size is an expression that evaluates

to an integer and specifies the number of elements.

5

ExamplesDeclaring arrays:double [] dailyTemps; // elements are doubles

String [] cdTracks; // elements are Strings

boolean [] answers; // elements are booleans

Auto [] cars; // elements are Auto references

int [] cs101, bio201; // two integer arrays

Instantiating these arrays:dailyTemps = new double[365]; // 365 elements

cdTracks = new String[15]; // 15 elements

int numberOfQuestions = 30;

answers = new boolean[numberOfQuestions];

cars = new Auto[3]; // 3 elements

cs101 = new int[5]; // 5 elements

bio201 = new int[4]; // 4 elements

6

Default Values for Elements

• When an array is instantiated, the elements are assigned default values according to the array data type.

7

Array data type Default value

byte, short, int, long 0

float, double 0.0

char space

boolean false

Any object reference (for example, a String)

null

Example array of integers• int [ ] myarray=new int[5];

– The array size is 5 and the index will run from 0 to 4.

index

0 1 2 3 4

• Notice that initial values are 0 s since the array was declared to be an array of

integer data types. 8

0

0

0

0

0

Assigning Initial Values to ArraysArrays can be instantiated by specifying a list of initial values.Syntax: datatype [] arrayName = { value0, value1, … };

where valueN is an expression evaluating to the data type of the array and is the value to assign to the element at index N.

Examples:int nine = 9;

int [] oddNumbers = { 1, 3, 5, 7, nine, nine + 2,

13, 15, 17, 19 };

Auto sportsCar = new Auto( "Ferrari", 0, 0.0 );

Auto [] cars = { sportsCar, new Auto( ),

new Auto("BMW", 100, 15.0 ) };

9

Instantiating an Array

• Or you can declare and then instantiate the array by indicating its size and then enter values one at a time i.e

double [] myarray; myarray=new double[10];Where 10 is the size of the array myarray.

10

Entering Array Elements

• Enter an element in a specific index location.• Suppose that we want to enter the number 10

in the position with index=2 in the array myintarray

int [] myintarray=new int[5]; myintarray[2]=10;• We can of course fill the array with multiple

element values by using a for loop.

11

Entering Array Elements

• i.e. for (int a=0 ; a<=myintarray.lenght-1; a++) myintarray[a]=(a+2); This loop enters the int values of a+2 into the

array myintarray.

12

Entering Array Elements

13

Array Index Value entered

0 2

1 3

2 4

3 5

4 6

Accessing Array Elements

• Array elements can be accessed by first declaring a data type variable similar to the data types held in the array and assigning the array element to that data type.

i.e. int x; x=myarray[2]; the element in index position 2 is assigned to x (i.e x=4 from previous

slide).

14

Calculating a TotalExample This code calculates the total value of all elements in the array myintarray,

which has previously been instantiated:

int total = 0; // initialize total for ( int i = 0; i <= myintarray.length-1; i++ ) { total += myintarray[i]; } System.out.println( "The total is " + total ); The output should be: The total is 20See Text Example 8.5 SummingArrayElements.java

15

Instantiating an Array of ObjectsTo instantiate an array with a class data type:

1. instantiate the array (elements are object references, initialized to null)

2. instantiate the objectsExample: // instantiate array; all elements are null Auto [] cars = new Auto[3]; // instantiate objects and assign to elements Auto sportsCar = new Auto( "Miata", 100, 5.0 ); cars[0] = sportsCar; cars[1] = new Auto( ); // cars[2] is still nullSee Text Example 8.2 AutoArray.java

16

Example of Arrays of Objects• Suppose we have a Person service class with attributes:public class Person{

String firstName=“ “;String lastName=“ “;int currentID=0;static int id=0;public Person(String fn, String ln){

setFirstName(fn);setLastName(ln);id++;currentID=id;

}

Followed by accessor /mutator and toString methods. NEVER INCLUDE THE id ATTRIBURES IN THE LIST OF ARGUMENTS OF THE CONSTRUCTOR1111

17

Arrays of ObjectsSuppose the following class uses the class Person. We want to create 50 person objects and

store them in an array :public class CreatePersons {

public static void main(String[] args) {

//for each of the instance variable we create an array.

String Fname=“ “;String Lname=“ “;//create (instantiate) an array of type Person to hold 50 Person objects.

// Although we fixed the size to 50 in this example in most cases the size will //be determined programmatically from the data in the text file that has the data.

Person [] personArray=new Person[50];

18

Arrays of Objects//create 50 Person objects and place them in the array personArrayfor (int i=0; i<=personArray.length-1; i++ ){

FName="p"+i;LName="Doe"+i;

personArray[i]=new Person(FName, LName);

}

19

Arrays of Objects//Now output the ids and the Person objects attributes (instance variables) for each Person

object in the array. for (int j=0; j<=personArray.length-1; j++)

{ System.out.println(" the id of each object is:"+" "+personArray[j].getCurrentID());System.out.println(“The attributes of each object are:”+”

“+personArray[j].toString()); }

}}

NOTE : calling the toString method in the above program is optiona, the same result will be accomplished if the code was written:

System.out.println(“The attributes of each object are:”+” “+personArray[j]);

20

Using Arrays in Classes

In a user-defined class, an array can be: – an instance variable of the class– a parameter to a method– a return value from a method– a local variable in a method

21

Methods with Array Parameters or Array return values

• To define a method that takes an array as a parameter, use this syntax: accessModifier returnType methodName(

dataType [] arrayName )

i.e. public int myMethod( Person [] aPersonArray)

• To define a method that returns an array, use this syntax: accessModifier dataType [] methodName(

parameterList )

i.e public Person [] myMethod (String [] aStringsArray)

22

Returned value data type Method argument data type

Methods with Array Parameters or Array return values

• To pass an array as an argument when calling a method, use the array name without brackets:

i.e. in the following call the method returns an array. We need to have an array of the data type for the array inatsntiate dto capture the returned array from the method call:

Person [] mynewPersonArray=new Person[50];

mynewPersonArray=myMethod(stringArray);

23

Arrays as Instance VariablesA constructor (or mutator) that accepts an array parameter should instantiate the

instance variable array and copy the elements from the parameter array to the instance variable.

// constructor public CellPhone( double [] bills ) { // instantiate instance variable array // with same length as parameter cellBills = new double [bills.length]; // copy parameter array to cellBills array for ( int i = 0; i < cellBills.length; i++ ) cellBills[i] = bills[i]; }

24

Accessors for ArraysSimilarly, an accessor method for the array instance variable should return a

reference to a copy of the array.public double [] getCellBills( ){ // instantiate temporary array double [] temp = new double [cellBills.length]; // copy instance variable values to temp for ( int i = 0; i < cellBills.length; i++ ) temp[i] = cellBills[i]; // return copy of array return temp;}

25

Finding min max Value in an array of numbers.

• Suppose that we have an array of numeric data type like int.

• We need to develop an algorithm for finding the first instance of the maximum number stored in the array (it is possible that the same max number appears more than once in the array.

26

Finding min max Value in an array of numbers.

• Suppose that I have the array:int [] intarray=new int[20];//Let us declare a variable called maxint max=0;//Let us iterate through the elements of the array and for compare each

element to the max variable’s number. //If we find an element with a value greater than the value held by max then

assign the value of that element to max and continue with the next comparison

//In the example code given next we also capture the index at which the element with the maximum value was found:

27

Finding min max Value in an array of numbers

int indexOfmax=0;for(int i=0; i<=intarray.length-1; i++){

if(max<intarray[i]){

max=intarray[i]; indexOfmax=i; }}To find the minimum value all we have to do is to reverse the inequality sign

in the if selection if(min>intarray)

28

Java Packages- Reminder• Let us repeat the basics about packaging one more

time!!!• User defined packaging.

– Suppose that we created a package for our user defined template class Auto :package name1.name2.name3;import java.util.Scanner;

import java.io.File;public class Auto

{ ………………………………

}

29

Java Packages

• We compile with the special command:• >javac –d . Auto.java• This command tells the compiler to create the

folders name1 and name 2 and name 3 with respect to the current directory

• and place Auto.class inside folder name3.

30

Java Packages

Current Directory (folder) Auto.java name1(folder)

name2 (folder)

name3 (folder) Auto.class

31

Java Packages

• How do we call the interpreter for class AutoClient from the current directory (folder)?

• We need to list the path to the AutoClass when we use the interpreter command:

i.e >java name1.name2.AutoClient• Notice that the reason we call the AutoClient class is

because this class has the main method. The Auto class will be called automatically.

32

Java Packages

• Pre defined library classes are grouped into packages according to their functionality:

i.e.

package java.lang Provides classes that are fundamental to the design of the Java programming language.Every java program automatically imports all the classes of this package without the need for an import statement.– Includes such classes as :

• String, Math , System, Integer, Float and others.

33

Java Packages

• There are over 200 packages in the java library– Number of classes varies in each package with

some having over 20 classes.– Remember that a package can include something

called “interfaces”.– For now let us think of an interface as a class whose

methods have no code (no implementation). We will come back to the subject of interfaces later on.

34

Javadocs (optional material)

• Automatic generation of documentation for your user defined classes in html format.

• It is another tool available in the jdk (see bin subfolder in the installation folder of the jdk).

• To generate documentation use the command javadoc and the nam eof your class followed by the .java extension:– >javadoc Persons.java or– >javadoc *.java (means all files in the folder that

end with .java extansion).

35

Javadocs

• The tool reads all comments added (/** to */)• plus additional information that we add in the

source code file (i.e. describe parameters using the symbol @) i.e.

– @ param id denotes the id number of a person advancing for each new Person object instantiated.

36

Javadoc Example/** This class describes Persons */public class Person { /** @param firstName provides the first name of a Person */

String firstName;static int id;int currentid;

public Person(){

firstName="John";id++;currentid=id;

}

37

Output html File• Package Class Tree Deprecated Index Help • PREV CLASS NEXT CLASS FRAMES NO FRAMES All Classes All Classes SUMMARY: NESTED | FIELD |

CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD • Class Person• java.lang.Object Person public class Person extends java.lang.Object This class describes Persons • Constructor Summary Person()

Method Summary void method1() Methods inherited from class java.lang.Object clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

• Constructor Detail Person• public Person() Method Detail method1• public void method1() Package Class Tree Deprecated Index Help • PREV CLASS NEXT CLASS FRAMES NO FRAMES All Classes All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

38