|
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)
String course;
course = new String("CS159");
course.toLowerCase();
String course;
course = new String("CS159");
course = course.toLowerCase();
+
String object is created
String course, number;
course = new String("CS");
number = new String("159");
// This line won't compile because it isn't a statement
course + number;
String course, number;
course = new String("CS");
number = new String("159");
course += number; // course = course + number;
+ operator
need not be a String if it can be converted into
one
int number;
String course, dept;
dept = new String("CS");
number = 159;
course = dept + number;
+ is also used as the "positive"
operator and the addition operator, it is easy to make
mistakesString s; s = "Value: "; s += 'a' + 'b';
s 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