Class and Object
Download
Report
Transcript Class and Object
String class
Construct a string
String str = new String(“welcome”);
Char[] charr = {‘G’, ‘o’, ‘o’, ‘d’};
String mes = new String(charr);
A full list of String class methods and
constructors P259 Chapter 7.2
Some String methods
int length()
String subString( int beginindex)
String toLowerCase()
String concat( String )
char chatAt( ont index)
boolean equals( String anotherString)
continue
String concatenation
String s3 = s1.concat(s2);
S3 = s1 + s2;
S3 = message + “and “+ “HTML”;
Extracting substring
String message = “Welcome to
Java”.subString(1,11) + “HTML”;
continued
String comparisons
If( string1 == string2)
Will check if string1 and string 2 refer to same
object
To find out whether two string objects have
same content, use equals()
If( string1.equals(string2))
S1.compareTo(s2) return 0 if s1 is equals to s2,
less than 0 if s1 is lexicographically less than s2,
and greater than 0 if s1 is lexicographically
greater than s2
Can be used in sorting algorithm
Finding a character in a string
int indexOf( int ch)
“welcome to Java”.indexOf(‘w’) returns
0
“welcome to Java”.indexOf(“come”)
return 3
lastIndexOf return the index of the
character last time appear in string
Converting characters and
numeric values to strings
The valueOf method can be used to convert
an array of characters into a string.
There are several overloaded versions of
the valueOf method that can be used to
convert a character and numeric values to
strings with different parameter type
For example, to convert a double value 5.44
to a string,
String.valueOf(5.44)
Character class
Java provide a wrapper class for every data
type.
Character for char
You can create a Character object from a
char value
Character ch = new Character(‘a’);
charValue() method return the character
value wrapped in the Character object.
See page 268 Chapter 7.3 for the full list of
methods in Character class