ioop review 2 - Rowan University
Download
Report
Transcript ioop review 2 - Rowan University
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)
Base-10
10 digits: 0 - 9 (decimal)
place values: 10x
103
1000
102
100
101
10
100
1
i.e. 6543
6 x 103
6000
5 x 102
500
4 x 101
40
3 x 100
3
6000 + 500 + 40 + 3 = 6543
3
Base-2
2 digits: 0 - 1 (binary)
place values: 2x
23
8
0 x 23
0
22
4
21
2
i.e. 0101
(binary)
2
1
1x2
4
0x2
0
20
1
1 x 20
1
0 + 4 + 0 + 1 = 5 (decimal)
4
Bits & Bytes
bit = binary digit (0-1)
byte = 8 bits
27
128
26
64
25
32
24
16
23
8
22
4
21
2
20
1
i.e. 00110101 (binary)
0
27
0
0
26
0
1
25
32
1
24
16
0
23
0
1
22
4
0
21
0
1
20
1
0 + 0 + 32 + 16 + 0 + 4 + 0 + 1 = 53
(decimal)
5
32-bit vs. 64-bit
Machines
• system architecture
• instruction set
• machine language
x86 = 32-bit
x64 = 64-bit
6
Class diagram
(static view)
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
7
Object diagram
(dynamic view)
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
8
Primitive types
vs. Object types
SomeObject obj;
int i;
32
object type
primitive type
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
9
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
10
Primitive types
vs. Object types
ObjectType a;
ObjectType b;
b = a;
int a;
int b;
32
32
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
11
Java operators
12
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”);
13
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
14
Java
relational operators
Boolean result
Tests equality …. not identity!!
15
Java
logical operators
&&
||
^
BINARY
and
or
exclusive or
UNARY
!
not
16
Logic operators
for boolean values
Operands
&&
||
^
T
T
T
T
F
T
F
F
T
T
F
T
F
T
T
F
F
F
F
F
Which are examples of short-circuit operators?17
Logic operators
for boolean values
Operands
&&
||
^
T
T
T
T
F
T
F
F
T
T
F
T
F
T
T
F
F
F
F
F
18
What is the result?
35 / 9 == 4
false
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
19
Internal and external
method calls
• Internal method call
methodName();
No variable name is required
• External method call
object.methodName();
Uses dot (.) operator
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
20
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.
21
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
22
null vs. void
null
• 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
23
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
arbitrary
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
24
A basic enumerated type
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
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
25
Using enumerated types
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);
}
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
26
String type
commandWord
data type
using enum
CommandWord type
commandWord
if(commandWord.equals("help")) {
printHelp();
}
else if(commandWord.equals("go")) {
goRoom(command);
}
else if(commandWord.equals("quit")) {
wantToQuit = quit(command);
}
public enum CommandWord
{
GO, QUIT, HELP, UNKNOWN
}
if(commandWord == CommandWord.HELP) {
printHelp();
}
else if(commandWord == CommandWord.GO) {
goRoom(command);
}
else if(commandWord == CommandWord.QUIT) {
wantToQuit = quit(command);
}
27
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;
}
28
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:
simple type
int
float
char
...
wrapper class
Integer
Float
Character
...
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
29
Wrapper classes
wrap the value
int i = 18;
Integer iwrap = new Integer(i);
…
unwrap it
int value = iwrap.intValue();
In practice, autoboxing and
unboxing mean we don't often
have to do this explicitly
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
30
Autoboxing and unboxing
private ArrayList<Integer> markList;
…
public void storeMark(int mark)
{
markList.add(mark);
autoboxing
}
int firstMark = markList.remove(0);
unboxing
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
31
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
32
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
33
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
34
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
35
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
36
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
37
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
38
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
39
String concatenation
• 4+5
9
overloading
• "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
40
What is the output?
• System.out.println(5 + 6 + "hello");
11hello
• System.out.println("hello" + 5 + 6);
hello56
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
41
String equality
if(input == "bye") {
...
}
tests identity
if(input.equals("bye")) {
...
tests equality
}
** Always use .equals( )
for text equality
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
42
Identity vs equality 1
Other (non-String) objects:
:Person
:Person
“Fred”
“Jill”
person1
person2
person1 = = person2 ?
43
Identity vs equality 1
Other (non-String) objects:
:Person
:Person
“Fred”
“Jill”
person1
person2
person1 = = person2 ?
false
44
Identity vs equality 2
Other (non-String) objects:
:Person
“Fred”
person1
:Person
same
value
“Fred”
person2
person1 = = person2 ?
45
Identity vs equality 2
Other (non-String) objects:
:Person
“Fred”
person1
:Person
same
value
“Fred”
person2
person1 = = person2 ?
false
46
Identity vs equality 3
Other (non-String) objects:
:Person
:Person
“Fred”
“Fred”
person1
person2
person1 = = person2 ?
47
Identity vs equality 3
Other (non-String) objects:
:Person
:Person
“Fred”
“Fred”
person1
person2
person1 = = person2 ?
true
48
Identity vs equality (Strings)
String input = reader.getInput();
if(input = = "bye") {
= = tests identity
...
}
:String
"bye"
input
==
:String
"bye"
?
(may be) false!
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
49
Identity vs equality (Strings)
String input = reader.getInput();
if(input.equals("bye")) {
.equals tests
equality
...
}
:String
"bye"
input
:String
.equals
?
"bye"
true!
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
50
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
51
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( )
Beware: strings are immutable!
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
52
Immutable String
String method
String toUpperCase()
Incorrect use
input.toUpperCase();
Correct use
input = input.toUpperCase();
if(input.toUpperCase().contains())
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
53
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
54
String .split
String[ ] 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
55
Using regex
String.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
AND
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
56
Replaces ALL (one or more) white spaces with a SINGLE space
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
57
Declaring array variables
• 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 declarations
int hourCounts;
// single int variable
int[] hourCounts; // int-array variable
hourCounts = new int[24];
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
58
Creating an array object
Array variable declaration
public class LogAnalyzer
— does not contain size
{
private int[] hourCounts;
private LogfileReader reader;
Array object creation
public LogAnalyzer()
— specifies size
{
hourCounts = new int[24];
reader = new LogfileReader();
}
...
}
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
59
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
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
60
The hourCounts array
private int[] hourCounts;
hourCounts = new int[24];
=
new int[24];
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
61
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
62
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
63
Standard array use
private int[] hourCounts;
private String[] names;
declaration
...
hourCounts = new int[24];
names = new String[10];
creation
...
hourcounts[i] = 0;
hourcounts[i]++;
System.out.println(hourcounts[i]);
use
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
64
Array literals
{3, 15, 4, 5, …}
• The size is inferred from the data:
declaration,
creation and
initialization
private int[ ] numbers = { 3, 15, 4, 5 };
• Array literals in this form can only be
used in declarations and NOT like this:
XX
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
65
Array length
private int[] numbers = {
3, 15, 4, 5 };
int n = numbers.length;
NO brackets!
NO parentheses!
• 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
66
Topics (3)
•
•
•
•
•
•
•
•
ArrayList
HashSet
HashMap
Collection constructor copying
Random
Collections.shuffle()
Anonymous Objects
Chaining
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
67
Generic classes
for 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
68
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 to
myMusic:
MusicOrganizer
files
:ArrayList<String>
new
69
Key methods of class
ArrayList
The ArrayList class implements
list functionality with methods for
the following operations:
—
—
—
—
add(item)
remove(item)
get(index)
size()
70
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
71
Adding a third file
• 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
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
72
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
73
ArrayList Index numbering
• 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]
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
74
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
files.remove(1);
• 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
75
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, …
76
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
77
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
}
Compare
with code
for an
ArrayList!
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
78
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
79
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
80
Using maps
in a telephone directory
A map with strings as keys and values:
name and telephone number
:HashMap
"Charles Nguyen"
"(531) 9392 4587"
"Lisa Jones"
"(402) 4536 4674"
"William H. Smith"
"(998) 5488 0123"
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
81
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
82
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
83
New COPY of
an existing ArrayList
ArrayList<Track> copiedList = new ArrayList<Track>(tracks);
• 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
84
Random library class
import java.util.Random;
Random rand = new Random();
int index = rand.nextInt(size);
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
85
Using Random
• The library class Random can be used
to generate random numbers
import java.util.Random;
...
Random rand = new Random();
...
int num = rand.nextInt();
int value = 1 + rand.nextInt(100);
int index = rand.nextInt(list.size());
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
86
Collections library class
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
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
87
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(…));
88
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();
89
Chaining method calls
• Each method in the chain is called on
the object returned from the
previous method call in the chain.
String name =
lot.getHighestBid().getBidder().getName();
Returns a Bid object from the Lot
Returns a Person object from the Bid
Returns a String object from the Person
90
Topics (4)
• Iterations
• Definite vs. Indefinite vs. Infinite
• for-each, for, while loops
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
91
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
92
For-each loop pseudo code
General form of the for-each loop
for keyword
loop header
for(ElementType element : collection) {
loop body
}
Statement(s) to be repeated
Pseudo-code expression of the actions of a for-each loop
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
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
93
for-each
PROS
•
•
•
•
•
•
•
•
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]
94
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
95
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 task96
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
97
While loop pseudo code
General form of a while loop
while keyword
boolean test is true
while(loop condition) {
Statements to be repeated
loop body
}
Pseudo-code expression
of the actions of a while loop
while we wish to continue, do the things in the loop body
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
98
Looking for your keys
while(true)
while(the keys are missing)
{
look in the next place;
}
while(!(false))
while(not (the keys have been found))
{
look in the next place;
}
99
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
100
for-each == while
public void listAllFiles()
{
for(String filename : files) {
System.out.println(filename);
}
}
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
101
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
102
while loop search
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
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
103
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
104
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
105
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
106
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
107
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
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
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
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
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
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
Searching a collection
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.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
114
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
}
}
115
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.
116
While with non-collections
// Print all even numbers from 2 to 30
local variable
START: index start
int index = 2;
STOP: index end
while(index <= 30)
{
System.out.println(index);
index = index + 2;
increment
}
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.
117
Topics (5)
• Iterator and iterator
• Class vs. Instance
― Variables
― Constants
― Methods
• main method
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
118
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
119
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()
120
Using an Iterator object
java.util.Iterator
returns an Iterator object
Iterator<ElementType> it = myCollection.iterator();
while(it.hasNext()) {
call it.next() to get the next object
do something with that 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
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
121
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)
122
Iterator object
An iterator, after one
iteration, pointing to the
next item to be
processed.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
123
Iterator mechanics
Objects First with Java
124
myList:List
:Element
myList of type List
:Element
:Element
:Element
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
125
myList:List
myList.iterator()
:Element
:Element
:Element
:Element
:Iterator
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
126
myList:List
:Element
:Element
:Element
:Element
:Iterator:Iterator
hasNext()?
✔
next()
Element e = iterator.next();
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
127
myList:List
:Element
:Element
:Iterator
:Element
:Element
:Iterator
hasNext()?
✔
next()
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
128
myList:List
:Element
:Element
:Element
:Iterator
:Element
:Iterator
hasNext()?
✔
next()
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
129
myList:List
:Element
:Element
:Element
:Element
:Iterator
hasNext()?
:Iterator
✔
next()
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
130
myList:List
:Element
:Element
:Element
:Element
:Iterator
hasNext()?
✗
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
131
Track example
private ArrayList<Track> tracks;
tracks:
ArrayList<Track>
:Track
:Track
:Track
tracks:
ArrayList<Track>
0
:Track
:Track
1
2
3
:Track
:Track
Each Track has:
•String artist
•String title
•String filename
:Track
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
132
Track example
tracks:
ArrayList<Track>
0
:Track
:Track
1
2
3
:Track
:Track
public void listAllFiles()
{
Iterator<Track> it = tracks.iterator();
while(it.hasNext())
{
Track t = it.next();
System.out.println(t.getDetails());
}
}
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
133
Track example
Iterator<Track> it = tracks.iterator();
tracks:
ArrayList<Track>
0
:Track
it
:Iterator
1
:Track
2
3
:Track
:Track
• 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
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
134
Track example
while(it.hasNext())
tracks:
ArrayList<Track>
0
:Track
it
:Iterator
:Track
1
2
3
:Track
:Track
it.hasNext()?
true
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
135
Track example
Track t = it.next();
tracks:
ArrayList<Track>
0
:Track
=
t
:Track
1
2
3
:Track
:Track
it.next( ) will:
it
it
:Iterator
:Iterator
1)Return element(object) at it
2)Move to the next element
136
Track example
System.out.println(t.getDetails());
tracks:
ArrayList<Track>
0
:Track
:Track
it
:Iterator
t
1
2
3
:Track
:Track
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.
137
Track example
Exit 1st iteration of while body
and repeat loop
tracks:
ArrayList<Track>
0
:Track
:Track
it
:Iterator
X
t
1
2
3
:Track
:Track
while(it.hasNext())
{
Track t = it.next();
System.out.println
(t.getDetails());
}
138
Track example
2nd iteration
tracks:
ArrayList<Track>
0
:Track
1
:Track
2
3
:Track
:Track
next
hasNext
=
t
it
:Iterator
true
while(it.hasNext())
{
Track t = it.next();
System.out.println
(t.getDetails());
}
139
Track example
Exit 2nd iteration
tracks:
ArrayList<Track>
0
:Track
:Track
it
:Iterator
X
t
1
2
3
:Track
:Track
while(it.hasNext())
{
Track t = it.next();
System.out.println
(t.getDetails());
}
140
Track example
3rd iteration
tracks:
ArrayList<Track>
0
:Track
2
:Track
=
t
1
it
:Iterator
3
:Track
:Track
while(it.hasNext())
{
Track t = it.next();
System.out.println
(t.getDetails());
}
141
Track example
Exit 3rd iteration
tracks:
ArrayList<Track>
0
:Track
1
2
:Track
it
:Iterator
X
t
3
:Track
:Track
while(it.hasNext())
{
Track t = it.next();
System.out.println
(t.getDetails());
}
142
Track example
4th iteration
tracks:
ArrayList<Track>
0
:Track
1
2
:Track
while(it.hasNext())
{
Track t = it.next();
System.out.println
(t.getDetails());
}
3
:Track
:Track
=
it
:Iterator
t
143
Track example
Exit 4th iteration
tracks:
ArrayList<Track>
0
:Track
1
2
:Track
while(it.hasNext())
{
Track t = it.next();
System.out.println
(t.getDetails());
}
3
:Track
:Track
it
:Iterator
X
t
144
Track example
5th iteration
tracks:
ArrayList<Track>
0
:Track
:Track
false
while(it.hasNext())
{
Track t = it.next();
System.out.println
(t.getDetails());
}
1
2
3
:Track
:Track
hasNext
it
:Iterator
NO more elements,
so the while loop STOPS!!
145
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
146
Removing elements
for each track in the collection
{
if track.getArtist( ) is the out-of-favor artist:
collection.remove(track)
}
• 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
147
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 sync148
Removing from a collection
tracks:
ArrayList<Track>
0
:Track
=
t
1
:Track
it
:Iterator
2
3
:Track
:Track
while(it.hasNext())
{
Track t = it.next();
String artist = t.getArtist();
if(artist.equals(artistToRemove))
{
it.remove();
}
149
}
Removing from a collection
tracks:
ArrayList<Track>
0
:Track
1
X
:Track
2
3
:Track
:Track
remove
=
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
150
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
151
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
152
for loop pseudo-code
General form of the for loop
for(initialization; condition; post-body action) {
statements to be repeated
}
Equivalent in while-loop form
initialization;
while(condition) {
statements to be repeated
post-body action
}
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
153
A Java example
for loop version
for(int hour = 0; hour < hourCounts.length; hour++) {
System.out.println(hour + ": " + hourCounts[hour]);
}
while loop version
int hour = 0;
while(hour < hourCounts.length) {
System.out.println(hour + ": " + hourCounts[hour]);
hour++;
}
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
154
Practice
• Given an array of numbers, print out all the
numbers in the array using a for loop:
int[] numbers = { 4, 1, 22, 9, 14, 3, 9};
for ...
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
155
Practice
• Given an array of numbers, print out all the
numbers in the array using a for loop:
int[] numbers = { 4, 1, 22, 9, 14, 3, 9};
for(int num = 0; num < numbers.length; num++)
{
System.out.println(numbers[num]);
}
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
156
Practice
• Fill an array with the first 25 numbers in
the Fibonacci sequence:
0 1 1 2 3 5 8 13 21 34 ...
int[] fib = new int[25];
fib[0] = 0;
fib[1] = 1;
for ...
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
157
Practice
• Fill an array with the first 25 numbers in
the Fibonacci sequence:
0 1 1 2 3 5 8 13 21 34 ...
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];
}
158
for loop with flexibility
Print multiples of 3 that are below 40
• Start at any element
for(int num = 3; num < 40; num = num + 3) {
System.out.println(num);
}
• End at any element
for(int num = 3; num < 40; num = num + 3) {
System.out.println(num);
}
• Bigger steps of larger increments
for(int num = 3; num < 40; num = num + 3) {
System.out.println(num);
}
159
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
160
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) 161
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]
162
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
163
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
164
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
165
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
166
Class constants
• static: class variable
• final: constant
private 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
167
Class constants
private static final int GRAVITY = 3;
private int xPosition;
private int yPosition;
168
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
169
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
170
The main method
• 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!
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
171
The main method
• 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
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
172
Main method
example
public static void main(String[] args)
{
Game game = new Game();
game.play();
}
• 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
173
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
174
The BlueJ directory structure
project: calculator
Calculator
UserInterface
CalcEngine
c:\bluej\calculator\
Calculator.java
Calculator.class
Calculator.ctxt
CalcEngine.java
CalcEngine.class
CalcEngine.ctxt
package.bluej
UserInterface.java
UserInterface.class
UserInterface.ctxt
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
175
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
176
Standard Java files
• source files: *.java
Java source files contain the source code
in readable form, as typed in by the
programmer.
• class files: *.class
Java class files contain byte code (a
machine readable version of the class).
They are generated by the compiler from
the source file.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
177
The edit-compile-execute
Cycle
source file
class file
011010
110101
010001
011010
110101
1001
10
1
0111
0110110
editor
compiler
(javac)
virtual machine
(java)
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
178
Editing
• 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!
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
179
Command line invocation
• 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
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
180
Compiling
• JDK compiler: javac
• To invoke: javac ClassName.java
compiles 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
181
Compiler
error messages
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.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
182
Execution
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
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
183
Problem
Execute what?
• 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?
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
184