Computer Science Test #2 Review, Fall 2008 by w6JLcR7

VIEWS: 11 PAGES: 26

									Computer Science Test #2 Review                                           Page 1 of 26

Chapter 7: Objects and Classes
Section 7.1: Introduction
Procedural programming: data and operations on that data are separate, which requires sending data to methods
via a parameter list.
Object-oriented programming: data and operations on that data are stored in a single entity called an object,
which many times eliminates the need for sending data to methods, and allows for more consistent and error-
free operations on the data, and code that is easier to use, re-use, and maintain.

Section 7.2: Defining Classes for Objects
Vocabulary:
       Object-oriented programming: programming using objects
       state of an object: the values stored in its data fields (i.e., its properties)
       behavior of an object: the methods that go along with the object
       class: a template of the data and methods of an object
       object / instance: a specific example of a class existing in memory
       instantiation: the act of creating an instance of a class
       data field: the information that must be stored to represent the state of an object
       method: a block of code that defines a behavior of an object
       constructor: a special method that is used to initialize an object
       main class: a class containing a main method. Most classes do not contain a main method.
       UML (Unified Modeling Language) class diagram: a visual representation of a class where the name
of the class, its data fields, and its methods are all summarized as shown below.

                 Chap07Circle                     circle1: Chap07Circle
-radius :                              double     -radius :                 5
-x_0 :                                 double     -x_0 :                    0
-y_0 :                                 double     -y_0 :                    0
+Chap07Circle( )
+Chap07Circle (newRadius: double)
+Chap07Circle (newRadius: double, x: double, y:
double)
+getRadius( ): double                             circle2: Chap07Circle
+getArea( ): double                               -radius :                 25
+getCircumference( ): double                      -x_0 :                    5
+getX( ): double                                  -y_0 :                    10
+getY( ): double
+setRadius (newRadius: double)                    circle3: Chap07Circle
+setX (x: double)                                 -radius :                 125
+setY (y: double)                                 -x_0 :                    0
+contains (x: double, y: double); boolean         -y_0 :                    0
+toString ( ): String
                                                  circle4: Chap07Circle
                                                  -radius :                 0
                                                  -x_0 :                    0
                                                  -y_0 :                    0
Computer Science Test #2 Review                                          Page 2 of 26

Section 7.3: Constructors

      Constructors can be (and usually are overloaded)
      Classes usually define a constructor without arguments (i.e., a no-arg constructor )
      Default constructors are provided automatically by the compiler (as a no-arg constructor with no body)
       if no constructors are given.
      A constructor’s name must match the name of the class
      Constructors do not have a return type (not even void)
      Constructors are invoked using the new operator when an object is created.
      Constructors play the role of initializing objects.

Section 7.4: Accessing Objects via Reference Variables
Objects, their data fields, and their methods are stored in blocks of memory. We reference the block of memory
for any given object using references variables.

Section 7.4.1: Reference Variables and Reference Types
    A reference variable is a variable used to refer to a specific instance of an object.
    Reference variables are declared with a line of code that has the class name followed by the variables
       name:
       ClassName objectRefVar;
       Chap07Circle circle1;
    A reference type is the class to which a reference variable refers. Any reference variable can refer to
       any object of the same reference type (i.e., same class). Example:
       Chap07Circle circle1 = new Chap07Circle(5);
       Chap07Circle circle2 = new Chap07Circle(1);
       circle1 = circle2;
    To create an instance of an object and assign it to a reference variable:
       objectRefVar = new ClassName;
       circle1 = new Chap07Circle(5);
    To declare a new reference variable, create an instance of an object and assign it to the reference
       variable all in one line of code:
       ClassName objectRefVar = new ClassName;
       Chap07Circle circle1 = new Chap07Circle(5);
    An object reference variable only stores the memory location of a particular instance of an object (and
       not the object itself).
    Arrays are really objects in Java…

Section 7.4.2: Accessing an Object’s Data and Methods
    The dot operator (.) is placed after a reference variable to access the (public) data fields and (public)
       methods of the object referred to by that variable.
           o objectRefVar.dataField references a public data field of the object
           o objectRefVar.method(arguments) references a public method of the object
           o Example: circle1.setRadius(-3);
    An instance variable is a data field whose value depends on a specific instance of an object.
    An instance method is a method in an object that can only be invoked on a specific instance of an object.
    A calling object is the object on which an instance method is called.
    Sometimes you can create an instance of an object and use one of its methods without assigning the
       object to a reference variable. This is called an anonymous object. Example:
Computer Science Test #2 Review                                               Page 3 of 26

             o System.out.println("The area of the circle1 object is: " + circle1.getArea());
             o System.out.println("The area of a circle of radius 2 is: " +
               new Chap07Circle(2).getArea());

Section 7.4.3: Example: Declaring Classes and Creating Objects
    You can have two classes in one file, but only one of the classes can be a public class, and the name of
       the file must match the name of the public class.
    See www.cs.armstrong.edu/liang/intro7e/book/TestCircle1.java
    See www.cs.armstrong.edu/liang/intro7e/book/Circle1.java

Section 7.4.4: Reference Data Fields and the null Value
    Data fields can be of reference types. That is, you can have a reference to another object inside an
   object.
    Data fields that do not reference a type get a special value of null. null is a literal value like true or false.
    Default data field values:
           o null for a reference type
           o 0 for numeric types
           o false for Boolean types
           o '\u000' for char types
    Local variables inside a method do not receive default values. You must initialize them yourself.

Section 7.4.5: Differences Between Variables of Primitive Types and Reference Types
       The value stored in a primitive type is the actual number stored in the variable.
       The value stored in a reference type is a memory location of the object to which it refers.
       When a reference type is assigned to a new object, the memory occupied by the old object is “cleaned
up” by the JVM in a process known as garbage collection. That is, the memory is freed and can be re-allocated
as the program continues running.
       Tip: if you know that an object is no longer needed, you can assign null to the reference variable for the
object, which will prompt the JVM to perform garbage collection on the space occupied by the object.

Section 7.5: Using Classes from the Java Library
Section 7.5.1: The Date class

               java.util.Date                The class Date represents a specific instant in time, with
                                             millisecond precision.
+Date( )                                     Constructs a Date object for the current time.
+Date(msSinceTheEpoch: long)                 Constructs a Date object for a time of msSinceTheEpoch
                                             milliseconds since "the epoch" of January 1, 1970 GMT.
+toString( ): String                         Returns a string representing the date and time.
+getTime( ): long                            Returns the number of milliseconds since "the epoch" of January
                                             1, 1970 GMT.
+setTime(msSinceTheEpoch: long): void        Sets a Date object to a new time of msSinceTheEpoch
                                             milliseconds since "the epoch" of January 1, 1970 GMT.
Computer Science Test #2 Review                                              Page 4 of 26

Section 7.5.2: The Random class

        java.util.Random         An instance of this class is used to generate a stream of
                                 pseudorandom numbers.
+Random( )                       Constructs a Random object with the current time as its seed.
+Random(seed: long)              Constructs a Random object with the specified seed.
+nextInt( ): int                 Returns a random int value.
+nextInt(n: int ): int           Returns a random int value between 0 and n (exclusive).
+nextLong( ): long               Returns a random long value.
+nextDouble( ): double           Returns a random double value between 0.0 and 1.0
                                 (exclusive).
+nextFloat( ): float             Returns a random float value between 0.0F and 1.0F
                                 (exclusive).
+nextBoolean( ): boolean         Returns a random boolean value.

Section 7.5.3: Displayign GUI Components
Examples of Java classes that are used to produce Graphical User Interfaces:
      JFrame
      JButton
      JRadioButton
      JComboBox
      See www.cs.armstrong.edu/liang/intro7e/book/TestFrame.java
      See www.cs.armstrong.edu/liang/intro7e/book/GUIComponents.java


Section 7.6: Static Variables, Constants, and Methods
    An instance variable is a variable in a class whose value is tied to a specific instance of an object of that
       class.
    A static variable is a variable in a class that is stored in a common memory location. Thus, its value is
       shared by all instances of the class, and so if one object changes the value of the static variables, all
       objects see that change.
    Static variables are declared with the keyword modifier static before the variable name.
    Example:
       static int numberOFCircleObjects = 0;
    Static variables are underlined in UML diagrams.
    Constants in a class are shared by all objects of the class, and thus they are static variables also. So,
       when declare a constant in a class, you need to modify it as final static.
    Example:
       final static double PI = 3.1415927;

       A static method is a method in a class that can be called without creating an instance of the class.
       You call a static method with the name of the class, the dot operator, and the name of the method.
       Example: all the methods from the Math class are static methods.
        double theta = Math.acos(Math.sqrt(2));
       Static methods are underlined in UML diagrams.
       JDK 1.5 allows you to import static variables and methods directly from a class so that you do not have
        to use the class name to reference them.
       In a main class, all methods and variables (that are declared at the class level) must be static.
Computer Science Test #2 Review                                             Page 5 of 26

      See www.cs.armstrong.edu/liang/intro7e/book/Circle2.java
      See www.cs.armstrong.edu/liang/intro7e/book/TestCircle2.java




Section 7.7: Visibility Modifiers
    Visibility modifiers control access to data fields, methods, and classes.
    The two most common visibility modifiers are public and private.
           o public makes data fields, methods, and classes accessible from any class
           o private makes data fields and methods accessible from within their own class
           o If public or private are not used, then the data fields, methods, and classes are accessible by any
               class in the same package. This is known as package-private or package access.
    Packages are used to organize classes. To declare that a class is part of a package, use the following line
       of code at the start of the program:
       package packageName;
    There is no restriction on accessing methods or data fields from inside the same class.
    If an object is created within an object of the same class, then the parent object has access to all the
       private methods of the child object, because they are both of the same class.
    Do not use visibility modifiers on local variables within a method.
    A private constructor prohibits a user of your class from creating an instance of your class. (Used with
       classes containing all static methods).


Section 7.8: Data Field Encapsulation
    Data field encapsulation is a standard of object oriented design in which data fields in a class are
       declared private.
    A client program is a program that uses a class.
    You should use data field encapsulation because it prevents data in a class from being tampered with.
    You should use data field encapsulation because it prevents clients from setting your data fields to
       nonsensical, inconsistent values, which can lead to bugs (unless you write a lot of code to deal with
       nonsensical values).
    You should make your data fields private (i.e., encapsulate them) so that outside objects can not change
       their values directly.
    If you use data field encapsulation, then you have to provide an “interface” for clients to change the
       values of your data fields. This “interface” consists of methods that return the value of a data field and
       change the value of a data field (in a consistent manner).
    Accessor methods provide access to the value stored in a data field. The name of an accessor method
       starts with get by convention, unless the data field is a Boolean, in which case the method name starts
       with is. For example, the getRadius( ) method in the example code is an accessor method. Also,
       the contains method could have been called isInteriorPoint( ).
    Mutator methods change the value of a data field (in a consistent manner). The name of a mutator
       method starts with set by convention. For example, the setRadius( ) method is a mutator
       method.
    See www.cs.armstrong.edu/liang/intro7e/book/Circle3.java
    See www.cs.armstrong.edu/liang/intro7e/book/TestCircle3.java
Computer Science Test #2 Review                                            Page 6 of 26

Section 7.9: Passing Objects to Methods
    You can pass an object to a method.
    As with arrays, passing an object to a method is actually passing the reference of the object to the
       method.
    Thus, a method can change public data fields of an object.
    To pass a method, just put the object type followed by a reference variable for the object.
    See www.cs.armstrong.edu/liang/intro7e/book/TestPassObject.java
    Practice: Create a method that determines if two Chap07Circle object intersect.

Section 7.10: Array of Objects
    You can have an array of objects.
    First you must declare the array, and then write a loop to initialize each array element separately.
    See www.cs.armstrong.edu/liang/intro7e/book/TotalArea.java
    Practice: Modify the Chap07UseACircle class to create an array of random circles, then add up their
       areas.

Chapter 8: Strings and Text I/O
These notes are meant to accompany Introduction to Java Programming: Brief Version, seventh 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 use more methods from the String class.
    2. To open a file for either reading or writing using the Scanner and PrintWriter classes,
        respectively.
    3. To read or write data to file using the println() and next() methods of the Scanner and
        PrintWriter classes, respectively.
    4. To close a file once you are done with it.

package encryption;

import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;

/**
 * The EncryptionTool class contains methods for encrypting and decrypting
 * text files using a simple rotation (Caesar cipher) technique.
 * @author Kevin Mirus
 */
public class EncryptionTool
{
     /**The first character to be used in the rotation cipher*/
     public static final char FIRST_CHAR = ' ';
     /**The last character to be used in the rotation cipher*/
     public static final char LAST_CHAR = '~';
     public static final int CHAR_SPAN = LAST_CHAR - FIRST_CHAR;

       /**
        * Encrypts a given File by rotating characters by a given key value.
Computer Science Test #2 Review                         Page 7 of 26

       * 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.
                 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)
                             nextChar = nextChar - LAST_CHAR + FIRST_CHAR - 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(key, File)


     /**
      * 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
Computer Science Test #2 Review                         Page 8 of 26

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 = "";

                  //Loop through every character of the inputLine and decrypt it
using rotation.
                  for (int i = 0; i < inputLine.length(); i++)
                  {
                       int nextChar = (int) inputLine.charAt(i);
                       nextChar = nextChar - key;
                       if (nextChar < FIRST_CHAR)
                             nextChar = LAST_CHAR - (FIRST_CHAR - 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(int, File)


     /**
       * "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];
Computer Science Test #2 Review                        Page 9 of 26


            //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 = diskInput.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++)
                      {
                            if (key == 0) possibleSolution[numLinesRead][key]="";
                            int nextChar = (int) inputLine.charAt(i);
                            nextChar = nextChar - key;
                            if (nextChar < FIRST_CHAR)
                                 nextChar = LAST_CHAR - (FIRST_CHAR - nextChar) +
1;
                            possibleSolution[numLinesRead][key] += (char)
nextChar;
                      }
                 }
                 numLinesRead++;
            }

            //Close the input file.
            diskInput.close();

            return possibleSolution;

     }//end of rotationDecipher(File)

}//end of class EncryptionTool


package encryption;

import java.io.File;
import java.util.Scanner;

/**
 * /** The EncryptionToolUserInterface class implements an application that uses
the
 * EncryptionTool class to encrypt and decrypt text files.
 * @author Kevin Mirus
 *
 */
public class EncryptionToolUserInterface
{
Computer Science Test #2 Review                        Page 10 of 26

       /** 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.");
            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())
                     {
                           EncryptionTool.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())
                     {
                           EncryptionTool.rotationDecrypt(key, decryptFile);
Computer Science Test #2 Review                                        Page 11 of 26

                                    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 =
EncryptionTool.rotationDecipher(decipherFile);

                                    for (key = 0; key < EncryptionTool.CHAR_SPAN+1; key++)
                                    {
                                         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 EncryptionToolUserInterface

Book’s Statement of Skills:
   1. To use the String class to process fixed strings. (8.2)
   2. To use the Character class to process a single character. (8.3)
   3. To use the StringBuilder and StringBuffer classes to process flexible strings. (8.4)
   4. To distinguish between the String, StringBuilder, and StringBuffer classes. (8.2 – 8.4)
   5. To learn how to pass strings to the main method from the command line. (8.5)
Computer Science Test #2 Review                                             Page 12 of 26

   6.   To discover file properties and to delete and rename files using the File class. (8.6)
   7.   To write data to a file using the PrintWriter class. (8.7.1)
   8.   To read data from a file using the Scanner class. (8.7.2)
   9.   (Optional GUI) To open files using a dialog box. (8.8)


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 Test #2 Review                                                     Page 13 of 26

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…
    See http://java.sun.com/javase/6/docs/api/java/lang/String.html
    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
                                                   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.
+CASE_INSENSITIVE_ORDER: Comparator                A Comparator that orders String objects as by
                                                   compareToIgnoreCase.
+String()                                          Constructs a default String.
+String(bytes: byte[])                             Constructs a new String by decoding the specified array of
                                                   bytes using the platform's default charset.
+String(bytes: byte[], charset: Charset )          Constructs a new String by decoding the specified array of
                                                   bytes using the specified charset.
+String(bytes: byte[], offset: int, length: int)   Constructs a new String by decoding the specified subarray of
                                                   bytes using the platform's default charset.
+String(bytes: byte[], offset: int, length: int,   Constructs a new String by decoding the specified subarray of
charset: Charset)                                  bytes using the specified charset.
+String(bytes: byte[], offset: int, length: int,   Constructs a new String by decoding the specified subarray of
charsetName: String)                               bytes using the specified charset.
+String(bytes: byte[], charsetName: String)        Constructs a new String by decoding the specified array of
                                                   bytes using the specified charset.
+String(value: char[])                             Allocates a new String so that it represents the sequence of
                                                   characters currently contained in the character array argument.
+String(value: char[], offset: int, count: int)    Allocates a new String that contains characters from a
                                                   subarray of the character array argument.
+String(codePoints: int[], offset: int, count:     Allocates a new String that contains characters from a
int)                                               subarray of the Unicode code point array argument.
+String(original: String)                          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.
+String(buffer: StringBuffer)                      Allocates a new string that contains the sequence of
                                                   characters currently contained in the string buffer argument.
+String(builder: StringBuilder)                    Allocates a new string that contains the sequence of
                                                   characters currently contained in the string builder argument.
+charAt(index: int): char                          Returns the char value at the specified index.
+charAt(int index): char                           Returns the char value at the specified index.
                                                   Returns the character (Unicode code point) at the specified
+codePointAt(int index): int                       index.
                                                   Returns the character (Unicode code point) before the
codePointBefore(int index): int                    specified index.
Computer Science Test #2 Review                                                     Page 14 of 26

+codePointCount(int beginIndex, int                Returns the number of Unicode code points in the specified
endIndex): int                                     text range of this String.
+compareTo(String anotherString): int              Compares two strings lexicographically.
                                                   Compares two strings lexicographically, ignoring case
+compareToIgnoreCase(String str): int              differences.
+concat(String str): String                        Concatenates the specified string to the end of this string.
                                                   Returns true if and only if this string contains the specified
+contains(CharSequence s): boolean                 sequence of char values.

+contentEquals(CharSequence cs): boolean           Compares this string to the specified CharSequence.
+contentEquals(StringBuffer sb): boolean           Compares this string to the specified StringBuffer
                                                   Returns a String that represents the character sequence in the
+copyValueOf(char[] data): String                  array specified.
+copyValueOf(char[] data, int offset, int          Returns a String that represents the character sequence in the
count): String                                     array specified.
+endsWith(String suffix): boolean                  Tests if this string ends with the specified suffix.
+equals(Object anObject): boolean                  Compares this string to the specified object.
+equalsIgnoreCase(String anotherString):           Compares this String to another String, ignoring case
boolean                                            considerations.
format(Locale l, String format, Object... args):   Returns a formatted string using the specified locale, format
String                                             string, and arguments.
                                                   Returns a formatted string using the specified format string and
+format(String format, Object... args): String     arguments.
                                                   Encodes this String into a sequence of bytes using the
                                                   platform's default charset, storing the result into a new byte
+getBytes():byte[]                                 array.
                                                   Encodes this String into a sequence of bytes using the given
+getBytes(Charset charset): byte[]                 charset, storing the result into a new byte array.
                                                   Encodes this String into a sequence of bytes using the named
+getBytes(String charsetName): byte[]              charset, storing the result into a new byte array.
+getChars(int srcBegin, int srcEnd, char[]         Copies characters from this string into the destination
dst, int dstBegin): void                           character array.
+hashCode(): int                                   Returns a hash code for this string.
                                                   Returns the index within this string of the first occurrence of the
+indexOf(int ch): int                              specified character.

                                                   Returns the index within this string of the first occurrence of the
+indexOf(int ch, int fromIndex): int               specified character, starting the search at the specified index.
                                                   Returns the index within this string of the first occurrence of the
+indexOf(String str): int                          specified substring.
                                                   Returns the index within this string of the first occurrence of the
+indexOf(String str, int fromIndex): int           specified substring, starting at the specified index.
+intern():String                                   Returns a canonical representation for the string object.
+isEmpty(): boolean                                Returns true if, and only if, length() is 0.
                                                   Returns the index within this string of the last occurrence of the
+lastIndexOf(int ch): int                          specified character.
                                                   Returns the index within this string of the last occurrence of the
                                                   specified character, searching backward starting at the
+lastIndexOf(int ch, int fromIndex): int           specified index.
                                                   Returns the index within this string of the rightmost occurrence
+lastIndexOf(String str): int                      of the specified substring.
Computer Science Test #2 Review                                                    Page 15 of 26

                                                   Returns the index within this string of the last occurrence of the
                                                   specified substring, searching backward starting at the
+lastIndexOf(String str, int fromIndex): int       specified index.
+length():int                                      Returns the length of this string.
                                                   Tells whether or not this string matches the given regular
+matches(String regex): boolean                    expression.
+offsetByCodePoints(int index, int                 Returns the index within this String that is offset from the given
codePointOffset): int                              index by codePointOffset code points.
+regionMatches(boolean ignoreCase, int
toffset, String other, int ooffset, int len):
boolean                                            Tests if two string regions are equal.
+regionMatches(int offset, String other, int
offset, int len): boolean                          Tests if two string regions are equal.
+replace(char oldChar, char newChar):              Returns a new string resulting from replacing all occurrences of
String                                             oldChar in this string with newChar.
                                                   Replaces each substring of this string that matches the literal
+replace(CharSequence target,                      target sequence with the specified literal replacement
CharSequence replacement): String                  sequence.
+replaceAll(String regex, String                   Replaces each substring of this string that matches the given
replacement): String                               regular expression with the given replacement.
+replaceFirst(String regex, String                 Replaces the first substring of this string that matches the
replacement): String                               given regular expression with the given replacement.
                                                   Splits this string around matches of the given regular
+split(String regex): String[]                     expression.
                                                   Splits this string around matches of the given regular
+split(String regex, int limit): String[]          expression.
+startsWith(String prefix): boolean                Tests if this string starts with the specified prefix.
                                                   Tests if the substring of this string beginning at the specified
+startsWith(String prefix, int toffset): boolean   index starts with the specified prefix.
+subSequence(int beginIndex, int endIndex):        Returns a new character sequence that is a subsequence of
CharSequence                                       this sequence.
+substring(int beginIndex): String                 Returns a new string that is a substring of this string.
+substring(int beginIndex, int endIndex):
String                                             Returns a new string that is a substring of this string.
+toCharArray():char[]                              Converts this string to a new character array.
                                                   Converts all of the characters in this String to lower case using
+toLowerCase():String                              the rules of the default locale.
                                                   Converts all of the characters in this String to lower case using
+toLowerCase(Locale locale): String                the rules of the given Locale.
+toString():String                                 This object (which is already a string!) is itself returned.
                                                   Converts all of the characters in this String to upper case using
+toUpperCase():String                              the rules of the default locale.
                                                   Converts all of the characters in this String to upper case using
+toUpperCase(Locale locale): String                the rules of the given Locale.
                                                   Returns a copy of the string, with leading and trailing
+trim():String                                     whitespace omitted.
+valueOf(boolean b): String                        Returns the string representation of the boolean argument.
+valueOf(char c): String                           Returns the string representation of the char argument.
+valueOf(char[] data): String                      Returns the string representation of the char array argument.
+valueOf(char[] data, int offset, int count):      Returns the string representation of a specific subarray of the
String                                             char array argument.
Computer Science Test #2 Review                                            Page 16 of 26

+valueOf(double d): String                   Returns the string representation of the double argument.
+valueOf(float f): String                    Returns the string representation of the float argument.
+valueOf(int i): String                      Returns the string representation of the int argument.
+valueOf(long l): String                     Returns the string representation of the long argument.
+valueOf(Object obj): String                 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 used by the
JVM to reduce memory load when the same string literal is used more than once in a program.
       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.
Computer Science Test #2 Review                            Page 17 of 26

/**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.
         */
       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:");
Computer Science Test #2 Review                              Page 18 of 26

            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));
            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   = Hello.
String s2   = hello.
Under the   equals() method:
s1 and s2   have DIFFERENT contents.
Under the   equalsIgnoreCase() method:
s1 and s2   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
Computer Science Test #2 Review                                        Page 19 of 26

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:
s5.endsWith("vin") returns: true

Section 8.2.4: String Length, Characters, and Combining Strings
       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)

      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.5: 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: Converting, Replacing, and Splitting Strings
       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.
Computer Science Test #2 Review                                         Page 20 of 26

       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.
       The method split(String regex, int limit) of the String class returns an array of
Strings where each string in the array is obtained by splitting the original string around matches of the given
regular expression (extract tokens from a string with the specified delimiter).
        Example:
        String[] tokens = Java#HTML#Perl.split(#, 0);
        for (int i = 0; I < tokens.length; i++)
               System.out.println(tokens[i] +  );
        Produces as output:
        Java HTML Perl


Section 8.2.7 Matching, Replacing, and Splitting by Patterns
A regular expression is a string that specifies a pattern in a text string to look for.
       The method matches(String regex) of the String class returns whether or not the String
matches the regular expression regex.
        Example: All the following return true because the substring .* of the regular expression Java.*
        matches any zero or more characters.
        Java is fun..matches(Java.*)
        Java is cool..matches(Java.*)
        Java is powerful..matches(Java.*)
        Example: Check to see if two strings are valid social security numbers.
        String validSSN = 111-11-1111;
        System.out.println(validSSN.matches([\\d][ \\d][ \\d]- +
                 [ \\d][ \\d]-[ \\d][ \\d][ \\d][ \\d]));
        String inValidSSN = 22-11-1111;
        System.out.println(inValidSSN.matches([\\d][ \\d][ \\d]- +
                 [ \\d][ \\d]-[ \\d][ \\d][ \\d][ \\d]));
       The method replaceAll(String regex, String replacement) of the String class
replaces all matches of the regular expression regex with the string replacement.
        Example:
        String s = a+b$#c.replaceAll([$+#],NNN);
        System.out.println(s);
        //returns aNNNbNNNNNNc
        Java is cool..matches(Java.*)
        Java is powerful..matches(Java.*)
       The method split(String regex) of the String class returns an array of Strings where each
string in the array is obtained by splitting the original string at matches of the given regular expression.
        Example:
        String[] tokens = Java,C?C#,C++.split([.,:;?]);
        for (int i = 0; i < tokens.length; i++)
                 System.out.println(tokens[i]);
        //returns
        Java
        C
Computer Science Test #2 Review                                       Page 21 of 26

     C#
     C++
***Same as Table 8.1 in intro6e p281
***with modifications

Table 1: Frequently Used Regular Expressions

   Regular Expression         Matches                 Example

   x                    a specified character x     Java matches Java
   .                    any single character        Java matches J..a
   (ab|cd)              ab or cd                    ten matches t(en|im)
   [abc]                a, b, or c                  Java matches Ja[uvwx]a
   [^abc]               any character except        Java matches Ja[^ars]a
                        a, b, or c
   [a-z]                a through z                 Java matches [A-M]av[a-d]
   [^a-z]               any character except        Java matches Jav[^b-d]
                        a through z
   [a-e[m-p]]           a through e or              Java matches
                         m through p                  [A-G[I-M]]av[a-d]
   [a-e&&[c-p]]         intersection of a-e         Java matches
                         with c-p                     [A-P&&[I-M]]av[a-d]

   \d                   a   digit, same as [0-9]    Java2 matches "Java[\\d]"
   \D                   a   non-digit               $Java matches "[\\D][\\D]ava"
   \w                   a   word character          Java matches "[\\w]ava"
   \W                   a   non-word character      $Java matches "[\\W][\\w]ava"
   \s                   a   whitespace character    "Java 2" matches "Java\\s2"
   \S                   a   non-whitespace char     Java matches "[\\S]ava"

   p*                   zero or more                Java matches "a*"
                         occurrences of pattern p   bbb matches "a*"
   p+                   one or more                 Java matches "a+"
                         occurrences of pattern p   bbb matches "a+"
   p?                   zero or one                 Java matches "J?Java"
                         occurrence of pattern p    ava matches "J?ava"
   p{n}                 exactly n                   Java matches "a{1}"
                         occurrences of pattern p   Java does not match "a{2}"
   p{n,}                at least n                  Java matches "a{1,}"
                         occurrences of pattern p   Java does not match "a{2,}"
   p{n,m}               between n and m             Java matches "a{1,9}"
                         occurrences (inclusive)    Java does not match "a{2,9}"

The above table is from
http://www.cs.armstrong.edu/liang/intro7e/supplement/SupplementRegularExpression.doc

Section 8.2.8 Finding a Character or a Substring in a String
Welcome to Java.indexOf(W)                   returns        0.
Welcome to Java.indexOf(o)                   returns        4.
Welcome to Java.indexOf(o, 5)                returns        8.
Welcome to Java.indexOf(come)                returns        3.
Welcome to Java.indexOf(Java)                returns        11.
Welcome to Java.indexOf(Java, 5) returns                    -1.
Welcome to Java.lastIndexOf(W)               returns        0.
Welcome to Java.lastIndexOf(o)               returns        8.
Welcome to Java.lastIndexOf(o, 5)returns                    4.
Computer Science Test #2 Review                                           Page 22 of 26



Section 8.2.9 Conversion Between Strings and Arrays
       The method toCharArray() of the String class converts a string into a character array
        Example:
        char[] chars = Java. toCharArray ();
        for (int i = 0; i < chars.length; i++)
                System.out.println(chars[i]);
        //returns
        J
        a
        v
        a
       The method getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
of the String class copies a substring of characters starting at index srcBegin and ending at index srcEnd
– 1 into array dst starting at index dstBegin.
       The constructor String(char[]) of the String class creates a string containing all the characters
in the character array.
       The static method valueOf(char[]) of the String class returns a string containing all the
characters in the character array.

Section 8.2.10 Converting Characters and Numeric Values to Strings
       The static methods valueOf(char[]),valueOf (char) , valueOf(double) ,
valueOf(float) , valueOf(int), and valueOf(long) of the String class return a string
representation of the given character, array of characters, or number.
       The static methods Double.parseDouble(String) and Integer.parseInt(String)
return a numerical representation of the given string.

Section 8.2.11 Problem: Checking Palindromes
      See www.cs.armstrong.edu/liang/intro7e/book/CheckPalindrome.java

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.
       See http://java.sun.com/javase/6/docs/api/java/lang/Character.html


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.
      See http://java.sun.com/javase/6/docs/api/java/lang/StringBuffer.html
Computer Science Test #2 Review                                         Page 23 of 26

       The StringBuilder class was introduced in JDK 1.5, and is more efficient when it will be accessed by a
single task.
       See http://java.sun.com/javase/6/docs/api/java/lang/StringBuilder.html


Section 8.4.1 Modifying Strings in the StringBuilder
      The append method can be used to append information to the end of a StringBuilder object.
      The delete and deleteCharAt methods can be used to delete a range of characters or a single
character, respectively, from a StringBuilder object.
      The insert method can be used to insert characters into the middle of a StringBuilder object.
      The replace method can be used to replace characters into the middle of a StringBuilder object.
      The setCharAt method can be used to replace a single character in the middle of a
StringBuilder object.
      The reverse method can be used to reverse the order of all characters in a StringBuilder object.


Section 8.4.2 The toString, capacity, length, setLength, and charAt Methods
      The toString method returns a String object from the a StringBuilder object.
      The capacity method returns the number of characters this StringBuilder object can store
without increasing its size.
      The charAt method returns a single character from a StringBuilder object.
      The length method returns the number of characters stored in a StringBuilder object.
      The setLength sets a new length for a StringBuilder object (characters are either deleted or null
characters are appended).
      The subString method returns a substring within a StringBuilder object.
      The trimToSize method reduces the capacity of a StringBuilder object to the length of the
character array it stores.



Section 8.4.3 Problem: Ignoring Nonalphanumeric Charcters When Checking Palindromes
      See www.cs.armstrong.edu/liang/intro7e/book/PalindromeIgnoreNonAlphanumeric.java


Section 8.5 Command Line Arguments
      The main method always has an array of String objects for an input parameter…
       public static void main(String[] args) {…}
      The array of String objects is created and passed to main when the compiled Java program is run
from the command line with stuff typed after the name of the program…
       java myProgram First Name hello 23
      You have to write the code that processes the array of Strings.
Computer Science Test #2 Review                                          Page 24 of 26

Section 8.5.1 Passing Strings to the main Method
      To send strings to your program from the command line, simple type them after the name of the
program with a space between each string …
       java myProgram First Name hello 23
      You have to write the code that processes the array of Strings.

Section 8.5.2 Problem: Calculator
      See www.cs.armstrong.edu/liang/intro7e/book/Calculator.java


Section 8.6 The File Class
      The java.io.File class is used to obtain file properties and to delete and rename files.
      The File class does not contain methods to read the contents of or write to a file.
      See http://java.sun.com/javase/6/docs/api/java/io/File.html
      See www.cs.armstrong.edu/liang/intro7e/book/TestFileClass.java

Section 8.7 File Input and Output
      The File class does not contain methods to read the contents of or write to a file.
      In order to perform I/O (input/output), you need to use objects that have appropriate methods for reading
and writing data.
      The two classes this chapter uses are the Scanner class for reading and the PrintWriter class for
writing.
      See http://java.sun.com/javase/6/docs/api/java/util/Scanner.html
      See http://java.sun.com/javase/6/docs/api/java/io/PrintWriter.html


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. In this chapter, opening a file will be accomplished by creating
       an instance of a Scanner object or a PrintWriter object.
   2. Read data from or write data to the file. In this chapter, we will read from a file using one of the
       next* methods of the Scanner class, and we will write to a file using one of the print* methods of
       the PrintWriter class.
   3. Close the file. In this chapter, we will close a file by using the close() method of the Scanner and
       PrintWriter classes.

Extra Java thing: any method that does I/O need to have throws Exception tacked on after the parameter list.
Computer Science Test #2 Review                                            Page 25 of 26

Examples:
Text Input                                                Text Output
//Create a File object.                                   //Create a File object.
java.io.File inputFile = new                              java.io.File outputFile = new
    java.io.File(inputData.txt);                            java.io.File(outputData.txt);

//Open the file for reading.                              //Open the file for writing.
Scanner diskInput = new Scanner                           PrintWriter diskOutput = new
  (inputFile);                                               PrintWriter (outputFile);

//Read a line of text from the File.                      //Write a line of text to the File.
String firstLine = diskInput.next();                      diskOutput.println(Here is a line of
                                                          text written on the disk.);
//Close the File.                                         //Close the File.
diskInput.close();                                        diskOutput.close();

Section 8.7.1 Writing Data Using PrintWriter
       See www.cs.armstrong.edu/liang/intro7e/book/WriteData.java
       The print methods of the PrintWriter class write various types of information without including a
line feed.
       The println methods of the PrintWriter class write various types of information with a line feed.
       The printf method of the PrintWriter class performs formatted writes.
       The close method of the PrintWriter class closes the file that was opened for writing.

Section 8.7.2 Reading Data Using Scanner
      See www.cs.armstrong.edu/liang/intro7e/book/ReadData.java
      The hasNext method of the Scanner class returns true if the Scanner has more data to be read.
      The next method of the Scanner class returns the next token as a string delimited by whitespace.
      The nextLine method of the Scanner class returns a line of text ending with the line separator.
      The nextByte method of the Scanner class returns the next token as a byte.
      The nextInt method of the Scanner class returns the next token as an int.
      The nextShort method of the Scanner class returns the next token as a short.
      The nextLong method of the Scanner class returns the next token as a long.
      The nextDouble method of the Scanner class returns the next token as a double.
      The nextFloat method of the Scanner class returns the next token as a float.

Section 8.7.3 How Does Scanner Work?
      By skipping delimiters (i.e., whitespace), and the reading in a token up to the next delimiter.

Section 8.7.4 Problem: Replacing Text
      See www.cs.armstrong.edu/liang/intro7e/book/ReplaceText.java

Section 8.8 (GUI) File Dialogs
      See http://java.sun.com/javase/6/docs/api/javax/swing/JFileChooser.html
      See www.cs.armstrong.edu/liang/intro7e/book/ReadFileUsingJFileChooser.java
Computer Science Test #2 Review   Page 26 of 26

								
To top