Strings
Strings
Declaring a String:
String message = "Welcome to Java!"
String message = new String("Welcome to Java!);
String Comparisons
equals
String s1 = "Welcome";
String s2 = "welcome";
if (s1.equals(s2))
{ // s1 and s2 have the same contents
if (s1 == s2)
{
// s1 and s2 have the same reference
compareTo(Object object)
String s1 = "Welcome";
String s2 = "welcome";
if (s1.compare(s2) > 0)
{ // s1 is greater than s2 }
else if (s1.compare(s2 == 0)
{ // s1
else
// s1 is less than s2
Substrings
String is an immutable class; its values
String Concatenation
String s3 = s1.contact(s2);
String s3 = s1 + s2;
Use message.charAt(index)
String Conversions
Thecontentsofastringcannotbe
changedoncethestringiscreated.
Butyoucanconvertastringtoanew
stringusingthefollowingmethods:
toLowerCase
toUpperCase
trim
replace(oldChar,newChar)
Example 7.1
Finding Palindromes
Objective:
Run
StringBuffer Constructors
public StringBuffer()
No characters, initial capacity 16 characters.
StringTokenizer(String s, String
delim, boolean returnTokens)
StringTokenizer(String s, String
delim)
StringTokenizer(String s)
boolean hasMoreTokens()
String nextToken()
Example 7.4
Testing StringTokenizer
TestStringTokenizer
Run
Command-Line Parameters
class TestMain
{
public static void main(String[] args)
{ ... }
}
java
Processing
Command-Line Parameters
In the main method, get the arguments from
args[0], args[1], ..., args[n], which
corresponds to arg0, arg1, ..., argn in
the command line.
Example 7.5
Using Command-Line Parameters
java Calculator - 2 3
Run
java Calculator / 2 3