Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Java Programming Week 1: Java Fundamental Revision (Text book: ch1, ch2, ch3, ch4)"— Presentation transcript:

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

2 COIT11134-Java Programming2 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

3 COIT11134-Java Programming3 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

4 COIT11134-Java Programming4 Course Structure 1. 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

5 COIT11134-Java Programming5 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

6 COIT11134-Java Programming6 Assessment Assignment 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

7 COIT11134-Java Programming7 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.

8 COIT11134-Java Programming8 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

9 COIT11134-Java Programming9 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

10 COIT11134-Java Programming10 Java Examples A Java Application Example

11 COIT11134-Java Programming11 Java Examples A Java Applet Example http://java.sun.com/applets/jdk/1.4/demo/apple ts/SortDemo/example1.html 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 http://forum.java.sun.com/forum.jspa?forumID =31 (In many J2EE application, online forum, registration, normally need to operate on databases)

12 COIT11134-Java Programming12 Questions How long would it take to learn the entire Java Library?

13 COIT11134-Java Programming13 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

14 COIT11134-Java Programming14 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).

15 COIT11134-Java Programming15 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.

16 COIT11134-Java Programming16 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

17 COIT11134-Java Programming17 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)

18 COIT11134-Java Programming18 The Compilation Process

19 COIT11134-Java Programming19 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;

20 COIT11134-Java Programming20 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…

21 COIT11134-Java Programming21 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

22 COIT11134-Java Programming22 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

23 COIT11134-Java Programming23 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

24 COIT11134-Java Programming24 A Representation of Two String Objects

25 COIT11134-Java Programming25 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"

26 COIT11134-Java Programming26 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

27 COIT11134-Java Programming27 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

28 COIT11134-Java Programming28 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

29 COIT11134-Java Programming29 Method Definitions Method definition specifies types of explicit parameters and return value Continued…

30 COIT11134-Java Programming30 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

31 COIT11134-Java Programming31 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)

32 COIT11134-Java Programming32 Rectangular Shapes and Rectangle Objects Objects of type Rectangle describe rectangular shapes

33 COIT11134-Java Programming33 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

34 COIT11134-Java Programming34 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)

35 COIT11134-Java Programming35 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

36 COIT11134-Java Programming36 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

37 COIT11134-Java Programming37 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);

38 COIT11134-Java Programming38 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;

39 COIT11134-Java Programming39 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

40 COIT11134-Java Programming40 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…

41 COIT11134-Java Programming41 Object Variables and Number Variables An Object Variable containing an Object Reference

42 COIT11134-Java Programming42 Object Variables and Number Variables A Number Variable Stores a Number

43 COIT11134-Java Programming43 Copying Numbers int luckyNumber = 13; int luckyNumber2 = luckyNumber; luckyNumber2 = 12;

44 COIT11134-Java Programming44 Copying Object References Rectangle box = new Rectangle(5, 10, 20, 30); Rectangle box2 = box; box2.translate(15, 25);

45 COIT11134-Java Programming45 Implement Classes

46 COIT11134-Java Programming46 Behavior of bank account (abstraction): deposit money withdraw money get balance Designing the Public Interface of a Class

47 COIT11134-Java Programming47 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

48 COIT11134-Java Programming48 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…

49 COIT11134-Java Programming49 Designing the Public Interface of a Class: Method Definition public void deposit(double amount) {... } public void withdraw(double amount) {... } public double getBalance() {... } Examples

50 COIT11134-Java Programming50 Constructor Definition A constructor initializes the instance variables Constructor name = class name public BankAccount() { // body--filled in later } Continued…

51 COIT11134-Java Programming51 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

52 COIT11134-Java Programming52 Constructor Definition accessSpecifier ClassName(parameterType parameterName,...) { constructor body } Example: public BankAccount(double initialBalance) {... } Purpose: To define the behavior of a constructor

53 COIT11134-Java Programming53 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

54 COIT11134-Java Programming54 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() {... }

55 COIT11134-Java Programming55 Answers harrysChecking.withdraw(harrysChecking.getBalance())

56 COIT11134-Java Programming56 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; }

57 COIT11134-Java Programming57 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

58 COIT11134-Java Programming58 Instance Fields

59 COIT11134-Java Programming59 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

60 COIT11134-Java Programming60 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; }

61 COIT11134-Java Programming61 Implementing Constructors Constructors contain instructions to initialize the instance fields of an object public BankAccount() { balance = 0; } public BankAccount(double initialBalance) { balance = initialBalance; }

62 COIT11134-Java Programming62 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; }

63 COIT11134-Java Programming63 File BankAccount.java 01: /** 02: A bank account has a balance that can be changed by 03: deposits and withdrawals. 04: */ 05: public class BankAccount 06: { 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…

64 COIT11134-Java Programming64 File BankAccount.java 19: public BankAccount(double initialBalance) 20: { 21: balance = initialBalance; 22: } 23: 24: /** 25: Deposits money into the bank account. 26: @param amount the amount to deposit 27: */ 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…

65 COIT11134-Java Programming65 File BankAccount.java 37: */ 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 balance 47: */ 48: public double getBalance() 49: { 50: return balance; 51: } 52: 53: private double balance; 54: }

66 COIT11134-Java Programming66 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…

67 COIT11134-Java Programming67 File BankAccountTester.java 01: /** 02: A class to test the BankAccount class. 03: */ 04: public class BankAccountTeste 05: { 06: /** 07: Tests the methods of the BankAccount class. 08: @param args not used 09: */ 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: }

68 COIT11134-Java Programming68 Fundamental Data Types

69 COIT11134-Java Programming69 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

70 COIT11134-Java Programming70 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

71 COIT11134-Java Programming71 Primitive Types TypeDescriptionSize 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 Continued…

72 COIT11134-Java Programming72 Primitive Types TypeDescriptionSize double The double-precision floating-point type, with a range of about ±10 308 and about 15 significant decimal digits 8 bytes float The single-precision floating-point type, with a range of about ±10 38 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

73 COIT11134-Java Programming73 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…

74 COIT11134-Java Programming74 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

75 COIT11134-Java Programming75 Constants: final Declaring 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;

76 COIT11134-Java Programming76 Constants: static final Use, 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;

77 COIT11134-Java Programming77 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

78 COIT11134-Java Programming78 Some Math Methods Math.sqrt(x) square root Math.pow(x, y) power x y Math.exp(x) exex 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

79 COIT11134-Java Programming79 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”

80 COIT11134-Java Programming80 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);

81 COIT11134-Java Programming81 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"

82 COIT11134-Java Programming82 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();

83 COIT11134-Java Programming83 File InputTester.java 01: import java.util.Scanner; 02: 03: /** 04: This class tests console input. 05: */ 06: public class InputTester 07: { 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…

84 COIT11134-Java Programming84 File InputTester.java 18: 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…

85 COIT11134-Java Programming85 File InputTester.java Enter price: 7.55 Enter dollars: 10 Enter quarters: 2 Enter dimes: 1 Enter nickels: 0 Enter pennies: 0 Your change is 3.05 Output

86 COIT11134-Java Programming86 Reading Input from a Dialog Box

87 COIT11134-Java Programming87 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);

88 COIT11134-Java Programming88 References Sun Microsystems “Java Downloads”. http://java.sun.com/j2se/index.jsp (Sun) http://java.sun.com/j2se/index.jsp Horstmann C. 2007, Big Java, Wiley & Sons


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

Similar presentations


Ads by Google