Chapter 10
Chapter 10
Class abstraction ⇨ the separation of class implementation from the use of a class.
Class Encapsulation ⇨ the details of implementation are encapsulated and hidden from the user.
Class’s contract ⇨ the collection of public constructors, methods, and data fields that are accessible
from outside the class, together with the description of how these members are expected to behave.
The creator of a class describes the functions of the class and lets the user know how the class can be
used; but the user of the class does not need to know how the class is implemented.
For example, you can create a Circle object and find the area of the circle without knowing how
the area is computed.
i.e. Consider getting a loan; (Chapter 2) presented a program for computing the monthly and total
payments. The code cannot be reused in other programs, because the code is in the main method.
The object-oriented programming paradigm focuses on objects, and actions are defined along with the
data in objects. To tie a date with a loan, you can define a loan class with a date along with the loan’s
other properties as data fields.
1|Page
To make it reusable; The Loan class can be implemented as the following ⇨
2|Page
Notice; When a loan object is created, its date is stored in the loanDate field. The getLoanDate method
returns the date.
3|Page
10.3 Thinking in Objects
i.e. ComputeAndInterpretBMI.java, (Chapter 3) presented a program for computing the body mass
index (BMI). The code cannot be reused in other programs, because the code is in the main method.
4|Page
5|Page
The following program test the BMI class ⇨
The instance method getBMI() returns the BMI. Since the weight and height are instance data fields in
the object, the getBMI() method can use these properties to compute the BMI for the object. And the
instance method getStatus() returns a string that interprets the BMI.
The procedural paradigm focuses on designing methods. The object-oriented paradigm couples data
and methods together into objects.
6|Page
10.4 Class Relationships
10.4.1 Association
Association ⇨ is a general binary relationship that describes an activity between two separate
classes which establishes through their Objects.
For example, a student taking a course is an association between the Student class and the
Course class, and a faculty member teaching a course is an association between the Faculty
class and the Course class.
An association is illustrated by a solid line between two classes with an optional label that describes
the relationship. I.e. the labels are Take and Teach.
Each class involved in the relationship may have a role name that describes the role it plays in the
relationship. I.e. teacher is the role name for Faculty.
Each class involved in an association may specify a multiplicity, which is placed at the side of the class
to specify how many of the class’s objects are involved in the relationship.
I.e. each student may take any number of courses, and each course must have at least 5 and
at most 60 students. Each course is taught by only one faculty member, and a faculty member
may teach from 0 to 3 courses per semester.
The relationships between Student → Course and Faculty → Course may be implemented using the
classes as the following ⇨
7|Page
The relation “a student takes a course” is implemented using the addCourse method in the Student
class and the addStudent method in the Course class.
The relation “a faculty teaches a course” is implemented using the addCourse method in the Faculty
class and the setFaculty method in the Course class.
10.4.2 Aggregation
3. In Aggregation, both the entries (instances) can survive individually which means ending one
entity will not affect the other entity.
The owner object is called an aggregating object, and its class is called an aggregating class. The
subject object is called an aggregated object, and its class is called an aggregated class.
8|Page
Consider the following example to illustrate Concept of Aggregation:
9|Page
10 | P a g e
Output Explanation: In this example, there is an Institute which has no. of departments like CSE, EE.
Every department has no. of students. So, we make an Institute class that has a reference to List
of Objects of the Department class.
That means Institute class is associated with Department class through its Object(s). And
Department class has also a reference to List of Objects of the Student class means it is associated
with the Student class through its Object(s).
10.4.3 Composition
Composition ⇨ is a restricted form of Aggregation in which two entities are highly dependent on each
other.
11 | P a g e
1. It represents part-of relationship.
3. When there is a composition between two entities, the composed object cannot exist without
the other entity.
12 | P a g e
13 | P a g e
Output explanation: In the above example, a library can have no. of books on the same or different
subjects. So, If Library gets destroyed then All books within that particular library will be destroyed.
i.e. books can not exist without libraries. That’s why it is composition.
Dependency: Aggregation implies a relationship where the child can exist independently of the parent.
For example, Bank and Employee, delete the Bank and the Employee still exist. whereas Composition
implies a relationship where the child cannot exist independent of the parent. For example, Human and
heart, heart don’t exist separate to a Human.
I.e. “a student has a name” is a composition relationship between the Student class and the
Name class because Name is dependent on Student, whereas “a student has an address” is an
aggregation relationship between the Student class and the Address class because an address
can exist by itself.
14 | P a g e
Different between Aggregation & Composition in implementation:
Aggregation may exist between objects of the same class. For example, a person may have a supervisor.
Suppose you need to process course information. Each course has a name and has students enrolled.
You should be able to add/drop a student to/from the course. You can use a class to model the courses,
as shown in the following ⇨
15 | P a g e
The Course class is implemented in the following ⇨
For simplicity, assume the maximum course enrollment is 100. The array is created using new
String[100]. The addStudent method adds a student to the array. Whenever a new student is added to
the course, numberOfStudents is increased.
The array size is fixed to be 100, so you cannot have more than 100 students in the course. You can
improve the class by automatically increasing the array size in Programming Exercise 10.9.
The user can create a Course object and manipulate it through the public methods addStudent,
dropStudent, getNumberOfStudents, and getStudents. However, the user doesn’t need to know how
these methods are implemented. The Course class encapsulates the internal implementation.
16 | P a g e
The following program test the Course class ⇨
Recall that a stack is a data structure that holds data in a last-in, first-out fashion, as shown in the
following:
17 | P a g e
For example, the compiler uses a stack to process method invocations. When a method is invoked, its
parameters and local variables are pushed into a stack. When a method calls another method, the new
method’s parameters and local variables are pushed into the stack. When a method finishes its work
and returns to its caller, its associated space is released from the stack.
I.e. You can define a StackOfIntegers class to model stacks that holds the int values as the following ⇨
18 | P a g e
The elements in the stack are stored in an array named elements. When you create a stack, the array
is also created. The no-arg constructor creates an array with the default capacity of 16. The variable
size counts the number of elements in the stack, and size – 1 is the index of the element at the top.
To implement push(int value), assign value to elements[size] if (size < capacity). If (size >= capacity),
create a new array of twice the current capacity, copy the contents of the current array to the new
array, and assign the reference of the new array to the current array in the stack.
19 | P a g e
The following program test the Stack class ⇨
A primitive-type value is not an object, but it can be wrapped in an object using a wrapper class in the
Java API.
Java provides Boolean, Character, Double, Float, Byte, Short, Integer, and Long wrapper classes in the
java.lang package for primitive data types.
A Wrapper class is a class whose object wraps or contains primitive data types. When we create an
object to a wrapper class, it contains a field and, in this field, we can store primitive data types. In other
words, we can wrap a primitive value into a wrapper class object.
Wrapper class in java provides the mechanism to convert primitive data type into object is called boxing
and object into primitive data type is called unboxing.
Autoboxing: Automatic conversion of primitive types to the object of their corresponding wrapper
classes. For example – conversion of int to Integer, long to Long, double to Double etc.
20 | P a g e
Unboxing: Automatically converting an object of a wrapper class to its corresponding primitive type.
For example – conversion of Integer to int, Long to long, Double to double, etc.
valueOf(String s);
method that creates Wrapper object for a given String.
valueOf(String s, int radix);
method that creates a Wrapper object for the given String with specified radix.
valueOf(primitive p);
method that creates a Wrapper object for the given primitive type.
toString();
method that converts the Wrapper object to String.
toString(primitive p);
method that converts primitive type to String.
toString(primitive p, int radix);
method that converts primitive type to specified radix String.
We can use three ways to construct the instance of the Wrapper Classes:
21 | P a g e
Method 2: Using the valueOf() method provided by the Wrapper class ⇨
The following example shows the difference between the two methods in the creation of instances
of the Wrapper classes;
22 | P a g e
In the case of creating objects with the help of the constructor of the wrapper class, each time a
new memory is allocated in the heap and the objects point to the different memory locations. Hence,
in the above example, In this case, both num1 and num2 are pointing to different memory locations,
thus on the comparison, they return false.
In the case of the valueOf() method as the valueOf() method checks if any memory is allocated to
the same value for that class in the heap. If it finds the value, then it provides the location of the
previously allotted memory to the new instance and both start pointing to the same memory
location in the heap. Hence, on the comparison, it returns true.
The wrapper classes do not have no-arg constructors. The instances of all wrapper classes are
immutable; this means that, once the objects are created, their internal values cannot be changed.
Numeric wrapper classes are very similar to each other. Each contains the methods doubleValue(),
floatValue(), intValue(), longValue(), shortValue(), and byteValue(). These methods “convert” objects
into primitive-type values.
You can construct a wrapper object either from a primitive data type value or from a string
representing the numeric value;
23 | P a g e
The key features of Integer and Double are shown in the following figure ⇨
You should use the static valueOf method to create an instance. Java enables frequently used wrapper
objects to be reused through the valueOf method. An instance created using valueOf may be shared,
which is fine because the wrapper objects are immutable.
For example, in the following code, x1 and x2 are different objects, but x3 and x4 are the same
objects created using the valueOf method. Note that Integer x5 = 32, is same as Integer x5 =
Integer.valueOf(32).
24 | P a g e
Each numeric 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.
I.e. 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):
Each numeric wrapper class contains the methods doubleValue(), floatValue(), intValue(), longValue(),
and shortValue() for returning a double, float, int, long, or short value for the wrapper object.
The numeric wrapper classes contain the compareTo method for comparing two numbers and returns
1, 0, or –1, if this number is greater than, equal to, or less than the other number.
The numeric wrapper classes have a useful static method, valueOf(String s). This method creates a
new object initialized to the value represented by the specified string.
25 | P a g e
The numeric wrapper classes has two overloaded parsing methods to parse a numeric string into an
appropriate numeric value based on 10 (decimal) or any specified radix. (e.g., 2 for binary, 8 for octal,
and 16 for hexadecimal).
A primitive-type value can be automatically converted to an object using a wrapper class, and vice
versa, depending on the context.
The compiler will automatically box a primitive value that appears in a context requiring an object, and
unbox an object that appears in a context requiring a primitive value.
For instance, the following statement in (a) can be simplified as in (b) using autoboxing.
In line 1, the primitive values 1, 2, and 3 are automatically boxed into objects Integer.valueOf(1),
Integer.valueOf(2), and Integer.valueOf(3). In line 2, the objects intArray[0], intArray[1], and
intArray[2] are automatically unboxed into int values that are added together.
26 | P a g e
10.9 The BigInteger and BigDecimal Classes
The BigInteger and BigDecimal classes in the java.math package can be used to represent integers or
decimal numbers of any size and precision, but both are immutable.
BigInteger class is used for the mathematical operation which involves very big integer calculations
that are outside the limit of all available primitive data types.
BigInteger class is very handy to use because of its large method library and it is also used a lot in
competitive programming
The BigDecimal class provides operations on double numbers for arithmetic, scale handling, rounding,
comparison, format conversion and hashing. It can handle very large and very small floating-point
numbers with great precision.
abs();
Method that returns a BigInteger / BigDecimal whose value is the absolute value of this
BigInteger.
add(BigInteger / BigDecimal val);
Method that returns a BigInteger / BigDecimal whose value is (this + val).
subtract(BigInteger / BigDecimal val);
Method that returns a BigInteger / BigDecimal whose value is (this - val).
multiply(BigInteger / BigDecimal val);
Method that returns a BigInteger / BigDecimal whose value is (this * val).
27 | P a g e
divide(BigInteger / BigDecimal val);
Method that returns a BigInteger / BigDecimal whose value is (this / val).
doubleValue();
Converts this BigInteger / BigDecimal to a double.
intValue();
Converts this BigInteger / BigDecimal to an int.
longValue();
Converts this BigInteger / BigDecimal to a long.
valueOf(long val);
Returns a BigInteger / BigDecimal whose value is equal to that of the specified long.
equals(Object x);
Compares this BigInteger / BigDecimal with the specified Object for equality.
gcd(BigInteger / BigDecimal val);
Returns a BigInteger / BigDecimal whose value is the greatest common divisor of abs(this) and
abs(val).
isProbablePrime(int certainty);
Returns true if this BigInteger / BigDecimal is probably prime, false if it's definitely composite.
nextProbablePrime();
Returns the first integer greater than this BigInteger / BigDecimal that is probably prime.
max(BigInteger / BigDecimal val);
Returns the maximum of this BigInteger / BigDecimal and val.
min(BigInteger / BigDecimal val);
Returns the minimum of this BigInteger / BigDecimal and val.
pow(int exponent);
Returns a BigInteger / BigDecimal whose value is (thisexponent).
toString();
Returns the decimal String representation of this BigInteger / BigDecimal.
doubleValue();
Converts this BigInteger / BigDecimal to a double.
28 | P a g e
intValue();
Converts this BigInteger / BigDecimal to an int.
longValue();
Converts this BigInteger / BigDecimal to a long.
Note the factorial of an integer can be very large. The following code gives a method that can return
the factorial of any integer ⇨
A String object is immutable; its contents cannot be changed once the string is created.
1. String(String str); Allocates a new String from the given specified string.
29 | P a g e
2. String(char[] char_array); Allocates a new String from the given Character array.
The answer is no. The first statement creates a String object with the content "Java" and assigns its
reference to s. The second statement creates a new String object with the content "HTML" and assigns
its reference to s.
The first String object still exists after the assignment, but it can no longer be accessed,
because variable s now points to the new object.
The JVM uses a unique instance for string literals with the same character sequence in order to
improve efficiency and save memory. Such an instance is called an interned string.
30 | P a g e
10.10.3 Methods of String Class
length();
Returns the number of characters in the String.
charAt(int in);
Returns the char at the from the ith index.
substring (int i);
Return the substring from the ith index character to end.
substring (int i, int j);
Return the substring from the i to j-1 index.
concat(String str);
Concatenates the specified string to the end of this string.
contains(CharSequence str);
Returns true if and only if this string contains the specified sequence of char values.
indexOf(String str);
Returns the index within the string of the first occurrence of the specified string.
compareTo(String anotherString);
Compares two strings lexicographically.
compareToIgnoreCase(String anotherString);
Compares two strings lexicographically, ignoring case considerations.
31 | P a g e
equals(Object anObject);
Compares this string to the specified object.
equalsIgnoreCase(String anotherString);
Compares string to another string, ignoring case considerations.
toLowerCase();
Converts all the characters in the String to lower case.
toUpperCase();
Converts all the characters in the String to upper case.
trim();
Returns the copy of the String, by removing whitespaces at both ends.
replace(char oldChar, char newchar);
Returns new string by replacing all occurrences of oldChar with newChar.
copyValueOf(char[] data);
Returns a String that represents the character sequence in the array specified.
copyValueOf(char[] data, int offset, int count);
Returns a String that represents the character sequence in the array specified.
32 | P a g e
split(String regex, int limit);
Splits this string around matches of the given regular expression.
toCharArray();
Converts this string to a new character array.
valueOf(char[] data);
Returns the string representation of the char array argument.
valueOf(double d);
Returns the string representation of the double argument.
valueOf(int i);
Returns the string representation of the int argument.
valueOf(object obj);
Returns the string representation of the Object argument.
33 | P a g e
10.10.3 Matching, Replacing, and Splitting by Patterns
A regular expression (abbreviated regex) is a string that describes a pattern for matching a set of
strings. You can match, replace, or split a string by specifying a pattern.
The matches method is very similar to the equals method. I.e. the following two statements both
evaluate to true:
However, the matches method is more powerful. It can match not only a fixed string, but also a set of
strings that follow a pattern. I.e. the following statements all evaluate to true:
Java.* is a regular expression. It describes a string pattern that begins with Java followed by
any zero or more characters.
For example; the following statement returns a new string that replaces $, +, or # in “a+b$#c” with
the string “NNN“.
Here, the regular expression [$+#] specifies a pattern that matches $, +, or #. Thus, the output
is aNNNbNNNNNNc.
For example; the following statement splits the string into an array of strings delimited by punctuation
marks.
34 | P a g e
Here, the regular expression [.,:;?] specifies a pattern that matches . , , , : , ; or ?. Thus, the
string is split into Java, C, C#, and C++, which are stored in array tokens.
To convert a string into an array of characters, use the toCharArray method. I.e. The following
statement converts the string Java to an array:
You can also use the getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) method to copy a
substring of the string from index srcBegin to index srcEnd–1 into a character array dst starting from
index dstBegin.
For example, the following code copies a substring "3720" in "CS3720" from index 2 to index
6–1 into the character array dst starting from index 4:
To convert an array of characters into a string, use the String(char[]) constructor or the
valueOf(char[]) method. I.e. The following statement constructs a string from an array using the String
constructor:
I.e. The next statement constructs a string from an array using the valueOf method.
35 | P a g e
10.10.5 Converting Characters and Numeric Values to Strings
Recall that you can use Double.parseDouble(str) or Integer.parseInt(str) to convert a string to a double
value or an int value.
You can convert a character or a number into a string by using the string concatenating operator.
Another way is to use the overloaded static valueOf method.
For example, to convert a double value 5.44 to a string, use String.valueOf(5.44). The return
value is a string consisting of the characters '5', '.', '4', and '4'.
The String class contains the static format method to return a formatted string. The syntax to invoke
this method is;
This method is similar to the printf method except that the format method returns a formatted string,
whereas the printf method displays a formatted string.
36 | P a g e
10.11 The StringBuilder and StringBuffer Classes
The StringBuilder and StringBuffer classes are similar to the String class except that the String class
is immutable.
You can add, insert, or append new contents into StringBuilder and StringBuffer objects, whereas the
value of a String object is fixed once the string is created.
The StringBuilder class is similar to StringBuffer except that the methods for modifying the buffer in
StringBuffer are synchronized, which means that only one task is allowed to execute the methods.
Use StringBuffer if the class might be accessed by multiple tasks concurrently, because
synchronization is needed in this case to prevent corruptions to StringBuffer.
Using StringBuilder is more efficient if it is accessed by just a single task, because no synchronization
is needed in this case.
StringBuffer represents growable and writable character sequences. StringBuffer may have
characters and substrings inserted in the middle or appended to the end.
1. StringBuffer(): creates an empty string buffer with the initial capacity of 16.
3. StringBuffer(int capacity): creates an empty string buffer with the specified capacity.
37 | P a g e
10.11.2 StringBuilder Class
The function of StringBuilder is very much similar to the StringBuffer class. However, the StringBuilder
class differs from the StringBuffer class on the basis of synchronization.
1. StringBuilder (): creates an empty string builder with the initial capacity of 16.
2. StringBuilder (String str): creates a string builder with the specified string.
3. StringBuilder (int capacity): creates an empty string builder with the specified capacity.
append(String str);
Appends the specified string to this character sequence.
append(char[] str);
Appends the string representation of the char array argument to this sequence.
append(char[] str, int offset, int len);
Appends the string representation of a subarray of the char array argument to this sequence.
delete(int start, int end);
Removes the characters in a substring of this sequence.
38 | P a g e
reverse();
reverses the current string.
deleteCharAt(int index);
Removes the char at the specified position in this sequence.
capacity();
Returns the current capacity.
charAt(int index);
Returns the char value in this sequence at the specified index.
ensureCapacity(int minimumCapacity);
Ensures that the capacity is at least equal to the specified minimum.
getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin);
Characters are copied from this sequence into the destination character array dst.
insert(int offset, char[] str);
Inserts the string representation of the char array argument into this sequence.
insert(int index, char[] str, int offset, int len);
Inserts the string representation of a subarray of the str array argument into this sequence.
insert(int offset, String str);
Inserts the string into this character sequence.
replace(int start, int end, String str);
Replaces the characters in a substring of this sequence with characters in the specified String.
setCharAt(int index, char ch);
The character at the specified index is set to ch.
setLength(int newLength);
Sets the length of the character sequence.
trimToSize();
Attempts to reduce storage used for the character sequence.
39 | P a g e
10.11.4 Modifying Strings in the StringBuilder
For example, the following code appends strings and characters into stringBuilder to form a new string,
Welcome to Java;
For example, the following code inserts "HTML and " at position 11 in stringBuilder (just before the J),
and the new stringBuilder is “Welcome to HTML and Java“.
For example, suppose stringBuilder contains Welcome to Java before each of the following methods is
applied:
For example, the following statement reverses the string in the builder and assigns the builder’s
reference to stringBuilder1. Thus, stringBuilder and stringBuilder1 both point to the same StringBuilder
object:
40 | P a g e
Returning the reference of a StringBuilder enables the StringBuilder methods to be invoked in a chain
such as the following:
Notice that; the capacity is the number of characters the string builder is able to store without having
to increase its size.
If the newLength argument is less than the current length of the string builder, the string builder is
truncated to contain exactly the number of characters given by the newLength argument.
If the newLength argument is greater than or equal to the current length, sufficient null characters
(\u0000) are appended to the string builder so length becomes the newLength argument.
Notice that; the length is the actual size of the string stored in the builder, and the capacity is the
current size of the builder. The builder’s capacity is automatically increased if more characters are
added to exceed its capacity.
Write a new program that ignores nonalphanumeric characters in checking whether a string is a
palindrome.
1. Filter the string by removing the nonalphanumeric characters. This can be done by creating an
empty string builder, adding each alphanumeric character in the string to a string builder, and
returning the string from the string builder. You can use the isLetterOrDigit(ch) method in the
Character class to check whether character ch is a letter or a digit
41 | P a g e
2. Obtain a new string that is the reversal of the filtered string. Compare the reversed string with
the filtered string using the equals method.
42 | P a g e
10.12 Regular Expressions
43 | P a g e