java programming week 1: java fundamental revision (text book: ch1, ch2, ch3, ch4)

88
Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

Upload: junior-mclaughlin

Post on 13-Dec-2015

258 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

Java Programming

Week 1: Java Fundamental Revision

(Text book: ch1, ch2, ch3, ch4)

Page 2: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 2

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/2009/T2/COIT11134/ Text book

Big Java, Cay Horstmann, 3nd Edition

Page 3: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 3

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

Page 4: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 4

Course Structure1. Java Revision (Java data types, object,

class, JDK)

2. Revision (decision and iteration), instance methods and static method

3. Interface and Polymorphism

4. Inheritance

5. Graphic User Interface

6. Array and ArrayList

Page 5: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 5

Course Structure cont.

7. Sorting and Searching

8. Sorting and Searching

9. Input/Ourput, Exception handling, Files and Streams

10. Object-Oriented Design

11. Object-Oriented Design

12. Multithreading and Final revision

Page 6: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 6

AssessmentAssignment 1:

GUI, Event Handling, Exception Handling (Week 6, 15%) Assignment 2:

Object Sorting (Week 10, 20%)

Final exam: All topics covered, 65%

Pass criteria: 50% plus overall AND 50% final exam

Page 7: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 7

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.

Page 8: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 8

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

Page 9: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 9

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

Page 10: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 10

Java ExamplesA Java Application Example

Page 11: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 11

Java Examples

A Java Applet Example http://java.sun.com/applets/jdk/1.4/demo/apple

ts/SortDemo/example1.htmlA 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)

Page 12: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 12

Questions

How long would it take to learn the entire Java Library?

Page 13: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 13

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

Page 14: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 14

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).

Page 15: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 15

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.

Page 16: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 16

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

Page 17: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 17

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)

Page 18: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 18

The Compilation Process

Page 19: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 19

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;

Page 20: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 20

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

Continued…

Page 21: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 21

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

Page 22: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 22

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

Page 23: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 23

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() // Errorgreeting.length() // OK

Page 24: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 24

A Representation of Two String Objects

Page 25: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 25

String Methods length(): counts the number of characters

in a string

toUpperCase(): creates another String object that contains the characters of the original string, with lowercase letters converted to uppercase

Continued…

String greeting = "Hello, World!"; int n = greeting.length(); // sets n to 13

String river = "Mississippi"; String bigRiver = river.toUpperCase(); // sets bigRiver to "MISSISSIPPI"

Page 26: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 26

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

Page 27: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 27

Return Values Return value: A result that the method has

computed for use by the code that called it

Continued…

int n = greeting.length(); // return value stored in n

Page 28: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 28

Passing Return Values

You can also use the return value as a parameter of another method:

Not all methods return values. Example:

Continued…

System.out.println(greeting.length());

println

Page 29: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 29

Method Definitions

Method definition specifies types of explicit parameters and return value

Continued…

Page 30: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 30

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

Page 31: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 31

Method Definitions

If method returns no value, the return type is declared as void

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) // in class PrintStream

public void println(String output)public void println(int output)

Page 32: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 32

Rectangular Shapes and Rectangle Objects

Objects of type Rectangle describe rectangular shapes

Page 33: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 33

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

Page 34: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 34

Constructing Objects

Detail:

1. The new operator makes a Rectangle object

2. 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

Rectangle box = new Rectangle(5, 10, 20, 30);

new Rectangle(5, 10, 20, 30)

Page 35: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 35

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

Page 36: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 36

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

Page 37: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 37

Accessor and Mutator Methods

Accessor method: does not change the state of the objects (e.g. get methods)

Mutator method: changes the state of the objects (e.g. set methods)

double width = box.getWidth();

box.translate(15, 25);

Page 38: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 38

Importing Packages

Java classes are grouped into packages

Import library classes by specifying the package and class name:

You don't need to import classes in the java.lang package such as String and System

import java.awt.Rectangle;

Page 39: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 39

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

Page 40: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 40

Object References Describe the location of objects The new operator returns a reference to a new

object

Multiple object variables can refer to the same object

Rectangle box = new Rectangle(5, 10, 20, 30);Rectangle box2 = box;box2.translate(15, 25);

Rectangle box = new Rectangle();

Continued…

Page 41: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 41

Object Variables and Number Variables

An Object Variable containing an Object Reference

Page 42: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 42

Object Variables and Number Variables

A Number Variable Stores a Number

Page 43: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 43

Copying Numbers

Copying Numbers

int luckyNumber = 13;int luckyNumber2 = luckyNumber;luckyNumber2 = 12;

Page 44: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 44

Copying Object References

Copying Object References

Rectangle box = new Rectangle(5, 10, 20, 30);Rectangle box2 = box;box2.translate(15, 25);

Page 45: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 45

Implement Classes

Page 46: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 46

Behavior of bank account (abstraction): deposit money withdraw money get balance

Designing the Public Interface of a Class

Page 47: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 47

Designing the Public Interface of a Class: Methods Methods of BankAccount class:

We want to support method calls such as the following:

harrysChecking.deposit(2000);harrysChecking.withdraw(500);System.out.println(harrysChecking.getBalance());

deposit withdraw getBalance

Page 48: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 48

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 { }

Continued…

Page 49: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 49

Designing the Public Interface of a Class: Method Definition

public void deposit(double amount) { . . . } public void withdraw(double amount) { . . . } public double getBalance() { . . . }

Examples

Page 50: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 50

Constructor Definition

A constructor initializes the instance variables Constructor name = class name

public BankAccount(){ // body--filled in later }

Continued…

Page 51: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 51

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

Page 52: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 52

Constructor Definition

accessSpecifier ClassName(parameterType parameterName, . . .) { constructor body }

Example:  public BankAccount(double initialBalance) { . . . }

Purpose:To define the behavior of a constructor

Page 53: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 53

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

Page 54: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 54

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() { . . . }

Page 55: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 55

Answers

harrysChecking.withdraw(harrysChecking.getBalance())

Page 56: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 56

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;}

Page 57: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 57

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

Page 58: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 58

Instance Fields

Instance Fields

Page 59: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 59

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

Page 60: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 60

Accessing Instance Fields The deposit method of the BankAccount class can access the private instance field:

Continued…

public void deposit(double amount){   double newBalance = balance + amount;   balance = newBalance;}

Page 61: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 61

Implementing Constructors Constructors contain instructions to initialize

the instance fields of an object

public BankAccount(){ balance = 0;}public BankAccount(double initialBalance){ balance = initialBalance;}

Page 62: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 62

Implementing Methods

Some methods do not return a value

Some methods return an output value

public void withdraw(double amount){ double newBalance = balance - amount; balance = newBalance;}

public double getBalance(){ return balance;}

Page 63: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 63

File BankAccount.java01: /**02: A bank account has a balance that can be changed by 03: deposits and withdrawals.04: */05: public class BankAccount06: { 07: /**08: Constructs a bank account with a zero balance.09: */10: public BankAccount()11: { 12: balance = 0;13: }14: 15: /**16: Constructs a bank account with a given balance.17: @param initialBalance the initial balance 18: */

Continued…

Page 64: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 64

File BankAccount.java19: public BankAccount(double initialBalance)20: { 21: balance = initialBalance;22: }23: 24: /**25: Deposits money into the bank account.26: @param amount the amount to deposit27: */28: public void deposit(double amount)29: { 30: double newBalance = balance + amount;31: balance = newBalance;32: }33: 34: /**35: Withdraws money from the bank account.36: @param amount the amount to withdraw

Continued…

Page 65: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 65

File BankAccount.java37: */38: public void withdraw(double amount)39: { 40: double newBalance = balance - amount;41: balance = newBalance;42: }43: 44: /**45: Gets the current balance of the bank account.46: @return the current balance47: */48: public double getBalance()49: { 50: return balance;51: }52: 53: private double balance;54: }

Page 66: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 66

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. Construct one or more objects of the class that

is being tested

2. Invoke one or more methods

3. Print out one or more results

Continued…

Page 67: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 67

File BankAccountTester.java

01: /**02: A class to test the BankAccount class.03: */04: public class BankAccountTeste05: {06: /**07: Tests the methods of the BankAccount class.08: @param args not used09: */10: public static void main(String[] args)11: {12: BankAccount harrysChecking = new BankAccount();13: harrysChecking.deposit(2000);14: harrysChecking.withdraw(500);15: System.out.println(harrysChecking.getBalance());16: }17: }

Page 68: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 68

Fundamental Data Types

Page 69: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 69

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

Page 70: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 70

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

Page 71: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 71

Primitive Types

Type Description Sizeint 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

Continued…

Page 72: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 72

Primitive Types

Type Description Sizedouble 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 units in the Unicode encoding scheme

2 bytes

boolean The type with the two truth values false and true

1 byte

Page 73: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 73

Number Types: Conversion

Type Casting: This is a method which is commonly used for type conversion.

Cast discards fractional portion.

double balance = 23.45;

int dollars = (int) balance; // OK

Continued…

Page 74: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 74

Number Types: Conversion

Math.round: Can be used to convert a floating point type to an integer type:

Conversions can be made larger types using standard assignments:

// if balance is 130.75, then rounded is set to 131

float balance = 130.75;long rounded = Math.round(balance);                           

int dollars = 15;float price = dollars; //OK

Page 75: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 75

Constants: final

Declaring <final> before type is Java’s standard for creating constants.

Once its value has been set, it cannot be changed

Convention: use all-uppercase characters for constant names and separate with underscore.

final int MINUTES_IN_HOUR = 60;

Page 76: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 76

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;

Page 77: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 77

Calling Static Methods

A static method does not operate on an object:

Static methods are defined inside classes

double x = 4;double root = x.sqrt(); // Error

double root = Math.sqrt(x); //OK

Page 78: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 78

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), Math.tan(x)

sine, cosine, tangent (x in radian)

Math.round(x) closest integer to x

Math.min(x, y), Math.max(x, y)

minimum, maximum

Page 79: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 79

Strings: Concatenation Use the <+> operator to add to a string:

If one of the arguments of the <+> operator is a string, the other is converted to a string.

String name = "Dave";String message = "Hello, " + name;// message is now "Hello, Dave"

String name = “Dave is: ";int age = 27;String person = name + age; // dave is “Dave is: 27”

Page 80: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 80

Conversion: Strings and Numbers Convert from string to number:

Convert from number to string:

int n = Integer.parseInt(str);double x = Double.parseDouble(str);

String str = "" + n;str = Integer.toString(n);

Page 81: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 81

Substrings

Supply start and end position.

(note: the start position you want, the end position you don’t

want) First position is at 0

Continued…

String greeting = "Hello, World!";String sub = greeting.substring(0, 5); // sub is "Hello"

Page 82: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 82

Reading Input Scanner class was added to read

keyboard input in a convenient manner

nextDouble reads a double nextLine reads a line (until user hits Enter) next reads a word (until any white space)

Scanner in = new Scanner(System.in);System.out.print("Enter quantity: ");int quantity = in.nextInt();

Page 83: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 83

File InputTester.java01: import java.util.Scanner;02: 03: /**04: This class tests console input.05: */06: public class InputTester07: {08: public static void main(String[] args)09: {10: Scanner in = new Scanner(System.in);11: 12: CashRegister register = new CashRegister();13: 14: System.out.print("Enter price: ");15: double price = in.nextDouble();16: register.recordPurchase(price);17:

Continued…

Page 84: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 84

File InputTester.java18: System.out.print("Enter dollars: ");19: int dollars = in.nextInt();20: System.out.print("Enter quarters: ");21: int quarters = in.nextInt();22: System.out.print("Enter dimes: ");23: int dimes = in.nextInt();24: System.out.print("Enter nickels: ");25: int nickels = in.nextInt();26: System.out.print("Enter pennies: ");27: int pennies = in.nextInt();28: register.enterPayment(dollars, quarters, dimes, nickels, pennies);29: 30: System.out.print("Your change is ");31: System.out.println(register.giveChange());32: }33: }

Continued…

Page 85: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 85

File InputTester.java

Enter price: 7.55Enter dollars: 10Enter quarters: 2Enter dimes: 1Enter nickels: 0Enter pennies: 0Your change is 3.05

Output

Page 86: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 86

Reading Input from a Dialog Box

Page 87: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 87

Reading Input From a Dialog Box

Convert strings to numbers if necessary:

Conversion throws an exception if user doesn't supply a number

String input = JOptionPane.showInputDialog(prompt)

int count = Integer.parseInt(input);

Page 88: Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)

COIT11134-Java Programming 88

References

Sun Microsystems “Java Downloads”. http://java.sun.com/j2se/index.jsp (Sun)

Horstmann C. 2007, Big Java, Wiley & Sons