presentation slides for ObjectOriented Problem Solving JAVA JAVA

presentation slides for Object-Oriented Problem Solving JAVA, JAVA Second Edition Ralph Morelli Trinity College Hartford, CT published by Prentice Hall Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

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, 2 E 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, 2 E 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, 2 E 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 (calculate. Area()). Values Variables A UML Object Diagram Java, 2 E 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, 2 E 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 Oil. Sensor object sends a warning message to the Controller, which turns on the Oil. Light. Method Calls Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

Collaboration Between Objects • A Rectangle. User object calls the calculate. Area() method of a Rectangle object, which returns 300. Method Call Association A UML Collaboration Diagram Java, 2 E 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 calculate. Area() method. Java, 2 E 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 calc. Perimeter() method. Java, 2 E 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, 2 E 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, 2 E 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, 2 E 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, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

Method Specification: calculate. Area() • Method Name: calculate. Area() • 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, 2 E 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 calculate. Area() { return length * width; } // calculate. Area() // Access method } // Rectangle class Java, 2 E 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, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

Primitive Data Types Java, 2 E 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 Applets Embedded program. Runs in a Web browser No main() method. Requires an HTML file Run using JDK’s appletviewer Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

The Hello. World Application /* * The Hello. World application program */ public class Hello. World { 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 Hello. World Execution starts on the first line of main() Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

Editing, Compiling, and Running Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

Java Library: System and Print. Stream • The java. lang. System class contains Print. Stream objects that perform Input/Output (I/O). • The java. lang. Print. Stream class contains the print() and println() methods that perform output. Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

Example: Old. Mac. Donald Program public class Old. Mac. Donald // Class header { // Start of body public static void main(String argv[]) // Main method { System. out. println(“Old Mac. Donald had a farm. ”); System. out. println(“E I O. ”); System. out. println(“And on his farm he had a duck. ”); System. out. println(“E I O. ”); System. out. println(“With a quack here. ”); System. out. println(“And a quack there. ”); System. out. println(“Here a quack, there a quack. ”); System. out. println(“Everywhere a quack. ”); System. out. println(“Old Mac. Donald had a farm”); System. out. println(“E I O. ”); } // End of main } // End of Old. Mac. Donald Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

Qualified Names • A qualified name takes the form reference. element. Name where reference refers to some object (or class or package) and element. Name 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 pet 1. eat(); // eat() method in pet 1 object java. awt. Button // Button class in java. awt package Java, 2 E 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, 2 E 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, 2 E 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 calculate. Area() { return length * width; } // calculate. Area // Access method Instance variables are usually private } // Rectangle class An object’s public methods make up its interface Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

The Rectangle. User Class • The Rectangle. User class will create and use 1 or more Rectangle instances. An application has a main() method Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

The Rectangle. User Class Definition An application must have a main() method public class Rectangle. User { public static void main(String argv[]) { Rectangle rectangle 1 = new Rectangle(30, 10); Rectangle rectangle 2 = new Rectangle(25, 20); System. out. println("rectangle 1 area " + rectangle 1. calculate. Area()); System. out. println("rectangle 2 area " + rectangle 2. calculate. Area()); } // main() } // Rectangle. User Object Creation Object Use Java, 2 E 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 rectangle 1 = new Rectangle(30, 10); Rectangle rectangle 2 = new Rectangle(25, 20); The objects (instances) store actual values. Java, 2 E 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("rectangle 1 area " + rectangle 1. calculate. Area()); System. out. println("rectangle 2 area " + rectangle 2. calculate. Area()); References to objects Printed output: Method calls rectangle 1 area 300 rectangle 2 area 500 Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

Define, Create, Use • Class definition: Define or more classes (Rectangle, Rectangle. User) • Object Instantiation: Create objects as instances of the classes (rectangle 1, rectangle 2) • Object Use: Use the objects to do tasks (rectangle 1. calculate. Area() ) Java, 2 E 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 parse. Int() method converts a String into an int. • Example: Converts “ 54” into 54 int number = Integer. parse. Int( “ 54”); Java, 2 E 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 Example: Input a Number public class Grader { public static void main(String argv[]) throws](http://slidetodoc.com/presentation_image/4e1453a12f1e5f4d7d58273d695fd63f/image-34.jpg)
Example: Input a Number public class Grader { public static void main(String argv[]) throws IOException Buffered. Reader input = new Buffered. Reader (new Input. Stream. Reader(System. in)); String input. String; { int midterm 1, midterm 2, final. Exam; // Three exam grades float sum; // The sum of the 3 grades System. out. print("Input your grade on the first midterm: "); input. String = input. read. Line(); midterm 1 = Integer. parse. Int(input. String); System. out. println("You input: " + midterm 1); Read an integer. // Similar code deleted here to input midterm 2 and final. Exam sum = midterm 1 + midterm 2 + final. Exam; System. out. print("Your average in this course is "); System. out. println(sum/3); } // main() } // Grader Java, 2 E 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, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

Parameter Scope Drawing boxes around modules helps visualize scope. Java, 2 E 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. pet 1. set. Name("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 set. Name(String s) {…} Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

Arguments and Parameters (cont) Create a Cyber. Pet instance Cyber. Pet pet 1 = new Call set. Name(), Cyber. Pet(); passing a String literal pet 1. set. Name("Socrates"); String s = "Hal"; pet 1. set. Name(s); Or, pass the value (“Hal”) stored in a String variable! Syntax errors: set. Name() requires a String argument pet 1. set. Name(Socrates); pet 1. set. Name(10); pet 1. set. Name(); Java, 2 E 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 Cyber. Pet pet 1 = new Cyber. Pet(); pet 1. set. Name("Pet 1"); Cyber. Pet pet 2 = new Cyber. Pet("Pet 2"); Java, 2 E 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 n 1, int n 2) { return (n 1 + n 2) / 2; } Return Value Java, 2 E 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, Cyber. Pet) are reference types. Reference arguments can be changed by a method call. Java, 2 E 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 primitive. Call(int n) { n = n + 1; } primitive. Call() will be passed an int value 5 int x = 5; primitive. Call(x); x stores the value 5 5 is copied into n when primitive. Call() is called. So primitive. Call() has no access to x itself and x remains equal to 5 even though n is incremented. Java, 2 E 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 reference. Call(Cyber. Pet p) { reference. Call() will be passed p. set. Name("Mary"); } a reference to a Cyber. Pet x = new Cyber. Pet("Harry"); reference. Call(x); x refers to a Cyber. Pet named “Harry” Passing x is like passing the object itself. x’s name will be “Mary” after the method is called. Java, 2 E 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, 2 E 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, 2 E 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 is. Sleeping false (1 + 1) == 2 • == is the equality operator in Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

The get. State() Method public String get. State() { if (is. Eating) return “Eating”; if (is. Sleeping) return “Sleeping”; return “Error in State”; } Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

The If-Then-Else Statement if ( boolean expression ) statement 1 else statement 2 ; • If the boolean expression is true, execute statement 1, otherwise execute statement 2. Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

Selection Statement Examples Simple If if (is. Eating) return "Eating"; If-then-else if (is. Eating) System. out. println("Is Eating"); else System. out. println("Is NOT Eating"); Multiway Selection if (is. Sleeping) System. out. println("I'm sleeping"); else if (is. Eating) System. out. println("I'm eating"); else if (is. Thinking) System. out. println("I'm thinking"); else System. out. println("Error: I don't know what I'm doing"); Java, 2 E 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 ( integral. Expression ) { case integral. Value 2 : statement 1; break; case integral. Value 2 : statement 2; break; … case integreal. Value. N : statement. N; break; default: statement. Default; } Java, 2 E 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”); } 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”); } Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

Inheritance: Object. to. String() Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

Overriding Object. to. String() Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

Polymorphic Object. to. String() Java, 2 E 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 (!). Boolean data have only two possible values, true and false. o 1 || o 2 is true if either o 1 or o 2 is true. o 1 && o 2 is true only if both o 1 and o 2 are true. !o 1 is true when o 1 is false. o 1 ^ o 2 is true if either o 1 or o 2 is true, but not when both are true. Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

Boolean Operator Precedence Order of Boolean Operators. 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 EVALUATION true || true && false true || false ==> true (true || true) && false true && false ==> false (true || (true && false) true || false ==> true Parentheses can override the built-in precedence order. Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

Numeric Data Types • Each bit can represent two values. • An n-bit quantity can represent 2 n 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. Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

Standard Arithmetic Operators • 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. 0/2 ==> ==> value 1. 5 A floating point result • Modulus operator (%) gives remainder of integer division. 6 4 6 3 % % 4 6 3 6 ==> ==> 6 4 6 3 mod mod 4 6 3 6 equals 2 4 0 3 Java, 2 E by R. Morelli Copyright 2002. All rights reserved. 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. 3/2. 0 3. 0/2 ==> 3. 0/2. 0 ==> value 1. 5 // Floating point result Java, 2 E by R. Morelli 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. Evaluate: Step 1. Step 2. Step 3. Step 4. Step 5. 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. 5/3/2. 0 5/(3/2. 0) Parentheses can be used to clarify precedence order. // 0. 5 // 3. 33 Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

Increment/Decrement Operators • Unary increment and decrement operators. Increment k, then use it. 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, 2 E 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. Example r += 3. 5 + 2. 0 * 9. 3; r = r + ( 3. 5 + 2. 0 * 9. 3 ); // r = r + 22. 1; Java, 2 E by R. Morelli 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). Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

Numeric Operator Precedence • Precedence Rule: Relational and equality operations are performed after arithmetic operations. • 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 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 Java, 2 E by R. Morelli 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, 2 E 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, 2 E 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, 2 E 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 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, 2 E 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. Java, 2 E 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, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

Conversion Methods Return type is char public char to. Upper. Case (char ch) { if ((ch >= 'a') && (ch <= 'z')) return (char)(ch - 32); return ch; } Parameter is char public int digit. To. Integer (char ch) { if ((ch >= '0') && (ch <= '9')) return ch - '0'; return -1 ; Return type is int } Java, 2 E by R. Morelli Copyright 2002. All rights reserved. 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 Arithmetic. Exception; } All Math class methods are static class methods. They are invoked as follows: Math. sqrt(55. 3) Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

Math Class Methods Java, 2 E by R. Morelli Copyright 2002. All rights reserved. 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, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

From the Java Library: Number. Format • Java provides the java. text. Number. Format class for representing currency and percentage values. An abstract class cannot be instantiated. . . …so use the static get. Instance() methods to create an instance. Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

From the Java Library: Number. Format • Java provides the java. text. Number. Format class for representing currency and percentage values. An abstract class cannot be instantiated. . . public abstract class Number. Format extends Format { // Class methods public static final Number. Format get. Instance(); public static final Number. Format get. Currency. Instance(); public static final Number. Format get. Percent. Instance(); // Public instance methods …so use the public final String format(double number); public final String format(long number); get. Instance() methods to public int get. Maximum. Fraction. Digits(); create an instance. public int get. Maximum. Integer. Digits(); public void set. Maximum. Fraction. Digits(int new. Value); public void set. Maximum. Integer. Digits(int new. Value); } Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

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, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

Design: The CDInterest Class Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

The CDInterest Application import java. io. *; import java. text. Number. Format; // Import the Java I/O Classes // For formatting as $nn. dd or n% public class CDInterest { private Buffered. Reader input = new Buffered. Reader // For input (new Input. Stream. Reader(System. in)); private String input. String; // 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 cd. Annual; // Accumulated principal, annual private double cd. Daily; // Accumulated principal, daily public static void main( String args[] ) throws IOException { CDInterest cd = new CDInterest(); cd. get. Input(); cd. calc. And. Report. Result(); } // main() } // CDInterest Algorithm: Input, process, output. Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

CDInterest. get. Input() Method The read. Line() method might cause an IOException. private void get. Input() 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 > "); input. String = input. read. Line(); principal = Double. parse. Double(input. String); System. out. print("Input the interest rate, e. g. 6. 5 > "); input. String = input. read. Line(); rate = (Double. parse. Double(input. String)) / 100. 0; System. out. print("Input the number of years, e. g. , 10. 5 > "); input. String = input. read. Line(); years = Double. parse. Double(input. String); Input must be } //get. Input() converted to double. Input values are stored in instance variables. Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

CDInterest. calc. And. Report. Result() Method private void calc. And. Report. Result() { // Calculate and output the result Number. Format dollars = Number. Format. get. Currency. Instance(); // Set up formats Number. Format percent = Number. Format. get. Percent. Instance(); percent. set. Maximum. Fraction. Digits (2); cd. Annual = principal * Math. pow(1 + rate, years); cd. Daily = principal * Math. pow(1 + rate/365, years Number. Format // Calculate class used to format 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( cd. Daily)); System. out. println("The resulting principal compounded yearly at " + percent. format(rate) + " is " + dollars. format( cd. Annual)); } // calc. And. Report. Result() 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 Output is properly formatted. Java, 2 E by R. Morelli Copyright 2002. All rights reserved. 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, 2 E 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, 2 E 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, 2 E 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, 2 E 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, 2 E 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 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, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

Implementation: Car. Loan Class Number. Format formats import java. text. Number. Format; public class Car. Loan { public static void main(String args[]) { double car. Price = 20000; // Car's actual price double car. Price. With. Loan; // Cost of the car plus financing the output. Number. Format dollars = Number. Format. get. Currency. Instance(); Number. Format percent = Number. Format. get. Percent. Instance(); percent. set. Maximum. Fraction. Digits (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 car. Price. With. Loan = car. Price * Math. pow(1 + rate / 100. 0 / 365. 0, years * 365. 0); System. out. print(dollars. format( car. Price. With. Loan) + "t"); } // for rate System. out. println(); // Start a new row } // for years } // main() } // Car. Loan Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

Conditional Loops • 3 N + 1 problem: If N is any positive integer, then the sequence generated by the following rules will always terminate at 1: • Non-counting algorithm: Algorithm for computing the 3 N+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 The loop iterates as long as N != 1 Sentinel bound. The loop terminates when N equals the sentinel value 1. Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

The While Structure • While structure to solve the 3 N+1 problem: Initializer N = 50; while (N != 1) { // System. out. print(N + " "); if (N % 2 == 0) // Loop N = N / 2; // body 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 ; Unlike the for statement, the while statement has no builtin initializer and updater. Java, 2 E by R. Morelli Copyright 2002. All rights reserved. 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, 2 E 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 losing. Grass(double per. Cent. Grass) { double amt. Grass = 100. 0; // Initialize amount of grass int n. Days = 0; // Initialize day counter do { // Repeat amt. Grass -= amt. Grass * LOSSRATE; // Update grass ++n. Days; // Increment days } while (amt. Grass > per. Cent. Grass); // While 50% grass return n. Days / 7; // Return number of weeks } // losing. Grass() Updater Limit bound: Terminate when a limit is reached. • Java’s do-while statement : do loop body while ( loop entry condition ) ; No built-in initializer or updater. Java, 2 E by R. Morelli Copyright 2002. All rights reserved. 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, 2 E 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 running. Total 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 running. Total 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 running. Total by count output the average as the result Java, 2 E 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 get. Input() when needed. public double input. And. Average. Grades() throws IOException { } grade = get. Input(); while (grade != 9999) { running. Total += grade; count++; grade = get. Input(); } // while // Initialize: priming input // Loop test: sentinel if (count > 0) return running. Total / count; else return 0; // Guard against divide-by-zero // Return the average // Update: get next input // Special (error) return value private double get. Input() throws IOException { System. out. print("Input grade (e. g. , 85. 3) or 9999 "); System. out. print("to indicate the end of the list >> "); String input. String = input. read. Line(); double grade = Double. parse. Double(input. String); System. out. println("You input " + grade + "n"); return grade; } Java, 2 E 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. to. String() method represents an object as a string. Java, 2 E 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, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

The String Class Java, 2 E 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, 2 E 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, 2 E 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 name 1 = ""; String name 2 = "Socrates"; String name 3 = "Socrates"; // Reference to the empty string // References to "Socrates" Java, 2 E by R. Morelli 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 name 4 = new String(); String name 5 = new String("Socrates"); String name 6 = name 4; // Creates an object Java, 2 E by R. Morelli Copyright 2002. All rights reserved. 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 last. Name = "Onassis"; String jackie = new String("Jacqueline " + "Kennedy " + last. Name); “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, 2 E 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 1 string 2 string 3 string 4 = = ""; // string 1. length() ==> 0 "Hello"; // string 2. length() ==> 5 "World"; // string 3. length() ==> 5; string 2 + " " + string 3; // string 4. 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, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

Converting Data to String • The String. value. Of() methods are class methods that convert primitive types into String objects. Static public String value. Of( primitive type String number = new String (String. value. Of(128)); truth = new String (String. value. Of(true)); bee = new String (String. value. Of('B')); pi = new String(String. value. Of(Math. PI)); Recall that one refers to class methods by using the class name as the qualifier. // // ); Creates "128" "true" "B" "3. 14159" Note the difference between ‘B’ and “B” Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

Finding Things within a String • The index. Of() and last. Indexof() methods are instance methods that can be used to find the index position of a character or a substring within a String. public int int index. Of(int character); index. Of(int character, int starting. Index); index. Of(String string, int starting. Index); public int int last. Index. Of(int character); last. Index. Of(int character, int starting. Index); last. Index. Of(String string, int starting. Index); Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

Index. Of() and Last. Index. Of() • The index. Of() method searches from left to right within a String for either a character or a substring. • The last. Index. Of() method searches from right to left for a character or substring. String string 1 string 2 string 3 string 4 = = ""; "Hello"; "World"; string 2 + " " + string 3; string 1. index. Of('o') string 2. index. Of('o') string 3. index. Of('o') string 4. index. Of('o') ==> ==> -1 4 string 1. last. Index. Of('o') string 2. last. Index. Of('o') string 3. last. Index. Of('o') string 4. last. Index. Of('o') ==> ==> -1 4 1 7 A return value of -1 means the character is not in the string. Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

Index. Of() and Last. Index. Of() • The index. Of() and last. Index. Of() methods can also be used to find substrings, such as “or”. String string 1 string 2 string 3 string 4 = = ""; "Hello"; "World"; string 2 + " " + string 3; string 1. index. Of("or") string 2. index. Of("or") string 3. index. Of("or") string 4. index. Of("or") ==> ==> -1 -1 1 7 string 1. last. Index. Of("or") string 2. last. Index. Of("or") string 3. last. Index. Of("or") string 4. last. Index. Of("or") ==> ==> -1 -1 1 7 A return value of -1 means that “or” is not in the string. Java, 2 E 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 index. Of() 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, 2 E 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: keyword. Search() 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 keyword. Search(String s, String keyword) { -1, no more String result. Str = ""; occurrences of s. int count = 0; int ptr = s. index. Of(keyword); while (ptr != -1) { Initializer ++count; Updater result. Str = result. Str + ptr + " "; ptr = s. index. Of(keyword, ptr + 1); // Find next occurrence } result. Str = count + ": " + result. Str; // Insert the count return result. Str; // Return as a String } // keyword. Search() Test Performed keyword. Search( "this is a test", "is") keyword. Search( "able was i ere i saw elba", "a") keyword. Search( "this is a test", "taste") Expected Result 2: 2 4 4: 0 6 18 24 0: Test data should test all possible outcomes. Java, 2 E by R. Morelli Copyright 2002. All rights reserved. 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 result. Str = result. Str + ptr + “ “; Java will create a new object (b) referenced by result. Str: The original result. Str object has no more references to it so it has to be garbage collected which takes time. This is the new result. Str. Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

Library: java. lang. String. Buffer • Objects of java. lang. String. Buffer class are strings that can be modified. Some of its methods are: Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

The Revised keyword. Search() public String keyword. Search(String s, String keyword) { String. Buffer result. Str = new String. Buffer(); // Create String. Buffer int count = 0; int ptr = s. index. Of(keyword); while (ptr != -1) { ++count; result. Str. append(ptr + " "); // Insert letters into it ptr = s. index. Of(keyword, ptr + 1); The revised } result. Str. insert(0, count + ": "); keyword. Search() return result. Str. to. String(); // Convert buffer back to a String uses a local } // keyword. Search() String. Buffer to build the result, but converts it back to String before returning. Java, 2 E 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 start. Index to end. Index public char. At(int index) public String substring(int start. Index, int end. Index) Takes the substring from start. Index to the end of string. Note: end. Index points to index after the last character taken. String str = "Hello. World"; str. substring(5) ==> "World" str. substring(3) ==> "lo. World"; // 0123456789 String str = "Hello. World"; str. substring(5, 7) ==> "Wo" str. substring(0, 5) ==> "Hello"; str. substring(5, str. length()) ==> "World" Java, 2 E 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. smith: bg 1 s 5 xxx • Algorithm: Use the index. Of() mccarthy: 2 ffo 900 ssi and substring() methods. public String get. Name(String str) { int pos. Colon = str. index. Of(': '); // Find the delimiter String result = str. substring(0, pos. Colon); // Extract the name return result; These 3 could be a single statement: } return str. substring(0, str. index. Of(‘: ’)); public String get. Password(String str) { int pos. Colon = str. index. Of(': '); // Find the delimiter String result = str. substring(pos. Colon + 1); // Extract the password return result; } Java, 2 E 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. // count. Char 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 count. Char(String str, char ch) { int counter = 0; // Initialize a counter for (int k = 0; k < str. length(); k++) // For each character if (str. char. At(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, 2 E 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 ends. With( String suffix) boolean starts. With(String prefix) String to. Upper. Case() String to. Lower. Case() String trim() Example "Perfection". ends. With("tion") "Perfection". starts. With("Per") "Perfection". to. Upper. Case() "Perfection". to. Lower. Case() " Perfection ". trim() Value true "PERFECTION" "perfection" "Perfection" • Note that methods such as to. Upper. Case(), to. Lower. Case(), and trim() produce a new String object because Strings cannot be modified. Java, 2 E 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 an. Object); // Overrides Object. equals() public boolean equals. Ignore. Case(String another. String) public int compare. To(String another. String) • Two strings are equal if they have the same letters in the same order: String s 1 = "hello"; String s 2 = "Hello"; s 1. equals(s 2) // false s 1. equals("hello”); // true • Error: Using == to compare two strings. For objects, o 1 == o 2 means o 1 and o 2 are identical. • The == operator is equivalent to Object. equal() method: o 1. equal(o 2) means o 1 and o 2 are identical. Java, 2 E 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 s 1 = new String("hello"); String s 2 = new String("hello"); String s 3 = new String("Hello"); String s 4 = s 1; // s 1 == String s 5 = "hello"; String s 6 = "hello"; We get the following equality results s 1. equals(s 2) s 1. equals(s 3) s 1. equals. Ignore. Case(s 3) s 1. equals(s 4) s 1. equals(s 5) s 1. equals(s 6) ==> ==> ==> true false true s 4 And the following identity results s 5 and s 6 refer to the same (identical) literal object. s 1 s 1 s 5 == == == s 2 s 3 s 4 s 5 s 6 ==> ==> ==> false true Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

String Identity vs. String Equality (cont) • In this figure, s 1, s 2, s 4, s 5, and s 6 are equal. • Strings s 1 and s 4 are identical, as are s 5 and s 6. Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

Library: java. util. String. Tokenizer • Break up a string into its tokens -- e. g. , breaking up a name and password pair in boyd: 14 ir. Xp. • The String. Tokenizer class is designed for this purpose. Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

String. Tokenizer (cont) • A String. Tokenizer breaks a string into tokens separated by delimiters, which by default value are the whitespace characters: String. Tokenizer s. Tokenizer = new String. Tokenizer("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: String. Tokenizer s. Tokenizer = new String. Tokenizer("http: //troy. trincoll. edu/~jjj/index. html”, ": /"); Tokens http troy. trincoll. edu ~jjj index. html Java, 2 E by R. Morelli 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, 2 E 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, 2 E 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) { String. Buffer result = new String. Buffer(""); // Use a String. Buffer String. Tokenizer words = new String. Tokenizer(s); // Break s into its words while (words. has. More. Tokens()) { // For each word in s result. append(encode(words. next. Token()) + " "); // Encode it } return result. to. String(); // Return the result } // encrypt() public String decrypt(String s) { String. Buffer result = new String. Buffer(""); // Use a String. Buffer String. Tokenizer words = new String. Tokenizer(s); // Break s into words while (words. has. More. Tokens()) { // For each word in s result. append(decode(words. next. Token()) + " "); // Decode it } return result. to. String(); // 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 An abstract method has no body, no implementation. // Abstract methods Java, 2 E by R. Morelli Copyright 2002. All rights reserved. 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, 2 E 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: Plain. Text: abcdefghijklmnopqrstuvwxyz Caesar. Shifted: 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' // // 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 Java, 2 E by R. Morelli 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) { String. Buffer result = new String. Buffer(); for (int k = 0; k < word. length(); k++) { char ch = word. char. At(k); ch = (char)('a' + (ch -'a'+ 3) % 26); result. append(ch); } return result. to. String(); } // 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) { String. Buffer result = new String. Buffer(); // Initialize a string buffer for (int k = 0; k < word. length(); k++) { // For each character in word char ch = word. char. At(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. to. String(); // Return the result as a string } // decode() } // Caesar Java, 2 E 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) { String. Buffer result = new String. Buffer(word); return result. reverse(). to. String(); } // 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 String. Buffer. Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java
![The Test. Encrypt Class public class Test. Encrypt { public static void main(String argv[]) The Test. Encrypt Class public class Test. Encrypt { public static void main(String argv[])](http://slidetodoc.com/presentation_image/4e1453a12f1e5f4d7d58273d695fd63f/image-130.jpg)
The Test. Encrypt Class public class Test. Encrypt { 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("Plain. Text: " + 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("Plain. Text: " + plain); // Display the results System. out. println("Encrypted: " + secret); System. out. println("Decrypted: " + transpose. decrypt(secret)); } // main() } // Test. Encrypt Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

The Test. Encrypt Output A Caesar cipher has different letters from the plaintext. ***** Caesar Cipher Encryption ***** Plain. Text: this is the secret message Encrypted: wklv lv wkh vhfuhw phvvdjh Decrypted: this is the secret message ***** Transpose Cipher Encryption ***** Plain. Text: 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, 2 E 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, 2 E 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 + 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, 2 E 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, 2 E 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, 2 E 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, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java
![Creating an Array of Cyber. Pets Cyber. Pet pethouse[] = new Cyber. Pet[3]; pethouse[0] Creating an Array of Cyber. Pets Cyber. Pet pethouse[] = new Cyber. Pet[3]; pethouse[0]](http://slidetodoc.com/presentation_image/4e1453a12f1e5f4d7d58273d695fd63f/image-137.jpg)
Creating an Array of Cyber. Pets Cyber. Pet pethouse[] = new Cyber. Pet[3]; pethouse[0] = new Cyber. Pet("Socrates"); pethouse[1] = new Cyber. Pet("Plato"); pethouse[2] = new Cyber. Pet("Aristotle"); // // Create an array of 3 Cyber. Pets the first Cyber. Pet the second Cyber. Pet the third Cyber. Pet • 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 Cyber. Pets. Java, 2 E 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, 8, 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, 2 E 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]); Note: length is an instance variable, not a method. Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

Example: Print an Array • Print an array of int and an array of double: public class Print. Arrays { static final int ARRSIZE = 10; // The array's size static int. Arr[] = new int[ARRSIZE]; // Create the int array static double real. Arr[] = { 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 < int. Arr. length; k++) System. out. println( int. Arr[k] + " t " + real. Arr[k]); } // main() } // Print. Arrays … in order to refer to them in static main() Uninitialized int array has default values of 0. 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 Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

Example: Store the First 100 Squares public class Squares { static final int ARRSIZE = 100; static int. Arr[] = new int[ARRSIZE]; // The array's size // Create an int array public static void main(String args[]) { for (int k = 0; k < int. Arr. length; k++) int. Arr[k] = (k+1) * (k+1); // Initialize the array System. out. print("The first 100 squares are"); // Print a heading for (int k = 0; k < int. Arr. length; k++) { // Print the array if (k % 10 == 0) System. out. println(" "); // 10 elements per row System. out. print( int. Arr[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, 2 E 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. 99999. • Using Math. random() to simulate a coin flip: int coin. Flip = (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, 2 E 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, 2 E 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 // Unsorted array // Compare adjacent elements // Swap, if necessary // Pass 1, 27 bubbles up // Pass 2, 24 bubbles up // Pass 4, the array is sorted Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

Class Design: The Sort Class Java, 2 E 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, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

Method Design: bubble. Sort() • 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 bubble. Sort(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 } // bubble. Sort() Note how an array parameter is specified. Note how an array argument is passed. int my. Arr[] = { 21, 13, 5, 10, 14 }; bubble. Sort(my. Arr); Java, 2 E 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 (an. Arr) and the parameter (arr) refer to the same object. Java, 2 E 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 add 1(int n) { Num’s value is copied to n System. out. println("n = " + n); n = n + 1; System. out. println("n = " + n); } • For the add 1() method, any changes made to its parameter n do not persist beyond the method. int Num = 5; System. out. println("Num = " + Num); add 1(Num); System. out. println("Num = " + Num); outputs Num n = Num = 5 5 6 = 5 Java, 2 E by R. Morelli Copyright 2002. All rights reserved. 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. Arr[] = { 21, 20, 27, 24, 19 }; Sort sorter = new Sort(); sorter. print(int. Arr); sorter. bubble. Sort(int. Arr); sorter. print(int. Arr); Outputs // Initialize // Print // Sort // Print again 21 19 20 20 27 21 24 24 19 27 Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java
![Implementation: The Sort Class public class Sort { public void print(int arr[]) { for Implementation: The Sort Class public class Sort { public void print(int arr[]) { for](http://slidetodoc.com/presentation_image/4e1453a12f1e5f4d7d58273d695fd63f/image-151.jpg)
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. Arr[] = { 21, 20, 27, 24, 19 }; Sort sorter = new Sort(); sorter. print(int. Arr); sorter. bubble. Sort(int. Arr); sorter. print(int. Arr); } // main() public void bubble. Sort(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 } // bubble. Sort() Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

Design: The Search Class Uses Two different search() strategies. Java, 2 E 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 sequential. Search(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 } // sequential. Search() Search fails if you get to the end of the array. Java, 2 E 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 Second guess First guess Too low 6 7 8 9 10 Second guess Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

The binary. Search() 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 binary. Search(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 } // binary. Search() Calculate a new midpoint. Update low and high to cut the array in half. Java, 2 E 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 Day index Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java
![A More Appropriate 2 -D Representation • What is rainfall[0][4] ? Avoid zero indexing A More Appropriate 2 -D Representation • What is rainfall[0][4] ? Avoid zero indexing](http://slidetodoc.com/presentation_image/4e1453a12f1e5f4d7d58273d695fd63f/image-157.jpg)
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] = 1. 15; // Rainfall for January 5 System. out. println(rainfall[4][1]); // April 1 st 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, 2 E 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 2 D-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 init. Rain(double rain[][]) { for (int month = 1; month < rain. length; month++) for (int day = 1; day < rain[month]. length; day++) rain[month][day] = 0. 0; } // init. Rain() Nested for loops iterate 12 x 31 times • Method call: pass the name of the array to the method: init. Rain(rainfall); // Sample method call Java, 2 E 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, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

Handling Exceptional Conditions • The avg. First. N() method expects that N > 0. • If N = 0, a divide-by-zero error occurs in avg/N. /** * Precondition: N > 0 * Postcondition: avg. First. N() equals the average of (1+2+…+N) */ public double avg. First. N(int N) { duuble sum = 0; for (int k = 1; k <= N; k++) sum += k; return sum/N; // What if N is 0 ? ? } // avg. First. N() Bad Design: Doesn’t guard against divide-by-0. Java, 2 E 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: avg. First. N() equals the average of (1+2+…+N) */ public double avg. First. N(int N) { duuble sum = 0; if (N <= 0) { System. out. println(“ERROR avg. First. N: N <= 0. Program terminating. ”); System. exit(0); } for (int k = 1; k <= N; k++) sum += k; return sum/N; // What if N is 0 ? ? } // avg. First. N() It’s sometimes risky to exit a program like this. Java, 2 E 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 Runtime. Exception and are not monitored by the compiler. Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

Some Important Exceptions Class Description Arithmetic. Exception Division by zero or some other kind of arithmetic problem Array. Index. Out. Of. Bounds- An array index is less than zero or Exception greater than or equal to the array's length File. Not. Found. Exception Reference to a unfound file Illegal. Argument. Exception Method call with improper argument Index. Out. Of. Bounds. Exception An array or string index out of bounds Null. Pointer. Exception Reference to an object which has not been instantiated Number. Format. Exception Use of an illegal number format, such as when calling a method String. Index. Out. Of. Bounds. Exception A String index less than zero or greater than or equal to the String's length Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

Some Common Exceptions Class Method Exception Raised Description Double value. Of(String) Number. Format. Exception The String is not a double Integer parse. Int(String) Number. Format. Exception The String is not a int String String(String) index. Of(String) last. Index. Of(String) char. At(int) substring(int, int) Null. Pointer. Exception The String is null String. Index. Out. Of. Bounds Exception The int is invalid index String. Index. Out. Of. Bounds Exception An int is invalid index Java, 2 E by R. Morelli Copyright 2002. All rights reserved. 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 { Buffered. Reader input = new Buffered. Reader (new Input. Stream. Reader(System. in)); String input. String = input. read. Line(); // May throw IOException } . . . because read. Line() may cause it. Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

The Exception Class Simple: only constructor methods. Java, 2 E 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, 2 E 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, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

Try, Throw and Catch public class Calc. Average { public double avg. First. N(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; } } // Calc. Average Throw in one class. . . Catch in the other. public class Calc. Avg. Test { public static void main(String args[]) { try { Calc. Average ca = new Calc. Average(); System. out. println(“AVG + “ + ca. avg. First. N(0)); } catch (Arithmetic. Exception e) { // Catch block: exception handler System. out. println(e. get. Message()); Effective Design: Java’s exception e. print. Stack. Trace(); handling mechanism allows you to System. exit(0); } separate normal code from } exception handling code. } // Calc. Avg. Test Java, 2 E 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, 2 E 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 Exception. Name(); } catch (Exception. Name Parameter. Name) { // Block of statements to be executed // If the Exception. Name exception is thrown in try }. . . // Possibly other catch clauses } catch (Exception. Name 2 Parameter. Name) { // Block of statements to be executed // If the Exception. Name 2 exception is thrown in try } finally { // Optional block of statements that is executed // Whether an exception is thrown or not } Java, 2 E 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 Runtime. Exception 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, 2 E 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, 2 E 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 method 1() which calls method 2() which calls method 3(). Java, 2 E 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 Calc. Average { public double avg. First. N(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; Arithmetic. Exception, so Java } handles the exception itself. public static void main(String args[]) { Calc. Average ca = new Calc. Average(); System. out. println( "AVG + " + ca. avg. First. N(0)); } // main() } // Calc. Average java. lang. Arithmetic. Exception: ERROR: Can't average 0 elements at Calc. Average. avg. First. N(Calc. Average. java: 9) at Calc. Average. main(Calc. Average. java: 20) at com. mw. Exec. run(Java. App. Runner. java: 47) Java, 2 E 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, 2 E 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: /** * Int. Out. Of. Range. Exception reports an exception when an * integer exceeds its bound. */ public class Int. Out. Of. Range. Exception extends Exception { public Int. Out. Of. Range. Exception (int Bound) { super("The input value exceeds the bound " + Bound); } } This error message will be printed when this exception is thrown. Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java

MULTIPLE THREADS – Executing in Parallel • Later Java, 2 E by R. Morelli Copyright 2002. All rights reserved. Chapter 0: Computers, Objects, and Java
- Slides: 178