Strings - James Madison University

Download Report

Transcript Strings - James Madison University

Strings and Text File I/O
(and Exception Handling)
Corresponds
with Chapters 8 and 17
The String Class


A class in the Java Class Library
Part of the java.lang package

NOTE: java.lang is the core package of the basic
Java classes, including:






String
System
Object
Math
lots of others
Strings are immutable (values cannot be
changed once created). Another string-like
object that can be changed is StringBuffer.
Initializing a String

The formal way:




String s = new String(“the string value”);
String() is a special method called a constructor, which is
called to create and initialize an object (more about
constructors when we do object-oriented programming)
This creates a new instance of the String class in the heap
A shortcut way…forget using new:


String s = “the string value”;
This does not instantiate a new string. Instead it points to a constant
string in the constants pool of memory.
NOTE: like with any other object instantiation, the variable s is NOT a
String object. It is a REFERENCE to a String object. The String object
itself is on the heap.
s points at it.
Comparing Strings


Suppose you have two string references, s1 and s2.
If you do the following:




To test for equality of value (not equality of reference),
you use this syntax:





if (s1 == s2)
This tests to see if the variables s1 and s2 are pointing to the
same string object.
This is NOT testing to see if the values in two different strings
are identical.
if (s1.equals(s2))
This will test to see if two different strings have the same value.
equals is an instance method of the String class
compareTo is another useful comparison method of the String
class.
See also equalsIgnoreCase and compareToIgnoreCase
Useful String Instance Methods






toUpperCase() – converts a string to upper case. Returns
a String.
toLowerCase() – converts a string to lower case. Returns
a String.
substring(int start, int end) – returns the String starting
a start, ending at end-1. (end is optional).
charAt(int position) – returns the char value at the
designated position.
length() – returns the number of characters in the string
There are lots more useful methods. Check out the
String class in the Java documentation and in chapter 7
of Liang.
An Example Using String Methods
Constants pool is a
memory location
that contains all
constants and
literals of the
application
s1 and s2 are equal. They
point to the same object,
which is a literal string
located in the constants
pool.
String Object
value a string
args
main’s
frame
String Object
s1
value another string
s2
Frame Stack
Heap
Constants
Pool
s1 and s2 are NOT equal.
They point to different
objects. But, the contents
of the strings pointed at
by s1 and s2 are equal.
String Object
value a string
args
main’s
frame
s1
s2
Frame Stack
String Object
value a string
String Object
String Object
value a string
value another string
Heap
Constants
Pool
S2 is changed to point to the other literal
string in the constants pool. The value of
the old string pointed at by s2 does not
change. Eventually, this string will be
discarded by the garbage collector.
String Object
value a string
args
main’s
frame
s1
s2
Frame Stack
String Object
value a string
String Object
String Object
value a string
value another string
Heap
Constants
Pool
S1 is changed to point to the same string
that s2 points at. The value of the old
string pointed at by s1 does not change.
Eventually, this string will be discarded
by the garbage collector.
String Object
value a string
args
main’s
frame
Frame Stack
value a string
String Object
String Object
value a string
value another string
s1
s2
String Object
Heap
Constants
Pool
Lesson Learned


Don’t expect s1==s2 to work the way you
want it to. This will be true ONLY if the
references are pointing to the same object
To test for equality of VALUE, use
s1.equals(s2), or another similar method.
Using other Methods in the
Example
Instance method toUpperCase called with respect to the string
object pointed at by s1. toUpperCase creates a new String object
and returns a reference to that new object, which contains the same
value as the string of s1, but entirely in upper case.
Instance method substring called with respect to the string object
pointed at by s1. substring creates a new String object and returns
a reference to that new object, which contains the characters from
position 3 to position 5 of the string pointed at by s1.
Using other Methods in the
Example
substring returns a
reference to a new
String object
toUpperCase called with
respect to the String object
returned from substring
NOTE: cascading method calls
Using StringTokenizer





Useful for breaking a string into individual
tokens.
A token is a single unit of the string (a
substring).
Tokens are separated by delimiters
Default delimiters are space, tab (\t), new line
(\n), and carriage return (\r)
You can specify your own delimiters if you want
StringTokenizer Class


Contained in the java.util package (need to import this
package)
Note: a
Constructors:
constructor is a




StringTokenizer(String str)
StringTokenizer(String str, String delim)
StringTokenizer(String str, String delim, boolean
returnDelimiters)
Important methods



method that is
invoked when an
object is
instantiated
(created)
countTokens() – returns the number of tokens in the string
hasMoreTokens() – returns true or false
nextToken() – returns the next token in the string
Example
from my own
notes
Import the package
Instantiate the
tokenizer object
Find out how many
tokens there are
Get each token
Instantiate the
tokenizer object
with special
delimiters
Instantiate the
tokenizer object with
special delimiters,
here the delimters
are tokens
output
output
output
Writing and Reading Text Files

Writing





Create a File instance
Create a PrintWriter to enable writing
Use the PrintWriter class’s print() or println() method to write to
the file
Use the PrintWriter class’s flush() method to force output from
memory buffer to the file
Reading:



Create a File instance
Create a Scanner instance to enable reading
Use Scanner’s various methods to read


hasNext() determines if there is anything more to read
Next(), nextDouble(), nextInt(), etc.
To use the file i/o examples, put the text files in folder c:\temp
The File Class


Used to internally represent an external
file
Creating an instance of the File will open
the associated file:


File myfile = new File(“filename”);
Files can then be used by:


Scanner – for input
PrintWriter – for output
The PrintWriter Class


Class that supports writing to an output
stream
Note: System.out is an output stream,
files can also be considered to be streams,
and PrintWriter is a class for writing to
output streams
What is a STREAM?


A data structure that represents the flow
of data between RAM and an external
device.
Example:



Streams for input and output devices (e.g.
keyboard, screen)
Streams for data files (on disk)
Streams for sockets (network connections)
Write example from textbook
Read example from textbook
hasNext() checks for EOF
Exceptions



In previous examples, the main method
throws exceptions.
This means the caller of the method is
responsible for handling the
exception…not very elegant
Instead, it is better if the exceptions
generated are caught…following example
shows this.
Read example from my samples
Input file
Output file
Instantiate
File and
Scanner
objects for
input
Read/Write example from my samples
Instantiate
File and
PrintWriter
objects for
output
Read/Write example from my samples
Here I use an
outer loop to
check for EOF,
and to read
the label and
initialize the
tot for
summing
Read/Write example from my samples
I use the inner
loop to to read all
the numbers from
the line and sum
them together.
Note that
hasNextDouble()
checks to see if
the next token is
a number.
Read/Write example from my samples
Note that the
same methods
print() and
println() can be
used for
System.out (the
standard output
display stream)
and for the
PrintWriter for
file output.
Read/Write example from my samples
Make sure to
close the
output file
after done
writing…this
forces any
data
remaining in
the memory
buffer to be
written to the
file
Exception Handling



Stream input requires use of Exception
handling
standard try/catch format OR
throws IOException in methods
try{
Exception Handling Using
try and catch
……..
If code within the try block causes
an error, the program will
automatically branch to the catch
block
}
catch (ExceptionType e){
……..
}
Read/Write example from my samples
Any code that could
cause an exception
should be placed in the
try portion. If an
exception occurs, the
program will
immediately branch to
the catch section
The Exception’s
toString() method gives
the specific error
message.
Reading Full Lines and Using
StringTokenizer

An alternative to reading one token at a
time from the file is to read an entire line,
then use StringTokenizer to break it up
into tokens
Using StringTokenizer with Files


StrngTokenizer can be used to divide the
line of text into separate data items
You can use Wrapper classes to convert
strings into numeric data for arithmetic
processing


Integer.parseInt(String) – converts a string
into an int
Double.parseDouble(String) – converts a
string into a double
To use StringTokenizer, you
must import the java.util
package, and for File you
need java.io.
To create a string tokenizer,
call the StringTokenizer
constructor, passing the
string to tokenize as an
argument.
The hasMoreTokens
method returns true or
false, depending on if
there are more tokens in
the string.
The nextToken
method returns a
string, which is the
next token in the
source string.
Here, I am checking
to see if the
character of the
token is a number (a
digit).
The parseDouble
method converts the
string into a number.
Program’s output