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

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.
  • objectRefVar.dataField references a public data field of the object
  • objectRefVar.method(arguments) references a public method of the object
  • 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:
  • System.out.println("The area of the circle1 object is: " + circle1.getArea());
  • 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
  • See

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:
  • null for a reference type
  • 0 for numeric types
  • false for Boolean types
  • '\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.

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
  • See

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.
  • See
  • See

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.
  • public makes data fields, methods, and classes accessible from any class
  • privatemakes data fields and methods accessible from within their own class
  • 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:

packagepackageName;

  • 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, inconsistentvalues, 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
  • See

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
  • 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
  • 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.
* 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 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];
//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
{
/** 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);
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: