CIT Final
When you deserialize an object using the readObject method, you must cast the return value to the desired class type
T
When you open a file withe the PrintWriter class, the class can potentially throw an IOException
T
You must have a return statement in a value-returning method
T
if ClassC is derived from ClassB which is derived from ClassA, this would be an example of
a chain of inheritance
The whole-part relationship created by object aggregation is more often called a ___ relationship
"has a"
How many times will the following do-while loop be executed int x = 11; do { x += 20; } while (x > 100);
1
What would be the value of bonus after the following statements are executed int bonus, sale = 1250; if (sales > 1000) bonus = 100; if (sales > 750) bonus = 50; if (sales > 500) bonus = 25; else bonus = 0;
25
What will be the value of pay after the following statements are executed int hours = 45; double pay, payRate = 10.00; pay = hours <= 40 ? hours * payRate : 40 * payRate + (hours - 40) *payRate * 1.5;
475.00
What is the value of x after the following code is executed
5.0
A Java program will not compile unless it contains the correct line numbers
F
When testing for character values, the switch statement does not test for the case of the character
F
Each different type of CPU has its own
machine language
Which symbol indicates that a member is public in a UML diagram
+
Subscripting always starts with
0
What are the tokens in the following code String str = "123-456-7890"; String [] tokens = str.split("-");
123, 456, 7890
It is common practice in object-oriented programming to make all of a class's
fields private
Which of the following is valid
float w; w = 1.0f;
An exception object's default error message can be retrieved using the ___ method
getMessage
Select all that apply. Any method that calls a method with a throws clause in its header must
handle the potential exception have the same throws clause
Another term for an object of a class is an
instance
Select all that apply. Which of the following types of values can be passed to a method that has an int parameter variable
int
Which of the following is a valid declaration for a ragged array with five rows but no columns
int [] [] ragged = new int [5] [];
Which of the following is not true about static methods
it is necessary for an instance of the class to be created to execute the method
When the this variable is used to call a constructor
it must be the first statement in the constructor making the call
Each repetition of a loop is known as an
iteration
If numbers is a two-dimensional array, which of the following would give the number of columns in row r
number [r].length
A set of programming language statements that perform a specific task is a
procedure
Computers can do many different jobs because they are
prorgammable
Which of the following is true about protected access
protected members may be accessed by methods in the same package or in a subclass, even when the subclass is in a different package
The scope of a private instance field is
the instance methods of the same class
In the following Java statement, what value is stored in the variable name String name = "John Doe";
the memory address where "John Doe" is located
For the following code, which statement is not true public class Sphere { private double radius; public double x; private double y; private double z; }
the z field is available to code written outside the Sphere class
When you make a copy of the aggregate object and of the objects that it references,
you are performing a deep copy
IN the following statement, which is the interface public class ClassA extends ClassB implements ClassC
ClassC
All methods in an abstract class must also be declared abstract
F
If a string has more than one character used as a delimiter, you must write a loop to determine the tokens, one for each delimiter character
F
In a for loop, the control variable is always incremented
F
In the method header the static method modifier means the method is available to code outside the class
F
Java is not case sensitive
F
Programs never need more than one path of execution
F
The String class's valueOf method accepts a string representation as an argument and returns its equivalent integer value
F
The throw statement informs the compiler that a method throws one or more exceptions
F
When catching multiple exceptions that are related to one another through inheritance you should handle the more general exception classes before the more specialized exception classes
F
Software refers to
Programs
Which of the following statements converts an int variable named number to a string and stores the value in the String object variable named str
String str = Integer.toString(number);
A constructor is a method that is automatically called when an object is created
T
A file must always be opened before using it and closed when the program is finished using it
T
A local variable's scope always ends at the closing brace of the block code in which it is declared
T
Constants, variables, and the values of expressions may be passed as arguments to a method
T
Each byte is assigned a unique number known as an address
T
Encapsulation refers to the combining of data and code into a single object
T
If a non-letter is passed to the toLowerCase or toUpperCase method, it is returned unchanged
T
If you write a toString method fro a class, Java will automatically call the method any time you concatenate an object of the class with a string
T
Methods are commonly used to break a problem into small manageable pieces
T
Shadowing is the term used to describe where the field name is hidden by the name of a local or parameter variable
T
The if-else statement will execute one group of statements if its boolean expression is true or another group if its boolean expression is false
T
Without programmers, the users of computers would have no software, and, without software, computers would not be able to do anything
T
Which of the following is a value that is written into the code of a program
a literal
Every Java application program must have
a method named main
What does the following UML diagram entry mean + setHeight(h : double) : void
a public method with a parameter of data type double that does not return a value
A ragged array is
a two-dimensional array where the rows have different numbers of columns
The StringBuilder class's insert method allows you to insert a(n) ___ into the calling object's string
all of these
When an array is passed to a method
all of these are true
The IllegalArgumentException class extends the RuntimeException class and is, therefore,
an unchecked exception class
A value-returning method must specify ___ as its return type in the method header
any valid data type
Values stored in local variables
are lost between calls to the method in which they are declared
All fields declared in an interface
are treated as final and static
___ tells the Java compiler that a method is meant to override a method in the superclass
@Override
When writing documentation comments for a method, you can provide a description of each parameter by using a
@param tag
Which of the following is not one of the major components of a typical computer system
All of the above are major components
Which of the following is not part of the programming process
All of these are parts of the programming process
Which of the following is a correct method header for receiving a two-dimensional array as an argument
public static void passArray (int [] [])
Byte code instructions are
read and interpreted by the JVM
What will be displayed after the following statements are executed String str = "red$green&blue#orange"; String[] tokens = str.split ("[$&#]"); for (String s : tokens) System.out.print(s + " " );
red green blue orange
If the following is from the method section of a UML diagram, which of the statements below is true + add (object2:Stock) : Stock
this is a public method named add that accepts and returns references to objects of the Stock class
All exceptions are instances of classes that extend the ___ class
throwable
The ___ method returns a copy of the calling String object with all leading and trailing whitespace characters deleted
trim
A flag may have the values
true or false
The boolean data type may contain which of the following range of values
true or false
In Java, when a character is stored in memory, it is actually the ___ that is stored
unicode number
The String class's ___ method accepts a value of any primitive data type as its argument and returns a string representation of the value
valueOf
Assume that inputFile references a Scanner object that was used to open a file. Which of the following while loops is the correct way to read data from the file until the end of the file is reached
while (inputFile.hasNext ()) {...}
To compare two objects in a class,
write an equals method that will make a field by field compare of the two objects
To serialize an object and write it to the file, use the ___ method of the ObjectOutputStream class
writeObject
If x has been declared an int, which of the following statements is invalid
x = 1,000;
What will be the value of x after the following code is executed int x, y = 15; x = y--;
15
What is the value of x after the following code has been executed int x = 75; int y = 90; if (x != y) x += y;
165
In the following statement, which is the subclass public class ClassA extends ClassB implements ClassC
ClassA
A method that gets a value from a class's field but does not change it is known as a mutator method
F
A sorting algorithm is used to locate a specific item in a larger collection of data
F
A sorting algorithm is a technique for scanning through an array and rearranging its contents in some specific order
T
An instance of a class does not have to exist in order for values to be stores in a class's static fields
T
Application software refers to programs that make the computer useful to the user
T
Because every class directly or indirectly inherits from the Object class, every class inherits the Object class's members
T
Because the subclass is more specialized than the superclass, it is sometimes necessary for the subclass to replace inadequate methods with more suitable ones
T
If you are using characters other than whitespaces as delimiters, you will probably want to trim the string before tokenizing; otherwise, the leading and/or following whitespaces will become part of the first and/or last token
T
The String[] args parameter in the main method header allows the program to receive arguments from the operating system command-line
T
The System.out.printf method allows you to format output in a variety of ways
T
The do-while loop is ideal in situations where you always want the loop to iterate at least once
T
The key word this is the name of a reference variable that an object can use to refer to itself
T
The RandomAccessFile class treats a file as a stream of
bytes
All of the exceptions you will handle are instances of classes that extend the ___ class
exception
Write a program to prompt the user for the radius of a circle and output the circle's area. The formula for the area of a circle is A=πr2
import java.util.Scanner; public class CircleArea { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); double r, area; System.out.println("This program finds the area of a circle."); System.out.print("Enter the radius: "); r = keyboard.nextDouble(); area = Math.PI*Math.pow(r,2); System.out.printf("The area is %.2f\n", area); } }
Which of the following statements converts a String object variable named str to an int and stores the value in the variable x
int x = Integer.parseInt(str);
If a method in a subclass has the same signature as a method in the superclass, the subclass method ___ the superclass method
overrides
A group of related classes is called a
package
All methods specified by an interface are
public
Write the Point, Shape, and Circle classes specified in the following UML diagram. Have the Circle class inherit from the abstract base class Shape. Have the setX and setY methods of the Point class throw an IllegalArgumentException for infinite or NaN input. Have the setRadius method of the Circle class throw an IllegalArgumentException for non-positive, infinite, or NaN input.
public class Point { private double x, y; public Point(double x, double y) { setX(x); setY(y); } public Point(Point p) { setX(p.x); setY(p.y); } public double getX() {return x;} public double getY() {return y;} private void setX(double x) { if (!Double.isFinite(x)) { throw new IllegalArgumentException("Invalid x: " + x); } this.x = x; } private void setY(double y) { if (!Double.isFinite(y)) { throw new IllegalArgumentException("Invalid y: " + y); } this.y = y; } public void translate(double dx, double dy) { setX(x + dx); setY(y + dy); } } public abstract class Shape { private Point center; public Shape(Point c) { center = new Point(c); } public Point getCenter() {return center;} public void translate(double dx, double dy) { center.translate(dx, dy); } } public class Circle extends Shape { private double radius; public Circle(Point c, double r) { super(c); setRadius(r); } public double getRadius() {return radius;} private void setRadius(double r) { if (!Double.isFinite(r) || r <= 0) { throw new IllegalArgumentException("Invalid radius: " + r); } radius = r; } }
Which of the following is not part of a method header
semicolon
If an if-else statement, if the boolean expression is false then
the statement or block following the else is executed
What will be the values of x and y after the following code is executed int x = 12, y = 5; x+= y--;
x = 17, y = 4
What will be the value of x after the following statements are executed int x = 10; switch (x) { case 10: x += 15; case 12: x += 5; break; default: x *= 3;
20
The key word this is the name of a reference variable that is available to all static methods
F
The term "no-arg constructor" is applied to any constructor that does not accept arguemnts
T
When a subclass extends a superclass, the public members of the superclass become public members of the subclass
T
When an array of objects is declared but not initialized, the array values are set to null
T
When an exception is thrown by a method that is executing under several layers of method calls, a stack trace indicates the method executing when an exception occurred and all of the methods that were called in order to execute that method
T
When you call one of the Scanner class's methods to read a primitive value, such as nextInt or nextDouble, and then call the nextLine method to read a string, an annoying and hard-to-find problem can occur
T
Write a program to prompt the user for 5 test scores, have the user input those scores, calculate the average of those scores, and display the average to the user. Use an integer array to store the test scores. Use a try catch block to validate that each entered test score is an integer.
import java.util.Scanner; public class TestScores { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); String input; int[] scores = new int[5]; double sum = 0, average; System.out.println("This program calculates " + "the average of " + scores.length + " test scores"); for (int i=0; i<scores.length; i++) { System.out.print("Enter score " + (i+1) + ": "); try { input = keyboard.nextLine(); scores[i] = Integer.parseInt(input); } catch (NumberFormatException nfe) { System.out.println("Invalid score!"); i--; } } for (int i=0; i<scores.length; i++) { sum += scores[i]; } average = sum / scores.length; System.out.printf("The average is %.2f\n", average); } }
Write a program that asks the user for a file name, reads a text file with the given name, and then displays for the user the number of words in the file.
import java.util.Scanner; import java.io.File; import java.io.FileNotFoundException; public class WordCount { public static void main(String[] args) throws FileNotFoundException { Scanner keyboard = new Scanner(System.in); Scanner fileInput; File f; String filename, line; int nWords = 0; System.out.println("This program counts the number of words in a file"); System.out.print("Enter a filename: "); filename = keyboard.nextLine(); f = new File(filename); fileInput = new Scanner(f); while (fileInput.hasNext()) { line = fileInput.nextLine(); nWords += line.split("\\s+").length; } System.out.println("The file " + filename + " has " + nWords + " words"); } }
You should always document a method by writing comments that appear
just before the method's definition
Which is a control structure that causes a statement or group of statements to repeat
loop
A ___ is a part of a method that contains a collection of statements that are performed when the method is executed
method body
Class objects normally have ___ that perform useful operations on their data, but primitive variable do not
methods
Any ___ argument passed to the Character class's toLowerCase method or toUpperCase method is returned as it is
nonletter
In the following code, what values could be read into number to terminate the while loop Scanner keyboard = new Scanner(System.in); System.out.print("Enter a number: "); int number = keyboard.nextInt(); while (number < 100 || number > 500) { System. out.print("Enter another number: "); number = keyboard.nextInt (); }
numbers in the range 100-500
Enumerated types have the ___ method which returns the position of an enum constant in the declaration list
ordinal
A ___ is a value that signals when the end of a list of values has been reached
sentinel
In order for an object to be serialized, its class must implement the ___ interface
serializable
Given the following method, which of these method calls is valid public static void showProduct (double num1, int num2) { double product; porduct = num1 * num2; System.out.println("The product is " + product); }
showProduct (3.3, 55);
Character literals are enclosed in ___ and string literals are enclosed in ___
single quotes, double quotes
If str1 and str2 are both String objects, which of the following expressions will correctly determine whether or not they are equal
str1.equals(str2)
A ___ is used as an index to pinpoint a specific element within an array
subscript
Variables are
symbolic names made up by the programmer that represent memory locations
In order to do a binary search on an array
the array must first be sorted
When you pass an argument to a method you should be sure that the argument's type is compatible with
the parameter variable's date type
In a try/catch construct, after the catch statement is executed
the program resumes at the statement that immediately follows the try/catch construct
If you attempt to perform an operation with a null reference variable
the program will terminate