(c) Copyright 2000, 2001, 2002, 2003, 2004 by Daniel Berleant
Announcements
See Web for updated HW2
Any general questions about the course?
...you may ask now, during break, or after class
(reminder: 3 weeks of Java then 13 weeks of UP)
Want to print out notes in small font to save ink?
Bring up URL in browser
Click "File," click "Edit with,"
Select entire document with mouse
Change font to 10 pt. (or whatever)
Bring to class to write on, etc.
New topic: Strings (and StringBuffers)
![]()
Converting Strings to Numbers
Strings are one of the most flexible forms of data
Strings can
be converted to floats
double f
=Double.parseDouble("4.5");
double g
=Double.parseDouble(myString);
Similarly,
strings can be converted to int
int numFromFile
=Integer.parseInt(str);
Classes
Integer
and Double are called
"type wrapper" classes
int, double are types, not classes (how can you tell?)
...therefore they have no methods
...but we wish they did!
...e.g. to convert Strings to int,double,etc.
...solution: "type wrapper" classes
...their purpose is to hold useful methods
...int is analogous to type wrapper class Integer
...double is analogous to type wrapper class Double
...Integer has methods like parseInt()
...parseInt()is static
...so you can call e.g.
Integer.parseInt("34");
...note you can't add two Integer objects!
(+ is not defined for objects of class Integer)
It works the
other way too. . .
Converting Objects to Strings
class Object contains a toString( ) method
Every other
class inherits from Object
. . . so
"every" object has a toString( )
method
Examples:
public class Whatever{
public static void
main(String args []){
Whatever w=new
Whatever();
System.out.println
(w.toString());
System.out.println
(System.out.toString());
}
}
This printed:
Whatever@73d6a5
java.io.PrintStream@111f71
Another
way: ""+3.7
More
About Strings
Strings can
also be new'ed
s=new String
("this string has spaces");
They can be
broken apart
String myString;
myString=new String
("zZZZZ *snore* ZZZZ");
myString.indexOf('Z');
myString.lastIndexOf('Z');
myString.indexOf('Z', 10);
myString.lastIndexOf('Z',10);
myString.indexOf("nor");
myString.lastIndexOf("ZZ");
myString.indexOf("ZZ", 10);
myString.lastIndexOf("ZZ",10);
![]()
Converting
Strings to numbers
int myNum;
String S="100";
myNum=Integer.parseInt(S);
What's going on?
There is a big difference between
100 and "100"
...and between
1 and '1' and "1" (and true)
For example, they have different bit patterns
To convert a string to a number:
use a predefined method
Every method must be in a class, in Java
the parseInt( ) method
could be in any class
...it could be in the class xcfre
...it could *not* be in int
...in fact, it's in the class Integer
myNum above is NOT an Integer,
it is an int
Integer is a class
containing methods useful for ints
You could define an object of class Integer...
but you could not add it!
(since it's not an int)
![]()
More About
Strings
You can declare something to be a String
Example: String
s;
You must allocate memory for it
Example:
s=new String("abcxyz");
NOTE: String
is capitalized!
s now refers to the string "abcxyz" (memory diagram
time?)
You can also initialize a new string to a copy of an existing
string
Example:
String s1=new String(s);
Something to note:
String( )
and
String("Help! I'm stuck in this monitor!");
are both ok -
The String class has more than one
constructor
String(...) is "overloaded"
![]()
String lengths
Here's how to print the length of string s1:
System.out.println(s1.length( ));
C equivalent:
printf("%d", length(str));
Let's compare
In Java, str is really a
string (not an array)
C has a collection of string functions somewhere
Java has a string class
(Remember, a class contains methods and data)
Strings in Java exemplify object-oriented programming
str.length() accesses the length method for strings
The dot provides access to the members of the String class
. . . such as length( )
. . . since str is a string
No arg since computer already knows we are dealing with
str
Why doesn't the C-like syntax work?
printf("%d", length(str));
to use a method ...
must tell the computer which class
![]()
More Ways to Initialize Strings
Suppose we have string variables str1,str2, etc.
str1=new String(
);
creates an empty string
str2=new
String(s);
creates a copy of string s
str3=new
String(chArray);
creates a string from an array of char
str4=new String(chArray,
startPos, numChars);
creates a string from the middle of an array of chars
Review:
String(...) methods are in the String class
Classes often have methods with the same name
(...not just constructor methods)
Here are some more String
things
![]()
str.charAt(3);
str.charAt(3);
3 is just an int
charAt() can be called with any int
str is the name of some string
What is C set to
if:
String str=new String("Hello");
Char C=str.charAt(3);
(count starting from 0)
![]()
str.equals("cde");
Checks if str equals "cde" (returns true or
false)
There are others:
str.equalsIgnoreCase("AbC")
str.compareTo("abc") (returns an int)
str.startsWith("abc") . . .
Some of these are overloaded
str.startsWith("de");
str.startsWith("de", 3);
. . . AND many more . . .
String and StringBuffer
--------------------------------------------
Here's
something a bit unexpected:
Strings canNOT be modified!
String s=new String("hElLo");
System.out.println(s.toLowerCase( ));
System.out.println(s);
s is not modified!
Sometimes we
want to modify a string
Method 1:
reassign the String "handle" (pointer):
String s;
s=myFile.read( );
doSomethingWith(s);
s=myFile.read( );
//re-assigned s
Method 2: use the StringBuffer class...
Example StringBuffer constructors:
StringBuffer( );
//makes an empty buffer
//with 16 spaces in it
StringBuffer(50);
//makes a buffer with 50 spaces
StringBuffer ("abc");
//makes a buffer with 3+16 spaces
Sample code:
public class ReverseIt {
public static void main
(String args[ ]){
System.out.println
(reverse(args[0]));
}
static String reverse(String myString){
int count;
int length=myString.length( );
StringBuffer reversed;
reversed=new StringBuffer(length);
for (count=length-1;
count>=0;
count--
){
reversed.append
(myString.charAt(count));
}
return reversed.toString( );
} //end method
} //end class
What
String and StringBuffer methods were used?
StringBuffer has various methods
(These are
for changing strings)
Suppose
reversed had the value "gnist"
reversed.append('A');
reversed.append(true);
reversed.append(3.7321);
reversed.append(77);
reversed.insert(1,"!!");
reversed.setCharAt(3, 'Z');
...and more! See partial table
(from http://java.sun.com/j2se/1.4.2/docs/api/index.html)
| Method Summary | |
StringBuffer |
append(boolean b)
Appends the string representation of the boolean argument to the
string buffer. |
StringBuffer |
append(char c)
Appends the string representation of the char argument to this
string buffer. |
StringBuffer |
append(char[] str)
Appends the string representation of the char array argument to
this string buffer. |
StringBuffer |
append(char[] str, int offset, int len)
Appends the string representation of a subarray of the char array
argument to this string buffer. |
StringBuffer |
append(double d)
Appends the string representation of the double argument to this
string buffer. |
StringBuffer |
append(float f)
Appends the string representation of the float argument to this
string buffer. |
StringBuffer |
append(int i)
Appends the string representation of the int argument to this
string buffer. |
StringBuffer |
append(long l)
Appends the string representation of the long argument to this
string buffer. |
StringBuffer |
append(Object obj)
Appends the string representation of the Object argument to this
string buffer. |
StringBuffer |
append(String str)
Appends the string to this string buffer. |
StringBuffer |
append(StringBuffer sb)
Appends the specified StringBuffer to this StringBuffer. |
Here is some sample code...
import java.lang.*;
public class Strings
{
String str;
public static void main(String args[])
{
String s1=new String( );
String s2=new String ("HELLO THERE!");
String s3=new String(s2);
s1=s2;
//s1 and s3 are different //strings!
s1=new String( ); //what does this do?
System.out.println( );
System.out.println(s1.length( ));
System.out.println(s2.length( ));
char chArray[ ]=new char [100];
for (int count=0; count<100; count++)
chArray[count]=(char)((int)'A'+count);
s3=new String(chArray);
System.out.println(s3);
String s4=new String(chArray, 10, 9);
System.out.println(s4.length( ));
System.out.println(s4);
//charAt( ) method...
System.out.println (s3.charAt(2));
System.out.println (s2.equals("HELLO THERE!"));
System.out.println (s2.equals("Hello there!"));
System.out.println(s2.equalsIgnoreCase
("Hello there!"));
//returns true or false (not -1,0,1) //returns -,0, or + int:
System.out.println
(s2.compareTo("Hello there!"));
}
}
class StringTokenizer
A string can
have spaces (and punctuation, etc.)
A token is a
piece of a string, like a word
...actually a
word-like unit you an define
To get the
tokens out,
use a StringTokenizer object
import java.util.*;
...
String myString=new
String("Please tokenize" +
"this string.");
StringTokenizer myTokenExtractor;
myTokenExtractor=
new StringTokenizer
(myString );
//myTokenExtractor=
//new StringTokenizer
//(myString, " \n\t\r,;.:?!")
////now punctuation also
////delimits
//myTokenExtractor=
//new StringTokenizer
//(myString," \n\t\r,;.:?!",
// true);
// //now delimiters are
// //also tokens
System.out.println
(myTokenExtractor.
countTokens( );
while
(myTokenExtractor.
hasMoreTokens( ))
System.out.println
(myTokenExtractor.
nextToken( ));
Let's look
over the code to understand
What a string tokenizer is and how to construct it
What methods it provides
Q: Is a string tokenizer a String object
or another kind?
Q: Is a string tokenizer associated with
a particular String?
Q: Is a space a default delimiter?
Q: Can any character be defined to be
a delimiter?
Q: Does a string tokenizer remember where
it was in the String?