Lecture4
Lecture4
LECTURE 4
Page 1 of 22
Contents
• Basic of object-oriented concept
o Object
o Class
• Introduction to Strings
o String operations
Page 2 of 22
BASIC OF OBJECT ORIENTED CONCEPT
Object-oriented programming (OOP) represents an attempt to make
programs more closely model the way people think about and deal
with the world. In the older styles of programming, a programmer
who is faced with some problem must identify a computing task that
needs to be performed in order to solve the problem. Programming
then consists of finding a sequence of instructions that will
accomplish that task. But at the heart of object-oriented
programming, instead of tasks we find objects—entities that have
behaviors that hold information, and that can interact with one
another. Programming consists of designing a set of objects that
somehow model the problem at hand. Software objects in the program
can represent real or abstract entities in the problem domain.
This is supposed to make the design of the program more natural
and hence easier to get right and easier to understand. To some
extent, OOP is just a change in point of view. We can think of an
object in standard programming terms as nothing more than a set of
variables together with some subroutines for manipulating those
variables. In fact, it is possible to use object-oriented
techniques in any programming language. However, there is a big
difference between a language that makes OOP possible and one that
actively supports it. An object-oriented programming language such
as Java includes a number of features that make it very different
from a standard language and it’s a more natural model compared to
other models since OOP’s approach is exactly the way humans view
problem solving. In order to make effective use of those features,
you have to “orient” you’re thinking correctly.
Page 3 of 22
Objects and Classes
Objects are closely related to classes. We have already been
working with classes for previous chapters, and we have seen that
a class can contain variables and subroutines. If an object is
also a collection of variables and subroutines, how do they differ
from classes? And why does it require a different type of thinking
to understand and use them effectively?
What is an Object?
An object is an individual, identifiable entity, either real or
abstract, that has a well-defined boundary.
Page 4 of 22
An object has two main properties, namely:
State: each object has attributes, whose values represent its
state.
Your attributes include your name, your Reg.no, your GPA, your
major, etc.
What is a Class?
A class is a general specification of attributes and behavior for
a set of objects. Each object is an instance of a class. It shares
the behavior of the class, but has specific values for the
attributes. Thus, a class can be viewed as an abstract
specification, while an object is a concrete instance of that
specification.
Page 5 of 22
An example of a class is Student, an abstract entity that has
attributes and a set of behavior. However, unless we have an actual
student, we cannot say what the ID number is or what the major is
or what the GPA is!
INTRODUCTION TO STRINGS
Is a string an object or a primitive data type? This question has
a clear answer — a string is an object! However, the way strings
typically appear in Java programs can lead to confusion. There are
shortcuts available for strings that are not available for other
objects in Java. These shortcuts are highly used and they give
strings the appearance of a primitive data type. But, strings are
objects and they possess all the attributes and behaviors of
objects in Java.
String as an object
A string is collection of characters grouped together. For example,
"hello" is a string consisting of the characters 'h', 'e', 'l',
'l', and 'o'. Note that a character constant is enclosed in single
Page 6 of 22
quotes, whereas a string constant is enclosed in double quotes. In
Java, a string is an object. As with primitive data types, an
object doesn't exist until it is declared. The following statement
declares a String object variable named greeting:
String greeting;
The first hint that we are not dealing with a primitive data type,
is that the word "String" begins with an uppercase character 'S'.
The names of Java's primitive data types all begin with lowercase
letters (e.g., int, double). Indeed, class names in Java all begin
with an uppercase letter. (Note that this is a convention, rather
than a rule.)
Page 7 of 22
To set aside memory to hold the string, we must construct a
greeting object. This job is performed by a type of method called
a constructor. The process of constructing an object is called
instantiating an object. This is performed as follows:
Note that the constructor method has the same name as the class.
In fact, this is a rule of the Java language. The reserved word
"new" signals to the compiler that new memory is to be allocated.
Since a constructor is a method, it is followed by a set of
parentheses containing arguments passed to it. In the example
above, the constructor contains no arguments. When a constructor
is used without arguments, it is called a default constructor. In
the case of the default String constructor, memory is set aside
for the content of the string, but there are no characters in the
string. This is an empty string, as shown in figure 1b. The arrow
emphasizes that greeting holds a reference, not a value. It points
to the object to which greeting refers.
Page 8 of 22
The statement above fulfills the complete task of instantiating a
String object variable named greeting and initializing it with a
reference to a String object containing "hello". This is
illustrated in figure 1c. Note in figure 1, the use of a rectangle
to denote a variable (in this case an object variable) and a
hexagon to denote an object.
So, now that we have a String object variable and a String object,
what can we do with them? Of course, the string can be printed.
The statement:
System.out.println(greeting);
Here is the output produced by the program:
hello
String operations
Perhaps the most fundamental of all Java operators is assignment.
One string can be assigned to another, just as one integer can be
assigned to another integer. Consider the following Java
statements:
// assignment of integers
int x;
int y;
x = 5;
y = x;
// assignment of strings
String s1;
String s2;
s1 = new String("Java is fun!");
s2 = s1;
Page 9 of 22
If you followed the preceding discussion carefully, it is apparent
that these two sets of statements are slightly different. Although
two String object variables are declared, only one String object
is instantiated. The assignment in the final line above makes a
copy of a reference to a String object. It does not copy the
object! This is illustrated in Figure 2 below:
Page 10 of 22
Strings as Primitive Data Types
Next to numbers, strings are the most common type of data
manipulated in computer programs. Because of this, String objects
are given somewhat special treatment in the Java language. A set
of shortcuts or special operations exist for String objects that
do not exist for most other objects. These shortcuts are extremely
handy, but they can also confuse students learning to program in
Java. In this section we will examine how strings are commonly
treated in Java. Please bear in mind that, for the most part, these
discussions do not apply to other types of objects. They are unique
to String objects. The following shortcut provides an alternate,
simplified way to instantiate a String object:
String greeting = "hello";
This looks very much like declaring and initializing a primitive
data type, like an int, but don't be fooled. The statement above
is just a shortcut for
Page 11 of 22
5 // change the value of an int variable
6 int x = 5;
7 x = 6;
8 System.out.println(x);
9
10 // change the value of a String object
11 String greeting = "hello";
12 greeting = "bonjour";
13 System.out.println(greeting);
14 }
15 }
This is not the case with strings. When a String object is assigned
a new value, the new value often differs from the old value. The
string "hello" contains five characters, whereas the string
"bonjour" contains seven characters. So, space for an extra two
characters is needed. Where does this space come from? Let's answer
Page 12 of 22
this question by first presenting the following rule for String
objects in Java:
String Concatenation
Next to assignment, one of the most common string operations is
joining two strings to form a new, larger string. This operation
Page 13 of 22
is called concatenation. Once again, String objects are given
somewhat special treatment in Java. Strings are most-commonly
concatenated using the + operator as a shorthand notation. For
example, the expression:
"happy" + "birthday"
Concatenates two strings to form a new string. The string
"birthday" is appended to the end of the string "happy" to form
"happybirthday". Forgetting to consider spaces is a common
programming slip when concatenating strings. The following
expression "happy" + " " + "birthday" gives the intended result,
concatenating three string to form a new string containing "happy
birthday". Concatenation can involve string literals as well as
String object variables and assignment.
The statements:
String s1 = "happy";
String s2 = " ";
String s3 = "birthday";
String name = "Billy";
String greeting = s1 + s2 + s3 + s2 + name;
Page 14 of 22
String Methods
Other than assignment and concatenation, string operations usually
employ methods of the String class. Including all variations, there
are over 50 methods in the String class; however, we will only
examine the most common. These are listed in Table 1 below:
Page 15 of 22
by the method. The compareTo() method returns an integer. A method
can also return an object; so a class name may appear instead of
a data type.
String Methods
The demo program DemoStringMethods.java below demonstrates all the
methods listed in Table 1 above.
1 public class DemoStringMethods
2 {
3 public static void main(String[] args)
4 {
5 String s1 = new String("Hello, world");
6 String s2 = "$75.35";
7 String s3 = "cat";
Page 16 of 22
8 String s4 = "dog";
9
10 System.out.println(s1.length());
11 System.out.println(s1.substring(7, 12));
12 System.out.println(s1.toUpperCase());
13 System.out.println(s1.toLowerCase());
14 System.out.println(s1.charAt(7));
15 System.out.println(s2.indexOf("."));
16 System.out.println(s2.substring(s2.indexOf(".") + 1,
s2.length()));
17 System.out.println(s3.compareTo(s4));
18 System.out.println(s3.equals(s4));
19 }
20 }
Here is the output produced by the program:
12
world
HELLO, WORLD
hello, world
w
3
35
-1
False
We'll have many opportunities the meet these methods later in more
interesting programs. For the moment, let's just examined the basic
operation of each.
Page 17 of 22
String()
In line 5, the String() constructor is used to instantiate a String
object. A reference to the object is assigned to the object
variable s1. In fact, String objects are rarely instantiated in
this manner. It is much more common to use the shorthand notation
shown in lines 6-8.
length()
In line 10, the length() method determines the length of s1. The
syntax shown in line 10 illustrates an "instance method" operating
on an "instance variable". Dot notation connects the instance
variable (s1) to the instance method ( length() ). s1 is called an
instance variable because the object to which it refers is an
"instance of" an object-a String object. The term "s1.length()" is
an expression. It returns an integer value equal to the length of
the string. So, the term "s1.length()" can be used anywhere an
integer can be used, such as inside the parentheses of the
println() method. The length of s1 is 12, as shown in the 1st line
of output.
substring()
In line 11, a substring is extracted from s1. The substring begins
at index 7 in the string and ends at index 11. In counting-out
character positions within strings, the first character is at index
"0". This is illustrated in Figure 6 below:
Page 18 of 22
passed to the substring() method are 7 and 12, respectively. The
2nd line of output shows the result: world.
Page 19 of 22
in the program's output in the 3rd line ("HELLO, WORLD") and 4th
line ("hello, world").
charAt()
In line 14, the charAt() method is used to determine which
character is at index 7 in the string referenced by s1. As evident
in Figure 6 above, the answer is "w" and this is shown in the 5th
line of output.
indexOf()
In line 15, the indexOf() method is demonstrated. The method is
called on the instance variable s2, which references a String
object containing "$75.35" (see line 6). The decimal point (".")
is at index 3, as shown in the 6th line of output. Line 16
demonstrates the convoluted sorts of operations that can be
performed with methods of the String class. The statement retrieves
the decimal places from the String object referenced by instance
variable s2. Have a close look at the syntax as see if you agree
with the result shown in the 7th line of output.
compareTo()
In line 17 the compareTo() method is demonstrated. As noted in
Table 1 above, the method performs lexical comparison between two
strings and returns an integer equal to the lexical difference
between the two strings. This sounds complex, but it's really quite
simple. "Lexical order" is, for the most part, "dictionary order";
so "able" precedes "baker", which in turn precedes "charlie", and
so on. The lexical difference between two strings is simply the
numerical difference between the Unicode’s of the characters at
the first position that differs in the two strings. For, example
the expression "able".compareTo("baker") equals -1. The first
characters differ and the numerical difference between them is one
Page 20 of 22
(1). Since 'a' precedes 'b' the value returned is minus one (-1).
The expression "aardvark".compareTo("able") also equals -1, but
this is the lexical difference between the second two characters
(since the first two are the same). In the example program, the
comparison is between "cat" and "dog" (see line 17). The lexical
difference, -1, appears in the 8th line of output.
"lightbulb".compareTo("light")
equals 4 and
"light".compareTo("lightbulb")
equals -4.
equals()
The last string method demonstrated in Figure 5 above is the
equals() method. equals() is a similar to compareTo() except it
only tests if for equality or inequality. The return type is a
boolean: true if the two strings are identical, false otherwise.
Page 21 of 22
Since "cat" is not equal to "dog", the result is false, as seen in
the 9th line output.
Page 22 of 22