Chapter 10 Thinking in Objects Liang Introduction to

Chapter 10 Thinking in Objects Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1

Motivations You see the advantages of object-oriented programming from the preceding chapter. This chapter will demonstrate how to solve problems using the object-oriented paradigm. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 2

Objectives q q q q q To apply class abstraction to develop software (§ 10. 2). To explore the differences between the procedural paradigm and objectoriented paradigm (§ 10. 3). To discover the relationships between classes (§ 10. 4). To design programs using the object-oriented paradigm (§§ 10. 5– 10. 6). To create objects for primitive values using the wrapper classes (Byte, Short, Integer, Long, Float, Double, Character, and Boolean) (§ 10. 7). To simplify programming using automatic conversion between primitive types and wrapper class types (§ 10. 8). To use the Big. Integer and Big. Decimal classes for computing very large numbers with arbitrary precisions (§ 10. 9). To use the String class to process immutable strings (§ 10. 10). To use the String. Builder and String. Buffer classes to process mutable strings (§ 10. 11). Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 3

Class Abstraction and Encapsulation q Class abstraction means to separate class implementation from the use of the class. q The creator of the class provides a description of the class and let the user know how the class can be used. q The user of the class does not need to know how the class is implemented. q The detail of implementation is encapsulated and hidden from the user. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 4

Designing the Loan Class A Loan is characterized by: - amount - interest rate - start date - duration (years) - monthly payment (need to be computed) - total payment (need to be computed) Each real-life loan is a loan object with specific values for those characterizes. (e. g. , car loan, mortgage, personal loan, etc. ) To program this concept, we need to define class Loan with data fields (attributes) and methods. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 5

Designing the Loan Class To achieve encapsulation, we need the following: 1. Define all variables to be private. No exceptions. 2. Define get (getter) and set (setter) methods for each private variable that users of the class need to access (as public methods). 3. Methods that users of the class need to know about must be defined as public. 4. Support methods must be defined as private. 5. All class methods have access to its variables. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 6

Designing the Loan Class The UML diagram serves as the contract Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 7

1 import java. util. Scanner; 2 3 public class Test. Loan. Class { 4 /** Main method */ 5 public static void main(String[] args) { 6 // Create a Scanner 7 Scanner input = new Scanner(System. in); 8 9 // Enter yearly interest rate 10 System. out. print( 11 "Enter annual interest rate, for example, 8. 25: " ); 12 double annual. Interest. Rate = input. next. Double(); 13 14 // Enter number of years 15 System. out. print("Enter number of years as an integer: " ); 16 int number. Of. Years = input. next. Int(); 17 18 // Enter loan amount 19 System. out. print("Enter loan amount, for example, 120000. 95: " ); 20 double loan. Amount = input. next. Double(); 21 22 // Create Loan object 23 Loan loan = 24 new Loan(annual. Interest. Rate, number. Of. Years, loan. Amount); 25 26 // Display loan date, monthly payment, and total payment 27 System. out. printf("The loan was created on %sn" + 28 "The monthly payment is %. 2 fn. The total payment is %. 2 fn" , 29 loan. get. Loan. Date(). to. String(), loan. get. Monthly. Payment(), 30 loan. get. Total. Payment()); 31 } 32 } Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 8

1 public class Loan { 2 private double annual. Interest. Rate; 3 private int number. Of. Years; 4 private double loan. Amount; 5 private java. util. Date loan. Date; 6 7 /** Default constructor */ 8 public Loan() { 9 this(2. 5, 1, 1000); 10 } 11 12 /** Construct a loan with specified annual interest rate, 13 number of years, and loan amount 14 */ 15 public Loan(double annual. Interest. Rate, int number. Of. Years, 16 double loan. Amount) { 17 this. annual. Interest. Rate = annual. Interest. Rate; 18 this. number. Of. Years = number. Of. Years; 19 this. loan. Amount = loan. Amount; 20 loan. Date = new java. util. Date(); 21 } 22 // continue next slide Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 9

23 /** Return annual. Interest. Rate */ 24 public double get. Annual. Interest. Rate() { 25 return annual. Interest. Rate; 26 } 27 28 /** Set a new annual. Interest. Rate */ 29 public void set. Annual. Interest. Rate(double annual. Interest. Rate) { 30 this. annual. Interest. Rate = annual. Interest. Rate; 31 } 32 33 /** Return number. Of. Years */ 34 public int get. Number. Of. Years() { 35 return number. Of. Years; 36 } 37 38 /** Set a new number. Of. Years */ 39 public void set. Number. Of. Years(int number. Of. Years) { 40 this. number. Of. Years = number. Of. Years; 41 } 42 43 /** Return loan. Amount */ 44 public double get. Loan. Amount() { 45 return loan. Amount; 46 } 47 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 10

48 /** Set a newloan. Amount */ 49 public void set. Loan. Amount(double loan. Amount) { 50 this. loan. Amount = loan. Amount; 51 } 52 53 /** Find monthly payment */ 54 public double get. Monthly. Payment() { 55 double monthly. Interest. Rate = annual. Interest. Rate / 1200; 56 double monthly. Payment = loan. Amount * monthly. Interest. Rate / (1 – 57 (1 / Math. pow(1 + monthly. Interest. Rate, number. Of. Years * 12))); 58 return monthly. Payment; 59 } 60 61 /** Find total payment */ 62 public double get. Total. Payment() { 63 double total. Payment = get. Monthly. Payment() * number. Of. Years * 12; 64 return total. Payment; 65 } 66 67 /** Return loan date */ 68 public java. util. Date get. Loan. Date() { 69 return loan. Date; 70 } 71 } Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 11

Object-Oriented Thinking Chapters 1 -8 introduced fundamental programming techniques for problem solving using loops, methods, and arrays. q The studies of these techniques lay a solid foundation for object-oriented programming. q q The procedural paradigm focuses on designing methods q Software design using the object-oriented paradigm focuses on objects and operations on objects. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 12

Procedural and Object-Oriented Pro. q In procedural languages, q The data is separated from the methods (or procedures). q Data is passed on to the procedure whenever we need to process the data. q In Object-Oriented (OO) programming q Data and the methods needed to process the data are forming so called Objects. q Classes provide more flexibility and modularity for building software applications. q Has the benefits of developing reusable code using objects and classes. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 13

The BMI Class Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 14

1 public class BMI { 2 private String name; 3 private int age; 4 private double weight; // in pounds 5 private double height; // in inches 6 public static final double KILOGRAMS_PER_POUND = 0. 45359237; 7 public static final double METERS_PER_INCH = 0. 0254; 8 9 public BMI(String name, int age, double weight, double height) { 10 this. name = name; 11 this. age = age; 12 this. weight = weight; 13 this. height = height; 14 } 15 16 public BMI(String name, double weight, double height) { 17 this(name, 20, weight, height); 18 } 19 20 public double get. BMI() { 21 double bmi = weight * KILOGRAMS_PER_POUND / 22 ((height * METERS_PER_INCH) * (height * METERS_PER_INCH)); 23 return Math. round(bmi * 100) / 100. 0; 24 } 25 // continue next slide Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 15

26 public String get. Status() { 27 double bmi = get. BMI(); 28 if (bmi < 18. 5) 29 return "Underweight"; 30 else if (bmi < 25) 31 return "Normal"; 32 else if (bmi < 30) 33 return "Overweight"; 34 else 35 return "Obese"; 36 } 37 38 public String get. Name() { 39 return name; 40 } 41 42 public int get. Age() { 43 return age; 44 } 45 46 public double get. Weight() { 47 return weight; 48 } 49 50 public double get. Height() { 51 return height; 52 } 53 } Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 16
![1 public class Use. BMIClass { 2 public static void main(String[] args) { 3 1 public class Use. BMIClass { 2 public static void main(String[] args) { 3](http://slidetodoc.com/presentation_image_h/0bedc4a89a932d48eb2287757c265519/image-17.jpg)
1 public class Use. BMIClass { 2 public static void main(String[] args) { 3 BMI bmi 1 = new BMI("John Doe", 18, 145, 70); 4 System. out. println("The BMI for " + bmi 1. get. Name() + " is " 5 + bmi 1. get. BMI() + " " + bmi 1. get. Status()); 6 7 BMI bmi 2 = new BMI("Peter King", 215, 70); 8 System. out. println("The BMI for " + bmi 2. get. Name() + " is " 9 + bmi 2. get. BMI() + " " + bmi 2. get. Status()); 10 } 11 } The BMI for John Doe is 20. 81 Normal The BMI for Peter King is 30. 85 Obese Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 17

Class Relationships q q Classes can be related in an OO program. Common relationships among classes are: Association: q Association is a general binary relationship that describes an activity between two classes. Aggregation and Composition: q Association that implies ownership (has-a relationship). q Composition means exclusive ownership (uniqueness) Inheritance (discussed in Chapter 11): q When a class is defined from (builds on) an existing class. q This is also know as parent/child (supercalss/subclass) relationship Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 18

Class Relationships Composition and Aggregation are the two forms of association. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 19

Association For example, ( association has bidirectional association. ) 1 faculty teaches 0 to 3 courses may be taught by 1 faculty. 1 student can take many (*) courses. 1 course can have 5 to 60 students. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 20

The association relations are implemented using data fields and methods in classes. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 21
![Implementation of Association Using Methods and Data Fields public class Student{ private Course[] course. Implementation of Association Using Methods and Data Fields public class Student{ private Course[] course.](http://slidetodoc.com/presentation_image_h/0bedc4a89a932d48eb2287757c265519/image-22.jpg)
Implementation of Association Using Methods and Data Fields public class Student{ private Course[] course. List; public void add. Course(Course course. Name) { //method details. . . } // other content } public class Course{ private Student[] class. List; private faculty. Name; public void add. Student(Student student. Name) { //method details. . . } public void set. Faculty(Faculty faculty. Name) { //method details. . . } // other content } public class Faculty{ private Course[] course. List; public void add. Course(Course course. Name) { //method details. . . } // other content } Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 22

Aggregation and Composition q Aggregation (models has-a relationship) is when an object has ownership of another object that may be owned by other objects. q. A student has an address that is also the address of other students (roommates). q Composition (It represents part-of relationship)is an aggregation relationship that implies exclusive ownership q q A student has a name that is unique for each student. Both relationships are implemented using data fields. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 23

Aggregation and Composition q q q The owner object is called an aggregating object and its class an aggregating class. The subject object is called an aggregated object and its class an aggregated class. “a student has a name” is a composition q Name is dependent on Student q “a student has an address” is an aggregation q an address can exist by itself Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 24

Class Representation A student has a name that is unique to each student. A student has an address that may be shared by other students. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 25

Aggregation or Composition q Aggregation implies a relationship where the child can exist independently of the parent. q. Class (parent) and Student (child). Delete the Class and the Students still exist. q Composition implies a relationship where the child cannot exist independent of the parent. q. House (parent) and Room (child). Rooms don't exist separate to a House. q Since aggregation and composition relationships are represented using classes in similar ways, many texts don’t differentiate them and call both compositions. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 26

Aggregation Between Same Class Aggregation may exist between objects of the same class. For example, a person may have a supervisor. public class Person { // The type for the data is the class itself private Person supervisor; . . . } Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 27

Aggregation Between Same Class What happens if a person has several supervisors? Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 28

Example: The Course Class a class for modeling courses Course Test. Course Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Run 29
![1 public class Test. Course { 2 public static void main(String[] args) { 3 1 public class Test. Course { 2 public static void main(String[] args) { 3](http://slidetodoc.com/presentation_image_h/0bedc4a89a932d48eb2287757c265519/image-30.jpg)
1 public class Test. Course { 2 public static void main(String[] args) { 3 Course course 1 = new Course("Data Structures"); 4 Course course 2 = new Course("Database Systems"); 5 6 course 1. add. Student("Peter Jones"); 7 course 1. add. Student("Brian Smith"); 8 course 1. add. Student("Anne Kennedy"); 9 10 course 2. add. Student("Peter Jones"); 11 course 2. add. Student("Steve Smith"); 12 13 System. out. println("Number of students in course 1: " 14 + course 1. get. Number. Of. Students()); 15 String[] students = course 1. get. Students(); 16 for (int i = 0; i < course 1. get. Number. Of. Students(); i++) 17 System. out. print(students[i] + ", "); 18 19 System. out. println(); 20 System. out. print("Number of students in course 2: " 21 + course 2. get. Number. Of. Students()); 22 } 23 } Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 30
![1 public class Course { 2 private String course. Name; 3 private String[] students 1 public class Course { 2 private String course. Name; 3 private String[] students](http://slidetodoc.com/presentation_image_h/0bedc4a89a932d48eb2287757c265519/image-31.jpg)
1 public class Course { 2 private String course. Name; 3 private String[] students = new String[4]; 4 private int number. Of. Students; 5 6 public Course(String course. Name) { 7 this. course. Name = course. Name; 8 } 9 10 public void add. Student(String student) { 11 students[number. Of. Students] = student; 12 number. Of. Students++; 13 } 14 15 public String[] get. Students() { 16 return students; 17 } 18 19 public int get. Number. Of. Students() { 20 return number. Of. Students; 21 } 22 23 public String get. Course. Name() { 24 return course. Name; 25 } 26 27 public void drop. Student(String student) { 28 // Left as an exercise in Exercise 10. 9 29 } 30 } Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 31

Designing the Stack. Of. Integers Class Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 32

Implementing Stack. Of. Integers Class Stack. Of. Integers Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 33

Example: The Stack. Of. Integers Class Test. Stack. Of. Integers Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. Run 34

Wrapper Classes Java primitive types are NOT objects. Often we need to treat primitive values as objects. The solution is to convert a primitive type value, such as 45, to an object that hold value 45. Java provides Wrapper Classes for all primitive types. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 35

Wrapper Classes q Boolean q q Character q Integer Long q Short q Float q Byte q Double NOTE: (1) The wrapper classes do not have no-arg constructors. (2) The instances of all wrapper classes are immutable, i. e. , their internal values cannot be changed once the objects are created. (3) A wrapper class object contains one value of the class type. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 36

The Integer and Double Classes Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 37

The Integer Class and the Double Class q Constructors q Class Constants MAX_VALUE, MIN_VALUE q Conversion Methods Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 38

Numeric Wrapper Class Constructors We can construct a wrapper object either from: 1) primitive data type value 2) string representing the numeric value The constructors for Integer and Double classes are: public Integer(int value) Integer(String s) Double(double value) Double(String s) Examples: Integer int. Object 1 = new Integer(90); Integer int. Object 2 = new Integer("90"); Double double. Object 1 = new Double(95. 7); Double double. Object 2 = new Double("95. 7"); // Similar syntax for Float, Byte, Short, and Long types. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 39

Numeric Wrapper Class Constants Each numerical wrapper class has 2 constants: MAX_VALUE: represents the maximum value of the type. MIN_VALUE: represents the minimum value of the type. Examples: System. out. println("Max integer is: " + Integer. MAX_VALUE); System. out. println("Min integer is: " + Integer. MIN_VALUE); System. out. println("Max float is: " + Float. MAX_VALUE); System. out. println("Min float is: " + Float. MIN_VALUE); System. out. println("Max short is: " + Short. MAX_VALUE); System. out. println("Min short is: " + Short. MIN_VALUE); System. out. println("Max byte is: " + Byte. MAX_VALUE); System. out. println("Min byte is: " + Byte. MIN_VALUE); Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 40

Conversion Methods Each numeric wrapper class implements conversion methods that convert an object of a wrapper class to a primitive type: double. Value(), float. Value(), int. Value() long. Value(), and short. Value(). Examples: Double my. Value = new Double(97. 50); System. out. println(my. Value. int. Value()); //gives 97 System. out. println(my. Value. float. Value()); //gives 97. 5 System. out. println(my. Value. short. Value()); //gives 97 System. out. println(my. Value. long. Value()); //gives 97 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 41

The Static value. Of Methods The numeric wrapper classes have a useful class method: value. Of(String s) This method creates a new object initialized to the value represented by the specified string. Examples: Double double. Object = Double. value. Of("95. 79"); Integer integer. Object = Integer. value. Of("86"); Float float. Object = Float. value. Of("95. 54"); Long long. Object = Long. value. Of("123456789"); Short short. Object = Short. value. Of("123"); Byte byte. Object = Byte. value. Of("12"); Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 42

Methods for Parsing Strings into Numbers Parsing methods allow us to pars numeric strings into numeric types. Each numeric wrapper class has two overloaded parsing methods: Public static int parse. Int(String s) Public static int parse. Int(String s, int radix) Examples: int A = Integer. parse. Int("25"); //A has 25 System. out. println(A); int B = Integer. parse. Int("110", 2); //B has 6 System. out. println(B); int C = Integer. parse. Int("25", 8); //C has 21 System. out. println(C); int D = Integer. parse. Int("25", 10); //D has 25 System. out. println(D); int E = Integer. parse. Int("25", 16); //E has 37 System. out. println(E); Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 43

Automatic Conversion Between Primitive Types and Wrapper Class Types JDK 1. 5 allows primitive type and wrapper classes to be converted automatically. For example, the following statement in (a) can be simplified as in (b): Integer[] int. Array = {1, 2, 3}; System. out. println(int. Array[0] + int. Array[1] + int. Array[2]); Unboxing Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 44

Big. Integer and Big. Decimal If you need to compute with very large integers or high precision floating-point values, you can use the Big. Integer and Big. Decimal classes in the java. math package. Both are immutable. Both extend the Number class and implement the Comparable interface. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 45

Big. Integer and Big. Decimal Big. Integer a = new Big. Integer("9223372036854775807"); Big. Integer b = new Big. Integer("2"); Big. Integer c = a. multiply(b); // 9223372036854775807 * 2 System. out. println(c); Big. Decimal a = new Big. Decimal(1. 0); Big. Decimal b = new Big. Decimal(3); Big. Decimal c = a. divide(b, 20, Big. Decimal. ROUND_UP); System. out. println(c); The output is: 18446744073709551614 0. 33333333334 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 46

1 import java. util. Scanner; 2 import java. math. *; 3 4 public class Large. Factorial { 5 public static void main(String[] args) { 6 Scanner input = new Scanner(System. in); 7 System. out. print("Enter an integer: "); 8 int n = input. next. Int(); 9 System. out. println(n + "! is n" + factorial(n)); 10 } 11 12 public static Big. Integer factorial(long n) { 13 Big. Integer result = Big. Integer. ONE; 14 for (int i = 1; i <= n; i++) 15 result = result. multiply(new Big. Integer(i+"")); 16 17 return result; 18 } 19 } Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 47

The String Class q The String class has 13 constructors and more than 40 methods for manipulating strings. q Obtaining String length and Retrieving Individual Characters in a string String Concatenation (concat) Substrings (substring(index), substring(start, end)) Comparisons (equals, compare. To) String Conversions Finding a Character or a Substring in a String Conversions between Strings and Arrays Converting Characters and Numeric Values to Strings q q q q Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 48

Constructing Strings q String new. String = new String(string. Literal); String message = new String("Welcome to Java“); q Since strings are used frequently, Java provides a shorthand initializer for creating a string: String message = new String("Welcome to Java“); q You can also create a string from an array of characters. char[] char. Array = {'G', 'o', 'd', 'D', 'a', 'y’}; String message = new String(char. Array); Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 49

Strings Are Immutable A String object is immutable; its contents cannot be changed. Does the following code change the contents of the string? String s = "Java"; s = "HTML"; Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 50

animation Trace Code String s = "Java"; s = "HTML"; Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 51

animation Trace Code String s = "Java"; s = "HTML"; Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 52

Interned Strings q Since strings are immutable and are frequently used. q To improve efficiency and save memory, the JVM uses a unique instance for string literals with the same character sequence. q Such an instance is called interned. For example, the following statements: Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 53

Examples display s 1 == s is false s 1 == s 3 is true A new object is created if you use the new operator. If you use the string initializer, no new object is created if the interned object is already created. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 54

animation Trace Code Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 55

Trace Code Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 56

Trace Code Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 57

Replacing and Splitting Strings Examples "Welcome". replace('e', 'A') returns a new string, WAlcom. A. "Welcome". replace. First("e", "AB") returns a new string, WABlcome. "Welcome". replace("e", "AB") returns a new string, WABlcom. AB. "Welcome". replace("el", "AB") returns a new string, WABcome. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 58
![Splitting a String[] tokens = "Java#HTML#Perl". split("#", 0); for (int i = 0; i Splitting a String[] tokens = "Java#HTML#Perl". split("#", 0); for (int i = 0; i](http://slidetodoc.com/presentation_image_h/0bedc4a89a932d48eb2287757c265519/image-59.jpg)
Splitting a String[] tokens = "Java#HTML#Perl". split("#", 0); for (int i = 0; i < tokens. length; i++) System. out. print(tokens[i] + " "); displays Java HTML Perl Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 59

Matching, Replacing and Splitting by Patterns You can match, replace, or split a string by specifying a pattern. This is an extremely useful and powerful feature, commonly known as regular expression. Regular expression is complex to beginning students. For this reason, two simple patterns are used in this section. Please refer to Supplement III. F, “Regular Expressions, ” for further studies. "Java". matches("Java"); "Java". equals("Java"); "Java is fun". matches("Java. *"); "Java is cool". matches("Java. *"); Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 60

Matching, Replacing and Splitting by Patterns The replace. All, replace. First, and split methods can be used with a regular expression. For example, the following statement returns a new string that replaces $, +, or # in "a+b$#c" by the string NNN. String s = "a+b$#c". replace. All("[$+#]", "NNN"); System. out. println(s); Here the regular expression [$+#] specifies a pattern that matches $, +, or #. So, the output is a. NNNb. NNNNNNc. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 61

Matching, Replacing and Splitting by Patterns The following statement splits the string into an array of strings delimited by some punctuation marks. String[] tokens = "Java, C? C#, C++". split("[. , : ; ? ]"); for (int i = 0; i < tokens. length; i++) System. out. println(tokens[i]); Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 62

Convert Character and Numbers to Strings The String class provides several static value. Of methods for converting a character, an array of characters, and numeric values to strings. These methods have the same name value. Of with different argument types: char, char[], double, long, int, and float. Examples: String A = String. value. Of(123); System. out. println(A); String B = String. value. Of(23. 5); System. out. println(B); String C = String. value. Of(true); System. out. println(C); char[] x = {'a', 'b', 'c'}; String D = String. value. Of(x); System. out. println(D); Output: 123 23. 5 true abc Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 63

String. Builder and String. Buffer q The String. Builder/String. Buffer class is an alternative to the String class. In general, a String. Builder/String. Buffer can be used wherever a string is used. String. Builder/String. Buffer is more flexible than String. q You can add, insert, or append new contents into a string buffer, whereas the value of a String object is fixed once the string is created. q q. Self study. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 64

q. Study Check points q. Study The String. Builder and String. Buffer Classes q. Do the programming exercises End of Chapter 10 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 65
- Slides: 65