Java Reference
In-Depth Information
2.6 Strings
As in C/C
,anarrayof Java
char
primitive type values can represent a string
of characters. (We discuss arrays in Chapter 3.) However, you will find it much
more convenient and common to use the
String
class that comes with the core
language. Strings were deliberately made very easy to use in Java, and they behave
almost like a primitive type. Though we haven't discussed classes yet, we present
some basics about Java strings here since they are essential to begin programming
anything of interest.
Yo u can create a string variable by enclosing the string literal in quotations:
++
String str1
="
A string
"
;
String str2
="
and another string
"
;
(This is the only class where the
“
new
„
operator isn't required to create an object
of that class.) You can append one string to another with a simple
“
+
„
operation.
(This is also the only case in Java of overloading an operator, i.e. redefining its
operation according to context.) For example,
String str3 = str1 + str2;
results in
str3
holding:
"
A string and another string
"
;
Avery useful capability of the
“
+
„
operator allows for default conversion of
primitive types to strings. Whenever you “add” a primitive type value, such as an
int
value, to a string, the primitive value converts to a
String
type and appends
to the string. For example, this code:
String str1 ="x =";
int i = 5;
String str2 = str1 + i;
results in
str2
holding
“
x
=
5
„
. This also works with
boolean
type values,
which result in
“
true
„
and
“
false
„
strings.
We discuss the
String
class and other string handling classes in more detail
in Chapters 3 and 10. Note that whenever we use the term string we refer to a
String
class object unless otherwise indicated.
2.7 Expressions
An expression performs an operation and returns a value. Here are some
examples:
i
=
2
- assignment puts 2 into the
i
variable and returns the value 2.
++k
- the
k
operand is incremented by 1 and the new value returned
x
<
y
-logical “less than” comparison, returns a Boolean true or false value.
Search WWH ::
Custom Search