Note - Briar Cliff University

guitarchanceSoftware and s/w Development

Aug 15, 2012 (5 years and 3 days ago)

343 views


1

Chapter 9 Strings and Text I/O

9.2 The String Class

A string is a sequence of characters. Strings are objects in Java. There are several ways to
create a string:

String message = "Hello";

String message = new String("Hello");

char[] charArray

= {'H', 'e', 'l', 'l', 'o'};

String message = new String (charArray);

Example code:


String message1 = "Hello";


String message2 = new String("HELLO");




// Convert a char array to a string:


char[] charArray = {'H', 'e', 'l', 'l
', 'o'};


String message3 = new String (charArray);




System.out.println (message1);


System.out.println (message2);


System.out.println (message3);

Strings are
immutable



they cannot be changed. If you have the following:

String pres = "Washington";

pres = "Adams";

The "Washington" String is thrown away and a new String with the value "Adams" is
created.

The String class has no methods for modifying a String object.

Since strings are objects, when we use the six relationa
l operators: ==, !=, >, <, >=, <=
all we are comparing is the addresses of the strings! To compare strings, use one of the
following methods:



equals(String otherString)



equalsIgnoreCase(String otherString)



compareTo(String otherString)



compareToIgnoreCase(
String otherString)

The two
equals

methods return
true

or
false.

The two
compare

methods return 0 if the strings are equal, a negative number if the
invoking string is less than
otherString
, and a positive number if the invoking string is
greater than
othe
rString
.

Sample code:

System.out.println ("Should be false: " + message1.equals(message2));

System.out.println ("Should be true: " + message1.equals(message3));


System
.out.println ("Should be true:
" +
me
ssage1.equalsIgnoreCase(message2));


2

String a="a",
b="b", A="A", B="B";

System.out.println ("Should be negative: " + a.compareTo(b));

System.out.println ("Should be positive: " + b.compareTo(a));

System.out.println ("Should be zero: " + a.compareTo(a));


System.out.println ("Should be negative: " + A.c
ompareTo(B));

System.out.println ("Should be positive: " + B.compareTo(A));


// A is code 65, a is code 97

System.out.println ("Should be negative: " + A.compareTo(a));

System.out.println ("Should be positive: " + a.compareTo(A));

System.out.println ("Shou
ld be zero: " + a.compareToIgnoreCase(A));

length()

The
length

method returns the number of characters in the string.

charAt(index)

The
charAt

method returns the character at the location in the string. String locations are
zero
-
based, so a 5
-
character

string has characters at locations 0 through 4.


System.out.println ("Should be 5: " + message1.length());


for (int i=0; i<message1.length(); i++)


System.out.println (message1.charAt(i));

substring(int beginIndex), substring(int

endIndex)

The substring method returns a substring. It has two versions:

// returns all characters to the end of the string

substring(int beginIndex)

// returns all characters from beginIndex up to endIndex


1
.

substring(int beginIndex, int endIndex)

Sample code


System.out.println ("Should be 'ello': " + message1.substring(1));


System.out.println ("Should be 'ell': " + message1.substring(1,4));

More common string methods



toLowerCase()

returns a lower
-
case version of the given string.



toUpperCase()

returns an upper
-
case version of the given string.



trim()

returns a copy of the string with leading and trailing spaces removed.



split(String delimiter)

returns an array of strings. This is very useful when
trying to separate the tokens in a
string. Note that the delimiter must be a regular
expression. The Java syntax for regular expressions requires that all characters be
inside of square brackets. We will not go into regular expressions, but if you want a
simple list of characters that can b
e used as delimiter characters, you must enclose
all of the characters within square brackets. For example to break a string wherever
a blank, a comma, or a tab occurs, use this:


[ ,
\
t]


3

Sample code


String sentence =


"Four score and seven
years ago, our fathers
\
tbrought forth";


String[] wordList = sentence.split("[ ,
\
t]");


for (int i=0; i<wordList.length; i++)


System.out.println (wordList[i]);

Converting between strings and arrays

To convert a string to a char array (so you can modify the individual characters), use the
toCharArray

method.

Sample code


char[] charList = message1.toCharArray();


for (int i=0; i<charList.length; i++)


System.out.println (charList[i])
;

9.2.10 Converting Characters and Numeric values to Strings

To convert numbers to strings:



toString()

To convert an array of characters to a string:



valueOf(char[] data)

returns a string made up of the given characters.

To convert a string to a number:



Double.parseDouble(String s)



Integer.parseInt(String s)

Sample code


double d = Double.parseDouble("12345.6789");


System.out.println (d);




int i = Integer.parseInt("12345");


System.out.println (i);

9.2.11 Formatting Strings

To
print formatted strings, use the static method:



String.format(formatString, str1, str2, …)

The format string is the same as used in the
printf

method.
A format string can contain
zero, one, or more

format specifiers
. The general form of a format specifier

is:


%[argument_index$][flags][width][.precision]conversion

where things in square brackets are optional, and

conversion

is a character indicating
the

conversion

to be applied to the corresponding variable value. The only required
characters in the format

specifier is the percent sign

%

and the

conversion

character.


Sample code


System
.
out
.
println
(
String
.
format
(
"Hi %s, you owe me $%5.2f."
,

"Jack"
,

25
.));


4

9.2.13 Problem: Converting Hexadecimals to Decimals

This is an interesting problem. Even though it is
in the book, derive it in class (as a group).
Note: Start at the left and convert the hex character to its decimal value. Every time you
move one character to the right, you multiply the current value by 16.

9.3 The Character Class

Java has a handful of da
ta types called primitives that are not objects. The primitives that
we will use are:
int, double, boolean, char
.

However, Java also provides a way to treat each of these data types as objects, too! These
classes are called
wrapper

classes because they "wr
ap" the primitive data inside of an
object. The wrapper class for the
char

primitive is the
Character

class.

Most of the methods of the
Character

class are static, which means that most of the time
you won't have to create a
Character

object. Some useful m
ethods:



Character.
isLetter(char ch)



Character.
isLetterOrDigit(char ch)



Character.
isLowerCase(char ch)



Character.
isUpperCase(char ch)



Character.
toUpperCase(char ch)



Character.
toLowerCase(char ch)

Note that all of the above methods are invoked by using the name of the
Character

class

not

by invoking an object.

Sample code


for (i=0; i<message1.length(); i++)


{


System.out.println (message1.charAt(i) + " is letter: " +



Character.isLetter(message1.charAt(i)));


System.out.println (message1.charAt(i) + " is letter or digit: " +


Character.isLetterOrDigit(message1.charAt(i)));


System.out.println (message1.charAt(i) + " is lowercase: " +



Character.isLowerCase(message1.charAt(i)));


System.out.println (message1.charAt(i) + " is uppercase: " +


Character.isUpperCase(message1.charAt(i)));


System.out.println (message1.charAt(i) + " to uppercase: " +



Character.toUpperCase(message1.charAt(i)));


System.out.println (message1.charAt(i) + " to lowercase: " +


Character.toLowerCase(message1.charAt(i)));


}

9.4 The S
tringBu
ilder class

Strings are
immutable



they cannot be changed. If you have the following:

String pres = "Washington";

pres = "Adams";

The "Washington" String is thrown away and a new String with the value "Adams" is
created.


5

The String class has no methods for modifying a String object.

Mo
difying a StringBuilder

If you want to modify a string (which you frequently do),

you should use the
StringBuilder

class. The
StringBuilder

class has most of the same methods as the String class has. It also
has the following methods for modifying a
String
Builder

object:



setCharAt(int index, char character)



append(String s)



i
nsert (int index, String s)



delete(int start, int end)



deleteCharAt(int index)



replace(int start, int end, String s)

Note: on
delete

and
replace
, the
end

variable is actually
one more
than the ending position
.
So, if you want to delete the 3 characters at positions 3, 4, and 5 in a string
s
, you would
have to do this:

s.delete(3, 6)

Also, all of the methods (except setCharAt) change the object, AND they return a reference
to the object.

Most of the time you don't need the reference, though.

Sample code


StringBuilder s = new StringBuilder("hello");


System.out.println("Original string: " + s);


s.setCharAt(0, 'H');


System.out.println ("Capitalize the 'h': " + s);


s.append( " how are you?");


System.out.println ("Add 'how are you?': " + s);


s.insert(6, "George, ");


System.out.println ("Insert 'George, ': " + s);


s.replace(6,12, "Thomas");


System.out.println ("Replace 'George' with

'Thomas': " + s);


s.deleteCharAt(12);


System.out.println ("Delete the comma: " + s);


s.delete(6, 13);


System.out.println ("Delete the word 'Thomas': " + s);


System.out.println (s);

Some other methods that do not change the St
ringBuilder



capacity(). The current capacity of the StringBuilder (max length).



length(). The current number of characters in the StringBuilder.



charAt(int). The character at the given location.

Sample code

System.out.println (s.capacity());

9.5 Command
Line Arguments

You can pass strings to a main method from the command line, like this:

java TestMain arg0, arg1, arg2


6

The values arg0, arg1, and arg2 are passed in as the
String[] args

parameters to the main
method. They can be accessed like this:

arg[0]

a
rg[1]

arg[2]

If you are using the NetBeans IDE and not the command line to run your program, you can
set the command line arguments like this:

1.

Click on File.

2.

Click on
Project Properties
.

3.

In the
Project Properties

window, click on
Run
.

4.

Enter the arguments i
n the
Arguments

text box. Separate them with spaces, not
commas.

5.

Click on
OK
.

Check out the Java calculator program (Listing 9.5).

9.6 The File Class

9.7 File Input and Output

9.7.1 Creating an output file

The following creates an output file (in the root level of the project) called
scores.txt
. Note
that it uses fully
-
qualified names for
File

and
PrintWriter
. If this was not done, we would
have to use an
import

statement:

import java.io.*;

Or, we could do
this:

import java.io.File;

import java.io.PrintWriter;

Here is the program:

public class WriteData {


public static void main(String[] args) throws Exception {


java.io.File file = new java.io.File("scores.txt");


if (file.exists()) {


System.o
ut.println("File already exists");


System.exit(0);


}



// Create a file


java.io.PrintWriter output = new java.io.PrintWriter(file);



// Write formatted output to the file


output.print("John T Smith ");


output.println(90);


o
utput.print("Eric K Jones ");


output.println(85);



// Close the file


7


output.close();


}

}

9.7.2 Reading Data Using Scanner

To read from the keyboard, we create a
Scanner

object for
System.in

(the keyboard).

To read from a file, we create a
Scanner

object for a
File

object.

To create a
File

object:

import java.io.File;

...

File inFile = new File("data.txt");

Then, to create a Scanner for the file:

Scanner input = new Scanner (inFile);

Once the scanner has been created, you can read from it us
ing the following methods:



nextInt()



nextDouble()



nextLine()

When done, close the file:



inFile.close();