Strings and Text I/O

advertisement
Computer Science Notes
Chapter 8
Page 1 of 16
Chapter 8: Strings and Text I/O
These notes are meant to accompany Introduction to Java Programming: Fundamentals First, sixth edition by Y.
Daniel Lang.
Programming Skills in a Nutshell:
At the end of this chapter you should have the following programming skills:
1. To open a file for either reading or writing using the Scanner and PrintWriter classes, respectively.
2. To read or write data to file using the println() and next() methods of the Scanner and PrintWriter
classes, respectively.
3. To close a file once you are done with it.
import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;
/**
* An EncryptionToolLastName contains methods for encrypting and decrypting
* text files using a simple rotation (Caesar cipher) technique.
* @author Firstname LastName
*
*/
public class EncryptionToolLastName
{
public static final char FIRST_CHAR = ' ';
public static final int FIRST_CHAR_VAL = (int) FIRST_CHAR;
public static final char LAST_CHAR = '~';
public static final int LAST_CHAR_VAL = (int) LAST_CHAR;
public static final int CHAR_SPAN = LAST_CHAR - FIRST_CHAR;
/**
* Encrypts a given File by rotating characters by a given key value.
* The encrypted file will have the source file's name with an extension of .rot
* @param key the key value
* @param sourceFile the File that will be encrypted
*/
public static void rotationEncrpyt(int key, File sourceFile) throws Exception
{
//Create a Scanner object to read in from the sourceFile.
Scanner diskInput = new Scanner(sourceFile);
//Create a target File for output.
File targetFile = new File (sourceFile.getName() + ".rot");
//Create a PrintWriter object to do the writing to targetFile.
PrintWriter diskOutput = new PrintWriter(targetFile);
//Process every line in the input file.
while (diskInput.hasNextLine())
{
//Read in the next line of text.
Computer Science Notes
Chapter 8
Page 2 of 16
String inputLine = diskInput.nextLine();
//Create a String to store the encrypted line of text.
String outputLine = "";
//Loop through every character of the inputLine and encrypt it using rotation.
for (int i = 0; i < inputLine.length(); i++)
{
int nextChar = (int) inputLine.charAt(i);
nextChar = nextChar + key;
if (nextChar > LAST_CHAR_VAL)
nextChar = nextChar - LAST_CHAR_VAL + FIRST_CHAR_VAL - 1;
outputLine = outputLine + (char) nextChar;
}
//Write the encrypted line of text to the output file.
diskOutput.println(outputLine);
}
//Close both input and output files.
diskInput.close();
diskOutput.close();
}//end of rotationEncrpyt()
/**
* Decrypts a given File by "un-"rotating characters by a given key value.
* It is expected that the encrypted file has an extension of .rot;
* the decrypted file's name will be the encrypted file's name less the extension .rot
* @param key the key value that was used to encrypt the file
* @param sourceFile the File that will be decrypted
*/
public static void rotationDecrypt(int key, File sourceFile) throws Exception
{
//Create a Scanner object to read in from the sourceFile.
Scanner diskInput = new Scanner(sourceFile);
//Create a target File for output.
File targetFile = new File (sourceFile.getName().substring(0, sourceFile.getName().length()-4));
//Create a PrintWriter object to do the writing to targetFile.
PrintWriter diskOutput = new PrintWriter(targetFile);
//Process every line in the input file.
while (diskInput.hasNextLine())
{
//Read in the next line of text.
String inputLine = diskInput .nextLine();
//Create a String to store the decrypted line of text.
String outputLine = "";
Computer Science Notes
Chapter 8
Page 3 of 16
//Loop through every character of the inputLine and decrypt it using rotation.
for (int i = 0; i < diskInput.length(); i++)
{
int nextChar = (int) inputLine.charAt(i);
nextChar = nextChar - key;
if (nextChar < FIRST_CHAR_VAL)
nextChar = LAST_CHAR_VAL - (FIRST_CHAR_VAL - nextChar);
outputLine = outputLine + (char) nextChar;
}
//Write the decrypted line of text to the output file.
diskOutput.println(outputLine);
}
//Close both input and output files.
diskInput .close();
diskOutput .close();
}//end of rotationDecrpyt()
/**
* "Deciphers" a given File that was encrypted using an unknown rotation key
* by reading up to the first five lines of the encrypted file, then applying
* all possible rotation keys to that file. The results are returned as a
* two-dimensional String array for the user to peruse and decide upon the proper
* rotation key.
* It is expected that the encrypted file has an extension of .rot.
* @param sourceFile the File that will be deciphered
*/
public static String[][] rotationDecipher(File sourceFile) throws Exception
{
String[][] possibleSolution = new String[5][CHAR_SPAN + 1];
//Create a Scanner object to read in from the sourceFile.
Scanner diskInput = new Scanner(sourceFile);
//Process up to the first five lines in the input file.
int numLinesRead = 0;
while (diskInput .hasNextLine() && numLinesRead<5)
{
//Read in the next line of text.
String inputLine = inputSource.nextLine();
//Loop through every character of the inputLine
for (int i = 0; i < inputLine.length(); i++)
{
//Loop through every possible key.
for (int key = 0; key < CHAR_SPAN + 1; key++)
{
Computer Science Notes
Chapter 8
Page 4 of 16
if (key == 0) possibleSolution[numLinesRead][key]="";
int nextChar = (int) inputLine.charAt(i);
nextChar = nextChar - key;
if (nextChar < FIRST_CHAR_VAL)
nextChar = LAST_CHAR_VAL - (FIRST_CHAR_VAL nextChar) + 1;
possibleSolution[numLinesRead][key] += (char) nextChar;
}
}
numLinesRead++;
}
//Close the input file.
diskInput.close();
return possibleSolution;
}//end of rotationDecipher()
}
import java.io.File;
import java.util.Scanner;
/**
* /** The LB08LastName class implements an application that uses the
* EncryptionToolLastName class to encrypt and decrypt text files.
* @author Firstname LastName
*
*/
public class LB08LastName
{
/** Prompts the user for encryption or decryption, the key, and the file.
* @param argv is not used.
*/
public static void main(String[] argv) throws Exception
{
//Tell the user what the program does
System.out.println("This program will encrypt or decrypt text files using a rotation cipher.");
Scanner input = new Scanner(System.in);
int continueConversions = 1;
String filename = "";
int key = 13;
do
{
System.out.println("Enter 1 if you want to encrypt an existing file.");
Computer Science Notes
Chapter 8
Page 5 of 16
System.out.println("Enter 2 if you want to decrypt an existing file.");
System.out.println("Enter 3 if you want to decipher an existing file for which you don't know the
key.");
int menuChoice = input.nextInt();
System.out.println("**************************************************");
switch (menuChoice)
{
case 1: //encrypt an existing file
System.out.println("Enter the file name.");
filename = input.next();
System.out.println("Enter the rotation key.");
key = input.nextInt();
File encryptFile = new File (filename);
if (encryptFile.exists())
{
EncryptionToolLastName.rotationEncrpyt(key, encryptFile);
System.out.println(filename + " successfully encrypted.");
}
else
System.out.println(filename + " does not exist.");
break;
case 2: //decrypt an existing file
System.out.println("Enter the file name.");
filename = input.next();
System.out.println("Enter the rotation key.");
key = input.nextInt();
File decryptFile = new File (filename);
if (decryptFile.exists())
{
EncryptionToolLastName.rotationDecrypt(key, decryptFile);
System.out.println(filename + " successfully decrypted.");
}
else
System.out.println(filename + " does not exist.");
break;
case 3: //decipher an existing file of unknown key
System.out.println("Enter the file name.");
filename = input.next();
File decipherFile = new File (filename);
if (decipherFile.exists())
{
String[][] possibleSolution =
EncryptionToolLastName.rotationDecipher(decipherFile);
for (key = 0; key < EncryptionToolLastName.CHAR_SPAN+1; key++)
{
Computer Science Notes
Chapter 8
Page 6 of 16
System.out.println("\nHere is the decryption for a key = " + key);
for (int lineNumber = 0; lineNumber<5; lineNumber++)
{
if (possibleSolution[lineNumber][key] != null)
System.out.println(possibleSolution[lineNumber][key]);
}
}
System.out.println();
}
else
System.out.println(filename + " does not exist.");
break;
default:
System.out.println("That was not a valid menu choice.");
}
System.out.println("\n**************************************************");
System.out.println("Enter 1 to run another file conversion or 0 to quit.");
continueConversions = input.nextInt();
} while(continueConversions == 1);
System.out.println("Encryption program terminated.");
}//end method main()
}//end class LB08LastName
Book’s Statement of Skills:
1. To use the String class to process fixed strings.
2. To use the Character class to process a single character.
3. To use the StringBuilder and StringBuffer classes to process flexible strings.
4. To know the difference between the String, StringBuilder, and StringBuffer classes.
5. To learn how to pass strings to the main method from the command line.
6. (Optional) To use the regular expressions to represent patterns for matching, replacing, or splitting
strings.
7. To discover file properties, delete, and rename files using the File class.
8. To write data to a file using the PrintWriter class.
9. To read data from a file using the Scanner class.
10. (Optional GUI) To add components to a frame.
Section 8.1: Introduction
A string is a sequence of characters. In Java, a string is an object. The String, StringBuilder, and StringBuffer
classes are used for storing and processing strings. The String class is immutable; the StringBuilder and
StringBuffer classes are not. This chapter also illustrates how to process command-line arguments to the main
method (which is an application of processing a String array), and how to perform simple text output and input
using the Scanner and PrintWriter classes (respectively)
Computer Science Notes
Chapter 8
Page 7 of 16
Section 8.2: The String Class
 The java.lang.String class models a sequence of characters as a string.
 The String class has 13 constructors and 53 methods…
 Some common String operations are:

Isolating individual characters

Comparing Strings

Searching for and manipulating substrings

Converting characters to upper case or lower case
java.lang.String
+CASE_INSENSITIVE_ORDER: Comparator
+String()
+String(bytes: byte[])
+String(bytes: byte[], charset: Charset )
+String(bytes: byte[], offset: int, length: int)
+String(bytes: byte[], offset: int, length: int,
charset: Charset)
+String(bytes: byte[], offset: int, length: int,
charsetName: String)
+String(bytes: byte[], charsetName: String)
+String(value: char[])
+String(value: char[], offset: int, count: int)
+String(codePoints: int[], offset: int, count:
int)
+String(original: String)
+String(buffer: StringBuffer)
+String(builder: StringBuilder)
+charAt(index: int): char
+charAt(int index): char
+codePointAt(int index): int
codePointBefore(int index): int
+codePointCount(int beginIndex, int
endIndex): int
The String class represents character strings. All string literals
in Java programs, such as "abc", are implemented as
instances of this class. Strings are constant; their values
cannot be changed after they are created. String buffers
support mutable strings.
A Comparator that orders String objects as by
compareToIgnoreCase.
Constructs a default EncryptionLastName.
Constructs a new String by decoding the specified array of
bytes using the platform's default charset.
Constructs a new String by decoding the specified array of
bytes using the specified charset.
Constructs a new String by decoding the specified subarray of
bytes using the platform's default charset.
Constructs a new String by decoding the specified subarray of
bytes using the specified charset.
Constructs a new String by decoding the specified subarray of
bytes using the specified charset.
Constructs a new String by decoding the specified array of
bytes using the specified charset.
Allocates a new String so that it represents the sequence of
characters currently contained in the character array argument.
Allocates a new String that contains characters from a
subarray of the character array argument.
Allocates a new String that contains characters from a
subarray of the Unicode code point array argument.
Initializes a newly created String object so that it represents the
same sequence of characters as the argument; in other words,
the newly created string is a copy of the argument string.
Allocates a new string that contains the sequence of
characters currently contained in the string buffer argument.
Allocates a new string that contains the sequence of
characters currently contained in the string builder argument.
Returns the char value at the specified index.
Returns the char value at the specified index.
Returns the character (Unicode code point) at the specified
index.
Returns the character (Unicode code point) before the
specified index.
Returns the number of Unicode code points in the specified
text range of this String.
Computer Science Notes
Chapter 8
+compareTo(String anotherString): int
+compareToIgnoreCase(String str): int
+concat(String str): String
+contains(CharSequence s): boolean
+contentEquals(CharSequence cs): boolean
+contentEquals(StringBuffer sb): boolean
+copyValueOf(char[] data): String
+copyValueOf(char[] data, int offset, int
count): String
+endsWith(String suffix): boolean
+equals(Object anObject): boolean
+equalsIgnoreCase(String anotherString):
boolean
format(Locale l, String format, Object... args):
String
+format(String format, Object... args): String
+getBytes():byte[]
+getBytes(Charset charset): byte[]
+getBytes(String charsetName): byte[]
+getChars(int srcBegin, int srcEnd, char[]
dst, int dstBegin): void
+hashCode(): int
+indexOf(int ch): int
+indexOf(int ch, int fromIndex): int
+indexOf(String str): int
+indexOf(String str, int fromIndex): int
+intern():String
+isEmpty(): boolean
+lastIndexOf(int ch): int
Page 8 of 16
Compares two strings lexicographically.
Compares two strings lexicographically, ignoring case
differences.
Concatenates the specified string to the end of this string.
Returns true if and only if this string contains the specified
sequence of char values.
Compares this string to the specified CharSequence.
Compares this string to the specified StringBuffer
Returns a String that represents the character sequence in the
array specified.
Returns a String that represents the character sequence in the
array specified.
Tests if this string ends with the specified suffix.
Compares this string to the specified object.
Compares this String to another String, ignoring case
considerations.
Returns a formatted string using the specified locale, format
string, and arguments.
Returns a formatted string using the specified format string and
arguments.
Encodes this String into a sequence of bytes using the
platform's default charset, storing the result into a new byte
array.
Encodes this String into a sequence of bytes using the given
charset, storing the result into a new byte array.
Encodes this String into a sequence of bytes using the named
charset, storing the result into a new byte array.
Copies characters from this string into the destination
character array.
Returns a hash code for this string.
Returns the index within this string of the first occurrence of the
specified character.
Returns the index within this string of the first occurrence of the
specified character, starting the search at the specified index.
Returns the index within this string of the first occurrence of the
specified substring.
Returns the index within this string of the first occurrence of the
specified substring, starting at the specified index.
Returns a canonical representation for the string object.
Returns true if, and only if, length() is 0.
Returns the index within this string of the last occurrence of the
specified character.
+lastIndexOf(String str): int
Returns the index within this string of the last occurrence of the
specified character, searching backward starting at the
specified index.
Returns the index within this string of the rightmost occurrence
of the specified substring.
+lastIndexOf(String str, int fromIndex): int
Returns the index within this string of the last occurrence of the
specified substring, searching backward starting at the
specified index.
+lastIndexOf(int ch, int fromIndex): int
Computer Science Notes
Chapter 8
+length():int
+matches(String regex): boolean
+offsetByCodePoints(int index, int
codePointOffset): int
+regionMatches(boolean ignoreCase, int
toffset, String other, int ooffset, int len):
boolean
+regionMatches(int offset, String other, int
offset, int len): boolean
+replace(char oldChar, char newChar):
String
+replace(CharSequence target,
CharSequence replacement): String
+replaceAll(String regex, String
replacement): String
+replaceFirst(String regex, String
replacement): String
+split(String regex): String[]
+split(String regex, int limit): String[]
+startsWith(String prefix): boolean
+startsWith(String prefix, int toffset): boolean
+subSequence(int beginIndex, int endIndex):
CharSequence
+substring(int beginIndex): String
+substring(int beginIndex, int endIndex):
String
+toCharArray():char[]
+toLowerCase():String
+toLowerCase(Locale locale): String
+toString():String
+toUpperCase():String
+toUpperCase(Locale locale): String
+trim():String
+valueOf(boolean b): String
+valueOf(char c): String
+valueOf(char[] data): String
+valueOf(char[] data, int offset, int count):
String
+valueOf(double d): String
+valueOf(float f): String
+valueOf(int i): String
Page 9 of 16
Returns the length of this string.
Tells whether or not this string matches the given regular
expression.
Returns the index within this String that is offset from the given
index by codePointOffset code points.
Tests if two string regions are equal.
Tests if two string regions are equal.
Returns a new string resulting from replacing all occurrences of
oldChar in this string with newChar.
Replaces each substring of this string that matches the literal
target sequence with the specified literal replacement
sequence.
Replaces each substring of this string that matches the given
regular expression with the given replacement.
Replaces the first substring of this string that matches the
given regular expression with the given replacement.
Splits this string around matches of the given regular
expression.
Splits this string around matches of the given regular
expression.
Tests if this string starts with the specified prefix.
Tests if the substring of this string beginning at the specified
index starts with the specified prefix.
Returns a new character sequence that is a subsequence of
this sequence.
Returns a new string that is a substring of this string.
Returns a new string that is a substring of this string.
Converts this string to a new character array.
Converts all of the characters in this String to lower case using
the rules of the default locale.
Converts all of the characters in this String to lower case using
the rules of the given Locale.
This object (which is already a string!) is itself returned.
Converts all of the characters in this String to upper case using
the rules of the default locale.
Converts all of the characters in this String to upper case using
the rules of the given Locale.
Returns a copy of the string, with leading and trailing
whitespace omitted.
Returns the string representation of the boolean argument.
Returns the string representation of the char argument.
Returns the string representation of the char array argument.
Returns the string representation of a specific subarray of the
char array argument.
Returns the string representation of the double argument.
Returns the string representation of the float argument.
Returns the string representation of the int argument.
Computer Science Notes
+valueOf(long l): String
+valueOf(Object obj): String
Chapter 8
Page 10 of 16
Returns the string representation of the long argument.
Returns the string representation of the Object argument.
Section 8.2.1: Constructing a String

You can construct a new String object from a string literal:
o Syntax: String newString = new String(stringLiteral);
o Example: String newString = new String(“My name is Kevin.”);

Since string literals are treated as String objects, you can also create a String as:
o Example: String newString = “My name is Kevin.”;

You can construct a new String object from an array of characters:
o Example:
char[] charArray = {H, e, l, l, o, ,,  , D, o, o, f, u, s, };
String newString = new String(charArray);
Section 8.2.2: Immutable Strings and Interned Strings

A String object is immutable, meaning its contents can not be changed. For example, the following
code does not change the value of any String object, but rather changes which String object the String variable
s refers to:
String s = “Hello”;
s = “Goodbye.”;

An interned string is a unique instance of a string literal with the same character sequence.

The intern() method of the String class returns an interned string.
Section 8.2.3: String Comparisons

Do not use the = = operator to determine if two strings have the same sequence of characters.

Instead, use the equals() method of the String class to determine if two strings have the same sequence
of characters.

The compareTo() method of the String class is used to “lexigraphically” compare (i.e., by comparing
ASCII values) whether one string comes before another one.

The equalsIgnoreCase() method of the String class determines if two strings have the same sequence
of characters, regardless of capitalization.

The compareToIgnoreCase() method of the String class determines whether one string comes before
another one, regardless of capitalization.

The regionMatches() method of the String class determines if two strings have the same sequence of
characters in a given region.

The startsWith() method of the String class determines if a strings starts with a given string.

The endsWith() method of the String class determines if a strings ends with a given string.
//import java.lang.String;
//Do not need above import because
//all classes from the java.lang package are imported autoatically.
/**The StringComparisons class implements an application that
* performs various comparisons between strings.
* @author Kevin Mirus
*/
public class StringComparisons
{
/**Shows how various strings compare under methods from teh String class.
* @param argv is not used.
Computer Science Notes
Chapter 8
Page 11 of 16
*/
public static void main(String[] argv)
{
//Declare first pair of strings to compare.
String s1 = "Hello.";
String s2 = "hello.";
//Declare second pair of strings to compare.
String s3 = "abc";
String s4 = "abg";
//Declare third pair of strings to compare.
String s5 = "Kevin";
String s6 = "Kevin";
//Declare fourth pair of strings to compare.
String s7 = "Goodbye.";
String s8 = "Goodbye!";
//Tell the user what the program does.
System.out.println("This program compares strings.\n");
System.out.println("String s1 = " + s1);
System.out.println("String s2 = " + s2);
System.out.println("Under the equals() method:");
if (s1.equals(s2))
System.out.println("s1 and s2 have THE SAME contents.");
else
System.out.println("s1 and s2 have DIFFERENT contents.");
System.out.println("Under the equalsIgnoreCase() method:");
if (s1.equalsIgnoreCase(s2))
System.out.println("s1 and s2 have THE SAME contents (ignoring
capitalization).");
else
System.out.println("s1 and s2 have DIFFERENT contents (ignoring
capitalization).");
System.out.println("\nString s3 = " + s3);
System.out.println("String s4 = " + s4);
System.out.println("Under the compareTo() method:");
System.out.println("s3.compareTo(s4) returns: " + s3.compareTo(s4));
System.out.println("s4.compareTo(s3) returns: " + s4.compareTo(s3));
System.out.println("s1.compareTo(s2) returns: " + s1.compareTo(s2));
System.out.println("s2.compareTo(s1) returns: " + s2.compareTo(s1));
System.out.println("String s5 = " + s5);
System.out.println("String s6 = " + s6);
System.out.println("s5.compareTo(s6) returns: " + s5.compareTo(s6));
System.out.println("String s7 = " + s7);
System.out.println("String s8 = " + s8);
System.out.println("s7.compareTo(s8) returns: " + s7.compareTo(s8));
System.out.println("\nUnder the compareToIgnoreCase() method:");
System.out.println("s3.compareToIgnoreCase(s4) returns: " +
s3.compareToIgnoreCase(s4));
System.out.println("s4.compareToIgnoreCase(s3) returns: " +
s4.compareToIgnoreCase(s3));
System.out.println("s1.compareToIgnoreCase(s2) returns: " +
s1.compareToIgnoreCase(s2));
System.out.println("s2.compareToIgnoreCase(s1) returns: " +
s2.compareToIgnoreCase(s1));
Computer Science Notes
Chapter 8
Page 12 of 16
System.out.println("s5.compareToIgnoreCase(s6) returns: " +
s5.compareToIgnoreCase(s6));
System.out.println("\nUnder the regionMatches() method:");
System.out.println("s1.regionMatches(1, s2, 1, 3) returns: " +
s1.regionMatches(1, s2, 1, 3));
System.out.println("(because \"ell\" is the same thing as \"ell\")");
System.out.println("\nUnder the startsWith() method:");
System.out.println("s1.startsWith(\"Hell\") returns: " +
s1.startsWith("Hell"));
System.out.println("\nUnder the endsWith() method:");
System.out.println("s5.endsWith(\"vin\") returns: " + s5.endsWith("vin"));
}//end main(String)
}//end class StringComparisons
This program compares strings.
String s1
String s2
Under the
s1 and s2
Under the
s1 and s2
= Hello.
= hello.
equals() method:
have DIFFERENT contents.
equalsIgnoreCase() method:
have THE SAME contents (ignoring capitalization).
String s3 = abc
String s4 = abg
Under the compareTo() method:
s3.compareTo(s4) returns: -4
s4.compareTo(s3) returns: 4
s1.compareTo(s2) returns: -32
s2.compareTo(s1) returns: 32
String s5 = Kevin
String s6 = Kevin
s5.compareTo(s6) returns: 0
String s7 = Goodbye.
String s8 = Goodbye!
s7.compareTo(s8) returns: 13
Under the compareToIgnoreCase() method:
s3.compareToIgnoreCase(s4) returns: -4
s4.compareToIgnoreCase(s3) returns: 4
s1.compareToIgnoreCase(s2) returns: 0
s2.compareToIgnoreCase(s1) returns: 0
s5.compareToIgnoreCase(s6) returns: 0
Under the regionMatches() method:
s1.regionMatches(1, s2, 1, 3) returns: true
(because "ell" is the same thing as "ell")
Under the startsWith() method:
s1.startsWith("Hell") returns: true
Under the endsWith() method:
Computer Science Notes
Chapter 8
Page 13 of 16
s5.endsWith("vin") returns: true
Section 8.2.4: String Length and Retrieving Individual Characters

The length() method of the String class returns the number of characters in the string.

The charAt(index) method of the String class returns the character at position index, where
0  index  length() – 1.

The charAt() method is an indication of the fact that a string is represented internally as a private array
of characters.

To get a single character for input from the keyboard, you can use keyboard.next().charAt(0)
Section 8.2.5: String Concatenation

You can use the + operator to concatenate strings…

Example:
String s1 = “Hello, ”;
String s2 = “Doofus.”;
String s3 = s1 + s2;


You also can use the concat() method of the String class to concatenate strings…
Example:
String s1 = “Hello, ”;
String s2 = “Doofus.”;
String s3 = s1.concat(s2);
Section 8.2.6: Obtaining Substrings

The method substring(int beginIndex, int endIndex) of the String class returns a new string that starts
with the character at index beginIndex and ends at the character at index endIndex.

The method substring(int beginIndex) of the String class returns a new string that starts with the
character at index beginIndex and goes to the end of the string.
Section 8.2.7: String Conversions

The method toLowerCase() of the String class returns a new string with all alphabetic characters
converted to lower case.

The method toUpperCase() of the String class returns a new string with all alphabetic characters
converted to upper case.

The method trim() of the String class returns a new string with all leading and trailing whitespace
trimmed away.

The method replace(char oldChar, char newChar) of the String class returns a new string with all
occurrences of oldChar replaced with newChar.

The method replaceFirst(String regex, String newString) of the String class returns a new string
with the first occurrences of the regular expression regex replaced with newString.

The method replaceAll(String regex, String newString) of the String class returns a new string with
every occurrence of the regular expression regex replaced with newString.
Computer Science Notes
Chapter 8
Page 14 of 16
Section 8.2.8 Finding a Character or a Substring in a String
Section 8.2.9 Conversion Between Strings and Arrays
Section 8. 2.10 Converting Characters and Numeric Values to Strings
Section 8.3: The Character Class

Java provides a wrapper class for every primitive data type.

A wrapper class stores the primitive data type and provides several useful methods relating to that data
type.

The Character class is a wrapper class for the primitive char data type, and provides methods like
isLetter() that determine whether or not the character is an alphabetic letter.
Section 8.4 The StringBuilder/StringBuffer Classes

Instances are like a String object, but more flexible (you can mutate the data fields).

You can add, insert, or append new content into a StringBuffer/StringBuilder object.

The StringBuffer class is older, and should be used when it will be accessed by multiple tasks
concurrently.

The StringBuilder class was introduced in JDK 1.5, and is more efficient when it will be accessed by a
single task.
Section 8.4.1 Modifying Strings in the Buffer
Section 8.4.2 The toString, capacity, setLength, and charAt Methods
Section 8.5 Command Line Arguments
Section 8.5.1 Passing Strings to the main Method
Section 8.6 Regular Expressions
Section 8.6.1 Matching Strings
Section 8.6.2 Regular Expression Syntax
Section 8.6.3 Replacing and Splitting Strings
Computer Science Notes
Chapter 8
Page 15 of 16
Section 8.7 The File Class
The java.io.File class is used to obtain file properties and to delete and rename files.
Section 8.8 Text I/O
There are 3 things you need to do in general in any programming language when dealing with disk files:
1. Open the file for reading or writing.
2. Read data from or write data to the file.
3. Close the file
Extra Java thing: any method that does I/O need to have throws Exception tacked on after the parameter list.
Text Input
java.io.File inputFile = new
java.io.File(“inputData.txt”);
Text Output
java.io.File outputFile = new
java.io.File(“outputData.txt”);
Scanner diskData = new Scanner (inputFile);
PrintWriter diskData = new PrintWriter (inputFile);
String firstLine = diskData.next();
diskData.println(“Her is a line of disk text.”);
diskData.close();
diskData.close();
Computer Science Notes
ASCII
value Character
32
33 !
34 "
35 #
36 $
37 %
38 &
39 '
40 (
41 )
42 *
43 +
44 ,
45 46 .
47 /
48 0
49 1
50 2
51 3
52 4
53 5
54 6
55 7
56 8
57 9
58 :
59 ;
60 <
61 =
62 >
63 ?
Chapter 8
ASCII
value Character
64 @
65 A
66 B
67 C
68 D
69 E
70 F
71 G
72 H
73 I
74 J
75 K
76 L
77 M
78 N
79 O
80 P
81 Q
82 R
83 S
84 T
85 U
86 V
87 W
88 X
89 Y
90 Z
91 [
92 \
93 ]
94 ^
95 _
ASCII
value Character
96 `
97 a
98 b
99 c
100 d
101 e
102 f
103 g
104 h
105 i
106 j
107 k
108 l
109 m
110 n
111 o
112 p
113 q
114 r
115 s
116 t
117 u
118 v
119 w
120 x
121 y
122 z
123 {
124 |
125 }
126 ~
Page 16 of 16
Download