java programming week 1: java fundamental revision (text book: ch1, ch2, ch3, ch4)
Post on 13-Dec-2015
260 Views
Preview:
TRANSCRIPT
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
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
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
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
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
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.
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
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
COIT11134-Java Programming 10
Java ExamplesA Java Application Example
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)
COIT11134-Java Programming 12
Questions
How long would it take to learn the entire Java Library?
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
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).
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.
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
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)
COIT11134-Java Programming 18
The Compilation Process
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;
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…
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
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
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
COIT11134-Java Programming 24
A Representation of Two String Objects
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"
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
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
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
COIT11134-Java Programming 29
Method Definitions
Method definition specifies types of explicit parameters and return value
Continued…
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
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)
COIT11134-Java Programming 32
Rectangular Shapes and Rectangle Objects
Objects of type Rectangle describe rectangular shapes
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
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)
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
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
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);
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;
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
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…
COIT11134-Java Programming 41
Object Variables and Number Variables
An Object Variable containing an Object Reference
COIT11134-Java Programming 42
Object Variables and Number Variables
A Number Variable Stores a Number
COIT11134-Java Programming 43
Copying Numbers
Copying Numbers
int luckyNumber = 13;int luckyNumber2 = luckyNumber;luckyNumber2 = 12;
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);
COIT11134-Java Programming 45
Implement Classes
COIT11134-Java Programming 46
Behavior of bank account (abstraction): deposit money withdraw money get balance
Designing the Public Interface of a Class
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
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…
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
COIT11134-Java Programming 50
Constructor Definition
A constructor initializes the instance variables Constructor name = class name
public BankAccount(){ // body--filled in later }
Continued…
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
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
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
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() { . . . }
COIT11134-Java Programming 55
Answers
harrysChecking.withdraw(harrysChecking.getBalance())
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;}
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
COIT11134-Java Programming 58
Instance Fields
Instance Fields
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
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;}
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;}
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;}
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…
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…
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: }
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…
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: }
COIT11134-Java Programming 68
Fundamental Data Types
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
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
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…
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
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…
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
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;
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;
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
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
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”
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);
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"
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();
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…
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…
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
COIT11134-Java Programming 86
Reading Input from a Dialog Box
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);
COIT11134-Java Programming 88
References
Sun Microsystems “Java Downloads”. http://java.sun.com/j2se/index.jsp (Sun)
Horstmann C. 2007, Big Java, Wiley & Sons
top related