0% found this document useful (0 votes)
24 views84 pages

Unit 3 - Objects and Classes

Unit 3 covers the fundamentals of objects and classes in Java, including the concepts of classes, objects, constructors, and visibility modifiers. It explains how to define classes, create objects, and utilize accessor and mutator methods for data encapsulation. Additionally, the unit discusses the differences between primitive and reference types, garbage collection, and the use of the 'this' reference keyword.

Uploaded by

Cookies Hang
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views84 pages

Unit 3 - Objects and Classes

Unit 3 covers the fundamentals of objects and classes in Java, including the concepts of classes, objects, constructors, and visibility modifiers. It explains how to define classes, create objects, and utilize accessor and mutator methods for data encapsulation. Additionally, the unit discusses the differences between primitive and reference types, garbage collection, and the use of the 'this' reference keyword.

Uploaded by

Cookies Hang
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit 3: Objects and Classes

Unit 3 Goals

• Concept of classes and objects


• Construct objects using constructor
• Overload constructors
• this reference
• Passing object reference to methods
• Visibility modifier
• Immutable object
• Instance vs. static
• Java Packages
• Java Random, String, StringBuilder, and Character classes

2
Defining Classes for Objects

• Object-oriented programming (OOP) involves programming


using objects.
• An object represents an entity in the real world that can be
clearly identified. For example, a student, a desk, a circle, a
button, and even a loan can all be viewed as objects.
• An object has a unique identity, attribute, and behavior.
• The identity is the name or id of an object
• The attribute of an object (also known as properties) consists of a
set of data fields with their current values.
• The behavior of an object (also known as actions) is defined by
methods.

3
Classes
• Classes are constructs that define objects of the same
type.
Access modifier Class Name

• Objects are instances of a class. public class Circle {


Class Members
Instance private int radius;
variables

Class Members
public double getArea() {
Instance //getArea() method implementation
method } //end of method body

} //end of class body

Class Name: Circle A class template

Data Fields:
radius is _______

Methods:
getArea

Circle Object 1 Circle Object 2 Circle Object 3 Three objects of


the Circle class
Data Fields: Data Fields: Data Fields:
radius is 10 radius is 25 radius is 125
4
Java Classes

• A Java class uses variables to define data fields


and methods to define behaviors.
• Additionally, a class provides a special type of
methods, known as constructors, which are
invoked to construct (and initialize) objects from
the class.

5
Java Classes
public class Circle {
/** The radius of this circle */
private double radius; Data field

/** Construct a circle object */


public Circle() { To create a circle object
with radius 1
radius = 1.0;
} Constructors

/** Construct a circle object */


public Circle(double newRadius) {
radius = newRadius;
- To construct a circle
with a specified radius
}

/** Return the area of this circle */


public double getArea() { Method
return radius * radius * 3.14159;
}
}
6
UML Class Diagram

UML (Unified Modeling Language) is a standardized modeling language for


object-oriented system analysis, design and deployment. It is an OMG’s
standard visual language.

UML Class Diagram Circle Class name Class name

-radius: double Data fields dataFieldType]


Data fields [dataFieldName:
-private Constructors and
+Circle()
+public Constructors [ methods
ClassName(parameterName: parameterType) ]
+Circle(newRadius: double) &
+getArea(): double Methods [ methodName(parameterName: parameterType) : returnType ]

circle2: Circle circle3: Circle UML


UML notation for
circle1: Circle
for objects
objects
radius = 1.0 radius = 25 radius = 125

OMG: Object Management Group


7
Visibility Modifiers

• private (-) : The data fields or methods can be accessed


only by the declaring class (within its own class).

• public (+) : The class, data field, or method is visible to any


class in any package (can be accessed from any other
classes).

private:

public:

8
Why data fields should be private?
• To protect data (encapsulation)
• To make class easier to maintain
How to retrieve and modify a data field?
• Use get (accessor) method to return its value (to make a private data field
accessible)
• Use set (mutator) method to set a new value (to modify private properties)

Circle
The - sign indicates
private modifier -radius: double The radius of this circle

Data field
encapsulation +Circle() Constructs a default circle object.
is to prevent direct +Circle(radius: double)
modifications of Constructs a circle object with the specified radius.
data fields. +getRadius(): double Returns the radius of this circle (accessor).
+setRadius(radius: double): void Sets a new radius for this circle (mutator).
+getArea(): double Returns the area of this circle.

9
Accessor & Mutator methods
• Accessor methods – methods to read private properties.
• Mutator methods – methods to modify private properties.

public class Circle {


private double radius;

// Accessor
public double getRadius() {
return radius;
}

// Mutator
public void setRadius(int r) {
if(r > 0) // guards illegal value
radius = r;
}

// ...
}

10
Accessing Object’s Members

// Create a circle with default radius


Circle c1 = new Circle();
c1.setRadius(10); // mutator method
System.out.println("Circle 1 area is : " + c1.getArea());

// Create a circle with radius 5.0


Circle c2 = new Circle(5.0);
System.out.println("Circle 2 area is : " + c2.getArea());

// mutator method guards illegal value!


// c2.radius = -10; // radius is private, cannot access directly!
c2.setRadius(-10);

11
Accessing Object’s Members
Dot operator or
Object member
access operator
// Create a circle with default radius
Circle c1 = new Circle();
c1.setRadius(10); // mutator method
System.out.println("Circle 1 area is : " + c1.getArea());

// Create a circle with radius 5.0


Circle c2 = new Circle(5.0);
System.out.println("Circle 2 area is : " + c2.getArea());

// mutator method guards illegal value!


// c2.radius = -10; // radius is private, cannot access directly!
c2.setRadius(-10);

Question: Can we invoke Circle.getArea() ??


No. getArea() is an instance method (nonstatic), it must be invoked from an object
using objectRefVar.methodName(arguments) 12
Constructors

13
Constructors
• Constructors are a special kind of methods that are invoked to
construct objects.
• Constructors must have the same name as the class itself.
• Constructors do not have a return type—not even void.
• A constructor with no parameters is referred to as a no-arg constructor.
• Constructors play the role of initializing objects.

public class Circle {


private double radius;

public Circle() { // no-arg constructor


radius = 1.0;
}

public Circle(double newRadius) { // second constructor


radius = newRadius;
}
} 14
Constructors
9 Rules about Constructors in Java
1. Constructors can be overloaded.
2. Default constructor: Java does not actually require an explicit
constructor in the class description. If you do not include a constructor,
then the Java compiler will create a default constructor with an empty
argument.
3. The compiler won’t generate the default constructor if there’s a already
constructor in the class.
4. The default constructor is only generated by the compiler.
5. Constructors are not inherited.
6. Constructors can be private!
7. The default constructor has same access modifier as the class.
8. A constructor calls the default constructor of its superclass.
9. The first statement in a constructor must call to this() or super().

15
Difference between constructor and method in Java

Constructors Methods

A method is a collection of
A constructor is used to construct
statements grouped together to
and initialize objects from a class.
perform an operation

A constructor must not have a return


A method must have a return type.
type – not even void

The constructor is invoked implicitly. The method is invoked explicitly.

The Java compiler provides a


The method is not provided by the
default constructor if you don't have
compiler in any case.
any constructor in a class.

The constructor name must be The method name may or may not
same as the class name. be same as the class name.
Default Constructor
• A class may be defined without constructors. In this case,
a no-arg constructor with an empty body is implicitly
declared in the class.
• This constructor, called a default constructor, is provided
automatically only if no constructors are explicitly defined
in the class.
public class Circle {
private double radius;

// public Circle() {......} // default constructor

What is the purpose of a default constructor?


- To provide the default values to the object
- E.g.: 0, null, etc., depending on the type.
17
Creating Objects Using Constructors
• Constructors are invoked using the new operator when an
object is created. Constructors play the role of initializing
objects.
• To reference an object, assign the object to a reference
variable. Syntax:
ClassName objectRefVar = new ClassName();
Example:
Assign object Create
reference an object

Circle c1 = new Circle(); Constructors

Assign object Create


reference an object

Circle myCircle = new Circle(5.0);


18
Creating Objects Using Constructors

Example: Create
Assign object
reference an object

Circle myCircle = new Circle(5.0); Constructors

Stack Heap
A Circle object
The myCircle
variable holds the
address of the Circle myCircle reference radius: 5.0
object.

Whenever an object is created, it is always stored in the Heap space and


stack memory contains the reference to it. Stack memory only contains
local primitive variables and reference variables to objects in heap space.
19
Copy Constructor
• Copy constructor is convenient way to construct an object as a copy of
another similar type of object.
• Copy constructor accepts only one argument of the same type to which
this constructor belongs to.
• Example:
public class Student
{
private int stuNum;

public Student(int sn)


{
stuNum = sn;
}
public Student(Student stuObj) // first declare a constructor that takes
an object of the same type as a parameter
{
stuNum = stuObj.stuNum; // copy field of the input object into
} the new instance

Student s1 = new Student(100);


Student s2 = new Student(s1); // s2 is a copy of s1 20
Calling Overloaded constructors

public class Circle {


private double radius;

public Circle(double radius) {


this.radius = radius;
} this must be explicitly used to reference the data
field radius of the object being constructed
public Circle() {
this(1.0);
} this is used to invoke another constructor

public double getArea() {


return this.radius * this.radius * Math.PI;
}
} Every instance variable belongs to an instance represented by this,
which is normally omitted

22
Data Values

23
Default Value for a Data Field

• The default value of a data field is:


– null for a reference type
(If a data field of a reference type does not reference any object, the data field holds a special
literal value, null)
– 0 for a numeric type
– false for a boolean type
– '\u0000' for a char type

public class Student {


String name; // name has default value null
int age; // age has default value 0
boolean isScienceMajor; // isScienceMajor has default value false
char gender; // gender has default value '\u0000‘

public Student() { // no-arg constructor


}
}

24
No Default Value for a Local Variable

• Java assigns no default value to a local variable inside a method.

public class Test {


public void method() {
int x; // x has no default value
String y; // y has no default value
System.out.println("x is " + x);
System.out.println("y is " + y);
}
}

Compilation error: variables not initialized

25
this Reference Keyword

26
this Reference

• The this keyword is the name of a reference that an object


can use to refer to itself.

public class Student


{
private int stuNum;

public Student()
{
stuNum = 100; // implicit
this.stuNum = 100; // explicit
}
}

27
this Reference
public class Student
{
private int stuNum;
Identical to the class field names
public Student(int stuNum)
{
stuNum = stuNum;
}

public void showStudent()


{
System.out.println("Student# : " + stuNum);
}
}
public class TestStudent1
{
public static void main(String[] args)
{ Output:
Student stu = new Student(101); Student# : ?
0
stu.showStudent();
}
}
28
this Reference

• To fix the problem, use this to reference a class’s hidden


data field explicitly.

public Student(int stuNum)


{
this.stuNum = stuNum;
}

Output:
Student# : 101

29
this Reference

• The this keyword can be used to invoke another constructor


of the same class.

public class Student


{
private int stuNum;

public Student(int stuNum)


{
this.stuNum = stuNum;
// other initialization...
}

public Student()
{
this(100); // invoke Student(100);
}
}

30
Differences Between Variables

31
Differences between Variables of
Primitive Data Types and Object (Reference) Types

• Every variable represents a memory location that holds a value.


• When you declare a variable, you telling the compiler what type
of value the variable can hold.
➢ For a variable of primitive type, the value is of the primitive type.
➢ For a variable of reference type, the value is a reference to where an
object is located.

Created using new Circle()


Primitive type int i = 1 i 1

Object type Circle c c reference c: Circle


(Class, Reference)
radius = 1
The value of int variable i is int value 1.
The value of Circle object c holds a reference to where the contents of the
Circle object are stored in memory.
32
Copying Variables of Primitive Data Types and Object Types

Primitive type assignment i = j


Before: After:

i 1 i 2

j 2 j 2

Object type assignment c1 = c2


Before: After:

c1 c1

c2 c2

c1: Circle C2: Circle c1: Circle C2: Circle


radius = 5 radius = 9 radius = 5 radius = 9

Garbage
33
Garbage Collection

• As shown in the previous figure, after the assignment


statement c1 = c2, c1 points to the same object
referenced by c2.
• The object previously referenced by c1 is no longer
referenced. This object is known as garbage.
• Garbage is automatically collected by JVM. The JVM will
automatically collect the space if the object is not
referenced by any reference variable.
• **TIP: If you know that an object is no longer needed,
you can explicitly assign null to a reference variable for
the object.

34
Passing Object References to Method

35
Passing Object References to a Method

• Recall that Java uses exactly one mode of passing


arguments: pass-by-value (pass a copy of the value to the
method).

• A class type variable does not hold the actual data item that
is associated with it, but holds the memory address of the
object.

• When an object is passed as an argument, it is actually a


reference to the object that is passed.

→ Passing an object is actually passing the reference of the object.

36
Passing Object References to a Method
• Example:

public static void main(String[] args) {


int n = 5;
Circle myCircle = new Circle();
methodX(n, myCircle);
}
public static void methodX(int m, Circle c) {
....
}
Stack Pass by value (here
the value is 5)
Space required for the
methodX Pass by value
int m: 5 (here the value is
Circle c: reference the reference for
the object) Heap
Space required for the
main method
int n: 5 A circle
myCircle: reference object
37
Passing Object References to a Method

• Pass-by-value on references can be best described


semantically as pass-by-sharing. The object referenced in
the method is the same as the object being passed.
(This is somewhat similar to pass-by-reference in some
other languages such as C++)

• Because the object’s reference gives the object’s location in


memory, the method will have access to the object and can
make changes to the original object from within the method.

38
Passing Objects
class PassObject {
public static void main(String[] args){
Student object
Student stu= new Student();
created

System.out.println(stu.cgpa); Output: 2.0

increaseCGPA(stu);

System.out.println(stu.cgpa); Output: 2.1


}
Note: the value is
changed on the
static void increaseCGPA(Student s) {
Student object
s.cgpa = s.cgpa +0.1;
because the memory
} address of the object
} is passed to the
class Student method.
{
double cgpa = 2.0;
} 39
Access/Visibility Modifiers

40
Visibility Modifiers

• private (-) : The data fields or methods can be accessed


only by the declaring class (within its own class).

• public (+) : The class, data field, or method is visible to any


class in any package (can be accessed from any other
classes).

• If public or private is not used, then by default, the class,


variable, or method can be accessed by any class in the
same package.

41
Visibility Modifiers

• The default modifier restricts access to within a package,


and the public modifier enables unrestricted access.

package p1; package p2;


class C1 { public class C2 { public class C3 {
... can access C1 cannot access C1;
} } can access C2;
}

42
Visibility Modifiers

• The private modifier restricts access to within a class, and


the public modifier enables unrestricted access.

package p1; package p2;


public class C1 { public class C2 { public class C3 {
public int x; void aMethod() { void aMethod() {
int y; C1 o = new C1(); C1 o = new C1();
private int z; o.x; //ok o.x; //ok
o.y; //ok o.y; //error!
public void m1() { o.z; //error! o.z; //error!
}
void m2() { o.m1(); //ok o.m1(); //ok
} o.m2(); //ok o.m2(); //error!
private void m3() { o.m3(); //error! o.m3(); //error!
} } }
} } }

43
Immutable

44
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 below, the class would
be immutable because radius is private and cannot be changed
without a set method.

Circle
-radius: double

+Circle()
+Circle(radius: double)
+getRadius(): double
+setRadius(radius: double): void
+getArea(): double

45
Immutable Objects and Classes
• If a class contains only private data fields and no set methods, is the
class immutable?

• Not necessary!
public class Person {
private int id;
private BirthDate birthDate;

public Person(int ssn, int year, int month, int day){


id = ssn;
birthDate = new BirthDate(year, month, day);
}

public int getId() {


return id; // return the value of id
}

public BirthDate getBirthDate() {


return birthDate; // return the reference of birthDate
}

public void showPersonInfo() {


System.out.println("ID is "+id);
birthDate.show();
}
46
}
Non-Immutable Example
class BirthDate {
int year, month, day;
public BirthDate(int year, int month, int day) {
this.year = year; this.month = month; this.day = day;
}
public BirthDate(BirthDate bd) { // copy constructor
this.year = bd.year; this.month = bd.month; this.day = bd.day;
}
public void setYear(int year) {
this.year = year;
}
public void show() {
System.out.println("BirthDate is "+day+"/"+month+"/"+year);
}
}

public static void main(String[] args) {


Person st = new Person(1234, 1980, 8, 15); ID is 1234
st.showPersonInfo(); BirthDate is 15/8/1980
// get reference of BirthDate and make change
BirthDate bd = st.getBirthDate();
bd.setYear(1990);
// after
System.out.println(); ID is 1234
st.showPersonInfo(); BirthDate is 15/8/1990
}
} 47
Immutable Objects and Classes

• getBirthDate() returns a reference to the birthdate object, and


through this reference, the content of birthdate object can be
changed (break encapsulation).
• To fix it, return a copy of the object.

public class Student {


private int id;
private BirthDate birthDate;

public Student(int ssn, int year, int month, int day){


id = ssn;
birthDate = new BirthDate(year, month, day);
}

public int getId() {


return id;
}

public BirthDate getBirthDate() {


return new BirthDate(birthDate); // assume copy constructor
}
}

48
Immutable Objects and Classes

• For a class to be immutable, it must meet the following


requirements:

• All data fields must be private.


• There can’t be any mutator (set) methods for data
fields.
• No accessor (get) methods can return a reference to
a data field that is mutable.

49
Strings are Immutable Objects

• Strings are immutable objects, which means String class


does not have any mutator methods, so its content will
not be changed.
String str1 = new String("testing");
String str2 = str1.toUpperCase();

str1 “testing”
return

str2 “TESTING”

• Passing immutable object reacts like passing primitive


types.

50
PassString.java
public class PassString
{
public static void main(String[] args)
{
// Create a String object containing "Shakespeare".
String name = "Shakespeare";

// Display the String referenced by the name variable.


System.out.println("In main, " + name);
Output: Shakespeare
// Call the changeName method, passing the
// address of the name variable as an argument.
changeName(name);

// Display the String referenced by the name variable.


System.out.println("Back in main, " + name);
Output: Shakespeare
}
name “Shakespeare”

public static void changeName(String str)


{
str
// Call a method referenced by str. return
System.out.println(str.replace('a', 'o'));
}
} Output: Shokespeore

51
Variables and Methods

52
Instance Variables and Methods

• Instance variable - is a variable defined in a class (i.e. a


member variable), for which each object of the class has a
separate copy, or instance. These variables can only be
accessed through the instance of the class (object!!).

• Instance method – A method that can only be accessed


through the instance of the class (object!!). These methods
can access to all (instance, static) variable that belongs to
the instance of the class.

53
Static Variables, Methods

• Static Variable – A static variable is shared by all objects


of the class. In fact, only one copy of this variable can
exists in the memory. This is also called class variable.

• Static Method – A static method belongs to the class and


cannot access the instance members (attribute of the
object of the class) of the class. Static methods are not tied
to a specific object.
• Static methods CANNOT make reference to non-
static methods or variables.

54
Static Variables, Methods
public class Emp
{
int empNum; // instance variable

//Declare static variable. The no. of objects created.


static int numberOfObjects = 0;

Emp() {
empNum = 999;
numberOfObjects++; Emp
}
empNum: int
Emp(int num) { numberOfObjects: int
empNum = num;
numberOfObjects++; +getNumberOfObjects(): int
} +getEmpNum(): int

//Declare static method. Return numberOfObjects


static int getNumberOfObjects() { UML Notation:
return numberOfObjects; +: public variables or methods
} underline: static variables or methods

public int getEmpNum() {


return empNum;
}
}

55
Static Variables, Methods
public class TestEmp
{
public static void main(String[] args)
{
Emp clerk = new Emp();
System.out.println("Clerk ID is " + clerk.empNum + " and of Emp object is " + clerk.numberOfObjects);

Emp lect= new Emp(101);


System.out.println("Lecturer ID is " + lect.empNum + " and of Emp object is " + lect.numberOfObjects);
}
}

instantiate Memory
clerk

empNum = 999 999 empNum After first employee


Emp numberOfObjects = 1 object was created,
numberOfObjects
empNum: int is 1.
numberOfObjects: int
1 numberOfObjects
getNumberOfObjects(): int
+getEmpNum(): int

UML Notation:
+: public variables or methods
underline: static variables or methods
56
Static Variables, and Methods
public class TestEmp
{
public static void main(String[] args)
{
Emp clerk = new Emp();
System.out.println("Clerk ID is " + clerk.empNum + " and of Emp object is " + clerk.numberOfObjects);

Emp lecturer= new Emp(101);


System.out.println("Lecturer ID is " + lect.empNum + " and of Emp object is " + lect.numberOfObjects);
}
}

instantiate Memory
clerk

empNum = 999 999 empNum After two employee


Emp numberOfObjects = 2 objects were created,
numberOfObjects
empNum: int is 2.
numberOfObjects: int
2 numberOfObjects
getNumberOfObjects(): int
+getEmpNum(): int instantiate lecturer

empNum = 101 101 empNum


UML Notation: numberOfObjects = 2
+: public variables or methods
underline: static variables or methods
57
Instance vs. Static

• A variable or method that is dependent on a specific


instance of the class must be an instance variable or
method. (e.g.: an Employee’s number, a Student’s ID)

• A variable or method that is shared by all the instances of a


class, or is not dependent on a specific instance, should be
declared static. (e.g.: number of Employee objects created)

• A static variable or method can be invoked from an instance


method, but an instance variable or method cannot be
invoked from a static method.

58
Instance method vs. Static method
Class (static) Class (static) Instance (non- Instance (non-
variable method static) variable static) method

Class (static)
method    
Instance (non-
static) method    
class MyClass {
private int instanceVar;
private static int staticVar;
public void instanceMethod() {
instanceVar++; // OK
instanceMethod2(); // OK
staticVar++; // OK
staticMethod2(); // OK
}
public static void staticMethod() {
instanceVar++; // Error
instanceMethod(); // Error
staticVar++; // OK
staticMethod2(); // OK
}
public void instanceMethod2() {}
public static void staticMethod2() {};
} 59
When to make a method static

• If a method doesn’t modify state of object, or not using any


instance variables.

• If a method only work on arguments, such as many of the


utility methods in Java, e.g.:
int m = Math.abs(-5);
String s = JOptionPane.showInputDialog(null, "nput a
number");
Arrays.sort(array);

• Convenience: to call a method without creating instance of


that class.

60
Java Package

61
Java Package
• Packages are nothing more than the way we organize files into different
directories according to their functionality, usability, as well as category
they should belong to.

• Suppose we have a file called HelloWorld.java, and we want to put this


file in a package world. First thing we have to do is to specify the
keyword package with the name of the package we want to use (world
in our case) on top of our source file, before the code that defines the
real classes in the package, as shown in our HelloWorld class below:

package world;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World");
}
}

62
Java Package

• Next, put the source file in a directory whose name reflects the name of
the package, for our example:

(..\src\)world\HellowWorld.java

• Like the .java source files, the compiled .class files should be in a series
of directories that reflect the package name:

(..\bin\)world\HellowWorld.class

• To use this world package in a Java project, we must include the


class directory in the build path

• To use HelloWorld from other packages, we need to first import it:

import world.HellowWorld;

63
Creating package with Eclipse

64
Creating package with Eclipse

HelloWorld in world package (world.HelloWorld) 65


How to create package

To use HelloWorld from other packages, we need to first import it:


import world.HellowWorld;
66
Java Library Class

67
Using Classes from the Java Library

• The Java API contains a rich set of classes for developing


Java programs. Following are a few useful classes in the
Java library.

➢ The Math class (already introduced in Unit 2)


➢ The Random class
➢ The String class
➢ The StringBuilder class
➢ The Character class

https://docs.oracle.com/javase/8/docs/api/

68
The Random Class
• You have used Math.random() to obtain a random double
value between 0.0 and 1.0 (excluding 1.0).
(0 <= Math.random() < 1.0)
• A more useful random number generator is provided in the
java.util.Random class.

java.util.Random
+Random() Constructs a Random object with the current time as its seed.
+Random(seed: long) Constructs a Random object with a specified seed.
+nextInt(): int Returns a random int value.
+nextInt(n: int): int Returns a random int value between 0 and n (exclusive).
+nextLong(): long Returns a random long value.
+nextDouble(): double Returns a random double value between 0.0 and 1.0 (exclusive).
+nextFloat(): float Returns a random float value between 0.0F and 1.0F (exclusive).
+nextBoolean(): boolean Returns a random boolean value.

69
The Random Class Example
• If two Random objects have the same seed, they will generate
identical sequences of numbers. For example, the following
code creates two Random objects with the same seed 3.

Random random1 = new Random(3);


System.out.print("From random1: ");
for (int i = 0; i < 10; i++)
System.out.print(random1.nextInt(1000) + " ");
Random random2 = new Random(3);
System.out.print("\nFrom random2: ");
for (int i = 0; i < 10; i++)
System.out.print(random2.nextInt(1000) + " ");

From random1: 734 660 210 581 128 202 549 564 459 961
From random2: 734 660 210 581 128 202 549 564 459 961

70
The String Class
• In Java, String is a class, you can create object of this class:
String greeting = new String("Greeting");

• Since strings are used frequently, Java provides a shorthand


initializer for creating a string:
String greeting = "Greeting";

• You can also create a string from an array of characters:


char[] ca = {'G', 'o', 'o', 'd', ' ', 'D', 'a', 'y'};
String message = new String(ca);
Output: Good Day

71
Interned String Instance
• Since strings are immutable and are frequently used, to
improve efficiency and save memory, the JVM uses a unique
instance for string literals called interned string.

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";
s2 : String
A string object for
"Welcome to Java"

• 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.

72
String Comparison

java.lang.String
+equals(s1: String): boolean Returns true if this string is equal to string s1.
+equalsIgnoreCase(s1: String): Returns true if this string is equal to string s1 case-
boolean insensitive.
+compareTo(s1: String): int Returns an integer greater than 0, equal to 0, or less than 0
to indicate whether this string is greater than, equal to, or
less than s1.
+compareToIgnoreCase(s1: String): Same as compareTo except that the comparison is case-
int insensitive.
+regionMatches(toffset: int, s1: String, Returns true if the specified subregion of this string exactly
offset: int, len: int): boolean matches the specified subregion in string s1.
+regionMatches(ignoreCase: boolean, Same as the preceding method except that you can specify
toffset: int, s1: String, offset: int, whether the match is case-sensitive.
len: int): boolean
+startsWith(prefix: String): boolean Returns true if this string starts with the specified prefix.
+endsWith(suffix: String): boolean Returns true if this string ends with the specified suffix.

73
String Comparisons
String s1 = new String("Welcome");
String s2 = "Welcome";
String s3 = "Welcome";

System.out.println("s1.equals(s2) : " + s1.equals(s2)); // true


System.out.println("s1 == s2 : " + (s1 == s2)); // false
System.out.println("s2.equals(s3) : " + s2.equals(s3)); // true
System.out.println("s2 == s3 : " + (s2 == s3)); // true

s3 = "Weldom";
System.out.println("Welcome > Weldom : " + s2.compareTo(s3) ); // -1

s3 = "Malaysia";
// true
System.out.println("Malaysia start with Mal : " + s3.startsWith("Mal"));

// false
System.out.println("Malaysia start with z : " + s3.startsWith("z"));

// true
System.out.println("lay is in Malaysia : " + "lay".regionMatches(0, s3,
2, 3));}

74
String Length, Characters, and Combining Strings

java.lang.String
+length(): int Returns the number of characters in this string.
+charAt(index: int): char Returns the character at the specified index from this string.
+concat(s1: String): String Returns a new string that concatenate this string with string s1.
string.

String s1 = new String("Hello");


int n = s1.length(); // n is 5
char c = s1.charAt(1); // c is 'e', start from 0

String s2 = s1.concat(" World!"); // Hello World!


String s3 = s1 + " World!"; // same as above

75
Extracting Substrings
java.lang.String
+subString(beginIndex: int): Returns this string’s substring that begins with the character at the
String specified beginIndex and extends to the end of the string.

+subString(beginIndex: int, Returns this string’s substring that begins at the specified
endIndex: int): String beginIndex and extends to the character at index endIndex – 1.
Note that the character at endIndex is not part of the substring.

String s1 = "Welcome to Java";


String s2 = s1.substring(0, 11) + "HTML";
// s2 = "Welcome to HTML

Indices 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

message W e l c o m e t o J a v a

message.substring(0, 11) message.substring(11) 76


Converting, Replacing, and Splitting Strings

java.lang.String
+toLowerCase(): String Returns a new string with all characters converted to lowercase.
+toUpperCase(): String Returns a new string with all characters converted to uppercase.
+trim(): String Returns a new string with blank characters trimmed on both sides.
+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.

77
Converting, Replacing, and Splitting Strings
"Welcome".toLowerCase() returns a new string, welcome.
"Welcome".toUpperCase() returns a new string, WELCOME.
" Welcome ".trim() returns a new string, Welcome.
"Welcome".replace('e', 'A') returns a new string, WAlcomA.
"Welcome".replaceFirst("e", "AB") returns a new string, WABlcome.
"Welcome".replace("e", "AB") returns a new string, WABlcomAB.
"Welcome".replace("el", "AB") returns a new string, WABcome.

78
Splitting a String

String[] tokens = "Java#HTML,Perl".split("[#,]");


for (int i = 0; i < tokens.length; i++)
System.out.print(tokens[i] + " ");

output:
Java HTML Perl

79
Finding a Character or a Substring in a String

java.lang.String
+indexOf(ch: char): int Returns the index of the first occurrence of ch in the string.
Returns -1 if not matched.
+indexOf(ch: char, fromIndex: Returns the index of the first occurrence of ch after fromIndex in
int): int the string. Returns -1 if not matched.
+indexOf(s: String): int Returns the index of the first occurrence of string s in this string.
Returns -1 if not matched.
+indexOf(s: String, fromIndex: Returns the index of the first occurrence of string s in this string
int): int after fromIndex. Returns -1 if not matched.
+lastIndexOf(ch:char): int Returns the index of the last occurrence of ch in the string.
Returns -1 if not matched.
+lastIndexOf(ch:char, Returns the index of the last occurrence of ch before fromIndex
fromIndex: int): int in this string. Returns -1 if not matched.
+lastIndexOf(s: String): int Returns the index of the last occurrence of string s. Returns -1 if
not matched.
+lastIndexOf(s: String, Returns the index of the last occurrence of string s before
fromIndex: int): int fromIndex. Returns -1 if not matched.

80
Finding a Character or a Substring in a String

"Welcome to Java".indexOf('W') returns 0.


"Welcome to Java".indexOf('x') returns -1.
"Welcome to Java".indexOf('o', 5) returns 9.
"Welcome to Java".indexOf("come") returns 3.
"Welcome to Java".indexOf("Java", 5) returns 11.
"Welcome to Java".indexOf("java", 5) returns -1.
"Welcome to Java".lastIndexOf('a') returns 14.

81
The StringBuilder Class
• The StringBuilder class is an alternative to the String class.

• StringBuilder is more flexible than String. 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
(immutable).

java.lang.StringBuilder

+StringBuilder() Constructs an empty string builder with capacity 16.


+StringBuilder(capacity: int) Constructs a string builder with the specified capacity.
+StringBuilder(s: String) Constructs a string builder with the specified string.

82
StringBuilder Examples
StringBuilder sb = new StringBuilder("Welcome to ");

sb.append("Java"); // can append any primitive type

sb.insert(11, "HTML and ");


sb.delete(11, 20);
sb.replace(11, 15, "HTML");
sb.reverse();

Output:
Welcome to Java
Welcome to HTML and Java
Welcome to Java
Welcome to HTML
LMTH ot emocleW

83
The Character Class
• The Character class has several static methods for determining a
character’s category (uppercase, lowercase, digit, and so on) and for
converting characters from uppercase to lowercase, and vice versa,.

java.lang.Character

+Character(value: char) Constructs a character object with char value


+charValue(): char Returns the char value from this object
+compareTo(anotherCharacter: Character): int Compares this character with another
+equals(anotherCharacter: Character): boolean Returns true if this character equals to another
+isDigit(ch: char): boolean Returns true if the specified character is a digit
+isLetter(ch: char): boolean Returns true if the specified character is a letter
+isLetterOrDigit(ch: char): boolean Returns true if the character is a letter or a digit
+isLowerCase(ch: char): boolean Returns true if the character is a lowercase letter
+isUpperCase(ch: char): boolean Returns true if the character is an uppercase letter
+toLowerCase(ch: char): char Returns the lowercase of the specified character
+toUpperCase(ch: char): char Returns the uppercase of the specified character
84
Exercise : Password checking

• Write a method that checks whether a string is a valid


password. Suppose the password rules are as follows:
➢ A password must have at least eight characters.
➢ A password consists of only letters and digits.
➢ A password must contain at least two digits.

85

You might also like