ioop review 5.0. topics (1) bits and bytes classes and objects primitive vs. object types java...

184
IOOP Review 5.0

Upload: heather-lane

Post on 03-Jan-2016

218 views

Category:

Documents


2 download

TRANSCRIPT

IOOP

Review

5.0

Topics (1)• Bits and Bytes• Classes and Objects• Primitive vs. Object Types• Java Operators and Expressions• Keyword this• null vs. void• Enumerated Type• Switch-case statement• Wrapper Classes

(autoboxing/unboxing)

3

Base-10

10 digits: 0 - 9 (decimal) place values: 10x

i.e. 6543

6000 + 500 + 40 + 3 = 6543

103 102 101 100 1000 100 10 1

6 x 103 5 x 102 4 x 101 3 x 100 6000 500 40 3

4

Base-2

2 digits: 0 - 1 (binary) place values: 2x

i.e. 0101 (binary)

0 + 4 + 0 + 1 = 5 (decimal)

23 22 21 20

8 4 2 1

0 x 23 1 x 22 0 x 21 1 x 20

0 4 0 1

5

Bits & Bytes

bit = binary digit (0-1) byte = 8 bits

i.e. 00110101 (binary)

0 + 0 + 32 + 16 + 0 + 4 + 0 + 1 = 53 (decimal)

27 26 25 24 23 22 21 20

128 64 32 16 8 4 2 1

0 0 1 1 0 1 0 127 26 25 24 23 22 21 20

0 0 32 16 0 4 0 1

6

32-bit vs. 64-bit Machines

• system architecture• instruction set

• machine language

x86 = 32-bit x64 = 64-bit

7

Class diagram (static view)

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

8

Object diagram(dynamic view)

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

9

Primitive types vs. Object types

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

32

object type

primitive type

SomeObject obj;

int i;

10

What is the output?

• int a;int b;a = 32;b = a;a = a + 1;System.out.println(b);

• Person a;Person b;a = new Person("Everett");b = a;a.changeName("Delmar");System.out.println(b.getName());

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

11

Primitive types vs. Object types

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

32

ObjectType a;

int a;

ObjectType b;

32

int b;

b = a;

12

Java operators

13

What is the output? System.out.println(18 % -7.0);

int a = 5;int b = 3;int c = ++a - 2 * b--;System.out.print(“a = ” + a + “\n”); System.out.print(“b = ” + b + “\n”); System.out.print(“c = ” + c + “\n”);

14

What is the output? System.out.println(18 % -7.0);

4.0

int a = 5;int b = 3;int c = ++a - 2 * b--;System.out.print(“a = ” + a + “\n”); System.out.print(“b = ” + b + “\n”); System.out.print(“c = ” + c + “\n”);

a = 6

b = 2

c = 0

15

Java relational operators

Boolean result

Tests equality …. not identity!!

16

Java logical operators

BINARY&& and|| or^ exclusive or

UNARY

! not

17

Logic operators for boolean values

Operands && || ^ T T T T FT F F T T

F T F T T

F F F F F

Which are examples of short-circuit operators?

18

Logic operators for boolean values

Operands && || ^ T T T T FT F F T T

F T F T T

F F F F F

19

What is the result?

35 / 9 == 4false

5 < 6 || false && 2 == 3 true

boolean test = false;

test=false==false;

System.out.println(test); true

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

20

Internal and external method calls

• Internal method callmethodName();

No variable name is required

• External method callobject.methodName();

Uses dot (.) operator

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

21

this keyword• this could be used as a reference to the

invoking object instead of method calls

public class MailItem { private String from; private String to; private String message;

public MailItem(String from, String to, String message) { this.from = from; this.to = to; this.message = message; }

Methods omitted. }

22

null

• null is a special value in Java• Object fields are initialized to null by default.

• You can test for and assign null:

private NumberDisplay hours;

if(hours != null) { ... }

hours = null;

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

23

null vs. voidnull

• object reference not defined and points to special value of “nothing”

• used to see if an object was created and actually exists

void• empty or no value/type• used as the return type for a

method when “nothing” is being returned

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

24

Enumerated Types• A language feature defining a type

• Declared like a class using enum instead of class to introduce a type name

• Used to define a list of variable names denoting the set of values belonging to this type:– Alternative to static int constants– When the constants’ values would be

arbitraryObjects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

25

A basic enumerated type

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

public enum CommandWord{ GO, QUIT, HELP, UNKNOWN}

• By convention, names are defined in CAPS

• Each name represents an object of the enum type, e.g. CommandWord.HELP

• Enum objects are not created directly

• Enum definitions can also have fields, constructors and methods

26

Using enumerated types

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

public enum CommandWord{ GO, QUIT, HELP, UNKNOWN}

String commandWord = command.getCommandWord();if(commandWord.equals("help")) {

printHelp();}else if(commandWord.equals("go")) {

goRoom(command);}else if(commandWord.equals("quit")) {

wantToQuit = quit(command);}

27

public enum CommandWord{ GO, QUIT, HELP, UNKNOWN}

if(commandWord.equals("help")) {printHelp();

}else if(commandWord.equals("go")) {

goRoom(command);}else if(commandWord.equals("quit")) {

wantToQuit = quit(command);}

if(commandWord == CommandWord.HELP) {printHelp();

}else if(commandWord == CommandWord.GO) {

goRoom(command);}else if(commandWord == CommandWord.QUIT) {

wantToQuit = quit(command);}

String type commandWo

rd

CommandWord type

commandWord

data type using enum

28

if(commandWord == CommandWord.HELP) {printHelp();

}else if(commandWord == CommandWord.GO) {

goRoom(command);}else if(commandWord == CommandWord.QUIT) {

wantToQuit = quit(command);}

Use switch to express code intent even more clearly ...

switch (commandWord) {case HELP:

printHelp();break;

case GO:goRoom(command);break;

case QUIT:wantToQuit = quit(command);break;

}

29

Wrapper classes• Primitive types are not objects types

• Primitive-type values must be wrapped in objects to be stored in a collection!

• Wrapper classes exist for all primitive types:

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

simple type wrapper classint Integerfloat Floatchar Character... ...

30

Wrapper classes

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

int i = 18; Integer iwrap = new Integer(i); …int value = iwrap.intValue();

wrap the value

unwrap it

In practice, autoboxing and unboxing mean we don't often have to do

this explicitly

31

Autoboxing and unboxing

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

private ArrayList<Integer> markList;

public void storeMark(int mark)

{

markList.add(mark);

}

int firstMark = markList.remove(0);

autoboxing

unboxing

32

Topics (2)• Library Classes & Java API• Interface vs. Implementation• The String Class• Overloading• Equality vs. Identity• String methods

• Immutable String• Regular Expressions [ ]+• Fixed-size Arrays

33

Using library classes

• Classes organized into packages

• Classes from the library must be imported using an import statement (except classes from java.lang)

• They can then be used like classes from the current project

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

34

Packages and import

• Single classes may be imported:

import java.util.ArrayList;

• Whole packages can be imported:

import java.util.*;

• Importation does NOT involve source code insertion

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

35

Reading class documentation

• Documentation of the Java libraries in HTML format

• Readable in a web browser

• Class API: Application Programmers Interface

• Interface description for all library classes

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

36 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

37

Interface vs implementation

The documentation includes (the WHAT):

• the name of the class

• a general description of the class

• a list of constructors and methods

• return values and parameters for constructors and methods

• a description of the purpose of each constructor and method

the interface of the class

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

38

Interface vs implementation

The documentation does not include (HOW):

• private fields (most fields are private)

• private methods

• the bodies (source code) of methods

the implementation of the class

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

39

The String class

• The String class is defined in the java.lang package

• It has some special features that need a little care

• In particular, comparison of String objects can be tricky

40

String concatenation

• 4 + 59

• "wind" + "ow""window"

• 4 + 5 + ”window" + 4 + 5”9window45"

• "# " + price + " cents""# 500 cents"

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

overloading

41

What is the output?

• System.out.println(5 + 6 + "hello");

• System.out.println("hello" + 5 + 6);

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

11hello

hello56

42

String equalityif(input == "bye") { ...}

if(input.equals("bye")) { ...}

** Always use .equals( )

for text equalityObjects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

tests identity

tests equality

43

Identity vs equality 1Other (non-String) objects:

person1 = = person2 ?

“Fred”

:Person

person1 person2

“Jill”

:Person

44

Identity vs equality 1Other (non-String) objects:

person1 = = person2 ?false

“Fred”

:Person

person1 person2

“Jill”

:Person

45

Identity vs equality 2Other (non-String) objects:

“Fred”

:Person

person1 person2

“Fred”

:Person

person1 = = person2 ?

same

value

46

Identity vs equality 2Other (non-String) objects:

“Fred”

:Person

person1 person2

“Fred”

:Person

person1 = = person2 ?false

same

value

47

Identity vs equality 3Other (non-String) objects:

“Fred”

:Person

person1 person2

“Fred”

:Person

person1 = = person2 ?

48

Identity vs equality 3Other (non-String) objects:

“Fred”

:Person

person1 person2

“Fred”

:Person

person1 = = person2 ?true

49

Identity vs equality (Strings)

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

"bye"

:String

input

"bye"

:String

String input = reader.getInput();if(input = = "bye") { ...}

= = ?

(may be) false!

= = tests identity

50

Identity vs equality (Strings)

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

"bye"

:String

input

"bye"

:String

String input = reader.getInput();if(input.equals("bye")) { ...}

.equals ?

true!

.equals tests equality

51

The problem with Strings

• The compiler merges identical String literals in the program code– The result is reference equality for

apparently distinct String objects

• But this cannot be done for identical Strings that arise outside the program’s code– e.g. from user input

52

Methods from String• boolean contains(char c)• boolean endsWith(String s)• int indexOf(String s)• int indexOf(String s, int i)• String substring(int b)• String substring(int b, int e)• String toUpperCase( )• String trim( )

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Beware: strings are immutable!

53

Immutable String

String methodString toUpperCase()

Incorrect useinput.toUpperCase();

Correct useinput = input.toUpperCase();

if(input.toUpperCase().contains())

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

54

Dividing Strings

public HashSet<String> getInput() { System.out.print("> "); String inputLine = reader.nextLine().trim().toLowerCase();

String[ ] wordArray = inputLine.split(" "); HashSet<String> words = new HashSet<String>();

for(String word : wordArray) { words.add(word); } return words;}

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

55

String .splitString[ ] split(String regex)

Splits this string around matches of the given regular expression.

String[] wordArray = inputLine.split(" ");Splits inputLine around the regular expression of “ ”.

Regular Expressions“ ” – space

“\t” - tab“\\s” - any white space

“[ \t]” – space or tab(grouping)“[ \t]+” – space or tab(one or more)

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

56

Using regexString.split()

String[] wordArray = origString.split(“[ \t]+”);Splits origString around (one or more) spaces and/or tabs

String[] wordArray = origString.split(“\\s+”);Splits origString around (one or more) spaces and/or tabs

String.trim().replaceAll()String newString =

origString.trim( ).replaceAll(“\\s+”, “ ”);Removes ALL leading and trailing spaces in origString with .trim

ANDReplaces ALL (one or more) white spaces with a SINGLE space

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

57

Fixed-size collections

• The maximum collection size may be pre-determined with an upper limit

• Array is an fixed-size collection type:

– stores object OR primitive data types

– special syntax unlike usual Java method calls (uses same as other languages)

– more efficient access than flexible-sized collections

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

58

Declaring array variables

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

• LogAnalyzer class contains the field:

private int[] hourCounts;— indicates hourCounts is of type integer

array

• int would be the base type of the array

— the array object would store type int values

• difference between declarationsint hourCounts; // single int variableint[] hourCounts; // int-array variable

hourCounts = new int[24];

59

Creating an array object

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

public class LogAnalyzer{ private int[] hourCounts; private LogfileReader reader;  public LogAnalyzer() { hourCounts = new int[24]; reader = new LogfileReader(); } ...}

Array object creation

— specifies size

Array variable declaration— does not contain size

60 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Creating an array object

new type[integer-expression]new int[24]

• creates an object of type integer array

• creates array capacity to hold 24 integers

61

The hourCounts array

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

private int[] hourCounts;

new int[24];

=

hourCounts = new int[24];

62

Accessing an array array[integer expression]

• Square-bracket notation is used to access an array element by indexing:

labels[6]machines[0]

people[x + 10 -y]

• Valid indices depend on the length of the array and range from [0 … (length-1)]

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

63

Using an array

• Elements are used like ordinary variables

• The target of an assignment:labels[5] = ... ;machines[index] = new Machine(10);

• In an expression:double half = readings[0] / 2;adjusted = hourCounts[hour] – 3;hourCounts[hour]++;System.out.print(item[1].getName());

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

64

Standard array use

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

private int[] hourCounts;private String[] names;

... hourCounts = new int[24];names = new String[10];

...

hourcounts[i] = 0;hourcounts[i]++;System.out.println(hourcounts[i]);

declaration

creation

use

65

Array literals {3, 15, 4, 5, …}

• Array literals in this form can only be used in declarations and NOT like this:

numbers = { 3, 15, 4, 5 };

• Related uses require new:

numbers = new int[ ] { 3, 15, 4, 5 };

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

private int[ ] numbers = { 3, 15, 4, 5 };

declaration, creation and initialization• The size is inferred from the data:

XX

66

Array length

• length is a field rather than a method

• It is fixed size and can not be changed

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

private int[] numbers = { 3, 15, 4, 5 };

int n = numbers.length;

NO brackets!NO parentheses!

67 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Topics (3)

• ArrayList• HashSet• HashMap• Collection constructor copying• Random• Collections.shuffle() • Anonymous Objects• Chaining

68

Generic classesfor items of any type

ArrayList<parameter-type>• These collections are known and defined

as parameterized or generic types

• parameter type between the angle brackets is the object type of the items in the list

— ArrayList<Person>— ArrayList<TicketMachine>

• An ArrayList may store any object type, but ALL objects in the list will be the same type

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

69

Creating an ArrayList object in the constructor

• In Java versions prior to version 7 files = new ArrayList<String>( );

• Java 7 introduced ‘diamond notation’

files = new ArrayList< >( );

where the type parameter can be inferred from the variable it is being assigned tomyMusic:

MusicOrganizer

files

:ArrayList<String>

new

70

Key methods of classArrayList

The ArrayList class implements list functionality with methods for the following operations:

— add(item)— remove(item)— get(index)— size()

71

Object structures with ArrayList collections

• Only a single field that stores an object of type ArrayList<String>

• All work to access and manage the data is done in ArrayList object

• Benefits of abstraction by not knowing details of how work is done

• Helps us avoid duplication of information and behavior

72

Adding a third file

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

• Dynamic capacity with ability to increase and/or decrease as needed with its add( ) and remove( ) methods

• Keeps an internal count of the number of items with size( ) method returning that count

• Maintains the items in the order inserted with each new item added to the end of the list

• As an item is removed, all items following after the removed item are shifted up and forward in order to fill the removed item’s space

73

Features of the collection• It increases its capacity as necessary• It keeps a private count of the number

of items in the list– size() accessor

• It keeps the objects in order of adding, but is otherwise unsorted

• Details of how this is done are hidden– Does that matter? – Does not knowing prevent us from using it?

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

74

ArrayList Index numbering

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

• Implicit numbering which starts with index 0 (same as String class)

• Last item in the collection has the index size-1

• Thus, valid index values would be between [0 . . . size( )-1]

75

Removal may affect numbering

• Removal process may change index values of other objects in the list

• Collection moves all subsequent items up by 1 position to fill the gap

• Indices of items in front of (preceding) the removed item are UNCHANGED

• Indices of items after (following) the removed item are decreased by 1

• Same “shifting” of items may also occur if adding new items into positions other than the end

files.remove(1);

76

The general utility of indices

• Index values:– start at 0– are numbered sequentially– have no gaps in consecutive objects

• Using integers to index collections has a general utility:– next: index + 1– previous: index – 1– last: list.size( ) – 1– the first three: items at indices 0, 1, 2

• We could use loops and iteration to access items in sequence: 0, 1, 2, …

77

Review• Items may be added and removed

• Each item has an index

• Index values may change if items are removed (or further items added)

• The main ArrayList methods are add, get, remove and size

• ArrayList is a parameterized or generic type

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

78

Using sets

import java.util.HashSet;

...HashSet<String> mySet = new HashSet<String>();

mySet.add("one");mySet.add("two");mySet.add("three");

for(String element : mySet) { do something with element}

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Compare with code

for an ArrayList!

79

ArrayList vs. HashSet• Similarities

− Contain a collection of objects− Add objects (.add method)− Remove objects (.remove method)− Number of elements (.size method)− Iterator ability (.iterator method)

• Differences− HashSet objects are unique, while

an ArrayList can have duplicate objects

− HashSet objects are not ordered, while ArrayList objects are ordered

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

80

Maps• Maps are flexible-sized collections

that contain pairs of values− pair is a key object and a value object

• Uses the key to easily lookup the value− instead of using an integer index

• For example, a telephone book:− name and phone number pair

• Reverse-lookup of key using value− not so easy

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

81

Using mapsin a telephone directory

A map with strings as keys and values: name and telephone number

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

"Charles Nguyen"

:HashMap

"(531) 9392 4587"

"Lisa Jones" "(402) 4536 4674"

"William H. Smith" "(998) 5488 0123"

82

Using maps.put and .get

Declaration and creation of phonebook HashMap:HashMap <String, String> phoneBook = new HashMap<String, String>();

HashMap .put method inserts an entry:phoneBook.put("Charles Nguyen", "(531) 9392 4587");phoneBook.put("Lisa Jones", "(402) 4536 4674");phoneBook.put("William H. Smith", "(998) 5488 0123");

HashMap .get method retrieves the value :String phoneNumber = phoneBook.get("Lisa Jones");System.out.println(phoneNumber);

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

83

List, Map and Set• Alternative ways to group objects

• Varying implementations available:−List: ArrayList, LinkedList−Set: HashSet, TreeSet

• HashMap is unrelated to HashSet, & HashSet is closer to ArrayList

• Name consist of 2 parts “Array” “List”−2nd word – collection type (List, Map, Set)−1st word – how it is implemented

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

84

New COPY of an existing ArrayList

• Declare a variable with the same ArrayList of <Element> type as the original ArrayList

• Create a new ArrayList object (with the same element type as original) to store the copy in

• Pass the original ArrayList as the parameter

• Point the variable to the new COPY of the original list with exact same contents

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

ArrayList<Track> copiedList = new ArrayList<Track>(tracks);

85

Random library class

Generates a pseudo-random number by:

• Using the Random library class imported from the java.util package

• Creating an instance of class Random and assigning it to a local variable

• With that instance, call the method nextInt to get a number

• Optional parameter – upper limit size passed

import java.util.Random;

Random rand = new Random();

int index = rand.nextInt(size);

86

Using Random

• The library class Random can be used to generate random numbers

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

import java.util.Random;...Random rand = new Random();...int num = rand.nextInt();int value = 1 + rand.nextInt(100);int index = rand.nextInt(list.size());

87

Collections library class

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

import java.util.Collections;

ArrayList<String> files = new ArrayList< >();

Collections.shuffle(files);

Shuffles the items in a collection by:

• Using the Collections library class imported from the java.util package

• Calls the method shuffle to randomly change the order of existing items in the collection without removing/adding items

• Parameter – pass the entire collection

88

Anonymous objects

• Objects are often created and handed on elsewhere immediately:

Lot furtherLot = new Lot(…);lots.add(furtherLot);

• We don’t really need furtherLot:

lots.add(new Lot(…));

89

Chaining method calls

• Methods often return objects

• We often immediately call a method on the returned object:

Bid bid = lot.getHighestBid();Person bidder = bid.getBidder();

• We can use the anonymous object concept and chain method calls:Person bidder = lot.getHighestBid().getBidder();

90

Chaining method calls

String name = lot.getHighestBid().getBidder().getName();

• Each method in the chain is called on the object returned from the previous method call in the chain.

Returns a Bid object from the Lot

Returns a Person object from the Bid

Returns a String object from the Person

91 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Topics (4)

• Iterations• Definite vs. Indefinite vs. Infinite• for-each, for, while loops

92

Iteration• We often want to perform some actions

an arbitrary number of times– e.g. print ALL the file names in the organizer– How many are there?

• Most programming languages include loop statements or iterative control structures to make this possible

• Java has several sorts of loop statement– We will start with its for-each loop

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

93

For-each loop pseudo code

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

for(ElementType element : collection) { loop body}

For each element in collection, do the things in the loop body.

** where element is indeed a variable declaration of type ElementType and the variable is known as the loop variable

loop headerfor keyword

Statement(s) to be repeated

Pseudo-code expression of the actions of a for-each loop

General form of the for-each loop

94

for-eachPROS• easy to use• access to ALL items one-by-one• ability to change the state of the item• terminates automatically• selective filter using if-else statements• actions in body may be complicated with multiple

lines• use on ANY type of collection• abstraction from details of how handling occurs

CONS• no index provided• can NOT stop during looping• definite iteration of ALL items• can NOT remove or add elements during loop• use for collections only• access must be to ALL items in sequence [0 to size-1]

95

Main concepts to be covered

• The difference between iterations:– definite … size – indefinite (unbounded) … 0 -

infinite

• The while loop

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

96

Search tasks are indefinite

• We cannot predict, in advance, how many places/times we have to look

• It may not be any at all (equal 0)

• Although, there may well be an absolute limit (equal ALL)– Checking EVERY possible location

• And INFINITE loops are also possible– Through error or the nature of the task

97

The while loop

• A for-each loop repeats the loop body for each object in a collection

• Sometimes we require more variation than this (and not access every item)

• We could use a boolean condition to decide whether or not to keep going (instead of going to the very end)

• A while loop provides this control

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

98

While loop pseudo code

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

while(loop condition) { loop body}

while we wish to continue, do the things in the loop body

boolean test is truewhile keyword

Statements to be repeated

Pseudo-code expression of the actions of a while loop

General form of a while loop

99

Looking for your keys

while(the keys are missing)

{

look in the next place;

}

while(not (the keys have been found))

{

look in the next place;

}

while(true)

while(!(false))

100

Looking for your keys

boolean searching = true;

while(searching) { if(they are in the next place) {

searching = false; }} Suppose we don’t find

them?Infinite loop

101

for-each == while

public void listAllFiles(){ int index = 0; while(index < files.size()) { String filename = files.get(index); System.out.println(filename); index++; }} Increment index by 1

while the value of index is less than the size of the collection, get and print the next file name, and then increment index

public void listAllFiles(){ for(String filename : files) { System.out.println(filename); }}

102

Elements of the loop

• We have declared an index variable

• The condition must be expressed correctly

• We have to fetch each element

• The index variable must be incremented explicitly

103

while loop search

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

PROS• can stop at any time during looping• indefinite iteration of SOME items using loop

condition• may change collection during loop• use explicit index variable inside and outside of loop• index variable records location of item at all times

CONS• more effort to code• requires index looping variable declaration• maintain looping variable and manually increment• correctly determine loop condition for termination• must .get item using index to access the item• NOT guaranteed to stop with possible infinite loop

104

for-each versus while• for-each

– easier to write– safer because it is guaranteed to stop– access is handled for you

Access ALL items without changing collection

• while– don’t have to process entire collection– doesn’t have to be used with a collection– take care to watch for an infinite loop

Access only SOME items, includes a record of the index location, and also could be used for non-collections

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

105

Searching a collection• A re-occurring fundamental activity

• Applicable beyond collections

• Indefinite iteration because we don’t know exactly where to look

• We must code for both success (stops midway) and failure (after all searched) using an exhausted search

• Either could make the loop condition false to terminate the loop

• Even works if collection is empty

106

Finishing a search

So when do we finish a search?

• No more items to check: index >= files.size()

OR

• Item has been found:found == true found ! searching

107

Continuing a search• With a while loop, we need to state

the condition for continuing

• The loop’s condition will then be the opposite of that for finishing

• Expressions & operators are inverted:

–>= becomes < –or becomes and– true becomes !true

108

Search condition >= becomes <

FINISH search when:• No more items OR Item is found

index >= files.size() || found

CONTINUE search while:• Still more items AND Item is not

found index < files.size() || !found

109

Search condition >= becomes <

FINISH search when:• No more items OR Item is found

index >= files.size() || found

CONTINUE search while:• Still more items AND Item is not

found index < files.size() || !found

110

Search condition OR becomes AND

FINISH search when:• No more items OR Item is found

index >= files.size() || found

CONTINUE search while:• Still more items AND Item is not

found index < files.size() && !found

111

Search condition OR becomes AND

FINISH search when:• No more items OR Item is found

index >= files.size() || found

CONTINUE search while:• Still more items AND Item is not

found index < files.size() && !found

112

Search condition true becomes !true

FINISH search when:• No more items OR Item is found

index >= files.size() || found

CONTINUE search while:• Still more items AND Item is not

found index < files.size() || !found

113

Search condition true becomes !true

FINISH search when:• No more items OR Item is found

index >= files.size() || found

CONTINUE search while:• Still more items AND Item is not

found index < files.size() || !found

114

Searching a collection

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

int index = 0;boolean found = false;while(index < files.size() && !found) { String file = files.get(index); if(file.contains(searchString)) { // We don't need to keep looking. found = true; } else { index++; }}

// Either we searched the whole collection, // or we found it at index.

115

Method findFirst public int findFirst(String searchString){ int index = 0; boolean searching = true;

while(searching && index < files.size()) { String filename = files.get(index); if(filename.contains(searchString)) { // Match found searching = false; // Stop searching } else // Not found here { // Keep searching index++; // Move to next item } }

if(searching) // NO match found { return -1; // Return out-of-bounds } // index for failures else { // Return item index of return index; // where it is found }}

116

Indefinite iteration

• Does the search still work if the collection is empty (but not null)?– Yes! The loop’s body would NOT be

entered in that case.

• Important feature of while:– The body of the while could be

executed zero or more times.

117

While with non-collections// Print all even numbers from 2 to 30

int index = 2;

while(index <= 30)

{

System.out.println(index);

index = index + 2;

}

NOTE: This while loop uses definite iteration, since it is clear from the start exactly how many times the loop will be repeated. But, we could NOT have used a for-each loop, because there is no collection of items.

local variable START: index start

STOP: index end

increment

118 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Topics (5)

• Iterator and iterator• Class vs. Instance

― Variables― Constants― Methods

• main method

119

Iterator type• Third variation to iterate over a

collection

• Uses a while loop and Iterator object

• But NO integer index variable

• Takes advantage of abstraction with use of library class (like for-each)

• import java.util.Iterator;

• Iterator class vs. iterator( ) method

120

Iterator and iterator()

• Collections (e.g. ArrayList) have an iterator() method

• This returns an Iterator object

• Iterator<E> has three methods:

– boolean hasNext()

– E next()

– void remove()

121

Using an Iterator object

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Iterator<ElementType> it = myCollection.iterator();while(it.hasNext()) { call it.next() to get the next object do something with that object}

java.util.Iteratorreturns an Iterator

object

• Declare variable it as type Iterator of ElementType

• Use iterator() method of collection (e.g. ArrayList) and assign the returned Iterator object to variable it

• it object *indexes* to the first element in the collection

• it.hasNext() checks to see if there is an object at the index

• it.next() will get the actual object and advance the index

122

Iterator object example java.util.Iterator

returns an Iterator object

public void listAllFiles(){ Iterator<Track> it = files.iterator(); while(it.hasNext()) { Track tk = it.next(); System.out.println(tk.getDetails()); }}

• Prints ALL tracks in the collection (like while & for-each)

• Still use while … BUT do not need an index variable

• Iterator keeps track of current location, if there are any more items (hasNext) and which one to return (next)

• Iterator.next returns next item AND moves past that item (can NOT go back)

123 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Iterator object

An iterator, after one iteration, pointing to the next item to be

processed.

124

Iterator mechanics

Objects First with Java

125 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

myList of type List

:Element

myList:List

:Element :Element:Element

126 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

:Element

myList:List

:Element :Element

:Iterator

myList.iterator()

:Element

127 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

:Element :Element :Element

:Iterator

hasNext()? ✔next()

Element e = iterator.next();

:Element

:Iterator

myList:List

128 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

:Element :Element :Element

hasNext()? ✔next()

:Element

:Iterator :Iterator

myList:List

129 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

:Element :Element :Element

hasNext()? ✔next()

:Element

:Iterator :Iterator

myList:List

130 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

:Element :Element :Element

hasNext()? ✔next()

:Element

:Iterator :Iterator

myList:List

131 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

:Element :Element :Element

hasNext()? ✗

:Element

:Iterator

myList:List

132 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Track example private ArrayList<Track> tracks;

:Track

tracks:ArrayList<Track>

:Track :Track:Track

:Track

tracks:ArrayList<Track>

:Track :Track:Track

0 1 2 3

Each Track has:•String artist•String title•String filename

133 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Track example

public void listAllFiles(){ Iterator<Track> it = tracks.iterator(); while(it.hasNext()) { Track t = it.next(); System.out.println(t.getDetails()); }}

:Track

tracks:ArrayList<Track>

:Track :Track:Track

0 1 2 3

134 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Track example Iterator<Track> it = tracks.iterator();

:Track

tracks:ArrayList<Track>

:Track :Track:Track

0 1 2 3

it:Iterator

• Use the iterator method of the ArrayList class to get an Iterator object for tracks

• Assigns the Iterator object to the local variable named it

135 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Track example while(it.hasNext())

:Track

tracks:ArrayList<Track>

:Track :Track:Track

0 1 2 3

it:Iterator it.hasNext()?

true

136

Track example Track t = it.next();

:Track

tracks:ArrayList<Track>

:Track :Track:Track

0 1 2 3

it:Iterator

it.next( ) will:

1)Return element(object) at it

2)Move to the next elementt

= it:Iterator

137

Track example System.out.println(t.getDetails());

:Track

tracks:ArrayList<Track>

:Track :Track:Track

0 1 2 3

t.getDetails( ) makes an external method call to the Track class with the t object to print out the String artist, title and filename fields.

t

it:Iterator

138

Track example

:Track

tracks:ArrayList<Track>

:Track :Track:Track

0 1 2 3

while(it.hasNext()) { Track t = it.next(); System.out.println (t.getDetails());}

t

it:Iterator

Exit 1st iteration of while bodyand repeat loop

X

139

Track example

:Track

tracks:ArrayList<Track>

:Track :Track:Track

0 1 2 3

while(it.hasNext()) { Track t = it.next(); System.out.println (t.getDetails());}

t

it:Iterator

2nd iteration

true

=

hasNextnext

140

Track example

:Track

tracks:ArrayList<Track>

:Track :Track:Track

0 1 2 3

while(it.hasNext()) { Track t = it.next(); System.out.println (t.getDetails());}

t

it:Iterator

Exit 2nd iteration

X

141

Track example

:Track

tracks:ArrayList<Track>

:Track :Track:Track

0 1 2 3

while(it.hasNext()) { Track t = it.next(); System.out.println (t.getDetails());}

t

it:Iterator

3rd iteration

=

142

Track example

:Track

tracks:ArrayList<Track>

:Track :Track:Track

0 1 2 3

while(it.hasNext()) { Track t = it.next(); System.out.println (t.getDetails());}

t

it:Iterator

Exit 3rd iteration

X

143

Track example

:Track

tracks:ArrayList<Track>

:Track :Track:Track

0 1 2 3

while(it.hasNext()) { Track t = it.next(); System.out.println (t.getDetails());}

t

it:Iterator

4th iteration

=

144

Track example

:Track

tracks:ArrayList<Track>

:Track :Track:Track

0 1 2 3

while(it.hasNext()) { Track t = it.next(); System.out.println (t.getDetails());}

t

it:Iterator

Exit 4th iteration

X

145

Track example

:Track

tracks:ArrayList<Track>

:Track :Track:Track

0 1 2 3

while(it.hasNext()) { Track t = it.next(); System.out.println (t.getDetails());}

it:Iterator

5th iteration

false hasNext

NO more elements,so the while loop

STOPS!!

146

Index versus Iterator• Ways to iterate over a collection:

– for-each loop (definite iteration)

• Process every element w/o removing an element

– while loop (indefinite iteration)

• Use if we might want to stop part way through

• Use for repetition that doesn't involve a collection

– Iterator object (indefinite iteration)

• Use if we might want to stop part way through

• Often used with collections where indexed access is not very efficient, or impossible

• Available for all collections in the Java class library

• Use to remove from a collection

• Iteration is important programming pattern

147

Removing elements

• Impossible with a for-each loop

– Trying to remove( ) during an iteration causes ConcurrentModificationException

• while loop possible, but NOT recommended

– Easy to get indices wrong when removing

• Proper solution is use of Iterator with while

for each track in the collection{ if track.getArtist( ) is the out-of-favor artist: collection.remove(track)}

148

Removing from a collection

Iterator<Track> it = tracks.iterator();while(it.hasNext()) { Track t = it.next(); String artist = t.getArtist(); if(artist.equals(artistToRemove)) { it.remove(); }}

Use the Iterator’s remove method.

• Does NOT use tracks collection variable in the loop body

• Must use Iterator’s remove( ) and NOT the ArrayList’s

• Iterator’s can only remove the last retrieved using next

• But it ALLOWS the element to be removed during loop

• Iterator abstracts removal and keeps iteration in sync

149

Removing from a collection

while(it.hasNext()) { Track t = it.next(); String artist = t.getArtist(); if(artist.equals(artistToRemove)) { it.remove(); }}

:Track

tracks:ArrayList<Track>

:Track :Track:Track

0 1 2 3

t

it:Iterator=

150

Removing from a collection

:Track

tracks:ArrayList<Track>

:Track :Track:Track

0 1 2 3

t

it:Iterator=

Iterator remove method will:•remove the LAST element that returned by Iterator•handle indices of remaining elements (abstraction)•keeps iteration properly in sync•BUT limited to removing only last element

remove

X

151

Review• Use an ArrayList to store an arbitrary

number of object in a collection

• Loop statements allow a block of statements to be repeated

• for-each iterates over a whole collection

• while loop allows the repetition to be controlled by a boolean expression

• All collection classes provide Iterator objects that provide sequential access and modification to a whole collection

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

152

The for loop• The two variations of the for loop

(use definite iteration): > for-each > for

• The for loop is often used:– to iterate a fixed number of times– with a variable that changes a fixed

amount on each iteration

• The for loop is similar to while loop

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

153

for loop pseudo-code

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

for(initialization; condition; post-body action) { statements to be repeated}

General form of the for loop

Equivalent in while-loop form

initialization;while(condition) { statements to be repeated post-body action}

154

A Java example

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

for(int hour = 0; hour < hourCounts.length; hour++) { System.out.println(hour + ": " + hourCounts[hour]);}

int hour = 0;while(hour < hourCounts.length) { System.out.println(hour + ": " + hourCounts[hour]); hour++;}

for loop version

while loop version

155

Practice

• Given an array of numbers, print out all the numbers in the array using a for loop:

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

int[] numbers = { 4, 1, 22, 9, 14, 3, 9};

for ...

156

Practice

• Given an array of numbers, print out all the numbers in the array using a for loop:

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

int[] numbers = { 4, 1, 22, 9, 14, 3, 9};

for(int num = 0; num < numbers.length; num++){ System.out.println(numbers[num]);}

157

Practice• Fill an array with the first 25 numbers in the

Fibonacci sequence:

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

int[] fib = new int[25];

fib[0] = 0;fib[1] = 1;

for ...

0 1 1 2 3 5 8 13 21 34 ...

158

Practice• Fill an array with the first 25 numbers in the

Fibonacci sequence:

int[] fib = new int[25];

fib[0] = 0;fib[1] = 1;

for(int num = 2; num < fib.length; num++){ fib[num] = fib[num - 1] +

fib[num - 2];}

0 1 1 2 3 5 8 13 21 34 ...

159

for loop with flexibilityPrint multiples of 3 that are below 40

• Start at any elementfor(int num = 3; num < 40; num = num + 3) { System.out.println(num);}

• End at any elementfor(int num = 3; num < 40; num = num + 3) { System.out.println(num);}

• Bigger steps of larger incrementsfor(int num = 3; num < 40; num = num + 3) { System.out.println(num);}

160

Arrays and for-each loops• Can we use for-each to access EVERY

element in the array collection without adding/removing any elements? YES

• for-each loops may be used on arrays:

for(int value : hourCounts) { System.out.println(num);}

• However, there is NO index counter to use if location of element is needed

161

for loops and iterators• Can we use a for loop with an Iterator to

access every element in a collection and remove selective elements? YES

• A special use of for loop may be used:for(Iterator<Track> it = tracks.iterator();

it.hasNext(); )

{ Track t = it.next(); if(t.getArtist().equals(artist)) { it.remove(); }}

• There is NO post-body action in the loop header, because the increment is being taken care of by it.next in the loop body

(But, the semicolon is still necessary)

162

for

PROS• may be used on a collection, non-collection or array

• flexibility on start/end item and increment amount

• ability to add/remove/change the item during the loop

• access to loop counter (variable) is provided

• increment is completed automatically after each iteration

• may even be used with Iterators

CONS• definite iteration so number of elements MUST be

known

• access to items in sequence [start to end]

163

Review• Arrays:

– are appropriate where a fixed-size collection is required

– use a special syntax (no methods)

• for loops:– are used when an index variable is

required– offer an alternative to while loops when

the number of repetitions is known– Used with a regular step size

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

164

Which loop should I use?• for-each:

– iterate over ALL elements in a collection– no adding or removing of any elements– no loop counter (index) is needed

• for:– definite iteration with known start and end– increment amount may be flexible (> 1)– loop counter (index) is needed

• while:– indefinite iteration with unknown # of iterations– loop end can be determined by some

condition(s)

> Non-collections:• use a for or while loop

> Removing elements:• (if examining ALL elements ) use for with Iterator • (if stopping before the collection ends) use while

165

Class variables

• A class variable is shared between ALL instances/objects of the class

• It is a field stored in the class and exists independent of any instances

• Designated by the static keyword

• Public static variables are accessed via the class name (NOT object name)– Thermometer.boilingPoint

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

166

Constants

• A variable, once set, can have its value fixed

• Designated by the final keyword– final int max = list.size();

• Final fields must be set in their declaration or the constructor

• Combining static and final is common

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

167

Class constants

• static: class variable

• final: constantprivate static final int gravity = 3;

• Public visibility is less of an issue with final fields

• Upper-case names often used for class constants:

public static final int BOILING_POINT = 100;

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

168

Class constantsprivate static final int GRAVITY = 3;

private int xPosition;private int yPosition;

169

Class Methods

• So far, only used instance methods

– invoked on an instance(object) of a class

• However, class methods are different

– may be invoked WITHOUT a class object

• Similar to class variables in that the class methods BELONG to the class

– having the class is enough to invoke it

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

170

Class Methods• Defined by adding static keyword in

front of the type name in the header public class Calendar {

public static int getNumberOfDaysThisMonth() { …

} …

• Such a method can then be called by specifying the class name

int days = Calendar.getNumberOfDaysThisMonth();

There is NO object so the name of class is used before the dot

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

171

The main method

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

• The java system will always execute a method called main with a certain signature:

public static void main(String[] args){

...}

• If compiling and executing from the command line, then the main method must exist!

172

The main method

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

• main must exist

• main must be public

• main must be static (class method)

• main must have a String[] parameter

• Only main can be invoked

Example of a class method(may be invoked without an class instance)

173

Main methodexample

• Consider placing in a separate class, containing just this

• The main method should– create an object– call the first method

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

public static void main(String[] args){ Game game = new Game(); game.play();}

174

BlueJ projects• A BlueJ project is stored in a

directory on disk

• A BlueJ package is stored in several different files

• Some files store the source code, some store the compiled code, some store additional information

• BlueJ uses standard Java format for some files and adds some additional files with extra information

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

175

The BlueJ directory structure

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

UserInterfaceUserInterface

CalcEngineCalcEngine

CalculatorCalculator

project: calculator c:\bluej\calculator\Calculator.javaCalculator.classCalculator.ctxtCalcEngine.javaCalcEngine.classCalcEngine.ctxtpackage.bluejUserInterface.javaUserInterface.classUserInterface.ctxt

176

The BlueJ file structure

• package.bluej – the package file. Contains information about classes in the package. One per package (project).

• *.java - standard Java source file (text). One per class.

• *.class - standard Java code file. One per class.

• *.ctxt - BlueJ context file. Contains extra information for a class. One per class.

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

177

Standard Java files

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

• source files: *.javaJava source files contain the source code in readable form, as typed in by the programmer.

• source files: *.javaJava source files contain the source code in readable form, as typed in by the programmer.

• class files: *.classJava class files contain byte code (a machine readable version of the class). They are generated by the compiler from the source file.

• class files: *.classJava class files contain byte code (a machine readable version of the class). They are generated by the compiler from the source file.

178

The edit-compile-execute Cycle

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

source file

011010

110101

010001

class file011010

110101

1001

10

1

0111

0110110

1

1

editorcompiler(javac)

virtual machine(java)

179

Editing

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

• A file can be edited in any text editor

– Notepad, emacs, jEdit, PFE, vi, …

• Don't use Microsoft Word: by default, Word does not save in text format

– Includes formatting (i.e. fonts, shapes, …)

• Make sure to save with a .java file extension before compiling!

180

Command line invocation

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

• Compilation and execution of Java in JDK are done from a command line

–Windows: DOS shell

–Unix: Unix shell

• Must make sure that commands for compiler (javac) and runtime (java) are in the command path

181

Compiling• JDK compiler: javac

• To invoke: javac ClassName.javacompiles source file and all classes that it depends on

• To find commands in path … either:? Change directory to location of commands

– cd C:\Program Files\Java\jdk1.7.0_65\bin– javac ClassName.java

? Ensure commands are in your command PATH– Control Panel -> System -> Advanced -> Environment Variables -> PATH

– Add “C:\Program Files\Java\jdk1.7.0_65\bin”– javac ClassName.java

• Creates byte file: ClassName.class

182

Compilererror messages

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

C:\bluej\project> javac ClassName.java

ClassName.java:22: ';' expected.

private Parser parser

^

1 error

C:\bluej\project>

The programmer has to open the file in the editor, find the line number, fix the error and recompile.

183

Execution

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

C:\bluej\project> java ClassName

• java starts the Java virtual machine

• The named class is loaded and execution is started

• Other classes are loaded as needed

• Only possible if class has been compiled

184

Problem Execute what?

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

• If we try:C:\bluej\project> java ClassName

• We get a compiler error:Exception in thread "main" java.lang.NoSuchMethodError: main

• The problem: there is NO instance object How does the system know which method to execute?