Using Strings
An Introduction with Examples in Java |
Prof. David Bernstein
|
Computer Science Department |
bernstdh@jmu.edu |
String
Objects:
String
objects are immutable (i.e.,
they can't be changed)toLowerCase()
) but the result, which is another
String
, is always assigned to a variable
or passed as an actual parametertoLowerCase()
toUpperCase()
String
object is created (the owning object
is not changed)+
operator
need not be a String
if it can be converted into
one+
is also used as the "positive"
operator and the addition operator, it is easy to make
mistakess
will be "Value: 195"
because
'a' + 'b'
is evaluated first and evalutes to the sum of the ASCII values
String
literalsboolean
char
String
new
Operator?new
operator creates (i.e., allocates memory
for an initializes) an objectString
variables without using new
String
object for each String
literalString s = "CS";
assigns the reference to the
literal to the variable s
String t = new String("CS");
creates a
String
object that contains the characters
'C'
and 'S'
and assigns the reference
to that object to the variable t
new
Operator? (cont.)new
operator you should
use it (even though it's a little inconvenient) because it
will keep you from making some subtle mistakesString
literals because
it is convenientString
Methodslength()
charAt(int)
String
Objects:
compareTo(java.lang.String)
equals(java.lang.String)
==
operator compares references not
the characters.)String
Methods (cont.)indexOf(java.lang.String)
indexOf(java.lang.String, int)
endsWith(java.lang.String)
startsWith(java.lang.String, int)
substring(int)
substring(int, int)
[]
operatorlen()
functionin
operator