10slide Comp2311
10slide Comp2311
OBJECT-ORIENTED PROGRAMMING
COMP2311
Instructor :Murad Njoum
Office : Masri322
1
Chapter 10 Thinking in Objects
and Strings -Revision
1
Constructing Strings
String newString = new String(stringLiteral);
2
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";
Trace Code s = "HTML";
String s = "Java"; s = "HTML";
3
3
Interned Strings
Since strings are immutable and are frequently used, to improve efficiency
and save memory, the JVM uses a unique instance for string literals with
the same character sequence. Such an instance is called interned. For
example, the following statements:
Examples
String s1 = "Welcome to Java"; s1
: String
s3
String s2 = new String("Welcome to Java"); Interned string object for
"Welcome to Java"
String s3 = "Welcome to Java";
4
display A new object is created if you use the new operator.
s1 == s2 is false If you use the string initializer, no new object is
s1 == s3 is true created if the interned object is already created.
Trace Code
s1
String s1 = "Welcome to Java"; : String
String s2 = new String("Welcome to Java"); Interned string object for
"Welcome to Java"
String s3 = "Welcome to Java";
5
Trace Code
s1
String s1 = "Welcome to Java"; : String
String s2 = new String("Welcome to Java"); Interned string object for
"Welcome to Java"
String s3 = "Welcome to Java";
s2 : String
A string object for
"Welcome to Java"
6
Trace Code
s1
String s1 = "Welcome to Java"; : String
s3
String s2 = new String("Welcome to Java"); Interned string object for
"Welcome to Java"
String s3 = "Welcome to Java";
s2 : String
A string object for
"Welcome to Java"
7
Replacing and Splitting Strings
java.lang.String
+replace(oldChar: char, Returns a new string that replaces all matching character in this
newChar: char): String string with the new character.
+replaceFirst(oldString: String, Returns a new string that replaces the first matching substring in
newString: String): String this string with the new substring.
+replaceAll(oldString: String, Returns a new string that replace all matching substrings in this
newString: String): String string with the new substring.
+split(delimiter: String): Returns an array of strings consisting of the substrings split by the
String[] delimiter.
8
Examples
9
String[] tokens =
"Java#HTML###Perl#hello#######".split("#",
0);
for (int i = 0; i < tokens.length; i++)
System.out.print(tokens[i] + " ");
System.out.print("hi");
10
Matching, Replacing and Splitting by Patterns
11
Convert Character and Numbers to
Strings
The String class provides several static valueOf methods for converting a
character, an array of characters, and numeric values to strings. These
methods have the same name valueOf with different argument types
char, char[], double, long, int, and float. For example, to convert a
double value to a string, use
String.valueOf(5.44). The return value is a string consisting of characters
‘5’, ‘.’, ‘4’, and ‘4’.
String.valueOf(tokens[0]).
12
StringBuilder and StringBuffer
13
StringBuilder Constructors
java.lang.StringBuilder
14
Modifying Strings in the Builder
java.lang.StringBuilder
+append(data: char[]): StringBuilder Appends a char array into this string builder.
+append(data: char[], offset: int, len: int): Appends a subarray in data into this string builder.
StringBuilder
+append(v: aPrimitiveType): StringBuilder Appends a primitive type value as a string to this
builder.
+append(s: String): StringBuilder Appends a string to this string builder.
+delete(startIndex: int, endIndex: int): Deletes characters from startIndex to endIndex.
StringBuilder
+deleteCharAt(index: int): StringBuilder Deletes a character at the specified index.
+insert(index: int, data: char[], offset: int, Inserts a subarray of the data in the array to the builder
len: int): StringBuilder at the specified index.
+insert(offset: int, data: char[]): Inserts data into this builder at the position offset.
StringBuilder
+insert(offset: int, b: aPrimitiveType): Inserts a value converted to a string into this builder.
StringBuilder
+insert(offset: int, s: String): StringBuilder Inserts a string into this builder at the position offset.
+replace(startIndex: int, endIndex: int, s: Replaces the characters in this builder from startIndex
String): StringBuilder to endIndex with the specified string.
+reverse(): StringBuilder Reverses the characters in the builder.
+setCharAt(index: int, ch: char): void Sets a new character at the specified index in this
builder.
15
Welcome JavaJava
Examples Welcome JavaJHTML andava
Welcome Java
Welcome ava
ava emocleW
ava emocleWHTML
wva emocleWHTML
StringBuilder stringBuilder = new StringBuilder("Welcome Java");
stringBuilder.append("Java");
stringBuilder.insert(13, "HTML and");
stringBuilder.delete(12, stringBuilder.length()) ;
stringBuilder.deleteCharAt(8);
stringBuilder.reverse();
stringBuilder.replace(11, 15, "HTML");
stringBuilder.setCharAt(0, 'w') ;
16
The toString, capacity, length, setLength, and charAt Methods
java.lang.StringBuilder
17
Regular Expressions
18
Matching Strings
"Java".matches("Java");
"Java".equals("Java");
"Java is fun".matches("Java.*")
"Java is cool".matches("Java.*")
"Java is powerful".matches("Java.*")
19
Regular Expression Syntax
"Java".matches("J..a");
"Java".matches("J(av|ba)a");
20
Thinking in Objects
21
Class Abstraction and Encapsulation
Class abstraction means to separate class implementation
from the use of the class. The creator of the class provides a
description of the class and let the user know how the class
can be used. The user of the class does not need to know
how the class is implemented. The detail of implementation
is encapsulated and hidden from the user.
22
Object-Oriented Thinking
Chapters 1-8 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.
23
Relations :
Association is a relation between two separate classes which establishes through their Objects.
Association can be one-to-one, one-to-many, many-to-one, many-to-many.
24
Association
Whenever two classes are connected to each other, an association relationship link can be used.
( No ownership , no lifetime dependency)
You can use a simple name for the relationship close to the line. For example, in a game, a player will have a lot of save files.
If we consider Player and SaveFile as classes, then we can create an association link for them like below:
25
Aggregation is a special form of Association where:
•It represents Has-A’s relationship.
•It is a unidirectional association i.e. a one-way relationship. For example, a
department can have students but vice versa is not possible and thus unidirectional
in nature.
•In Aggregation, both entries can survive individually which means ending one
entity will not affect the other entity.
26
Aggregation
With aggregation, an object will always be referenced by other objects.
( One owner instance but no lifetime dependency)
This can be shown by an open diamond (a diamond without any fill color) in the UML.
Previously we described aggregation and composition using the Vehicle class example.
We will use the same example for the UML diagrams.
27
Composition
If an object only contains one other object such that their lives are bound together,
( One owner instance and lifetime child instance dependent on lifetime of owner
instance )
then we can show this relationship with the composition arrow in UML.
28
Composition is a restricted form of Aggregation in which two entities are highly dependent on each
other.
•It represents part of relationship.
•In composition, both entities are dependent on each other.
•When there is a composition between two entities, the composed object cannot exist without the other
entity.
29
Aggregation vs Composition
1. 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. Example: Human
and heart, heart don’t exist separate to a Human.
31
Car Address
Engine Student
class Student {
class Car { private Address address;
private final Engine engine; Student(Address addr){
Car(){ address=addr;
engine=new Engine(); }
}//final initialized once }
} class Address {
String city;
class Engine {
String state;
private String type;
Address(String city, String state){
}
… this.city=city; this.state=state;
Car car=new Car(); }
… } …
Student student=new Student();
• Create instance: …
(engine automatically created once), student has passed parameters from other methods
• Delete instance: delete car instance ,automatically engine instance deleted and
can’t passed to other car instance, but inf class student deleted then address can
32
be passed to other students
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
34
Overloading Constructors
35
Wrapper Classes
qBoolean q Integer
qCharacter q Long
qShort q Float
qByte 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.
36
36
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
37
37
The Integer Class and the Double Class
qConstructors
qConversion Methods
38
38
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 value)
public Integer(String s)
public Double(double value)
public Double(String s)
39
39
Numeric Wrapper Class Constants
vEach numerical wrapper class has the constants MAX_VALUE and
MIN_VALUE.
v MAX_VALUE represents the maximum value of the corresponding primitive
data type. For Byte, Short, Integer, and Long,
vMIN_VALUE represents the minimum byte, short, int, and long values.
v For Float and Double, MIN_VALUE represents the minimum positive float
and double values.
v 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).
40
40
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.
41
41
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:
42
42
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.
43
43
Autoboxing and Unboxing
Autoboxing is the Java compiler’s automatic conversion
between the primitive types and their corresponding object
wrapper classes.
44
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):
Equivalent
Integer[] intArray = {new Integer(2), Integer[] intArray = {2, 4, 3};
new Integer(4), new Integer(3)};
Unboxing
45
45
BigInteger and BigDecimal
46
46
BigInteger and BigDecimal
BigInteger a = new BigInteger("9223372036854775807");
BigInteger b = new BigInteger("2");
BigInteger c = a.multiply(b); // 9223372036854775807 * 2
System.out.println(c);
LargeFactorial Run
import java.util.Scanner;
import java.math.*;
return result;
}
} 48