Transcript Slide 1

Java Programming
Week 1: Java Fundamental Revision
(Text book: ch1, ch2, ch3, ch4)
Course Introduction

Course Coordinator


Lily D. Li
Course Resources

Website (contains course profile, slides, study
guide including tuts tasks and news)


http://webfuse.cqu.edu.au/Courses/2008/T2/COIT11134/
Text book
Big Java, Cay Horstmann, 3nd Edition
COIT11134-Java Programming
2
Delivery Model

External Students


Textbook, Slides, Study Guide, online forum and
mailing lists
Internal Students



Above plus
2 hours lecture per week
2 hours lab per week
COIT11134-Java Programming
3
Course Structure
1.
2.
3.
4.
5.
6.
Java Revision (Java data types, object,
class, JDK)
Revision (decision and iteration), instance
methods and static method
Interface and Polymorphism
Inheritance
Graphic User Interface
Array and ArrayList
COIT11134-Java Programming
4
Course Structure cont.
7.
8.
9.
10.
11.
12.
Sorting and Searching
Sorting and Searching
Input/Ourput, Exception handling, Files
and Streams
Object-Oriented Design
Object-Oriented Design
Final revision
COIT11134-Java Programming
5
Assessment
Assignment 1:

GUI, Event Handling, Exception Handling
(Week 6,
15%)
Assignment 2:

Object Sorting
(Week 11, 20%)
Final exam:

All topics covered, 65%
Pass criteria:
50% plus overall AND 50% final exam
COIT11134-Java Programming
6
Week 1: Learning Objectives


Familiarise yourself with editing, compile and run
Java programs with TextPad if you are not
confident
Review topics in Chapter 1, Chapter 2, Chapter
3, Chapter 4 of the text book.
COIT11134-Java Programming
7
The Java Programming Language

Principles of Java






Simple to learn (API)
Safe to use
Platform-Independent (written once, run
everywhere) (JVM)
Rich Library Resources
Designed for the Internet
Apply to smallest embedded systems and largest
enterprise-wide application
COIT11134-Java Programming
8
Three types of Java programs



Java Applications
Run stand alone, any size, run from command line
or a GUI
Java Applets
Run in Java-enabled web browsers, launched from
HTML files
Java Servlets
Similar to Applets, generate contents for web page
(HTML doc), run in Java-enabled web server
COIT11134-Java Programming
9
Java Examples

A Java Application Example
COIT11134-Java Programming
10
Java Examples

A Java Applet Example


http://java.sun.com/applets/jdk/1.4/demo/apple
ts/SortDemo/example1.html
A Java Servlet Example

http://forum.java.sun.com/forum.jspa?forumID
=31
(In many J2EE application, online forum,
registration, normally need to operate on
databases)
COIT11134-Java Programming
11
Questions

How long would it take to learn the entire
Java Library?
COIT11134-Java Programming
12
Questions

How long would it take to learn the entire
Java Library?


No one person can learn the entire library, it is too
large.
It is still growing
COIT11134-Java Programming
13
The J2SE SDK
“The Java 2 Standard Edition, Standard Development Kit
(J2SE SDK) provides a complete environment for
application development on desktops and servers” (Sun,
2005).
COIT11134-Java Programming
14
The J2SE SDK Cont…

For this subject you will need

The recent version of the J2SE SDK, such as





J2SE SDK Java 6 or later
The previous Java 5 is also good enough for the
course
TextPad – a Text editor with Java compiling, execution built-in
You should have above software and environment
configured in the prerequisites course, if not, please do it in
week 1
If you are using university labs for your study, the software
is ready on campus labs.
COIT11134-Java Programming
15
Development Environment

Java programs can be developed, compiled
and executed in either




A Console Window (DOS Command Window)
or
An Integrated Development Environment (IDE) like Eclipse
or
Some development tools with Java built-in like TextPad
For this course, any environments are allowed to be
used, TextPad is preferred
COIT11134-Java Programming
16
A Simple Program Structure
public class HelloWorld
{
public static void main (String[ ] args)
{
System.out.println(“Hello, World!”);
}
}
main method is an entry of an Java application. It must be declared
as: public static void main (String[ ] args)
COIT11134-Java Programming
17
The Compilation Process
COIT11134-Java Programming
18
Types and Variables


Every value has a type
Variables



Store values
Can be used in place of the objects they store
Variable declaration and initialization
String greeting = "Hello, World!";
int luckyNumber = 13;
COIT11134-Java Programming
19
Identifiers


Identifier: name of a variable, method, or
class
Rules for identifiers in Java:






Can be made up of letters, digits, and the underscore (_)
character
Cannot start with a digit
Cannot use other symbols such as ? or %
Spaces are not permitted inside identifiers
You cannot use reserved words
They are case sensitive
COIT11134-Java Programming
Continued… 20
Identifiers



By convention, variable names start with a
lowercase letter
By convention, class names start with an
uppercase letter
By convention, method names start with a
lowercase letter
COIT11134-Java Programming
21
Objects and Classes


Object: entity that you can manipulate in your
programs (by calling methods)
Each object belongs to a class. For example,
System.out (will return an object type)
belongs to the class PrintStream
COIT11134-Java Programming
22
Methods





Method: Sequence of instructions that accesses the
data of an object
Methods are public interface: Specifies what you
can do with the objects of a class
You manipulate objects by calling its methods
Class: Set of objects with the same behavior
Class determines legal methods
String greeting = "Hello";
greeting.println() // Error
greeting.length() // OK
COIT11134-Java Programming
23
A Representation of Two String Objects
COIT11134-Java Programming
24
String Methods

length(): counts the number of characters
in a string
String greeting = "Hello, World!";
int n = greeting.length(); // sets n to 13

toUpperCase(): creates another String
object that contains the characters of the
original string, with lowercase letters converted
to uppercase
String river = "Mississippi";
String bigRiver = river.toUpperCase();
// sets bigRiver to "MISSISSIPPI"
COIT11134-Java Programming
Continued…
25
String Methods

When applying a method to an object, make
sure method is defined in the appropriate
class
System.out.length(); // This method call is an error
COIT11134-Java Programming
26
Return Values

Return value: A result that the method has
computed for use by the code that called it
int n = greeting.length(); // return value stored in n
COIT11134-Java Programming
Continued…
27
Passing Return Values

You can also use the return value as a
parameter of another method:
System.out.println(greeting.length());

Not all methods return values. Example:
println
COIT11134-Java Programming
Continued…
28
Method Definitions

Method definition specifies types of explicit
parameters and return value
COIT11134-Java Programming
Continued…
29
Method Definitions

Example: Class String defines
public int length()
// return type: int
// no explicit parameter
public String replace(String target, String replacement)
// return type: String;
// two explicit parameters of type String
COIT11134-Java Programming
30
Method Definitions

If method returns no value, the return type is
declared as void
public void println(String output) // in class PrintStream

A method name is overloaded if a class has
more than one method with the same name
(but different parameter types)
public void println(String output)
public void println(int output)
COIT11134-Java Programming
31
Rectangular Shapes and Rectangle
Objects

Objects of type Rectangle describe
rectangular shapes
COIT11134-Java Programming
32
Rectangular Shapes and
Rectangle Objects

A Rectangle object isn't a rectangular
shape–it is an object that contains a set of
numbers that describe the rectangle
COIT11134-Java Programming
33
Constructing Objects
new Rectangle(5, 10, 20, 30)

Detail:
1. The new operator makes a Rectangle object
It uses the parameters (in this case, 5, 10, 20, and 30)
to initialize the data of the object
3. It returns the object
Usually the output of the new operator is stored in a variable
2.

Rectangle box = new Rectangle(5, 10, 20, 30);
COIT11134-Java Programming
34
Constructing Objects



The process of creating a new object is called
construction
The four values 5, 10, 20, and 30 are called
the construction parameters
Some classes let you construct objects in
multiple ways
new Rectangle()
// constructs a rectangle with its top-left corner
// at the origin (0, 0), width 0, and height 0
COIT11134-Java Programming
35
Object Construction
new ClassName(parameters)
Example:
new Rectangle(5, 10, 20, 30)
new Rectangle()
Purpose:
To construct a new object, initialize it with the construction parameters, and
return a reference to the constructed object
COIT11134-Java Programming
36
Accessor and Mutator Methods

Accessor method: does not change the
state of the objects (e.g. get methods)
double width = box.getWidth();

Mutator method: changes the state
of the objects (e.g. set methods)
box.translate(15, 25);
COIT11134-Java Programming
37
Importing Packages

Java classes are grouped into packages

Import library classes by specifying the
package and class name:
import java.awt.Rectangle;

You don't need to import classes in the
java.lang package such as String and
System
COIT11134-Java Programming
38
The API Documentation





API doc: Application Programming Interface
docs
Lists classes and methods in the Java library
http://java.sun.com/javase/6/docs/api/
You will need to check Java API documents
very frequently in the future
It still grows
COIT11134-Java Programming
39
Object References


Describe the location of objects
The new operator returns a reference to a new
object
Rectangle box = new Rectangle();

Multiple object variables can refer to the same
object
Rectangle box = new Rectangle(5, 10, 20, 30);
Rectangle box2 = box;
box2.translate(15, 25);
COIT11134-Java Programming
40
Continued…
Object Variables and Number
Variables
An Object Variable containing an Object Reference
COIT11134-Java Programming
41
Object Variables and Number
Variables
A Number Variable Stores a Number
COIT11134-Java Programming
42
Copying Numbers
int luckyNumber = 13;
int luckyNumber2 = luckyNumber;
luckyNumber2 = 12;
Copying Numbers
COIT11134-Java Programming
43
Copying Object References
Rectangle box = new Rectangle(5, 10, 20, 30);
Rectangle box2 = box;
box2.translate(15, 25);
Copying Object References
COIT11134-Java Programming
44
Implement Classes
COIT11134-Java Programming
45
Designing the Public Interface
of a Class

Behavior of bank account (abstraction):



deposit money
withdraw money
get balance
COIT11134-Java Programming
46
Designing the Public Interface of a
Class: Methods

Methods of BankAccount class:
deposit
withdraw
getBalance

We want to support method calls such as the
following:
harrysChecking.deposit(2000);
harrysChecking.withdraw(500);
System.out.println(harrysChecking.getBalance());
COIT11134-Java Programming
47
Designing the Public Interface of a
Class: Method Definition





access specifier (such as public)
return type (such as String or void)
method name (such as deposit)
list of parameters (double amount for
deposit)
method body in { }
COIT11134-Java Programming
Continued…
48
Designing the Public Interface of a
Class: Method Definition
Examples
public void deposit(double amount) { . . . }
public void withdraw(double amount) { . . . }
public double getBalance() { . . . }
COIT11134-Java Programming
49
Constructor Definition


A constructor initializes the instance variables
Constructor name = class name
public BankAccount()
{
// body--filled in later
}
COIT11134-Java Programming
Continued…
50
Constructor Definition




Constructor body is executed when new
object is created
Statements in constructor body will set the
internal data of the object that is being
constructed
All constructors of a class have the same
name
Compiler can tell constructors apart because
they take different parameters
COIT11134-Java Programming
51
Constructor Definition
accessSpecifier ClassName(parameterType parameterName, . . .)
{
constructor body
}
Example:
public BankAccount(double initialBalance)
{
. . .
}
Purpose:
To define the behavior of a constructor
COIT11134-Java Programming
52
Class Definition
accessSpecifier class ClassName
{
constructors
methods
fields
}
Example:
public class BankAccount
{
public BankAccount(double initialBalance) { . . . }
public void deposit(double amount) { . . . }
. . .
}
Purpose:
To define a class, its public interface, and its implementation details
COIT11134-Java Programming
53
Question
How can you use the methods of the public
interface to empty the harrysChecking bank
account?
The public interface as following
public void deposit(double amount) { . . . }
public void withdraw(double amount) { . . . }
public double getBalance() { . . . }
COIT11134-Java Programming
54
Answers
harrysChecking.withdraw(harrysChecking.getBalance())
COIT11134-Java Programming
55
Instance Fields




An object stores its data in instance fields
Field: a technical term for a storage location
inside a block of memory
Instance of a class: an object of the class
The class declaration specifies the instance
fields:
public class BankAccount
{
. . .
private double balance;
}
COIT11134-Java Programming
56
Instance Fields

An instance field declaration consists of the
following parts:





access specifier (such as private)
type of variable (such as double)
name of variable (such as balance)
Each object of a class has its own set of
instance fields
You should declare all instance fields as
private
COIT11134-Java Programming
57
Instance Fields
Instance Fields
COIT11134-Java Programming
58
Instance Field Declaration
accessSpecifier class ClassName
{
. . .
accessSpecifier fieldType fieldName;
. . .
}
Example:
public class BankAccount
{
. . .
private double balance;
. . .
}
Purpose:
To define a field that is present in every object of a class
COIT11134-Java Programming
59
Accessing Instance Fields

The deposit method of the BankAccount
class can access the private instance field:
public void deposit(double amount)
{
double newBalance = balance + amount;
balance = newBalance;
}
Continued…
COIT11134-Java Programming
60
Implementing Constructors

Constructors contain instructions to initialize
the instance fields of an object
public BankAccount()
{
balance = 0;
}
public BankAccount(double initialBalance)
{
balance = initialBalance;
}
COIT11134-Java Programming
61
Implementing Methods

Some methods do not return a value
public void withdraw(double amount)
{
double newBalance = balance - amount;
balance = newBalance;
}

Some methods return an output value
public double getBalance()
{
return balance;
}
COIT11134-Java Programming
62
File BankAccount.java
01:
02:
03:
04:
05:
06:
07:
08:
09:
10:
11:
12:
13:
14:
15:
16:
17:
18:
/**
A bank account has a balance that can be changed by
deposits and withdrawals.
*/
public class BankAccount
{
/**
Constructs a bank account with a zero balance.
*/
public BankAccount()
{
balance = 0;
}
/**
Constructs a bank account with a given balance.
@param initialBalance the initial balance
*/
COIT11134-Java Programming
Continued… 63
File BankAccount.java
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
public BankAccount(double initialBalance)
{
balance = initialBalance;
}
/**
Deposits money into the bank account.
@param amount the amount to deposit
*/
public void deposit(double amount)
{
double newBalance = balance + amount;
balance = newBalance;
}
/**
Withdraws money from the bank account.
@param amount the amount to withdraw
COIT11134-Java Programming
Continued… 64
File BankAccount.java
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54: }
*/
public void withdraw(double amount)
{
double newBalance = balance - amount;
balance = newBalance;
}
/**
Gets the current balance of the bank account.
@return the current balance
*/
public double getBalance()
{
return balance;
}
private double balance;
COIT11134-Java Programming
65
Testing a Class


Test class: a class with a main method that
contains statements to test another class.
Typically carries out the following steps:
1.
2.
3.
Construct one or more objects of the class that
is being tested
Invoke one or more methods
Print out one or more results
COIT11134-Java Programming
Continued… 66
File BankAccountTester.java
01:
02:
03:
04:
05:
06:
07:
08:
09:
10:
11:
12:
13:
14:
15:
16:
17:
/**
A class to test the BankAccount class.
*/
public class BankAccountTeste
{
/**
Tests the methods of the BankAccount class.
@param args not used
*/
public static void main(String[] args)
{
BankAccount harrysChecking = new BankAccount();
harrysChecking.deposit(2000);
harrysChecking.withdraw(500);
System.out.println(harrysChecking.getBalance());
}
}
COIT11134-Java Programming
67
Fundamental Data Types
COIT11134-Java Programming
68
Categories of Variables

Categories of variables





Instance fields (balance in BankAccount)
Local variables (newBalance in deposit
method)
Parameter variables (amount in deposit
method)
An instance field belongs to an object
The fields stay alive until no method uses the
object any longer
COIT11134-Java Programming
69
Categories of Variables



In Java, the garbage collector periodically
reclaims objects when they are no longer
used
Local and parameter variables belong to a
method
Instance fields are initialized to a default
value, but you must initialize local variables
COIT11134-Java Programming
70
Primitive Types
Type
Description
Size
int
The integer type, with range
–2,147,483,648 to 2,147,483,647
4 bytes
byte
The type describing a single byte, with
range
–128 to 127
1 byte
short
The short integer type, with range
–32768 to 32767
2 bytes
long
The long integer type, with range –
9,223,372,036,854,775,808 to
–9,223,372,036,854,775,807
8 bytes
COIT11134-Java Programming
71
Continued…
Primitive Types
Type
Description
Size
double
The double-precision floating-point type,
with a range of about ±10308 and about
15 significant decimal digits
8 bytes
float
The single-precision floating-point type,
with a range of about ±1038 and about 7
significant decimal digits
4 bytes
char
The character type, representing code
2 bytes
units in the Unicode encoding scheme
The type with the two truth values false 1 byte
and true
boolean
COIT11134-Java Programming
72
Number Types: Conversion

Type Casting: This is a method which is
commonly used for type conversion.
double balance = 23.45;
int dollars = (int) balance; // OK
Cast discards fractional portion.
Continued…
COIT11134-Java Programming
73
Number Types: Conversion

Math.round: Can be used to convert a floating point
type to an integer type:
// if balance is 130.75, then rounded is set to 131
float balance = 130.75;
long rounded = Math.round(balance);

Conversions can be made larger types using standard
assignments:
int dollars = 15;
float price = dollars; //OK
COIT11134-Java Programming
74
Constants: final

Declaring <final> before type is Java’s standard for
creating constants.
final int MINUTES_IN_HOUR = 60;

Once its value has been set, it cannot be changed

Convention: use all-uppercase characters for constant
names and separate with underscore.
COIT11134-Java Programming
75
Constants: static final


Use <static final>, if constant values are needed in
several classes.
Give static final constants public access to enable
other classes to use them.
public class Math
{
. . .
public static final double E = 2.718281828;
public static final double PI = 3.14159265;
}
//this uses the constant to perform a calculation
double circumference = Math.PI * diameter;
COIT11134-Java Programming
76
Calling Static Methods

A static method does not operate on an object:
double x = 4;
double root = x.sqrt(); // Error
double root = Math.sqrt(x); //OK

Static methods are defined inside classes
COIT11134-Java Programming
77
Some Math Methods
Math.sqrt(x)
square root
Math.pow(x, y)
power xy
Math.exp(x)
ex
Math.log(x)
natural log
Math.sin(x), Math.cos(x), sine, cosine, tangent (x in
Math.tan(x)
radian)
Math.round(x)
closest integer to x
Math.min(x, y),
Math.max(x, y)
minimum, maximum
COIT11134-Java Programming
78
Strings: Concatenation

Use the <+> operator to add to a string:
String name = "Dave";
String message = "Hello, " + name;
// message is now "Hello, Dave"

If one of the arguments of the <+> operator is a string, the
other is converted to a string.
String name = “Dave is: ";
int age = 27;
String person = name + age; // dave is “Dave is: 27”
COIT11134-Java Programming
79
Conversion: Strings and
Numbers

Convert from string to number:
int n = Integer.parseInt(str);
double x = Double.parseDouble(str);

Convert from number to string:
String str = "" + n;
str = Integer.toString(n);
COIT11134-Java Programming
80
Substrings
String greeting = "Hello, World!";
String sub = greeting.substring(0, 5); // sub is "Hello"

Supply start and end position.
(note: the start position you want, the end position you don’t
want)

First position is at 0
Continued…
COIT11134-Java Programming
81
Reading Input

Scanner class was added to read
keyboard input in a convenient manner
Scanner in = new Scanner(System.in);
System.out.print("Enter quantity: ");
int quantity = in.nextInt();



nextDouble reads a double
nextLine reads a line (until user hits Enter)
next reads a word (until any white space)
COIT11134-Java Programming
82
File InputTester.java
01:
02:
03:
04:
05:
06:
07:
08:
09:
10:
11:
12:
13:
14:
15:
16:
17:
import java.util.Scanner;
/**
This class tests console input.
*/
public class InputTester
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
CashRegister register = new CashRegister();
System.out.print("Enter price: ");
double price = in.nextDouble();
register.recordPurchase(price);
COIT11134-Java Programming
Continued…
83
File InputTester.java
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33: }
System.out.print("Enter dollars: ");
int dollars = in.nextInt();
System.out.print("Enter quarters: ");
int quarters = in.nextInt();
System.out.print("Enter dimes: ");
int dimes = in.nextInt();
System.out.print("Enter nickels: ");
int nickels = in.nextInt();
System.out.print("Enter pennies: ");
int pennies = in.nextInt();
register.enterPayment(dollars, quarters, dimes,
nickels, pennies);
System.out.print("Your change is ");
System.out.println(register.giveChange());
}
COIT11134-Java Programming
84
Continued…
File InputTester.java
Output
Enter price: 7.55
Enter dollars: 10
Enter quarters: 2
Enter dimes: 1
Enter nickels: 0
Enter pennies: 0
Your change is 3.05
COIT11134-Java Programming
85
Reading Input from a Dialog
Box
COIT11134-Java Programming
86
Reading Input From a Dialog
Box
String input = JOptionPane.showInputDialog(prompt)

Convert strings to numbers if necessary:
int count = Integer.parseInt(input);

Conversion throws an exception if user
doesn't supply a number
COIT11134-Java Programming
87
References
Sun Microsystems “Java Downloads”.
http://java.sun.com/j2se/index.jsp (Sun)
Horstmann C. 2007, Big Java, Wiley & Sons
COIT11134-Java Programming
88