Introduction to Java_chapter10
Introduction to Java_chapter10
1 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
Motivations
You see the advantages of object-oriented programming
from the preceding two chapters. This chapter will
demonstrate how to solve problems using the object-
oriented paradigm. Before studying these examples, we
first introduce several language features for supporting
these examples.
2 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
Objectives
• To create immutable objects from immutable classes to protect the
contents of objects (§10.2).
• To determine the scope of variables in the context of a class (§10.3).
• To use the keyword this to refer to the calling object itself (§10.4).
• To apply class abstraction to develop software (§10.5).
• To explore the differences between the procedural paradigm and object-
oriented paradigm (§10.6).
• To develop classes for modeling composition relationships (§10.7).
• To design programs using the object-oriented paradigm (§§10.8–10.10).
• To design classes that follow the class-design guidelines (§10.11).
• To create objects for primitive values using the wrapper classes (Byte,
Short, Integer, Long, Float, Double, Character, and Boolean) (§10.12).
• To simplify programming using automatic conversion between primitive
types and wrapper class types (§10.13).
• To use the BigInteger and BigDecimal classes for computing very large
numbers with arbitrary precisions (§10.14).
3 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
Immutable Objects and Classes
If the contents of an object cannot be changed once the object
is created, the object is called an immutable object and its class
is called an immutable class. If you delete the set method in
the Circle class in the preceding example, the class would be
immutable because radius is private and cannot be changed
without a set method.
A class with all private data fields and without mutators is not
necessarily immutable. For example, the following class
Student has all private data fields and no mutators, but it is
mutable.
4 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
Example public class BirthDate {
private int year;
public class Student {
private int month;
private int id;
private BirthDate birthDate
birthDate;; private int day;
public Student(int
Student(int ssn
ssn,
, public BirthDate(int newYear,
int year, int month, int day) {
int newMonth, int newDay) {
id = ssn
ssn;;
birthDate = new BirthDate
BirthDate(
(year, month, day); year = newYear;
} month = newMonth;
day = newDay;
public int getId
getId()
() {
}
return id;
}
public void setYear(int newYear) {
public BirthDate getBirthDate
getBirthDate()
() { year = newYear;
return birthDate
birthDate;;
}
}
} }
5 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
What Class is Immutable?
6 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
Scope of Variables
• The scope of instance and static variables is the
entire class. They can be declared anywhere
inside a class.
• The scope of a local variable starts from its
declaration and continues to the end of the block
that contains the variable. A local variable must
be initialized explicitly before it can be used.
7 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
The this Keyword
• The this keyword is the name of a reference that
refers to an object itself. One common use of
the this keyword is reference a class’s hidden
data fields.
• Another common use of the this keyword to
enable a constructor to invoke another
constructor of the same class.
8 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
Reference the Hidden Data Fields
public class F { Suppose that f1 and f2 are two objects of F.
private int i = 5; F f1 = new F(); F f2 = new F();
private static double k = 0;
Invoking f1.setI(10) is to execute
void setI(int i) { this.i = 10, where this refers f1
this.i = i;
} Invoking f2.setI(45) is to execute
this.i = 45, where this refers f2
static void setK(double k) {
F.k = k;
}
}
9 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
Calling Overloaded Constructor
public class Circle {
private double radius;
11 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
Designing the Loan Class
Loan
- a n n u a l In t e r e s t R a t e : d o u b l e T h e a n n u a l i n t e r e s t r a t e o f t h e l o a n ( d e f a u l t : 2 .5 ) .
-n u m b e rO fY e a rs: in t T h e n u m b e r o f y e a rs f o r th e lo a n ( d e fa u lt: 1 )
- lo a n A m o u n t: d o u b le T h e lo a n a m o u n t ( d e f a u lt: 1 0 0 0 ).
- lo a n D a te : D a te T h e d a te th is lo a n w a s c r e a te d .
+ L o a n () C o n s tru c ts a d e fa u lt L o a n o b je c t.
+ L o a n ( a n n u a l In t e r e s t R a t e : d o u b l e , C o n s tru c ts a lo a n w ith s p e c ifie d in te r e s t r a te , y e a r s , a n d
n u m b e rO fY e a rs : in t, lo a n a m o u n t.
lo a n A m o u n t: d o u b le )
+ g e t A n n u a l In t e r e s t R a t e ( ) : d o u b l e R e tu rn s th e a n n u a l in te r e s t r a te o f th is lo a n .
+ g e tN u m b e rO fY e a rs(): in t R e tu rn s th e n u m b e r o f th e y e a r s o f th is lo a n .
+ g e t L o a n A m o u n t() : d o u b le R e tu rn s th e a m o u n t o f th is lo a n .
+ g e tL o a n D a te (): D a te R e tu rn s th e d a te o f th e c re a tio n o f th is lo a n .
+ s e tA n n u a lIn te r e s t R a te ( S e ts a n e w a n n u a l in te r e s t ra te to th is lo a n .
a n n u a l In t e r e s t R a t e : d o u b l e ) : v o i d
+ s e tN u m b e rO fY e a rs ( S e ts a n e w n u m b e r o f y e a r s to th is lo a n .
n u m b e rO fY e a rs : in t): v o id
+ s e tL o a n A m o u n t( S e ts a n e w a m o u n t to th is lo a n .
lo a n A m o u n t: d o u b le ) : v o id
+ g e tM o n th ly P a y m e n t() : d o u b le R e t u r n s t h e m o n t h l y p a y m e n t o f t h i s lo a n .
+ g e tT o ta lP a y m e n t() : d o u b le R e tu rn s th e to ta l p a y m e n t o f th is lo a n .
12 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
1 public class Loan {
Example of Loan 37
2 private double annualInterestRate; 38 /** Set a new numberOfYears */
3 private int numberOfYears; 39 public void setNumberOfYears(int numberOfYears) {
4 private double loanAmount; 40 this.numberOfYears = numberOfYears;
5 private java.util.Date loanDate; 41 }
6 42
7 /** Default constructor */ 43 /** Return loanAmount */
8 public Loan() { 44 public double getLoanAmount() {
9 this(2.5, 1, 1000); 45 return loanAmount;
10 } 46 }
11 47
12 /** Construct a loan with specified annual interest rate, 48 /** Set a newloanAmount */
13 number of years, and loan amount 49 public void setLoanAmount(double loanAmount) {
14 */ 50 this.loanAmount = loanAmount;
15 public Loan(double annualInterestRate, int numberOfYears, 51 }
16 double loanAmount) { 52
17 this.annualInterestRate = annualInterestRate; 53 /** Find monthly payment */
18 this.numberOfYears = numberOfYears; 54 public double getMonthlyPayment() {
19 this.loanAmount = loanAmount; 55 double monthlyInterestRate = annualInterestRate / 1200;
20 loanDate = new java.util.Date(); 56 double monthlyPayment = loanAmount * monthlyInterestRate / (1 –
21 } 57 (1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12)));
22 58 return monthlyPayment;
23 /** Return annualInterestRate */ 59 }
24 public double getAnnualInterestRate() { 60
25 return annualInterestRate; 61 /** Find total payment */
26 } 62 public double getTotalPayment() {
27 63 double totalPayment = getMonthlyPayment() * numberOfYears * 12;
28 /** Set a new annualInterestRate */ 64 return totalPayment;
29 public void setAnnualInterestRate(double annualInterestRate) { 65 }
30 this.annualInterestRate = annualInterestRate; 66
31 } 67 /** Return loan date */
32 68 public java.util.Date getLoanDate() {
33 /** Return numberOfYears */ 69 return loanDate;
34 public int getNumberOfYears() { 70 }
35 return numberOfYears; 71 }
36 }
13 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
Example of Loan, cont.
1 import java.util.Scanner;
2
3 public class TestLoanClass {
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 yearly interest rate, for example, 8.25: ");
12 double annualInterestRate = input.nextDouble();
13
14 // Enter number of years
15 System.out.print("Enter number of years as an integer: ");
16 int numberOfYears = input.nextInt();
17
18 // Enter loan amount
19 System.out.print("Enter loan amount, for example, 120000.95: ");
20 double loanAmount = input.nextDouble();
21
22 // Create Loan object
23 Loan loan =
24 new Loan(annualInterestRate, numberOfYears, loanAmount);
25
26 // Display loan date, monthly payment, and total payment
27 System.out.printf("The loan was created on %s\n" +
28 "The monthly payment is %.2f\nThe total payment is %.2f\n",
29 loan.getLoanDate().toString(), loan.getMonthlyPayment(),
30 loan.getTotalPayment());
31 }
32 }
14 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
Object-Oriented Thinking
Chapters 1-7 introduced fundamental programming
techniques for problem solving using loops, methods, and
arrays. The studies of these techniques lay a solid
foundation for object-oriented programming. Classes
provide more flexibility and modularity for building
reusable software. This section improves the solution for
a problem introduced in Chapter 3 using the object-
oriented approach. From the improvements, you will gain
the insight on the differences between the procedural
programming and object-oriented programming and see
the benefits of developing reusable code using objects
and classes.
15 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
The BMI Class
T h e g e t m e t h o d s f o r t h e s e d a ta f ie ld s a r e
p r o v i d e d i n t h e c la s s , b u t o m i tt e d i n t h e
U M L d ia g r a m f o r b r e v it y .
BMI
- n a m e : S tr i n g T he na m e o f the p er so n.
-a g e : i n t T he a ge o f th e perso n.
- w e i g h t: d o u b l e T h e w e i g h t o f th e p e r s o n in p o u n d s .
- h e ig h t : d o u b l e T h e h e i g h t o f t h e p e r s o n i n in c h e s .
+ B M I ( n a m e : S t r in g , a g e : i n t, w e ig h t: C r e a t e s a B M I o b j e c t w it h t h e s p e c i fi e d
d o u b l e , h e i g h t: d o u b l e ) n a m e , a g e , w e i g h t , a n d h e i g h t.
+ B M I ( n a m e : S t r in g , w e i g h t : d o u b l e , C r e a t e s a B M I o b j e c t w it h t h e s p e c i fi e d
h e ig h t : d o u b l e ) n a m e , w e i g h t, h e i g h t, a n d a d e fa u lt a g e
20.
+ g e tB M I ( ) : d o u b l e R e tu r n s t h e B M I
+ g e tS ta tu s( ) : S tr i n g R e tu r n s t h e B M I s ta tu s ( e .g ., n o r m a l,
o v e r w e i g h t, e tc .)
16 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
Example of BMI
1 public class BMI { 25
2 private String name; 26 public String getStatus() {
3 private int age; 27 double bmi = getBMI();
4 private double weight; // in pounds 28 if (bmi < 18.5)
5 private double height; // in inches 29 return "Underweight";
6 public static final double KILOGRAMS_PER_POUND = 0.45359237; 30 else if (bmi < 25)
7 public static final double METERS_PER_INCH = 0.0254; 31 return "Normal";
8 32 else if (bmi < 30)
9 public BMI(String name, int age, double weight, double height) { 33 return "Overweight";
10 this.name = name; 34 else
11 this.age = age; 35 return "Obese";
12 this.weight = weight; 36 }
13 this.height = height; 37
14 } 38 public String getName() {
15 39 return name;
16 public BMI(String name, double weight, double height) { 40 }
17 this(name, 20, weight, height); 41
18 } 42 public int getAge() {
19 43 return age;
20 public double getBMI() { 44 }
21 double bmi = weight * KILOGRAMS_PER_POUND / 45
22 ((height * METERS_PER_INCH) * (height * METERS_PER_INCH)); 46 public double getWeight() {
23 return Math.round(bmi * 100) / 100.0; 47 return weight;
24 } 48 }
49
50 public double getHeight() {
51 return height;
52 }
53 }
17 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
Example of BMI, cont.
1 import java.util.Scanner;
2
3 public class TestLoanClass {
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 yearly interest rate, for example, 8.25: ");
12 double annualInterestRate = input.nextDouble();
13
14 // Enter number of years
15 System.out.print("Enter number of years as an integer: ");
16 int numberOfYears = input.nextInt();
17
18 // Enter loan amount
19 System.out.print("Enter loan amount, for example, 120000.95: ");
20 double loanAmount = input.nextDouble();
21
22 // Create Loan object
23 Loan loan =
24 new Loan(annualInterestRate, numberOfYears, loanAmount);
25
26 // Display loan date, monthly payment, and total payment
27 System.out.printf("The loan was created on %s\n" +
28 "The monthly payment is %.2f\nThe total payment is %.2f\n",
29 loan.getLoanDate().toString(), loan.getMonthlyPayment(),
30 loan.getTotalPayment());
31 }
32 }
18 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
Object Composition
Composition is actually a special case of the aggregation
relationship. Aggregation models has-a relationships and
represents an ownership relationship between two
objects. 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.
Composition Aggregation
1 1 1..3 1
Name Student Address
19 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
Class Representation
An aggregation relationship is usually represented as a
data field in the aggregating class. For example, the
relationship in Figure 10.6 can be represented as follows:
...
}
20 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
Aggregation or Composition
Since aggregation and composition
relationships are represented using classes in
similar ways, many texts don’t differentiate
them and call both compositions.
21 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
Aggregation Between Same Class
Aggregation may exist between objects of the same class.
For example, a person may have a supervisor.
1
Person
Supervisor
1
1
Person
Supervisor
m
23 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
Example: The Course Class
Course
-courseName: String The name of th e course.
-students: String[] An array to store the students for the course.
-numberOfStudents: int The number of s tudents (default: 0).
+Course(courseName: String) Creates a course with the specified name.
+getCourseName(): String Returns the course name.
+addStudent(student: String): void Ad ds a new student to the course.
+dropStudent(student: String): void Drops a student from the course.
+getStudents(): String[] Returns the students in the course.
+getNumberOfStudents(): int Returns the number of students in the course.
24 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
Example of the Course
1 public class Course {
2 private String courseName;
3 private String[] students = new String[100];
4 private int numberOfStudents;
5
6 public Course(String courseName) {
7 this.courseName = courseName;
8 }
9
10 public void addStudent(String student) {
11 students[numberOfStudents] = student;
12 numberOfStudents++;
13 }
14
15 public String[] getStudents() {
16 return students;
17 }
18
19 public int getNumberOfStudents() {
20 return numberOfStudents;
21 }
22
23 public String getCourseName() {
24 return courseName;
25 }
26
27 public void dropStudent(String student) {
28 // Left as an exercise in Exercise 9.9
29 }
30 }
25 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
Example of the Course , cont.
1 public class TestCourse {
2 public static void main(String[] args) {
3 Course course1 = new Course("Data Structures");
4 Course course2 = new Course("Database Systems");
5
6 course1.addStudent("Peter Jones");
7 course1.addStudent("Brian Smith");
8 course1.addStudent("Anne Kennedy");
9
10 course2.addStudent("Peter Jones");
11 course2.addStudent("Steve Smith");
12
13 System.out.println("Number of students in course1: "
14 + course1.getNumberOfStudents());
15 String[] students = course1.getStudents();
16 for (int i = 0; i < course1.getNumberOfStudents(); i++)
17 System.out.print(students[i] + ", ");
18
19 System.out.println();
20 System.out.print("Number of students in course2: "
21 + course2.getNumberOfStudents());
22 }
23 }
26 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
Example: The
StackOfIntegers Class
StackOfIntegers
-elements: int[] An array to store integers in the stack.
-size: int The number of integers in the stack.
+StackOfIntegers() Constructs an empty stack with a default capacity of 16.
+StackOfIntegers(capacity: int) Constructs an empty stack with a specified capacity.
+empty(): boolean Returns true if the stack is empty.
+peek(): int Returns the integer at the top of the stack without
removing it from the stack.
+push(value: int): int Stores an integer into the top of the stack.
+pop(): int Removes the integer at the top of the stack and returns it.
+getSize(): int Returns the number of elements in the stack.
27 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
Example of the StackOfInteger
1 public class StackOfIntegers {
2 private int[] elements; 25
3 private int size;
26 /** Return and remove the top element from the stack*/
4
27 public int pop() {
5 /** Construct a stack with the default capacity 16 */
6 public StackOfIntegers() { 28 return elements[--size];
7 this(16); 29 }
8} 30
9 31 /** Return the top element from the stack */
10 /** Construct a stack with the specified maximum 32 public int peek() {
11 capacity */ 33 return elements[size - 1];
12 public StackOfIntegers(int capacity) { 34 }
13 elements = new int[capacity]; 35
14 } 36 /** Exercise3_21 whether the stack is empty */
15 37 public boolean empty() {
16 /** Push a new integer into the top of the stack */ 38 return size == 0;
17 public int push(int value) { 39 }
18 if (size >= elements.length) { 40
19 int[] temp = new int[elements.length * 2];
20 System.arraycopy(elements, 0, temp, 0, 21elements.length);
41 /** Return the number of elements in the stack */
21 elements = temp; 42 public int getSize() {
22 } 43 return size;
23 44 }
24 return elements[size++] = value;} 45 }
28 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
Example of the StackOfInteger, cont.
1 public class TestStackOfIntegers {
2 public static void main(String[] args) {
3 StackOfIntegers stack = new StackOfIntegers();
4
5 for (int i = 0; i < 10; i++)
6 stack.push(i);
7
8 while (!stack.empty())
9 System.out.print(stack.pop() + " ");
10 }
11 }
29 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
Designing the StackOfIntegers Class
Data3
Data2 Data2
Data1 Data1 Data1
Data2
Data1 Data1
30 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
Implementing
StackOfIntegers Class
elements[capacity – 1]
.
.
.
elements[size-1] top
capacity
.
. size
.
elements[1]
elements[0] bottom
31 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
Designing a Class
• (Coherence) A class should describe a single
entity, and all the class operations should logically
fit together to support a coherent purpose. You
can use a class for students, for example, but you
should not combine students and staff in the
same class, because students and staff have
different entities.
32 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
Designing a Class, cont.
• (Separating responsibilities) A single entity with too many
responsibilities can be broken into several classes to
separate responsibilities. The classes String, StringBuilder,
and StringBuffer all deal with strings, for example, but
have different responsibilities. The String class deals with
immutable strings, the StringBuilder class is for creating
mutable strings, and the StringBuffer class is similar to
StringBuilder except that StringBuffer contains
synchronized methods for updating strings.
33 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
Designing a Class, cont.
• Classes are designed for reuse. Users can
incorporate classes in many different combinations,
orders, and environments. Therefore, you should
design a class that imposes no restrictions on what
or when the user can do with it, design the
properties to ensure that the user can set
properties in any order, with any combination of
values, and design methods to function
independently of their order of occurrence.
34 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
Designing a Class, cont.
• Provide a public no-arg constructor and override
the equals method and the toString method
defined in the Object class whenever possible.
35 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
Designing a Class, cont.
• Follow standard Java programming style and
naming conventions. Choose informative
names for classes, data fields, and methods.
Always place the data declaration before the
constructor, and place constructors before
methods. Always provide a constructor and
initialize variables to avoid programming
errors.
36 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
Using Visibility Modifiers
• Each class can present two contracts – one for the users
of the class and one for the extenders of the class. Make
the fields private and accessor methods public if they are
intended for the users of the class. Make the fields or
method protected if they are intended for extenders of
the class. The contract for the extenders encompasses
the contract for the users. The extended class may
increase the visibility of an instance method from
protected to public, or change its implementation, but
you should never change the implementation in a way
that violates that contract.
37 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
Using Visibility Modifiers, cont.
• A class should use the private modifier to hide its
data from direct access by clients. You can use get
methods and set methods to provide users with
access to the private data, but only to private data
you want the user to see or to modify. A class
should also hide methods not intended for client
use. The gcd method in the Rational class in
Example 11.2, “The Rational Class,” is private, for
example, because it is only for internal use within
the class.
38 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
Using the static Modifier
39 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
Wrapper Classes
• Boolean Integer NOTE: (1) The wrapper classes do
not have no-arg constructors. (2)
• Character Long The instances of all wrapper
classes are immutable, i.e., their
• Short Float internal values cannot be changed
once the objects are created.
• Byte Double
40 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
40
The toString, equals, and hashCode
Methods
Each wrapper class overrides the toString,
equals, and hashCode methods defined in
the Object class. Since all the numeric
wrapper classes and the Character class
implement the Comparable interface, the
compareTo method is implemented in these
classes.
41 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
41
The Integer and Double Classes
java.lang.Integer java.lang.Double
-value: int -value: double
+MAX_VALUE: int +MAX_VALUE: double
+MIN_VALUE: int +MIN_VALUE: double
42 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
42
The Integer Class
and the Double Class
• Constructors
• Conversion Methods
43 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
43
Numeric Wrapper Class Constructors
You can construct a wrapper object either from a
primitive data type value or from a string
representing the numeric value. The constructors
for Integer and Double are:
public Integer(int
Integer(int value)
public Integer(String s)
public Double(double value)
public Double(String s)
44 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
44
Numeric Wrapper Class Constants
Each numerical wrapper class has the constants
MAX_VALUE and MIN_VALUE. MAX_VALUE represents
the maximum value of the corresponding primitive data
type. For Byte, Short, Integer, and Long, MIN_VALUE
represents the minimum byte, short, int, and long
values. For Float and Double, MIN_VALUE represents
the minimum positive float and double values. The
following statements display the maximum integer
(2,147,483,647), the minimum positive float (1.4E-45),
and the maximum double floating-point number
(1.79769313486231570e+308d).
45 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
45
Conversion Methods
Each numeric wrapper class implements the
abstract methods doubleValue, floatValue,
intValue, longValue, and shortValue, which
are defined in the Number class. These
methods “convert” objects into primitive
type values.
46 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
46
The Static valueOf Methods
The numeric wrapper classes have a useful
class method, valueOf(String s). This method
creates a new object initialized to the value
represented by the specified string. For
example:
47 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
47
The Methods for Parsing Strings into
Numbers
You have used the parseInt method in the
Integer class to parse a numeric string into
an int value and the parseDouble method in
the Double class to parse a numeric string
into a double value. Each numeric wrapper
class has two overloaded parsing methods to
parse a numeric string into an appropriate
numeric value.
48 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
48
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):
Unboxing
49 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
49
BigInteger and BigDecimal
If you need to compute with very large integers or
high precision floating-point values, you can use
the BigInteger and BigDecimal classes in the
java.math package. Both are immutable. Both
extend the Number class and implement the
Comparable interface.
50 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
50
BigInteger and BigDecimal
BigInteger a = new BigInteger("9223372036854775807");
BigInteger b = new BigInteger("2");
BigInteger c = a.multiply(b); // 9223372036854775807 * 2
System.out.println(c);
51 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
51
Example of the LargeFactorial
1 import java.math.*;
2
3 public class LargeFactorial {
4 public static void main(String[] args) {
5 System.out.println("50! is \n" + factorial(50));
6 }
7
8 public static BigInteger factorial(long n) {
9 BigInteger result = BigInteger.ONE;
10 for (int i = 1; i <= n; i++)
11 result = result.multiply(new BigInteger(i+""));
12
13 return result;
14 }
15 }
52 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.