Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^50) | Java Syntax and Semantics, Classes, and Objects
is, Java treats the sequence of two characters \’as a single character representing the quote.
When we want to write the quote as a character in Java, we thus write
‘\''
Notice that we use the backward slash, or backslash (), as the escape character rather than
the regular, forward slash (/). As we will see in Chapter 3, Java uses the regular slash as a di-
vision sign, so it is important to recognize that the two slashes are different. A moment’s
thought reveals that this scheme introduces a new problem: How do we write the backslash
as a character? The answer is that Java provides a second escape sequence,\, that allows
us to write a backslash. Thus we write the charvalue of backslash in Java as follows:
‘\’
Be careful that you don’t confuse this sequence with the //sequence, which begins a com-
ment in Java (we look at comments a little later in this chapter).
Java provides operations that allow us to compare data values of type char. The Unicode
character set has a collating sequence, a predefined ordering of all the characters. In Unicode,
‘A‘compares as less than ‘B‘,‘B‘as less than ‘C‘, and so forth. Also,‘ 1 ‘compares as less
than ‘ 2 ‘,‘ 2 ‘as less than‘ 3 ‘, and so on.
The typecharis one of Java’s primitive types. TheStringclass, which allows us to work
with collections of characters, such as words and sentences, is one of theObjecttypes in Java.
We’ve discussed classes and objects in the abstract sense as part of the problem-solving
process. Now we must further explore what classes and objects are in Java before we move
on to strings.


Classes and Objects


In Chapter 1, we identified two phases of programming: the problem-solving phase and the
implementation phase. Often the same vocabulary is used in different ways in the two phases.
In the problem-solving phase, for example, an object is an entity or some thingthat
makes sense in the context of the problem at hand. A group of objects with similar proper-
ties and behaviors is described by an object class, or classfor short. Object-oriented problem
solving involves isolating the objects that make up the problem. Objects interact with one
another by sending messages.
In the implementation phase, a classis a Java construct that allows the programmer to
describe an object. A classcontains fields (data values) and methods (subprograms) that
define the behavior of the object. Think of a class in the general sense as a pattern for what
an object looks like and how it behaves, and a Java classas the construct that allows you to
simulate the object in code. If a class is a description of an object, how do we get an object
that fits the description? We use an operator called new, which takes the class name and re-

T


E


A


M


F


L


Y


Team-Fly®

Free download pdf