Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
presentation slides for Object-Oriented Problem Solving JAVA, JAVA, JAVA Second Edition Ralph Morelli Trinity College Hartford, CT published by Prentice Hall Why Study Java? • Java is platform independent. – A Java program can be run without changes on different kinds of computers. • Java is a distributed language. – Java programs can easily be run on computer networks. • Java is a relatively secure language. – Java contains features that protect against viruses and other untrusted code. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java The Language Translation Process • A single expression in a high-level language (a+b/2) usually requires several primitive operations in the machine language. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java What Is Object-Oriented Programming? • Interacting Objects – An OOP is a set of interacting objects that communicate by sending messages to each Objects other. Messages A UML Sequence Diagram Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java What is an Object? • In the real world an object (person) has attributes (name, hair color) and behaviors (eating, brushing teeth). • In Java, an object (rectangle) has variables (length, width) and methods Type of Object (calculateArea()). Values Variables A UML Object Diagram Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java What is a Java Class? • A class (Rectangle) is a blueprint or template of all objects of a certain type. • An object is an instance of a class. Class Name Type of data Variables Method A UML Class Diagram Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java What is a Message? • A message represents the passing of information from one object to another. • In Java, passing a message is done by calling a method. The OilSensor object sends a warning message to the Controller, which turns on the OilLight. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Method Calls Chapter 0: Computers, Objects, and Java Collaboration Between Objects • A RectangleUser object calls the calculateArea() method of a Rectangle object, which returns 300. Method Call Association A UML Collaboration Diagram Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Extending a Class • Code Reuse: Inheritance allows us to define one class in terms of another. A Square is as Rectangle whose sides are equal. The Square class inherits the calculateArea() method. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Overriding a Method • Code Reuse: A method can be overridden by defining it in the subclass. A Square class can be given a more efficient calcPerimeter() method. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java What is a Polymorphism? • A polymorphic method has different behavior for different objects. The move() method is polymorphic. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Principles of Object Orientation • Divide-and-Conquer Principle – Problem solving: Break problems (programs) into small, manageable tasks. – Example: Sales agent, shipping clerk. • Encapsulation Principle – Problem solving: Each object knows how to solve its task and has the information it needs. – Example: Sales agent is the sales expert. The shipping clerk is the shipping expert. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Principles of Object Orientation (cont) • Interface Principle – Each object has a well-defined interface, so you know how to interact with it. – Example: Digital vs. analog clock interfaces. – Example: The sales agent must be told the name and part number of the software. • Information Hiding Principle – Objects hide details of their expertise. – Example: Customer needn’t know how the sales agent records the order. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Principles of Object Orientation (cont) • Generality Principle – Objects are designed to solve a kind of task rather than a singular task. – Example: Sales agents sell all kinds of stuff. • Extensibility Principle – An object’s expertise can be extended or specialized. – Example: One sales agent specializes in software sales and another in hardware sales. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Method Specification: calculateArea() • Method Name: calculateArea() • Task: To calculate the area of a rectangle • Information Needed (variables) – Length: A variable to store the rectangle's length (private) – Width: A variable to store the rectangle's width (private) • Algorithm: area = length x width Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Coding into Java public class Rectangle { private double length; private double width; // Class header // Instance variables public Rectangle(double l, double w) // Constructor method { length = l; width = w; } public double calculateArea() { return length * width; } // calculateArea() // Access method } // Rectangle class Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Java Language Summary: Class Definition public class Example extends Object { private double num = 5.0; public void print() { System.out.println(num); } // print() // Class header // Start of class body // Instance variable // // // // Method definition header Start of method body Output statement End of print method body public static void main(String args[]) // Method definition header { // Start of method body Example example; // Reference variable declaration example = new Example(); // Object instantiation statement example.print(); // Method call } // main() // End of method body } // Example // End of class body Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Primitive Data Types Type Keyword Size in Bits Examples boolean true or false boolean character 16 ‘A’, ‘5’, ‘+’ char byte 8 -128 to +127 byte integer 16 -32768 to +32767 short integer 32 -2147483648 to +2147483647 int integer 64 really big numbers long real number float 32 21.3, -0.45, 1.67e28 real number double 64 21.3, -0.45, 1.67e28 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Applications vs. Applets • • • • • Java Applications Stand-alone program Runs independently Has a main() method No HTML file Run using JDK’s java interpreter Java, Java, Java, 2E by R. Morelli • • • • • Java Applets Embedded program. Runs in a Web browser No main() method. Requires an HTML file Run using JDK’s appletviewer Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java The HelloWorld Application /* * The HelloWorld application program */ public class HelloWorld { Multi-line comment block // Class header // Start of class body Single-line comments public static void main(String argv[]) // Main method { System.out.println("Hello world!"); } // End of main } // End of HelloWorld Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Execution starts on the first line of main() Chapter 0: Computers, Objects, and Java Editing, Compiling, and Running Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Java Library: System and PrintStream • The java.lang.System class contains PrintStream objects that perform Input/Output (I/O). • The java.lang.PrintStream class contains the print() and println() methods that perform output. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Example: OldMacDonald Program public class OldMacDonald // Class header { // Start of body public static void main(String argv[]) // Main method { System.out.println(“Old MacDonald had a farm.”); System.out.println(“E I E I O.”); System.out.println(“And on his farm he had a duck.”); System.out.println(“E I E I O.”); System.out.println(“With a quack quack here.”); System.out.println(“And a quack quack there.”); System.out.println(“Here a quack, there a quack.”); System.out.println(“Everywhere a quack quack.”); System.out.println(“Old MacDonald had a farm”); System.out.println(“E I E I O.”); } // End of main } // End of OldMacDonald Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Qualified Names • A qualified name takes the form reference.elementName where reference refers to some object (or class or package) and elementName is the name of one of the object’s (or class’s or package’s) elements. • Use: To refer to elements in Java’s package, class, element hierarchy. • Context dependent. System.out.println(); //println() method in System.out class pet1.eat(); // eat() method in pet1 object java.awt.Button // Button class in java.awt package Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Class Definition • Five basic design questions: – What role will the object perform? – What data or information will it need? – What actions will it take? – What public interface will it present to other objects? – What information will it hide (keep private) from other objects? Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java The Rectangle Class • A class is a blueprint. It describes an object's form but it has no content. The instance variables, length and width, have no values yet. The class contains an object’s method definitions Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java The Rectangle Class Definition public class Rectangle { private double length; private double width; // Instance variables A public class is accessible to other classes public Rectangle(double l, double w) { length = l; width = w; } // Rectangle constructor // Constructor method public double calculateArea() { return length * width; } // calculateArea // Access method Instance variables are usually private } // Rectangle class An object’s public methods make up its interface Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java The RectangleUser Class • The RectangleUser class will create and use 1 or more Rectangle instances. An application has a main() method Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java The RectangleUser Class Definition Class Definition An application must have a main() method public class RectangleUser { public static void main(String argv[]) { Rectangle rectangle1 = new Rectangle(30,10); Rectangle rectangle2 = new Rectangle(25,20); System.out.println("rectangle1 area " + rectangle1.calculateArea()); System.out.println("rectangle2 area " + rectangle2.calculateArea()); } // main() } // RectangleUser Object Creation Object Use Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Creating Rectangle Instances • Create, or instantiate, two instances of the Rectangle class: Rectangle rectangle1 = new Rectangle(30,10); Rectangle rectangle2 = new Rectangle(25, 20); The objects (instances) store actual values. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Using Rectangle Instances • We use a method call to ask each object to tell us its area: System.out.println("rectangle1 area " + rectangle1.calculateArea()); System.out.println("rectangle2 area " + rectangle2.calculateArea()); References to objects Printed output: Java, Java, Java, 2E by R. Morelli Method calls rectangle1 area 300 rectangle2 area 500 Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Define, Create, Use • Class definition: Define one or more classes (Rectangle, RectangleUser) • Object Instantiation: Create objects as instances of the classes (rectangle1, rectangle2) • Object Use: Use the objects to do tasks (rectangle1.calculateArea() ) Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java From the Library: Integer • The java.lang.Integer class is a wrapper class that contains methods to convert primitive data into objects and vice versa. • The parseInt() method converts a String into an int. • Example: Converts “54” into 54 int number = Integer.parseInt( “54”); Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Example: Input a Number public class Grader { public static void main(String argv[]) throws IOException BufferedReader input = new BufferedReader (new InputStreamReader(System.in)); String inputString; { int midterm1, midterm2, finalExam; // Three exam grades float sum; // The sum of the 3 grades System.out.print("Input your grade on the first midterm: "); inputString = input.readLine(); midterm1 = Integer.parseInt(inputString); System.out.println("You input: " + midterm1); Read an integer. // Similar code deleted here to input midterm2 and finalExam sum = midterm1 + midterm2 + finalExam; System.out.print("Your average in this course is "); System.out.println(sum/3); } // main() } // Grader Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Parameter Scope • Scope defines where a variable can be used in a program. • Local Scope: a parameter’s scope is limited to the method in which it is declared. • Class Scope: an instance variable can be accessed anywhere within the class instance. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Parameter Scope Drawing boxes around modules helps visualize scope. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Arguments and Parameters • Arguments refer to the values that are used in the method call or method invocation. pet1.setName("Socrates"); • Qualified names (dot notation), are used to refer to methods within other classes. • The arguments used in the method call must match the parameters defined in method definition. public void setName(String s) {…} Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Arguments and Parameters (cont) Create a CyberPet instance CyberPet pet1 = new CyberPet(); pet1.setName("Socrates"); String s = "Hal"; pet1.setName(s); Or, Call setName(), passing a String literal pass the value (“Hal”) stored in a String variable! Syntax errors: setName() requires a String argument pet1.setName(Socrates); pet1.setName(10); pet1.setName(); Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Constructor Invocation • A constructor is invoked only once, in conjunction with the new keyword, when an instance of an object is created. • The arguments in the method call must match the parameters in the method definition. Constructor invocations CyberPet pet1 = new CyberPet(); pet1.setName("Pet1"); CyberPet pet2 = new CyberPet("Pet2"); Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Retrieving Information from an Object • Methods with non-void return types can be used to extract information from an object. • A method that returns a value may or may not have a formal parameter list. Return Type Parameters public double average (int n1, int n2) { return (n1 + n2) / 2; } Return Value Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Passing a Value vs. Passing a Reference • Passing a primitive value differs from passing a reference value • Values of type int, boolean, float, and double are examples of primitive types. A primitive argument cannot be changed by a method call. • All objects (String, CyberPet) are reference types. Reference arguments can be changed by a method call. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Passing a Primitive Value • For primitive type parameters, a copy of the argument’s value is passed to the method. public void primitiveCall(int n) { n = n + 1; } primitiveCall() will be passed an int value 5 int x = 5; primitiveCall(x); x stores the value 5 5 is copied into n when primitiveCall() is called. So primitiveCall() has no access to x itself and x remains equal to 5 even though n is incremented. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Passing a Reference Value • For reference parameters, a reference to an object is passed to the method. public void referenceCall(CyberPet p) { referenceCall() will be passed p.setName("Mary"); } a reference to a CyberPet CyberPet x = new CyberPet("Harry"); referenceCall(x); x refers to a CyberPet named “Harry” Passing x is like passing the object itself. x’s name will be “Mary” after the method is called. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Flow of Control: Selection Structures • Selection Control Structures allow the program to select one of multiple paths of execution. • The path is selected based on some conditional criteria, as is the case in a flowchart. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java The Simple If Statement if ( boolean expression ) statement ; • If the boolean expression evaluates to true, the statement will be executed. Otherwise, it will be skipped. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Boolean Expressions • Boolean expressions are expression that evaluate to either true or false. • Examples of Boolean Expressions: true isSleeping false (1 + 1) == 2 • == is the equality operator in Java Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java The getState() Method public String getState() { if (isEating) return “Eating”; if (isSleeping) return “Sleeping”; return “Error in State”; } Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java The If-Then-Else Statement if ( boolean expression ) statement1 else statement2 ; • If the boolean expression is true, execute statement1, otherwise execute statement2. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Selection Statement Examples Simple if (isEating) return "Eating"; If If-then-else if (isEating) System.out.println("Is Eating"); else System.out.println("Is NOT Eating"); Multiway Selection if (isSleeping) System.out.println("I'm sleeping"); else if (isEating) System.out.println("I'm eating"); else if (isThinking) System.out.println("I'm thinking"); else System.out.println("Error: I don't know what I'm doing"); Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java The Switch/Break Structure • Multiway selection can also be done with the switch/break structure. switch ( integralExpression ) { case integralValue2 : statement1; break; case integralValue2 : statement2; break; … case integrealValueN : statementN; break; default: statementDefault; } Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Switch/Break Examples Correct: Prints m=2 int m = 2; switch (m) { case 1 : System.out.println(“m=1”); break; case 2 : System.out.println(“m=2”); break; case 3 : System.out.println(“m=3”); break; default: System.out.println(“default”);} Java, Java, Java, 2E by R. Morelli Error: Prints ch=b.ch=c, default char ch = ‘b’; switch (ch) { case ‘a’ : System.out.println(“ch=a”); case ‘b’ : System.out.println(“ch=b”); case ‘c’ : System.out.println(“ch=c”); default: System.out.println(“default”); } Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Inheritance: Object.toString() Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Overriding Object.toString() Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Polymorphic Object.toString() Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Boolean Data and Operators Truth table definitions of the boolean operators: AND (&&), OR (||), EXCLUSIVE-OR (^) and NOT (!). Oper 1 o1 true true false false Oper 2 o2 true false true false Boolean data have only two possible values, true and false. AND o1 && o2 true false false false OR o1 || o2 true true true false o1 || o2 is true if either o1 or o2 is true. o1 && o2 is true only if both o1 and o2 are true. Java, Java, Java, 2E by R. Morelli XOR o1 ^ o2 false true true false Copyright 2002. All rights reserved. NOT !o1 false false true true !o1 is true when o1 is false. o1 ^ o2 is true if either o1 or o2 is true, but not when both are true. Chapter 0: Computers, Objects, and Java Boolean Operator Precedence Precedence Order of Boolean Operators. Precedence Order 1 2 3 4 5 Operator Operation () ! ^ && || Parentheses NOT XOR AND OR In a mixed expression, NOT would be evaluated before XOR, which would be evaluated before AND, which would be evaluated before OR. AND is evaluated before OR because it has higher precedence. EXPRESSION true || true && false EVALUATION true || false ==> true (true || true) && false (true || (true && false) true && false ==> false true || false ==> true Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Parentheses can override the built-in precedence order. Chapter 0: Computers, Objects, and Java Numeric Data Types • Each bit can represent two values. • An n-bit quantity can represent 2n values. 28 = 256 possible values. • Effective Design: Platform Independence. In Java a data type’s size is part of its definition and therefore remains consistent across all platforms. Type byt e short int long Number of Bits 8 16 32 64 Range of Values -128 to + 127 -32768 to 32767 -2147483648 to 2147483647 -263 to -263 -1 float double 32 64 -3.40292347 E+38 to 3.40292347 E+38 -1.79769313486231570 E+308 to 1.79769313486231570E+308 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Standard Arithmetic Operators Operation Addition Subtraction Multiplication Division Modulus Operator + * / % Java m +2 m–2 m*2 x/y x%y • Typed Operators: Integer division gives an integer result. Mixed integer and floating point expressions give a floating point result. 3/2 ==> value 1 An integer result 3.0/2.0 3/2.0 3.0/2 ==> ==> ==> value 1.5 value 1.5 value 1.5 A floating point result A floating point result A floating point result • Modulus operator (%) gives remainder of integer division. 6 4 6 3 Java, Java, Java, 2E by R. Morelli % % % % 4 6 3 6 ==> ==> ==> ==> Copyright 2002. All rights reserved. 6 4 6 3 mod mod mod mod 4 6 3 6 equals equals equals equals 2 4 0 3 Chapter 0: Computers, Objects, and Java Promotion • Promotion Rule: When two different types are involved in an expression, the smaller type (fewer bits) is promoted to the larger type before the expression is evaluated. If either operand is: double float long byt e or short 3/2.0 3.0/2 The other is promoted to double float long int ==> 3.0/2.0 ==> value 1.5 ==> 3.0/2.0 ==> value 1.5 Java, Java, Java, 2E by R. Morelli // Floating point result // Floating point result Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Numeric Precedence • Precedence Rule: In a mixed expression arithmetic operators are evaluated in precedence order. Operators of the same precedence are evaluated from left to right. Precedence Operator Order 1 () 2 * / % 3 + - Evaluate: Step 1. Step 2. Step 3. Step 4. Step 5. Operation Parentheses Multiplication, Division, Modulus Addition, Sub traction 9 + 6 - 3 * 6 / 2 ((9 + 6) - ((3 * 6) / 2 )) ((9 + 6) - (18 / 2 ) ) ((9 + 6) - 9 ) ( 15 - 9 ) 6 Or to avoid subtle semantic errors. Java, Java, Java, 2E by R. Morelli 5/3/2.0 5/(3/2.0) Copyright 2002. All rights reserved. Parentheses can be used to clarify precedence order. // 0.5 // 3.33 Chapter 0: Computers, Objects, and Java Increment/Decrement Operators • Unary increment and decrement operators. Increment k, then use it. Expression j = ++k; j = k++; j = --k; j = k--; Operation Preincrement Postincrement Predecrement Postdecrement Interpretation k = k + 1; j = k; j = k; k = k + 1; k = k – 1; j = k; j = k; k = k – 1; Use k , then increment it. • Language Rule: If ++k or --k occurs in an expression, k is incremented or decremented before its value is used in the rest of the expression. If k++ or k-- occurs in an expression, k is incremented or decremented after its value is used in the rest of the expression. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Assignment Operators • Shortcut assignment operators: combine an arithmetic and assignment operation into a single expression. Operator Operation = Simple assignment += Addition then assignment -= Subtraction then assignment *= Multiplication then assignment /= Division then assignment %= Remainder then assignment Example Interpretation m = n; m = n; m += 3; m = m + 3; m -= 3; m = m - 3; m *= 3; m = m * 3; m /= 3; m = m / 3; m %= 3; m = m % 3; Example r += 3.5 + 2.0 * 9.3; r = r + ( 3.5 + 2.0 * 9.3 ); Java, Java, Java, 2E by R. Morelli // r = r + 22.1; Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Relational Operators • Some relational operators require two symbols (which should not be separated by a space between them). Operator < > <= >= == != Operation less than greater than less than or equal to greater than or equal to equal to not equal to Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Example 5 < 10 10 > 5 5 <= 10 10 >= 5 5 == 5 5 != 4 Chapter 0: Computers, Objects, and Java Numeric Operator Precedence • Precedence Rule: Relational and equality operations are performed after arithmetic operations. Precedence Operator Order 1 () 2 ++ -3 * / % 4 + 5 < > <= >= 6 == != Operation Parentheses Increment, Decrement Multiplication, Division, Modulus Addition, Subtraction Relational Operators Equality Operators • Use parentheses to disambiguate and avoid syntax errors. Evaluate: 9 + 6 <= 25 * 4 + 2 Step 1. (9 + 6) <= ( (25 * 4) + 2) Step 2. (9 + 6) <= ( 100 + 2) Step 3. 15 <= 102 Step 4. true Java, Java, Java, 2E by R. Morelli Evaluate: 9 + 6 <= 25 * 4 == 2 Step 1. ( (9 + 6) <= (25 * 4) ) == 2 Step 2. ( (9 + 6) <= 100 ) == 2 Step 3. ( 15 <= 100 ) == 2 Step 4. true == 2 // Syntax Error Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Character Data and Operators • The char type is a primitive data type. • A character is represented by a 16-bit unsigned integer. • A total of 216 = 65536 characters can be represented. • Java uses the international Unicode character set. • The first 128 Unicode characters are identical to the characters in the 7-bit ASCII (American Standard Code for Information Interchange). Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java The ASCII Characters Code Char 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 SP ! " # $ % & ' ( ) * + , - . / Code Char 48 49 50 51 52 53 54 55 56 57 0 1 2 3 4 5 6 7 8 9 Code Char 58 59 60 61 62 63 64 : ; < = > ? @ Code Char 65 66 67 68 69 70 71 72 73 74 75 76 77 A B C D E F G H I J K L M Code Char 78 79 80 81 82 83 84 85 86 87 88 89 90 N O P Q R S T U V W X Y Z Code Char 91 92 93 94 95 96 [ \ ] ^ _ ` Code Char 97 98 99 100 101 102 103 104 105 106 107 108 109 a b c d e f g h i j k l m Code Char 110 111 112 113 114 115 116 117 118 119 120 121 122 n o p q r s t u v w x y z Code Char 123 124 125 126 { | } ~ Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Character to Integer Conversions • Character data may be manipulated as characters or as integers. Cast operator. char ch = 'a'; System.out.println(ch); System.out.println((int)'a'); // Displays 'a' // Displays 97 • A cast operator converts one type of data (‘a’) into another (97). • Java allows certain implicit conversions but other conversions require an explicit cast. char ch; int k; k = ch; // convert a char into an int ch = k; // Syntax error: can’t assign int to char Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Type Conversions • Rule: Java permits implicit conversions from a narrower to a wider type. • A cast operator must be used when converting a wider into a narrower type. • The cast operator can be used with any primitive type. It applies to the variable or expression that immediately follows it: int m = 5, n = 4; char ch = (char)(m + n); // Casts m plus n to a char char ch = (char)m + n; // Error: right hand side is an int Promotion Rule: Java promotes ‘5’ to 5 before carrying out the addition, giving 5 + 4 = 9. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Relational Operators • Since char data are represented as integers, Java can use integer order to represent lexical order. Operation Operator Java True Expressio n ‘a’ < ‘b’ precedes < ch1 < ch2 ‘c’ > ‘a’ follows > ch1 > ch2 ‘a’ <= ‘a’ precedes or equals <= ch1 <= ch2 ‘a’ >= ‘a’ follows or equals >= ch1 >= ch2 ‘a’ == ‘a’ equal to == ch1 == ch2 ‘a’ != ‘b’ not equal to != ch1 != ch2 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Example Character Conversions • Convert a character from lowercase to uppercase. (char)('a' - 32) ==> // Here’s Step 1. (char)((int)'a' - 32) // Step 2. (char)(97 - 32) // Step 3. (char) (65) // Step 4. 'A' // 'A' how it works: Java promotes 'a' to int Subtract Cast result to a char Giving 'A' • Convert a digit to an integer by subtracting ‘0’. ('9' - '0') ==> (57 - 48) ==> 9 Promotion Rule: Java promotes ‘9’ to 9 and ‘0’ to 0 before carrying out the subtraction. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Conversion Methods Return type is char public char toUpperCase (char ch) { if ((ch >= 'a') && (ch <= 'z')) return (char)(ch - 32); return ch; } Parameter is char public int digitToInteger (char ch) { if ((ch >= '0') && (ch <= '9')) return ch - '0'; return -1 ; Return } Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. type is int Chapter 0: Computers, Objects, and Java From the Java Library: java.lang.Math • The java.lang.Math class provides common mathematical functions such as sqrt(). The Math class can not be subclassed or instantiated. public final class Math {// final class cannot be subclassed private Math() {} // private constructor cannot be invoked ... public static native double sqrt (double a) throws ArithmeticException; } All Math class methods are static class methods. They are invoked as follows: Math.sqrt(55.3) Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Math Class Methods Method Description Examples abs(int x) abs(long x) abs(float x) ceil(double x) absolute value of x if x >= 0 abs(x) is x if x < 0 then abs(x) is -x rounds x to the sma llest integer not le ss than x rounds x to the large st integer not grea ter than x natural loga rithm of x ceil(8.3) is 9 ceil(-8.3) is -8 floor(8.9) is 8 floor(-8.9) is -9 log(2.718282 ) is 1 pow(3,4) is 81 pow(16.0, 0.5) is 4.0 random() is 0.5551 random() 0.8712 round(double x) x raised to the y power (xy) gener ates a pseudorandom number in the interval [0,1) rounds x to an integer sqrt(double x) square root of x floor(double x) log(double x) pow(double x, double y) double random() Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. round(26.51) i s 27 round (26.499) is 26 sqrt(4.0) is 2 Chapter 0: Computers, Objects, and Java Math Class Example: Rounding • When representing currency, it is often necessary round numbers to two decimal places: Algorithm to round 75.199999 1. Multiply the number by 100, giving 7519.9999. 2. Add 0.5 to the number giving 7520.4999. 3. Drop the fraction part giving 7520 4. Divide the result by 100, giving 75.20 • In Java, using the Math.floor() method: 3 1 2 4 R = Math.floor(R * 100.0 + 0.5) / 100.0; Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java From the Java Library: NumberFormat • Java provides the java.text.NumberFormat class for representing currency and percentage values. An abstract class cannot be instantiated... …so use the static getInstance() methods to create an instance. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java From the Java Library: NumberFormat • Java provides the java.text.NumberFormat class for representing currency and percentage values. An abstract class cannot be instantiated... public abstract class NumberFormat extends Format { // Class methods public static final NumberFormat getInstance(); public static final NumberFormat getCurrencyInstance(); public static final NumberFormat getPercentInstance(); // Public instance methods …so use the public final String format(double number); public final String format(long number); getInstance() methods public int getMaximumFractionDigits(); create an instance. public int getMaximumIntegerDigits(); public void setMaximumFractionDigits(int newValue); public void setMaximumIntegerDigits(int newValue); } Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java to Example: Calculating Compound Interest • Problem: Write an application that compares the difference between daily and annual compounding of interest for a Certificate of Deposit. • Use the formula a = p(1 + r)n, where: – a is the CD’s value at the end of the nth yr – p is the principal or original investment amount – r is the annual interest rate – n is the number of years or compounding period • Effective Design: Method Length. Methods should be focused on a single task. If you find your method getting longer than 20-30 lines, divide it into separate methods. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Design: The CDInterest Class Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java The CDInterest Application import java.io.*; import java.text.NumberFormat; // Import the Java I/O Classes // For formatting as $nn.dd or n% public class CDInterest { private BufferedReader input = new BufferedReader // For input (new InputStreamReader(System.in)); private String inputString; // Stores the input private double principal; // The CD's initial principal private double rate; // CD's interest rate private double years; // Number of years to maturity private double cdAnnual; // Accumulated principal, annual private double cdDaily; // Accumulated principal, daily public static void main( String args[] ) throws IOException { CDInterest cd = new CDInterest(); cd.getInput(); cd.calcAndReportResult(); } // main() } // CDInterest Algorithm: Input, process, output. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java CDInterest.getInput() Method The readLine() method might cause an IOException. private void getInput() throws IOException { // Prompt the user and get the input System.out.println(”Compares daily and annual CD compounding."); System.out.print("Input the initial principal, e.g. 1000.55 > "); inputString = input.readLine(); principal = Double.parseDouble(inputString); System.out.print("Input the interest rate, e.g. 6.5 > "); inputString = input.readLine(); rate = (Double.parseDouble(inputString)) / 100.0; System.out.print("Input the number of years, e.g., 10.5 > "); inputString = input.readLine(); years = Double.parseDouble(inputString); Input must } //getInput() be converted to double. Input values are stored in instance variables. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java CDInterest.calcAndReportResult() Method private void calcAndReportResult() { // Calculate and output the result NumberFormat dollars = NumberFormat.getCurrencyInstance(); // Set up formats NumberFormat percent = NumberFormat.getPercentInstance(); percent.setMaximumFractionDigits(2); cdAnnual = principal * Math.pow(1 + rate, years); cdDaily = principal * Math.pow(1 + rate/365, years NumberFormat used to format // Calculate class interest * 365); the output. // Print the results System.out.println("The original principal is " + dollars.format(principal)); System.out.println("The resulting principal compounded daily at " + percent.format(rate) + " is " + dollars.format(cdDaily)); System.out.println("The resulting principal compounded yearly at " + percent.format(rate) + " is " + dollars.format(cdAnnual)); } // calcAndReportResult() This program compares daily and annual compounding for a CD. Input the CD's initial principal, e.g. 1000.55 > 10000 Input the CD's interest rate, e.g. 6.5 > 7.768 Input the number of years to maturity, e.g., 10.5 > 10 The original principal is $10,000.00 The resulting principal compounded daily at 7.77% is $21,743.23 The resulting principal compounded yearly at 7.77% is $21,129.94 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Output is properly formatted. Chapter 0: Computers, Objects, and Java Counting Loops • The for statement is used for counting loops. for (int k = 0; k < 100; k++) System.out.println("Hello"); // For 100 times // Print "Hello" • Zero-indexing: the loop counter or loop variable k, known iterates between 0 and 99. • For statement syntax: for ( initializer ; loop entry condition ; updater ) for loop body ; Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java The For Structure • Syntax: for ( k = 0 ; k < 100 ; k++ ) System.out.println(“Hello”); • Semantics: Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Loop Variable Scope • If k is declared within the for statement, it cannot be used after the for statement: for (int k = 0; k < 100; k++) System.out.println("Hello"); System.out.println("k = " + k); // Syntax error, k is undeclared • If k is declared before the for statement, it can be used after the for statement: int k = 0; // Declare the loop variable here for (k = 0; k < 100; k++) System.out.println("Hello"); System.out.println("k = " + k); // So it can be used here Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Compound Loop Body • Compound statement or block :a sequence of statements enclosed within braces, {...}. • For loop body: Can be a simple or compound statement. for (int k = 0; k < 100; k++) // Print 0 5 10 15 ... 95 if (k % 5 == 0) // Loop body is a single if statement System.out.println("k= " + k); for (char k = 'a' ; k <= 'z'; k++) System.out.print (k + " "); for (int k = 1 ; k <= 10; k++) { int m = k * 5; System.out.print (m + " "); } for (int k = 1 ; k <= 10; k++) int m = k * 5; System.out.print (m + " "); // Print 'a' 'b' 'c' ... 'z' // Loop body is a single print() // Print 5 10 15 20 ... 50 // Begin body // End body Compound statement. // Loop body // Syntax error: Outside scope of loop Debugging Tip: Don’t forget the braces! Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Nested Loops • Suppose you wanted to print the following table: 1 2 3 4 2 4 6 8 3 6 9 12 4 8 12 16 5 10 15 20 6 12 18 24 7 14 21 28 8 16 24 32 9 18 27 36 • You could use a nested for loop. The outer loop prints the four rows and in each row, the inner loop prints the 9 columns. for (int row = 1; row <= 4; row++) { // For each of 4 rows for (int col = 1; col <= 9; col++) // For each of 9 columns System.out.print(col * row + "\t"); // Print 36 numbers System.out.println(); // Start a new row } // for row Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Example: Car Loan Table • Design a program to print a table for the total cost of car financing options. Loan Rates Years Year Year Year Year Year Year Year 2 3 4 5 6 7 8 8% $23,469.81 $25,424.31 $27,541.59 $29,835.19 $32,319.79 $35,011.30 $37,926.96 9% $23,943.82 $26,198.42 $28,665.32 $31,364.50 $34,317.85 $37,549.30 $41,085.02 10% $24,427.39 $26,996.07 $29,834.86 $32,972.17 $36,439.38 $40,271.19 $44,505.94 11% $24,920.71 $27,817.98 $31,052.09 $34,662.19 $38,692.00 $43,190.31 $48,211.60 • Nested loop algorithm: Outer loop iterates over the years 2 through 8. The inner loop iterates over the rates 8 through 11. • Cost Formula: a = p(1 +r)n where total cots is a, for a loan of p at a rate of r for a period of n years. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Implementation: CarLoan Class formats the output. NumberFormat import java.text.NumberFormat; public class CarLoan { public static void main(String args[]) { double carPrice = 20000; // Car's actual price double carPriceWithLoan; // Cost of the car plus financing NumberFormat dollars = NumberFormat.getCurrencyInstance(); NumberFormat percent = NumberFormat.getPercentInstance(); percent.setMaximumFractionDigits(2); // Print table for (int rate = 8; rate <= 11; rate++) // Print column heading System.out.print("\t" + percent.format(rate/100.0) + "\t" ); System.out.println(); for (int years = 2; years <= 8; years++) { // For years 2..8 System.out.print("Year " + years + "\t"); // Print row heading for (int rate = 8; rate <= 11; rate++) { // Calc and print value carPriceWithLoan = carPrice * Math.pow(1 + rate / 100.0 / 365.0, years * 365.0); System.out.print(dollars.format(carPriceWithLoan) + "\t"); } // for rate System.out.println(); // Start a new row } // for years } // main() } // CarLoan Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Conditional Loops • 3N + 1 problem: If N is any positive integer, then the sequence generated by the following rules will always terminate at 1: Case N is odd N is even • Non-counting algorithm: Algorithm for computing the 3N+1 sequence While N is not equal to 1, do: { Print N. If N is even, divide it by 2. If N is odd, multiply N by 3 and add 1. } Print N Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Operation N=3 * N +1 N=N/2 The loop iterates as long as N != 1 Sentinel bound. The loop terminates when N equals the sentinel value 1. Chapter 0: Computers, Objects, and Java The While Structure • While structure to solve the 3N+1 problem: Initializer Loop body N = 50; while (N != 1) { // System.out.print(N + " "); if (N % 2 == 0) // N = N / 2; // else // N = 3 * N + 1; // } System.out.println(N); // Loop entry condition While N not 1 // Print N If N is even divide it by 2 Updaters If N is odd multiply N by 3 and add 1 Print N • Java’s while statement: while ( loop entry condition ) loop body ; Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Unlike the for statement, the while statement has no builtin initializer and updater. Chapter 0: Computers, Objects, and Java Principles of the While Structure • Effective Design: Loop structure. A loop structure must include an initializer, a boundary condition, and an updater. The updater should guarantee that the boundary condition is reached, so the loop will eventually terminate. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java The Do-While Structure • Problem: How many days will it take for half the lawn to disappear if it loses 2% of its grass a day? Initializer Loop body public int losingGrass(double perCentGrass) { double amtGrass = 100.0; // Initialize amount of grass int nDays = 0; // Initialize day counter do { // Repeat amtGrass -= amtGrass * LOSSRATE; // Update grass ++nDays; // Increment days } while (amtGrass > perCentGrass); // While 50% grass return nDays / 7; // Return number of weeks } // losingGrass() Updater Limit bound: Terminate when a limit is reached. • Java’s do-while statement : do loop body while ( loop entry condition ) Java, Java, Java, 2E by R. Morelli ; Copyright 2002. All rights reserved. No built-in initializer or updater. Chapter 0: Computers, Objects, and Java Principles of the Do-While Structure • Effective Design: Do-While Structure. • The do-while loop is designed for solving problems in which at least one iteration must occur. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Example: Computing Averages • Problem: Compute your exam average. Grades, represented as real numbers will be input from the keyboard using the sentinel value 9999 to signify the end of the list. While loop works even if no grades are entered initialize runningTotal to 0 // Initialize initialize count to 0 Priming read: Read a prompt and read the first grade // Priming read while the grade entered is not 9999 { // Sentinel bound value to initialize loop add it to the runningTotal variable and to update it add 1 to the count prompt and read the next grade // Update } if (count > 0) // Guard against dividing by 0 divide runningTotal by count output the average as the result Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Design: Modularity and Localization • Design: Use separate methods for input and averaging tasks and call getInput() when needed. public double inputAndAverageGrades() throws IOException { } grade = getInput(); while (grade != 9999) { runningTotal += grade; count++; grade = getInput(); } // while // Initialize: priming input // Loop test: sentinel if (count > 0) return runningTotal / count; else return 0; // Guard against divide-by-zero // Return the average // Update: get next input // Special (error) return value private double getInput() throws IOException { System.out.print("Input grade (e.g., 85.3) or 9999 "); System.out.print("to indicate the end of the list >> "); String inputString = input.readLine(); double grade = Double.parseDouble(inputString); System.out.println("You input " + grade + "\n"); return grade; } Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Introduction • A data structure is a collection of data that is organized (structured) in some way. • A string is a collection of character (char) data. Strings are important data structures in a programming language • Strings are used to represent a wide variety of data. • In Java, the Object.toString() method represents an object as a string. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java String Basics • A java.lang.String object is a sequence of characters plus a collection of methods for manipulating strings. • Unlike other Java objects, Strings have certain characteristics in common with the primitive data types. • For example, strings can have literals. A String literal is a sequence of zero or more characters contained in double quotes -- for example, “Socrates” and “” (empty string). Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java The String Class Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Constructing Strings • String constructors: public String(); public String(String initial_value); // Creates an empty string // Creates a copy of a string • The following constructor statement creates a String object and makes name a reference to it: String name = new String(); String instance variables. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Constructing Strings (cont) • A literal -- e.g., “Socrates” -- is considered a reference to a String object. All occurrences of “Socrates” in a program refer to the same object. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Constructing Strings (cont) • When literals are assigned to String variables Java makes those variables serve as references to the literals. String name1 = ""; String name2 = "Socrates"; String name3 = "Socrates"; Java, Java, Java, 2E by R. Morelli // Reference to the empty string // References to "Socrates" Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Constructing Strings (cont) • New String objects are created whenever the String constructors are used: String name4 = new String(); String name5 = new String("Socrates"); String name6 = name4; Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. // Creates an object Chapter 0: Computers, Objects, and Java Concatenating Strings • When surrounded on either side by a String, the + symbol is used as a binary concatenation operator. It has the effect of joining two strings together. String lastName = "Onassis"; String jackie = new String("Jacqueline " + "Kennedy " + lastName); “Jacqueline Kennedy Onassis” • Primitive types are automatically promoted to strings when mixed with concatenation operators. System.out.println("The square root of 25 = " + 5); Output: The square root of 25 = 5 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Indexing Strings • The number of characters in a string is its length. String String String String string1 string2 string3 string4 = = = = ""; // string1.length() ==> 0 "Hello"; // string2.length() ==> 5 "World"; // string3.length() ==> 5; string2 + " " + string3; // string4.length() ==> 11; • The position of a character within a string is called its index. Strings are zero indexed -- the first character is at index 0. Note: Because of zero indexing, the last character in a string of 8 characters is at index 7. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Converting Data to String • The String.valueOf() methods are class methods that convert primitive types into String objects. Static public String valueOf( primitive type String String String String number = new String (String.valueOf(128)); truth = new String (String.valueOf(true)); bee = new String (String.valueOf('B')); pi = new String(String.valueOf(Math.PI)); Recall that one refers to class methods by using the class name as the qualifier. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. // // // // ); Creates Creates Creates Creates "128" "true" "B" "3.14159" Note the difference between ‘B’ and “B” Chapter 0: Computers, Objects, and Java Finding Things within a String • The indexOf() and lastIndexof() methods are instance methods that can be used to find the index position of a character or a substring within a String. public public public public int int int int indexOf(int character); indexOf(int character, int startingIndex); indexOf(String string); indexOf(String string, int startingIndex); public public public public int int int int lastIndexOf(int character); lastIndexOf(int character, int startingIndex); lastIndexOf(String string); lastIndexOf(String string, int startingIndex); Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java IndexOf() and LastIndexOf() • The indexOf() method searches from left to right within a String for either a character or a substring. • The lastIndexOf() method searches from right to left for a character or substring. String String String String string1 string2 string3 string4 = = = = ""; "Hello"; "World"; string2 + " " + string3; string1.indexOf('o') string2.indexOf('o') string3.indexOf('o') string4.indexOf('o') ==> ==> ==> ==> -1 4 1 4 string1.lastIndexOf('o') string2.lastIndexOf('o') string3.lastIndexOf('o') string4.lastIndexOf('o') ==> ==> ==> ==> -1 4 1 7 A return value of -1 means the character is not in the string. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java IndexOf() and LastIndexOf() • The indexOf() and lastIndexOf() methods can also be used to find substrings, such as “or”. String String String String string1 string2 string3 string4 = = = = ""; "Hello"; "World"; string2 + " " + string3; string1.indexOf("or") string2.indexOf("or") string3.indexOf("or") string4.indexOf("or") ==> ==> ==> ==> -1 -1 1 7 string1.lastIndexOf("or") string2.lastIndexOf("or") string3.lastIndexOf("or") string4.lastIndexOf("or") ==> ==> ==> ==> -1 -1 1 7 A return value of -1 means that “or” is not in the string. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Example: Keyword Search • Finding a keyword within a string is a task that word processors and browsers must do. • Algorithm Design: Find every occurrence of some keyword, K, within a string, S: Suppose S is our string and K is the keyword. Initialize a counter variable and result string. Set P to the indexOf() the first occurrence of K in S. While ( P != -1 ) While loop because there may Increment the counter be 0 or more occurrences. Insert P into the result string Set P to the next location of the keyword in S Insert the count into the result string Return the result string as a String When P is -1, there are no more occurrences of K in S. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Implementation: Keyword Search /** * Pre: s and keyword are any Strings * Post: keywordSearch() returns a String containing the * number of occurrences of keyword in s, followed * by the starting location of each occurrence Bound: When ptr is */ public String keywordSearch(String s, String keyword) { -1, no more String resultStr = ""; occurrences of s. int count = 0; int ptr = s.indexOf(keyword); while (ptr != -1) { Initializer ++count; Updater resultStr = resultStr + ptr + " "; ptr = s.indexOf(keyword, ptr + 1); // Find next occurrence } resultStr = count + ": " + resultStr; // Insert the count return resultStr; // Return as a String } // keywordSearch() Test Performed keywordSearch( "this is a test","is") keywordSearch( "able was i ere i saw elba","a") keywordSearch( "this is a test","taste") Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Expected Result 2: 2 4 4: 0 6 18 24 0: Test data should test all possible outcomes. Chapter 0: Computers, Objects, and Java Automatic Garbage Collection • Immutability: Java Strings cannot be modified. Whenever you assign a new value to a String, Java must create a new String object and discard the old one. In resultStr = resultStr + ptr + “ “; Java will create a new object (b) referenced by resultStr: The original resultStr object has no more references to it so it has to be garbage collected which takes time. Java, Java, Java, 2E by R. Morelli This is the new resultStr. Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Library: java.lang.StringBuffer • Objects of java.lang.StringBuffer class are strings that can be modified. Some of its methods are: Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java The Revised keywordSearch() public String keywordSearch(String s, String keyword) { StringBuffer resultStr = new StringBuffer(); // Create StringBuffer int count = 0; int ptr = s.indexOf(keyword); while (ptr != -1) { ++count; resultStr.append(ptr + " "); // Insert letters into it ptr = s.indexOf(keyword, ptr + 1); The revised } resultStr.insert(0, count + ": "); keywordSearch() return resultStr.toString(); // Convert buffer back to a String uses a local } // keywordSearch() StringBuffer to build the result, but converts it back to String before returning. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Retrieving Parts of Strings • The String class contains methods to retrieve characters and substrings from a string. Takes the substring from startIndex to endIndex public char charAt(int index) public String substring(int startIndex) public String substring(int startIndex, int endIndex) Takes the substring from startIndex to the end of string. Note: endIndex points to index after the last character taken. String str = "HelloWorld"; str.substring(5) ==> "World" str.substring(3) ==> "loWorld"; // 0123456789 String str = "HelloWorld"; str.substring(5,7) ==> "Wo" str.substring(0,5) ==> "Hello"; str.substring(5, str.length()) ==> "World" Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Example: Names and Passwords • Problem: Suppose user names and passwords are stored as delimited strings where ‘:’ is the delimiter. Write methods to get the name and password. • Algorithm: Use the indexOf() smith:bg1s5xxx mccarthy:2ffo900ssi and substring() methods. public String getName(String str) { int posColon = str.indexOf(':'); // Find the delimiter String result = str.substring(0, posColon); // Extract the name return result; These 3 could be a single statement: } return str.substring(0, str.indexOf(‘:’)); public String getPassword(String str) { int posColon = str.indexOf(':'); // Find the delimiter String result = str.substring(posColon + 1); // Extract the password return result; } Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Processing Each Character in a String • For example, suppose you want to count the number of occurrences of a certain character in a string: Use the string’s length as a bound. // countChar counts the number of ch’s in str // Precondition: Neither str nor ch are null // Postcondition: countchar() == the number of ch in str public int countChar(String str, char ch) { int counter = 0; // Initialize a counter for (int k = 0; k < str.length(); k++) // For each character if (str.charAt(k) == ch) // If it's a ch counter++; // count it return counter; // Return the result } Possible off-by-one Error: Remember that the last character in a string is at index length()-1. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Miscellaneous String Methods • The String class contains additional useful string manipulation methods, including the following: Method Signature boolean endsWith( String suffix) boolean startsWith(String prefix) String toUpperCase() String toLowerCase() String trim() Example "Perfection".endsWith("tion") "Perfection".startsWith("Per") "Perfection".toUpperCase() "Perfection".toLowerCase() " Perfection ".trim() Value true true "PERFECTION" "perfection" "Perfection" • Note that methods such as toUpperCase(), toLowerCase(), and trim() produce a new String object because Strings cannot be modified. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java String Identity vs. String Equality • Methods for comparing strings: public boolean equals(Object anObject); // Overrides Object.equals() public boolean equalsIgnoreCase(String anotherString) public int compareTo(String anotherString) • Two strings are equal if they have the same letters in the same order: String s1 = "hello"; String s2 = "Hello"; s1.equals(s2) // false s1.equals("hello”); // true • Error: Using == to compare two strings. For objects, o1 == o2 means o1 and o2 are identical. • The == operator is equivalent to Object.equal() method: o1.equal(o2) means o1 and o2 are identical. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java String Identity vs. String Equality (cont) Given the following declarations String s1 = new String("hello"); String s2 = new String("hello"); String s3 = new String("Hello"); String s4 = s1; // s1 == String s5 = "hello"; String s6 = "hello"; We get the following equality results s1.equals(s2) s1.equals(s3) s1.equalsIgnoreCase(s3) s1.equals(s4) s1.equals(s5) s1.equals(s6) ==> ==> ==> ==> ==> ==> true false true true true true s4 And the following identity results s5 and s6 refer to the same (identical) literal object. Java, Java, Java, 2E by R. Morelli s1 s1 s1 s1 s5 == == == == == s2 s3 s4 s5 s6 Copyright 2002. All rights reserved. ==> ==> ==> ==> ==> false false true false true Chapter 0: Computers, Objects, and Java String Identity vs. String Equality (cont) • In this figure, s1, s2, s4, s5, and s6 are equal. • Strings s1 and s4 are identical, as are s5 and s6. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Library: java.util.StringTokenizer • Break up a string into its tokens -- e.g., breaking up a name and password pair in boyd:14irXp. • The StringTokenizer class is designed for this purpose. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java StringTokenizer (cont) • A StringTokenizer breaks a string into tokens separated by delimiters, which by default value are the whitespace characters: StringTokenizer sTokenizer = new StringTokenizer("This is an English sentence."); In this case, the period is part of last token Tokens This is an English sentence. • The delimiters can be specified as a String parameter: StringTokenizer sTokenizer = new StringTokenizer("http://troy.trincoll.edu/~jjj/index.html”, ":/"); Tokens Java, Java, Java, 2E by R. Morelli http troy.trincoll.edu ~jjj index.html Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java OO Design: Abstract Cipher Class • Problem: Create a collection of Cipher classes, including a Caesar cipher and a transposition cipher. • Methods used by all ciphers -- encrypt(), decrypt(), encode() and decode() -- should be defined or implemented in a superclass. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java OO Design: Abstract Cipher Class The Cipher class is abstract because some of its methods are not implemented. The encrypt() and decrypt() methods are the same for every subclass and should be implemented in the superclass. The encode() and decode() methods are different for every subclass, so they must be defined abstractly in the superclass. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Class Design: The Cipher Superclass The encrypt() and decrypt() methods work the same for every cipher, so they are completely implemented. import java.util.*; public abstract class Cipher { public String encrypt(String s) { StringBuffer result = new StringBuffer(""); // Use a StringBuffer StringTokenizer words = new StringTokenizer(s); // Break s into its words while (words.hasMoreTokens()) { // For each word in s result.append(encode(words.nextToken()) + " "); // Encode it } return result.toString(); // Return the result } // encrypt() public String decrypt(String s) { StringBuffer result = new StringBuffer(""); // Use a StringBuffer StringTokenizer words = new StringTokenizer(s); // Break s into words while (words.hasMoreTokens()) { // For each word in s result.append(decode(words.nextToken()) + " "); // Decode it } return result.toString(); // Return the decryption } // decrypt() Polymorphism: encode() and decode() are implemented differently in each cipher. public abstract String encode(String word); public abstract String decode(String word); } // Cipher Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. An abstract method has no body, no implementation. // Abstract methods Chapter 0: Computers, Objects, and Java Rules for Abstract Methods and Classes • Any class containing an abstract method must be declared an abstract class. • An abstract class cannot be instantiated. It must be subclassed. • A subclass of an abstract class may be instantiated only if it implements all of the superclass's abstract methods. A subclass that implements only some of the abstract methods must itself be declared abstract. • A class may be declared abstract even it contains no abstract methods. It could contain instances variables that are common to all its subclasses. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Class Design: Caesar Cipher • In a Caesar cipher, which was first used by Julius Caesar in the Gaulic campaigns, letters of the alphabet are shifted by three letters, wrapping around at the end of the alphabet: PlainText: abcdefghijklmnopqrstuvwxyz CaesarShifted: defghijklmnopqrstuvwxyzabc • An expression to shift a character: ch = (char)('a' + (ch -'a'+ 3) % 26); (char)('a' + (ch -'a'+ 3) % 26) (char)('a' + ('y' - 'a' +3) % 26) (char)(97 + (121 - 97 + 3) % 26) (char)(97 + (27 % 26)) (char)(97 + 1) (char)(98) 'b' Java, Java, Java, 2E by R. Morelli // // // // // // // Perform Caesar shift Perform Caesar shift on 'y' Map 'y' to 0..25 Shift by 3, wrapping around Map result back to 'a' to 'z' Convert from int to char Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Implementation: Caesar Class public class Caesar extends Cipher { Caesar inherits from Cipher, so it must implement encode() and decode(). public String encode(String word) { StringBuffer result = new StringBuffer(); for (int k = 0; k < word.length(); k++) { char ch = word.charAt(k); ch = (char)('a' + (ch -'a'+ 3) % 26); result.append(ch); } return result.toString(); } // encode() // Initialize a string buffer // For each character in word // Get the character // Perform caesar shift // Append it to new string // Return the result as a string public String decode(String word) { StringBuffer result = new StringBuffer(); // Initialize a string buffer for (int k = 0; k < word.length(); k++) { // For each character in word char ch = word.charAt(k); // Get the character ch = (char)('a' + (ch - 'a' + 23) % 26); // Perform reverse caesar shift result.append(ch); // Append it to new string } return result.toString(); // Return the result as a string } // decode() } // Caesar Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Implementation: Transpose Class Transpose inherits from Cipher, so it must implement encode() and decode(). public class Transpose extends Cipher { public String encode(String word) { StringBuffer result = new StringBuffer(word); return result.reverse().toString(); } // encode() public String decode(String word) { return encode(word); } // decode } // Transpose // Initialize a buffer // Reverse and return it // Just call encode This version of transpose just reverses the word using the reverse() method from StringBuffer. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java The TestEncrypt Class public class TestEncrypt { public static void main(String argv[]) { Caesar caesar = new Caesar(); String plain = "this is the secret message"; // Here's the message String secret = caesar.encrypt(plain); // Encrypt the message System.out.println(" ******** Caesar Cipher Encryption *********"); System.out.println("PlainText: " + plain); // Display the results System.out.println("Encrypted: " + secret); System.out.println("Decrypted: " + caesar.decrypt(secret)); // Decrypt Transpose transpose = new Transpose(); secret = transpose.encrypt(plain); System.out.println("\n ******** Transpose Cipher Encryption *********"); System.out.println("PlainText: " + plain); // Display the results System.out.println("Encrypted: " + secret); System.out.println("Decrypted: " + transpose.decrypt(secret)); } // main() } // TestEncrypt Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java The TestEncrypt Output A Caesar cipher has different letters from the plaintext. ********* Caesar Cipher Encryption ********* PlainText: this is the secret message Encrypted: wklv lv wkh vhfuhw phvvdjh Decrypted: this is the secret message ********* Transpose Cipher Encryption ********* PlainText: this is the secret message Encrypted: siht si eht terces egassem Decrypted: this is the secret message A Transpose cipher has the same letters as the plaintext, but they’re rearranged. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java One-Dimensional Arrays • An array element is referred to its position within the array. • For an n-element array named arr, the elements are named arr[0], arr[1], arr[2], ...,arr[n-1]. • The following array contains 15 int elements. Arrays are zero indexed. • Array syntax : arrayname [ subscript ] where arrayname is the array name and subscript is an integer giving the element’s relative position. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Referring to Array Elements • Valid References: Suppose j is 5 and k is 7. arr[4] arr[j] arr[j + k] arr[k % j] // Refers to 16 // Is arr[5] which refers to 20 // Is arr[5+7] which is arr[12] which refers to 45 // Is arr[7%5] which is arr[2] which refers to -1 • Invalid References: arr[5.0] arr['5'] arr["5"] arr[-1] arr[15] arr[j*k] // // // // // // 5.0 is a float and can't be an array subscript '5' is a character not an integer "5" is a string not an integer Arrays cannot have negative subscripts The last element of arr has subscript 14 Since j*k equals 35 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Are Arrays Objects? • Arrays are (mostly) treated as objects: – Instantiated with the new operator. – Have instance variables (e.g., length). – Array variables are reference variables. – As a parameter, a reference to the array is passed rather than copies of the array’s elements. • But… – There is no Array class. So arrays don’t fit into the Object hierarchy. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Declaring and Creating an Array • Creating a one-dimensional array: Indicate both the array’s element type and its length. • Declare the array’s name and create the array itself. int arr[]; arr = new int[15]; // Declare a name for the array // Create the array itself • Combine two steps into one: int arr[] = new int[15]; The array’s name is arr. The array contains 15 int variables. • 15 variables: arr[0], arr[1], .., arr[14] (zero indexed) Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Creating an Array of Strings Declare array variable. Instantiate the array. Store 5 Strings in it. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Creating an Array of CyberPets CyberPet pethouse[] = new CyberPet[3]; pethouse[0] = new CyberPet("Socrates"); pethouse[1] = new CyberPet("Plato"); pethouse[2] = new CyberPet("Aristotle"); // // // // Create Create Create Create an array of 3 CyberPets the first CyberPet the second CyberPet the third CyberPet • Debugging Tip: Creating a new array does not also create the objects that are stored in the array. They must be instantiated separately. There are four objects here. One array and 3 CyberPets. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Initializing Arrays • Array elements are initialized to default values: – Integer and real types are initialized to 0. – Reference types (objects) are initialized to null. • Arrays can be assigned initial values when they are created: int arr[] = { -2,8,-1,-3,16,20,25,16,16,8,18,19,45,21,-2 } ; String strings[] = { "hello", "world", "goodbye", "love"} ; • Java Language Rule: When an array initialization expression is used, don’t use the keyword new to create the array. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Assigning and Using Array Values • Subscripted array variables are used like other variables: arr[0] = 5; arr[5] = 10; arr[2] = 3; strings[0] = "who"; strings[1] = "what"; strings[2] = strings[3] = "where"; • A loop to assign the first 15 squares, 1, 4, 9 …, to for (int k = 0; k < arr.length; k++) the array arr: arr[k] = (k+1) * (k+1); • A loop to print the values of arr: for (int k = 0; k < arr.length; k++) System.out.println(arr[k]); Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Note: length is an instance variable, not a method. Chapter 0: Computers, Objects, and Java Example: Print an Array • Print an array of int and an array of double: public class PrintArrays { static final int ARRSIZE = 10; // The array's size static int intArr[] = new int[ARRSIZE]; // Create the int array static double realArr[] = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10 }; // And a double array public static void main(String args[]) { System.out.println("Ints \t Reals"); for (int k = 0; k < intArr.length; k++) System.out.println( intArr[k] + " \t " + realArr[k]); } // main() } // PrintArrays … in order to refer to them in static main() Java, Java, Java, 2E by R. Morelli Uninitialized int array has default values of 0. Copyright 2002. All rights reserved. These must be static ... Program Output Ints Reals 0 1.1 0 2.2 0 3.3 0 4.4 0 5.5 0 6.6 0 7.7 0 8.8 0 9.9 0 10.1 Chapter 0: Computers, Objects, and Java Example: Store the First 100 Squares public class Squares { static final int ARRSIZE = 100; static int intArr[] = new int[ARRSIZE]; // The array's size // Create an int array public static void main(String args[]) { for (int k = 0; k < intArr.length; k++) intArr[k] = (k+1) * (k+1); // Initialize the array System.out.print("The first 100 squares are"); // Print a heading for (int k = 0; k < intArr.length; k++) { // Print the array if (k % 10 == 0) System.out.println(" "); // 10 elements per row System.out.print( intArr[k] + " "); } // for Program Output } // main() The first 100 squares are } // Squares 1 4 9 16 25 36 49 64 81 100 121 144 169 196 225 256 289 324 361 400 441 484 529 576 625 676 729 784 841 900 961 1024 1089 1156 1225 1296 1369 1444 1521 1600 1681 1764 1849 1936 2025 2116 2209 2304 2401 2500 2601 2704 2809 2916 3025 3136 3249 3364 3481 3600 3721 3844 3969 4096 4225 4356 4489 4624 4761 4900 5041 5184 5329 5476 5625 5776 5929 6084 6241 6400 6561 6724 6889 7056 7225 7396 7569 7744 7921 8100 8281 8464 8649 8836 9025 9216 9409 9604 9801 10000 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Generating Random Numbers • A random number generator generates numbers that can be used to simulate a coin toss or die roll. • The numbers generated are pseudorandom. • Math.random() generates a double value in the range [0.0, 1.0) -- that is, 0.0 to 0.999999999. • Using Math.random() to simulate a coin flip: int coinFlip = (int)(Math.random() * 2); // Heads or tails • (Math.random() * 2) gives some value in the range 0.0 to 1.999999. When this value is converted to an int by (int), it gives either 0 or 1, corresponding to heads or tails. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Generating Random Numbers (cont) • An expression of the form (int)(Math.random() * N) will generate random integer values in the range 0 to N-1. • N is called the scaling factor. • To generate values in the range 0 to 5, use: (int)(Math.random() * 6); • To simulate a die roll we must shift the values into the range 1 to 6: int die = 1 + (int)(Math.random() * 6); Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Array Algorithm: Sorting • Bubble sort algorithm: On each pass through the array, the largest unsorted element “bubbles up” to the “top.”. • For an N element array, N-1 passes are needed: 1. For each of the N-1 passes over the entire array 2. For each of the N-1 pairs of adjacent elements in the array 3. If lower indexed element is greater than the higher indexed element 4. Swap the two elements 21 20 27 24 19 [20 21] 27 24 19 20 21 [ 24 27 ] 19 20 21 24 [19 27 ] 20 21 19 24 | 27 20 19 21 | 24 27 | 19 20 21 24 27 Java, Java, Java, 2E by R. Morelli // Unsorted array // Compare adjacent elements // Swap, if necessary // Pass 1, 27 bubbles up // Pass 2, 24 bubbles up // Pass 4, the array is sorted Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Class Design: The Sort Class Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Algorithm Design: Swapping Elements • A temporary variable must be used when swapping the values of two variables in memory. • Suppose you have the array: 1 4 2 8 • Swapping 4 and 2 the wrong way: arr[pair-1] = arr[pair]; arr[pair] = arr[pair-1]; results in: 1 2 2 8 • Swapping 4 and 2 the proper way: temp = arr[pair-1]; // Save first element in temp arr[pair-1] = arr[pair]; // Overwrite first with second arr[pair] = temp; // Overwrite second with temp (i.e.,first) results in: 1 2 4 8 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Method Design: bubbleSort() • Array parameters are references. Changes made to the array in the method will persist. /** * Goal: Sort the values in arr into ascending order * Pre: arr is not null. * Post: The values arr[0]...arr[arr.length-1] will be * arranged in ascending order. */ public void bubbleSort(int arr[]) { int temp; // Temporary variable for swap for (int pass = 1; pass < arr.length; pass++) // For each pass for (int pair = 1; pair < arr.length; pair++) // For each pair if (arr[pair-1] > arr[pair]) { // Compare temp = arr[pair-1]; // and swap arr[pair-1] = arr[pair]; arr[pair] = temp; } // if } // bubbleSort() Note how an array parameter is specified. Note how an array argument is passed. int myArr[] = { 21, 13, 5, 10, 14 }; bubbleSort(myArr); Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Passing an Array Parameter When an array is passed to a method, both the array reference (anArr) and the parameter (arr) refer to the same object. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Pass by Value • Pass by Value: When a value of primitive type is passed to a method, a copy of the value is passed. Any changes to the copy, have no effect on the original value. public void add1(int n) { Num’s value is copied to n System.out.println("n = " + n); n = n + 1; System.out.println("n = " + n); } • For the add1() method, any changes made to its parameter n do not persist beyond the method. int Num = 5; System.out.println("Num = " + Num); add1(Num); System.out.println("Num = " + Num); Java, Java, Java, 2E by R. Morelli outputs Copyright 2002. All rights reserved. Num n = n = Num = 5 5 6 = 5 Chapter 0: Computers, Objects, and Java Pass by Reference • Pass by Reference: When a reference to an object (e.g., and array) is passed to a method, changes made to the object do persist beyond the method. int intArr[] = { 21, 20, 27, 24, 19 }; Sort sorter = new Sort(); sorter.print(intArr); sorter.bubbleSort(intArr); sorter.print(intArr); Outputs Java, Java, Java, 2E by R. Morelli // Initialize // Print // Sort // Print again 21 19 Copyright 2002. All rights reserved. 20 20 27 21 24 24 19 27 Chapter 0: Computers, Objects, and Java Implementation: The Sort Class public class Sort { public void print(int arr[]) { for (int k = 0; k < arr.length; k++) System.out.print( arr[k] + " \t "); System.out.println(); } // print() // For each integer // Print it public static void main(String args[]) { int intArr[] = { 21, 20, 27, 24, 19 }; Sort sorter = new Sort(); sorter.print(intArr); sorter.bubbleSort(intArr); sorter.print(intArr); } // main() public void bubbleSort(int arr[]) { } // Sort int temp; for (int pass = 1; pass < arr.length; pass++) for (int pair = 1; pair < arr.length; pair++) if (arr[pair-1] > arr[pair]) { temp = arr[pair-1]; arr[pair-1] = arr[pair]; arr[pair] = temp; } // if } // bubbleSort() Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Design: The Search Class Uses Two different search() strategies. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Array Algorithm: Sequential Search • Problem: Search an array for a key value. If the array is not sorted, we have to search sequentially. /** * Performs a sequential search of an integer array * @param arr is the array of integers * @param key is the element being searched for * @return the key's index is returned if the key is * found otherwise -1 is returned * Pre: arr is not null * Post: either -1 or the key's index is returned */ Return as public int sequentialSearch(int arr[], int key) { soon as the for (int k = 0; k < arr.length; k++) if (arr[k] == key) key is return k; found. return -1; // Failure } // sequentialSearch() Search fails if you get to the end of the array. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Array Algorithm: Binary Search • Binary search uses a divide-and-conquer strategy on a sorted array. • Divide the array in half on each iteration, limiting the search to that half which could contain the key. • Example: Guessing a number between 1 and 10. 1 2 3 4 5 6 7 8 9 10 Too high 1 2 3 4 Too low First guess 6 7 8 9 10 Second guess Second guess Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java The binarySearch() Method • Algorithm Design: low and high point to first and last elements of the subarray, and mid gives its current midpoint. If low becomes greater than high, the key is not in the array. /** * Pre: arr is an array of int in ascending order * Post: -1 or arr[k] where arr[k] == key */ public int binarySearch(int arr[], int key) { int low = 0; // Initialize bounds int high = arr.length - 1; while (low <= high) { // While not done int mid = (low + high) / 2; if (arr[mid] == key) return mid; // Success else if (arr[mid] < key) low = mid + 1; // Search top half else high = mid - 1; // Search bottom half } // while return -1; // Post condition: low > high implies search failed } // binarySearch() Calculate a new midpoint. Update low and high to cut the array in half. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Two-Dimensional Arrays • Two-dimensional array: an array whose components are themselves arrays. • Example: Compiling daily rainfall data. A onedimensional array makes it hard to calculate average monthly rainfall: double rainfall[] = new double[365]; • A two-dimensional array is an array of arrays. The first is the 12 months, indexed from 0 to 11. Each month array is an array of 31 days, indexed from 0 to 30. double rainfall[][] = new double[12][31]; Month index Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Day index Chapter 0: Computers, Objects, and Java A More Appropriate 2-D Representation • What is rainfall[0][4] ? Avoid zero indexing by creating an extra row and column and ignoring the 0 indexes. double rainfall[][] = new double[13][32]; Don’t use the 0 indexes. January 5 is now at rainfall[1][5] rainfall[1][5] = 1.15; // Rainfall for January 5 System.out.println(rainfall[4][1]); // April 1st rainfall[13][32] = 0.15 ; // No such element rainfall[11][32] = 1.3; // No such column rainfall[13][30] = 0.74; // No such row Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Initializing a Two-Dimensional Array • We can use unit indexed loops to initialize the twodimensional rainfall array: /** * Initializes a 2-D array * @param rain is a 2D-array of rainfalls A 2-D array * Pre: rain is non null parameter * Post: rain[x][y] == 0 for all x,y in the array * Note that the loops use unit indexing. */ public void initRain(double rain[][]) { for (int month = 1; month < rain.length; month++) for (int day = 1; day < rain[month].length; day++) rain[month][day] = 0.0; } // initRain() Nested for loops iterate 12 x 31 times • Method call: pass the name of the array to the method: initRain(rainfall); // Sample method call Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Introduction • No matter how well designed a program is, there is always the chance that some kind of error will arise during its execution. • A well-designed program should include code to handle errors and other exceptional conditions when they arise. • This chapter describes Java's exception handling features. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Handling Exceptional Conditions • The avgFirstN() method expects that N > 0. • If N = 0, a divide-by-zero error occurs in avg/N. /** * Precondition: N > 0 * Postcondition: avgFirstN() equals the average of (1+2+…+N) */ public double avgFirstN(int N) { duuble sum = 0; for (int k = 1; k <= N; k++) sum += k; return sum/N; // What if N is 0 ?? } // avgFirstN() Bad Design: Doesn’t guard against divide-by-0. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Traditional Error Handling • Error-handling code built right into the algorithm: /** * Precondition: N > 0 * Postcondition: avgFirstN() equals the average of (1+2+…+N) */ public double avgFirstN(int N) { duuble sum = 0; if (N <= 0) { System.out.println(“ERROR avgFirstN: N <= 0. Program terminating.”); System.exit(0); } for (int k = 1; k <= N; k++) sum += k; return sum/N; // What if N is 0 ?? } // avgFirstN() It’s sometimes risky to exit a program like this. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Java’s Exception Hierarchy • Unchecked exceptions: belong to a subclass of RuntimeException and are not monitored by the compiler. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Some Important Exceptions Class Description ArithmeticException ArrayIndexOutOfBoundsException FileNotFoundException IllegalArgumentException IndexOutOfBoundsException NullPointerException NumberFormatException StringIndexOutOfBoundsException Java, Java, Java, 2E by R. Morelli Division by zero or some other kind of arithmetic problem An array index is less than zero or greater than or equal to the array's length Reference to a unfound file Method call with improper argument An array or string index out of bounds Reference to an object which has not been instantiated Use of an illegal number format, such as when calling a method A String index less than zero or greater than or equal to the String's length Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Some Common Exceptions Class Method Exception Raised Description Double valueOf(String) NumberFormatException The String is not a double Integer parseInt(String) NumberFormatException The String is not a int String String(String) indexOf(String) lastIndexOf(String) charAt(int) NullPointerException NullPointerException NullPointerException StringIndexOutOfBounds Exception StringIndexOutOfBounds Exception StringIndexOutOfBounds Exception The String is null The String is null The String is null substring(int) substring(int,int) Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. The int is invalid index The int is invalid index An int is invalid index Chapter 0: Computers, Objects, and Java Checked Exceptions • Checked exception: must either be caught or declared within the method where it is thrown. • Monitored by the Java compiler. IOException must • Example: IOException be declared ... public static void main(String argv[]) throws IOException { BufferedReader input = new BufferedReader (new InputStreamReader(System.in)); String inputString = input.readLine(); // May throw IOException } ...because readLine() may cause it. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java The Exception Class Simple: only constructor methods. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Exception Handling • When an exception occurs, an object will throw an exception. The exception handler, possibly the same object, will catch it. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Example: Two Classes Throw in one class... …Catch in the other. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Try, Throw and Catch public class CalcAverage { public double avgFirstN(int N ){ double sum = 0; try { // Try block: exception thrower if (N <= 0) throw new Exception("ERROR: Can't average 0 slements"); for (int k = 1; k <= N; k++) sum += k; return sum/N; } } // CalcAverage Throw in one class... ...Catch in the other. public class CalcAvgTest { public static void main(String args[]) { try { CalcAverage ca = new CalcAverage(); System.out.println(“AVG + “ + ca.avgFirstN(0)); } catch (ArithmeticException e) { // Catch block: exception handler System.out.println(e.getMessage()); Effective Design: Java’s exception e.printStackTrace(); handling mechanism allows you to System.exit(0); } separate normal code from } exception handling code. } // CalcAvgTest Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Try/Throw/Catch • A try block contains statements that may cause an exception. It signals your intention to handle the exception. • Throwing an exception is like pulling the fire alarm. Once an exception is thrown, control is transferred to an appropriate catch clause. • Exceptions are handled in the catch clause. • The finally block is optional. Unless the program is exited, it is executed whether an exception is thrown or not. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Try/Throw/Catch (cont) try { // Block of statements // At least one of which may throw an exception if ( /* Some condition obtains */ ) throw new ExceptionName(); } catch (ExceptionName ParameterName) { // Block of statements to be executed // If the ExceptionName exception is thrown in try } ... // Possibly other catch clauses } catch (ExceptionName2 ParameterName) { // Block of statements to be executed // If the ExceptionName2 exception is thrown in try } finally { // Optional block of statements that is executed // Whether an exception is thrown or not } Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Restrictions on try/catch/finally • A try block must be followed by one or more catch clauses. • A catch clause may only follow a try block. • A throw statement is used to throw both checked and unchecked exceptions. • Unchecked exceptions belong to RuntimeException or its subclasses. • Checked exceptions must be caught or declared. • A throw statement must be contained within the dynamic scope of a try block, and the type of Exception thrown must match at least one of the try block’s catch clauses. Or, the throw statement must be contained within a method or constructor that has a throws clause for the type of thrown Exception. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Dynamic versus Static Scope Static scope: how the program is written. Dynamic scope: how the program is run. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java The Method Call Stack • The method call stack keeps track of the methods that are called during program execution. The current method is on the top of the stack. Dynamic scope: main() calls method1() which calls method2() which calls method3(). Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Default Exception Handling • Java can handle unchecked exceptions itself. public class CalcAverage { public double avgFirstN(int N ){ double sum = 0; try { // Try block: exception thrower if (N <= 0) throw new Exception("ERROR: Can't average 0 slements"); for (int k = 1; k <= N; k++) sum += k; No catch clause for return sum/N; ArithmeticException, so } Java handles the exception itself. public static void main(String args[]) { CalcAverage ca = new CalcAverage(); System.out.println( "AVG + " + ca.avgFirstN(0)); } // main() } // CalcAverage java.lang.ArithmeticException: ERROR: Can't average 0 elements at CalcAverage.avgFirstN(CalcAverage.java:9) at CalcAverage.main(CalcAverage.java:20) at com.mw.Exec.run(JavaAppRunner.java:47) Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Programmer-Defined Exceptions • Programmer-defined exceptions are defined by extending the Exception class. Thrown when an integer exceeds a certain bound. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java Creating Your Own Exceptions • An exception for validating that an integer is less than or equal to a certain maximum value: /** * IntOutOfRangeException reports an exception when an * integer exceeds its bound. */ public class IntOutOfRangeException extends Exception { public IntOutOfRangeException (int Bound) { super("The input value exceeds the bound " + Bound); } } This error message will be printed when this exception is thrown. Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java MULTIPLE THREADS – Executing in Parallel • Later Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java