Sunteți pe pagina 1din 26

Week 1 Study Questions

1. What does the acronym CVS stand for? Concurrent Versioning System
2. What does IDE stand for? Integrated Development Environment
3. What IDE will we use in class this semester? Eclipse
4. What does CPU stand for? Central Processing Unit
5. Define the term "bit". A "binary digit" -- either 0 or 1.
6. Define the term "byte". A sequence of 8 bits.
7. What is "hardware"? Name some examples. Physical components of the computer. (Things you can "touch").
Examples include: CPU, RAM chips, mother board, disk drives, monitor, mouse, keyboard, cables.
8. What is "software"? Name some examples. These are the "programs" or "apps" that you can run on a computer.
Examples: Internet browsers, games, word processors, spreadsheet programs, the operating system, etc.
9. Name several different operating systems. Some are: Windows XP, Mac OS X, unix, linux, solaris.
10. Give some examples of secondary memory devices. Hard drives, floppy disks, flash memory devices, CD's ,
DVD's
11. What is the advantage of primary memory over secondary? It is typically much faster.
12. What is the advantage of secondary memory over primary? It is permanent. (Also usually there is more of it!)
13. What does I/O stand for? Give some examples of I/O devices. Input/Output. These are devices that allow you to
communicate with the computer: monitor, keyboard, mouse, printer, etc.
14. How many different combinations of 0's and 1's can be represented using 7 bits? 27=128
15. How many bytes are in a kilobyte? Megabyte? Gigabyte? 210=1024 220 230
16. Name four things that the operating system does for you. Any of: Process management, memory management,
primitive I/O, Windowing, Primitive network control, security management.
17. What do you call the language that the CPU uses (0's and 1's represent instructions in this language). machine
language
18. How does "assembly language" relate to your answer to the previous question? Assembly language is a mnemonic
representation of machine language.
19. Name some higher level languages that were NOT designed for object oriented programming. Fortran, Cobol, C,
etc.
20. Name some higher level languages that WERE designed for object oriented programming. C++, Java, etc.
21. Translate the number 123 into base 7 representation. 234 (base 7)
22. Translate the binary (base 2) number 1011010 into base 10 representation. 90
23. Translate the hexadecimal (base 16) number 7F into binary representation. 01111111

Week 2 Study Questions

1. When your Java program is compiled, what type of file is created? (Hint: It is NOT machine language.) bytecode
2. What does it mean for someone to say that a Java program is "portable"? The same bytecode will run successfully
on any platform (provided that the Java Virtual Machine (JVM) is available.)
3. TRUE/FALSE: Inserting unnecessary spaces and/or blank lines could cause your Java program to malfunction.
FALSE
4. List the four Java primitive types that can be used to store integer values. long, int, short, byte
5. How much memory is required to store each of the four types mentioned in the previous question? long: 8, int: 4,
short: 2, byte: 1
6. What advantage do you gain from using one of the types of integer types that requires MORE memory? You can
store a wider range of values (larger values).
7. List the two Java primitive types that can be used to store floating point values. float, double
8. How much memory is required to store each of the two types mentioned in the previous question? double: 8,
float: 4
9. What advantage do you gain from using double instead of float? more precision (it will retain more digits)
10. List the two Java types that are used to store values that are not numbers. char and boolean
11. Write a statement that declares a variable named counter of type int, and stores the value 182 in the variable. int
counter = 182;
12. Write a statement that simultaneously declares three variables of type boolean, named x, y, and z. boolean x, y, z;
13. What values can a boolean variable achieve? true or false
14. Write a java class called "Fred". Put in a main method. Have the main method store your age in a variable named
age. Then main should print out a line that has your name, followed by your age. (Use a ?string literal? for your
name, but use the variable to access your age.)

public class Fred {

public static void main(String[] args) {


int age = 12;
System.out.println("Fawzi Emad, age is " + age);
}
}

15. Practice using BOTH styles for Java comments. // comment using first style, /* comment using second style */
16. Is the following statement valid: int x = 34.7; no
17. Is the following statement valid: double y = 12; yes
18. Is the following statement valid: boolean q = 17 < 25; yes
19. Evaluate the following Java expression: 9 - 15 * 6 / 11 + 4 5
20. Evaluate the following Java expression: 75 % 7 5
21. Never forget that you should not compare two Strings with the == operator. Suppose you have two String
variables, x and y. Give an expression that can be used to check whether or not the Strings x and y are identical.
x.equals(y)
22. What is "concatenation"? What operator do you use to concatenate Strings? +
23. What is the difference between System.out.print and System.out.println? System.out.println moves the cursor
down to the next line after it does it's output.
24. Suppose you have a String variable called s. What expression will return the number of characters in the String?
s.length()
25. Give examples of "literals" of each of the following types: String, char, long, int, float, double, boolean. hi", 'x',
32L, 16, 15.7F, 373.2, true
26. What "escape sequence" would you use in a String to indicate a "new line"? \n
27. What is the difference between "syntax errors" and "logical errors"? Syntax errors are due to your failure to
follow the rules of the language. Logical errors are where you have written a valid Java program, but it does not
behave the way it should.
28. If your program compiles and runs, but behaves incorrectly, are you probably suffering from "syntax" or "logical"
errors? logical
29. If Eclipse flags your code with a red mark and won't let you compile it, are you suffering from "syntax" or
"logical" errors? syntax

Week 3 Study Questions

1. What are the three logical operators? &&, ||, !


2. Write "truth-tables" for && and ||.

A B A && B A || B
--------------------------------------------------
T T T T
T F F T
F T F T
F F F F

3. Is the following boolean expression true or false?


((3 < 5) && !(1 > 14) && (-5 < -15)) || ((6 == 6) && !(2 == 2)) False
4. If s1 and s2 are variables representing Strings, what Java boolean expression is equivalent to "s1 is not the same
as s2"? !s1.equals(s2)
5. What statement must be included at the top of a file in order to use the Scanner in the file? import
java.util.Scanner;
6. Write a java class called "UserInput". In the main method, declare three variables: an int, a float, and a String.
Name the variables "age", "weight", and "name". Create a variable called "scan" of type Scanner, and set it equal
to a new Scanner. (Use the syntax shown in class). Prompt the user to enter his/her age, weight, and name, then
read these entries in using the scanner and set the variables accordingly. Then print the values of the three
variables with appropriate labels. For example: "Name: Frank Age: 17 weight: 151.4".

import java.util.Scanner;

public class UserInput {


public static void main(String[] args) {
int age;
float weight;
String name;
Scanner scan = new Scanner(System.in);
System.out.print("Enter your age: ");
age = scan.nextInt();
System.out.print("Enter your weight: ");
Weight = scan.nextFloat();
System.out.print("Enter your name: ");
name = scan.next();
System.out.println("Name: " + name + ", age: " + age + ", weight: " + weight);
}
}

7. Write a java class called "FahrenheitToCelcius". The main method will ask the user to enter a temperature in
Fahrenheit. (Use a variable of type "double" to store the value.) Then calculate the equivalent temperature in
Celcius, and print out a message telling the user what you found. [Recall: C = (5/9)(F-32).] Hint: Be careful about
doing arithmetic with integers! Check your program by entering 212 degrees. The output should be 100.

import java.util.Scanner;

public class FahrenheitToCelcius {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter temp (F): ");
double fahrenheit = scanner.nextDouble();
double celcius = 5.0/9.0 * (fahrenheit - 32);
System.out.println("That is " + celcius + " degrees C.");
}
}

8. Modify the "FahrenheitToCelcius" question in the previous question so that the user can either go from F to C or
vice versa.

import java.util.Scanner;

public class FahrenheitToCelcius {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter 1 to go from F to C; 2 for C to F: ");
int response = scanner.nextInt();
if (response == 1) {
System.out.print("Enter temp (F): ");
double fahrenheit = scanner.nextDouble();
double celcius = 5.0/9.0 * (fahrenheit - 32);
System.out.println("That is " + celcius + " degrees C.");
} else {
System.out.print("Enter temp (C): ");
double celcius = scanner.nextDouble();
double farenheit = celcius * 9.0 / 5.0 + 32;
System.out.println("That is " + farenheit + " degrees F.");
}
}
}

9. FOR THIS EXERCISE, YOU SHOULD STRIVE TO AVOID REDUNDANT CODE! Write a java class called
"RequestInfo". The main method will ask the user to enter his species. If the user enters "dog", then ask him to
enter the number of cats he has eaten this year. If the user enters "cat", ask him to enter the number of hairballs he
has coughed up this year. If the user enters "human", ask him to enter BOTH the number of cats he has eaten this
year AND the number of hairballs he has coughed up this year. If the user enters anything else (not dog, cat or
human), tell him that he is from another planet, and terminate the program. If the user DID enter one of the three
valid species (dog, cat, human) then print out a report in the following format:

Species: dog
Number of cats eaten: 54
Number of hairballs: 0
import java.util.Scanner;

public class RequestInfo {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("What is your species? ");
String answer = scanner.next();
int catsEaten = 0, hairballs = 0;
if (answer.equals("dog") || answer.equals("cat") || answer.equals("human")) {
if (!answer.equals("cat")) {
System.out.print("How many cats have you eaten this year? ");
catsEaten = scanner.nextInt();
}
if (!answer.equals("dog")) {
System.out.println("How many hairballs have you coughed up this year? ");
hairballs = scanner.nextInt();
}
System.out.println("Species: " + answer);
System.out.println("Number of cats eaten: " + catsEaten);
System.out.println("Number of hairballs: " + hairballs);
} else {
System.out.println("You are from another planet!");
}
}
}

10. Write a program that computes the letter grade for a student based on his/her numerical total. The program will
read in the total and compute the letter grade based on the following: to get an A the total must be at least 90.0. To
get a B it must be at least 80.0. For a C, at least 70.0. For a D, at least 60.0. Less than 60.0 is an F.

import java.util.Scanner;

public class LetterGrade {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("What is your numerical total: ");
double total = scanner.nextDouble();
char grade;
if (total >= 90.0) {
grade = 'A';
} else if (total >= 80.0) {
grade = 'B';
} else if (total >= 70.0) {
grade = 'C';
} else if (total >= 60.0) {
grade = 'D';
} else {
grade = 'F';
}
System.out.println("Your grade is " + grade);
}
}

11. Write a program that asks the user to enter up to four scores from 1 to 10. At the end the program will print out
the total of the scores, but without including the highest score. The catch is that at any time the user may enter 999
to indicate that he has no more scores to report. YOU MAY NOT USE ANY LOOPS! For example, here are a
couple of possible runs of the program:

Example 1:
Enter score 1: 5
Enter score 2: 7
Enter score 3: 9
Enter score 4: 3
The total (without the highest) was: 15

Example 2:
Enter score 1: 8
Enter score 2: 9
Enter score 3: 999
The total (without the highest) was: 8
import java.util.Scanner;

public class Scores {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);


int highest = 0;
int total = 0;
System.out.println("Enter up to 4 scores; use 999 if you are done.");
System.out.print("Score 1: ");
int score = scanner.nextInt();
if (score != 999) {
if (score > highest) {
highest = score;
}
total = total + score;
System.out.print("Score 2: ");
score = scanner.nextInt();
if (score != 999) {
if (score > highest) {
highest = score;
}
total = total + score;
System.out.print("Score 3: ");
score = scanner.nextInt();
if (score != 999) {
if (score > highest) {
highest = score;
}
total = total + score;
System.out.print("Score 4: ");
score = scanner.nextInt();
if (score != 999) {
if (score > highest) {
highest = score;
}
total = total + score;
}
}
}
}
total = total - highest;
System.out.println("total (without highest) is: " + total);
}
}

12. Decide which of the following variable names are valid in Java: dog, x11, _tomato, big$deal, how&why, 22down,
aBcDeFg, _$__$, under_score, _5_$_5_hello13. Valid ones are: dog, x11, _tomato, big$deal, aBcDeFg, _$__$,
under_score, _5_$_5_hello
13. Write a program that asks the user for an integer, call it n. The program will then add up all of the integers from 1
to n and print out the total. For example, if the user enters 4, then the output should be 10. (Because 1 + 2 + 3 + 4
= 10).

Scanner s = new Scanner(System.in);


System.out.println("Enter n: ");
int n = s.nextInt();
int total = 0;
int counter = 1;
while(counter <= n) {
total += counter;
counter++;
}
System.out.println("Total is: " + total);

14. The factorial of an integer is the product of all positive integers that are less than or equal to it. For example, 4
factorial is 2 * 3 * 4 = 24. Write a program that asks the user to enter a value, n, and then prints n factorial.

Scanner s = new Scanner(System.in);


System.out.println("Enter n: ");
int n = s.nextInt();
int product = 1;
int counter = 2;
while (counter <= n) {
product *= counter;
counter++;
}
System.out.println(n + " factorial is " + product);

15. Write a program that asks the user to enter two values: x and y. You must then compute the product of all integers
from x to y. For example, if the user has entered 10 and 7, then the output should be 5040 (because 7 * 8 * 9 * 10
= 5040).

Scanner s = new Scanner(System.in);


System.out.println("Enter x: ");
int x = s.nextInt();
System.out.println("Enter y: ");
int y = s.nextInt();
int stepAmount; // determines whether to count up or down
if (x < y) {
stepAmount = 1;
} else {
stepAmount = -1;
}
int product = x; // to accumulate the answer
int counter = x; // will go from x to y in steps of "stepAmount"
while (counter != y) {
counter += stepAmount;
product *= counter;
}
System.out.println("Product is: " + product);

16. Write a program that simulates the reading password process you go through while logging into a computer
account. The program will ask for a password, compare the value against two possible passwords (that are built-
in), and print "Welcome" if the password provided by the user is valid. Otherwise, ask the user to enter the
password again. (This process repeats.)

final String password1 = "hello";


final String password2 = "there";
Scanner s = new Scanner(System.in);
String entry;
do {
System.out.println("Enter password: ");
entry = s.next();
} while (!(entry.equals(password1) || entry.equals(password2)));
System.out.println("Welcome!");

17. Write a program that asks the user to enter the number of rows and columns. It will then print out a rectangular
grid of asterisks. For example, if the user has entered 6 rows and 3 columns, then the output should be:

***
***
***
***
***
***
Scanner s = new Scanner(System.in);
System.out.println("Rows: ");
int rows = s.nextInt();
System.out.println("Cols: ");
int cols = s.nextInt();
int rowCounter = 0;
while (rowCounter++ < rows) {
int colCounter = 0;
while (colCounter++ < cols) {
System.out.print("*");
}
System.out.println();
}

18. Write a program that asks the user for a size (an integer). The program will then print out four different triangles
made out of asterisks of that size. (You will need to print out spaces sometimes in front of the asterisks.) Below is
the output if the user selected size 4:

****
***
**
*

*
**
***
****

****
***
**
*

*
**
***
****
Scanner s = new Scanner(System.in);
System.out.println("Size: ");
int size = s.nextInt();
int rowCounter;
rowCounter = 0;
while (rowCounter++ < size) {
int colCounter = 0;
while (colCounter++ <= size - rowCounter) {
System.out.print("*");
}
System.out.println();
}
System.out.println();

rowCounter = 0;
while (rowCounter++ < size) {
int colCounter = 0;
while (colCounter++ < rowCounter) {
System.out.print("*");
}
System.out.println();
}
System.out.println();

rowCounter = 0;
while (rowCounter++ < size) {
int colCounter = 0;
while(colCounter++ < size) {
if (colCounter < rowCounter) {
System.out.print(" ");
} else {
Sytem.out.print("*");
}
}
System.out.println();
}
System.out.println();

rowCounter = 0;
while (rowCounter++ < size) {
int colCounter = 0;
while(colCounter++ < size) {
if (colCounter <= size - rowCounter) {
System.out.print(" ");
} else {
Sytem.out.print("*");
}
System.out.println();
}

19. Write a program that asks the user for a size, and then prints out a multiplication table of that size. (You don't
have to worry about spacing correctly, just try to get the numbers to all come out on the right rows.) For example,
if the user requests size 4, the output should be:

1234
2468
3 6 9 15
4 8 12 16
Scanner s = new Scanner(System.in);
System.out.println("Size: ");
int size = s.nextInt();
int rowCounter = 0;
while (rowCounter++ < size) {
int colCounter = 0;
while (colCounter++ < size) {
System.out.print(colCounter * rowCounter + " ");
}
System.out.println();
}

Week 4 Study Questions

1. Go back to the loop questions from the previous week and implement them all using for-loops instead of while
loops!
2. What will the output be:

int x = 2, y = 7;
if (y < 1 && x++ < 7) {
System.out.println("hello");
}
System.out.println("x = " + x); Output: x = 2

3. What will the output be:

int x = 7;
int y = x++ + 3;
int z = 7 * --x + 4;
System.out.println("x = " + x + ", y = " + y + ", z = " + z); Output: x = 7, y = 10, z = 53

4. What will the output be:

int x = 5;
x += 7;
x -= 2;
x /= 2;
x *= 8;
x %= 11;
System.out.println(x); Output: 7

5. Write a chart showing the precedence of all of the following operators: = , < , ==, &&, ||, !=, ++, + (addition), +=,
--, *

++, --
*
+
<
==, !=
&&
||
=, +=

6. If two operators occur in the same expression, and they are on the same level in the precedence chart (it is a "tie"),
how do you decide which operator gets evaluated first? Go from left to right (unless they are assignment
operators, in which case go from right to left.)
7. Using parentheses indicate the order in which each of the following expressions will be evaluated or state that the
expression represents an invalid expression. You may assume that all variables are of type int.

x/y*z%w
x ++ + y ++
x + y + z != w % p * 2
x < y || z > m && y <= 4
((x / y) * z) % w
(x++) + (y++)
((x + y) + z) != ((w % p) * 2)
(x < y) || ((z > m) && (y <= 4))

8. Which of the following code fragments are OK, and which will cause problems?

int x = 52;
double y = x;
double x = 14;
int y = x;
int x = 7;
long y = x;
long x = 17L;
short y = x;
OK
NOT OK
OK
NOT OK

9. Show how to use "explicit casting" to force the troublesome examples in the previous question to work.

For part b:

int y = (int) x;

For part d:

short y = (short)x;

Week 5 Study Questions

1. What is meant by "the state" of an object? The data that the object maintains.
2. What is meant by "the behavior" of an object? These are "actions" that the object can perform.
3. How is the state of an object represented in the corresponding class definition? Using instance variables
4. How is the behavior of an object represented in the corresponding class definition? Using instance methods
5. What is "the heap"? The heap is the region in memory where Objects are stored. When objects are no longer
being used, that memory is "recycled" automatically so that it can be used by other Objects later.
6. What is a "reference variable"? A reference variable stores the memory address of an object. We say that the
variable "refers" to the object.
7. Draw the memory map (including the "variable stack" and the "heap") for the following code fragment:

double x = 7.9;
double y = x;
String q = new String("Cat");
String r = q;
String s = new String("Cat");
8. What is actually stored in the variable "q" in the previous question? q holds the memory location corresponding to
the place where the String "cat" is in RAM
9. Given the code fragment above, is it correct to say that "q is a String object"? Is it correct to say that "q refers to a
String object"? Is it correct to say that "x is a double"? Is it correct to say that "x refers to a double"? You should
NOT say "q is a String". You SHOULD say "q refers to a String". It is correct to say "x is a double", but you
should NOT say "x refers to a double", since x is not a reference variable.
10. How many String objects are actually created (instantiated) in the code fragment above? two
11. After the code fragment above has been executed, decide which of the following expressions are true and which
are false:

x == y
q == r
r == s
q == s
q.equals(r)
r.equals(s)
q.equals(s)
x == y TRUE
q == r TRUE
r == s FALSE
q == s FALSE
q.equals(r) TRUE
r.equals(s) TRUE
q.equals(s) TRUE

12. What is aliasing? Aliasing is having more than one reference variable that refer to the same object (for example, r
and q in the previous question.)
13. What is meant by the term "garbage" in Java? Write a code fragment that creates garbage. Any object that is on
the heap, but no longer referred to by any variable is called "garbage". Here is a short example:

String p = "junk";
p = "other";

(Now the String that says "junk" is garbage.)

14. Consider the assignment statement:

x = y;

If the variables are of type "int", does the integer get copied? If the variables are of type "String", does the String
get copied? For primitive types (like int), the data is copied. For reference variables (like a String reference), the
memory locations are copied, NOT the objects themselves.

15. Write a class called "Cat". Invent a few "instance variables" that make sense for a Cat. Write some instance
methods (behaviors) that Cats should be able to do. Make sure that you have practiced some method(s) that
require parameters to be passed in. Make sure that you have practiced some methods that return a value. Answers
will vary...
16. Write a driver for the Cat class that you created above. The driver should create a few Cats and then test out all of
the methods that you have written. Try to test everything thoroughly! Answers will vary…

Week 6 Study Questions

1. Continue writing the "Cat" class mentioned in the previous week's questions. Add an equals method and a
toString method that returns the state of the Cat in some reasonable String format. (Answers vary)
2. Write a class whose members include a few static variables and a few static methods. Then write a driver that
calls the static methods and uses the static variables in some way. (Answers vary)
3. True/False: In order to run a static method, you must run it for a particular object (the current object). False
4. True/False: In order to run an instance method, you must run it for a particular object (the current object). True
5. True/False: An instance variable can be declared as "static". False
6. True/False: The same class can contain some members that are static and some members that are non-static. True
7. Which kinds of variables are given default values if you do not initialize them? (Local/ instance/static? Which
ones?) instance and static
8. What default values are used for the variables mentioned above? 0 for all primitive types (false for boolean,
ASCII code 0 for char); "null" for reference variables
9. When writing JUnit tests, is it better to write many small tests, or a few long ones? Lots of small ones
10. What is JUnit? A useful feature of Java that allows us to quickly write "unit tests" for classes we are writing. The
tests can be run conveniently and repeatedly so that as changes are made to the code we can quickly verify that
everything still works properly!
11. Give an example of the correct syntax for "assertTrue" in a JUnit test. assertTrue(x < 4); // test will pass if and
only if the value of x is less than 4

If a JUnit test has several separate assertions in it, will the test continue after one of the assertions fails? No

12. If a JUnit test suite has several different JUnit tests in it (separate methods), will the rest of the tests run after one
of them fails? Yes

Week 7 Study Questions

1. In what kind of methods does it make sense to use "this"? Instance methods and constructors.
2. What does "this" refer to? The "current object".
3. If you do not write any constructors, what values will instance variables of the following primitive types be
assigned: int, double, boolean, char ? 0 for int, 0.0 for double, false for boolean, ASCII code 0 for char
4. If you do not write any constructors, what values will instance variables that are references by assigned? null
5. Under what circumstances will Java provide a default constructor for you automatically? If you do not write any
constructors yourself.
6. What is a copy constructor? Give an example. The copy constructor accepts an argument that is the same type as
the object being constructed. It initializes the fields of the current object to match that of the parameter. Example:

public Cat(Cat x) {
numWhiskers = x.numWhiskers;
name = x.name;
}

7. What is a Stack (in general, not just in Java)? A stack is a simple linear data type in which elements are both
inserted ("pushed") and removed ("popped") from the same end. (We usually picture the stack vertically, and say
that we "push" and "pop" items from the top.)
8. When you push an entry into the stack does it go on the top or bottom? top
9. When you pop an entry from the stack, does it come off the top or bottom? top
10. Draw a diagram showing both the Stack and the Heap at the moment this program terminates:

public static void main(String[] args) {

int x = 0;
String y = new String("xyz");
String z = y;
String a = new String(y);
f(x, y, z, a);
}

public static void f(int j, String k, String m, String r) {


System.exit(1);
}

11. True/False: In java, when you pass a reference variable as an argument to a method, it is possible for the method
to modify the object to which the variable refers. TRUE
12. What does API stand for? Application Programming Interface
13. If someone showed you a Java class, how can you quickly identify which members were part of the API for that
class? Look for "public" members.
14. If a member is declared as public, can it be accessed from inside the same class? YES.
15. If a member is declared as public, can it be accessed from another class? YES
16. If a member is declared as private, can it be accessed from inside the same class? YES
17. If a member is declared as private, can it be accessed from another class? No
18. What is a "setter"? A method that modifies the value of an instance variable of the object.
19. What is a "getter"? A method that returns the value of an instance variable of the object.
20. Explain why it is important to limit the number of public members. Encapsulation of the fields (instance
variables) of a class is very important. We frequently need to make changes to a class. If these changes do not
modify the class API, then the modified class will work perfectly well within an existing project. However, if you
modify the class in such a way that the API is changed, then you will have to re-program other components of the
project so that they will work with the new class. By limiting the API we are free to make more extensive changes
to the class without having to re-program other parts of the project.
21. Name and describe the two visibility specifiers that you should know at this point. public: these members are
visible everywhere
private: these members are visible only within the class
22. True/False: If you change a class in such a way that the API changes, then other classes which depend on this one
will have to be re-coded. TRUE
23. True/False: If you change a class without modifying the API, then other classes which depend on this one will
have to be re-coded. FALSE
24. What package is the Scanner class located in? What is the fully qualified name of the Scanner class? java.util is
the package. The fully qualified name is "java.util.Scanner"
25. What is accomplished when you type "import java.awt.Color;" at the top of a file? Now whenever you type
"Color", the compiler knows that you are talking about the Color class that resides in the package called
"java.awt".
26. What is accomplished when you type "import java.awt.*;" at the top of a file? You are importing EVERYTHING
that is in the package java.awt.
27. Which java package is automatically imported in its entirety into every Java program you write? java.lang
28. What method of the String class can be used to pick out one particular character in the string? charAt
29. What method of the String class can tell you how many characters are in the String? length
30. What method of the String class can be used to compare to Strings for alphabetical order? compareTo
31. What method of the String class can select a portion of an existing String? substring
32. Write a method called "count". The method should be public and static. It takes one parameter, (a reference to a
String). The method will return an int. The return value should be equal to the number of X's that appear in the
String. For example, if the parameter is: "XaXXXbXXc" then the return value would be 6.

public static int count(String s) {

int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == 'X') {
count++;
}
}
return count;
}

Week 8 Study Questions

1. What is the output for the following program?

public class Nonsense {

public static void foo(int x) {


if (x == 2) {
throw new NullPointerException();
} else if (x == 3) {
throw new NumberFormatException();
}
System.out.println("A");
}

public static void main(String[] args) {


for (int i = 1; i <= 3; i++) {
try {
foo(i);
System.out.println("B");
} catch (NullPointerException e) {
System.out.println("C");
} finally {
System.out.println("D");
}
System.out.println("E");
}
System.out.println("F");
}
}

A,B,D,E,C,D,E,D

2. Consider the following class:

public class Tornado {

private static final int MAX_STRENGTH = 7;


public String name = "Bill";
private void causeDamage() {
// imagine code here
}

public static int calculateTrajectory() {


// imagine code here
}
}
Below, assume that the variable "t" refers to a Tornado object. The table below has rows corresponding to various
expressions related to the Tornado class. The columns list various places where one might consider using those
expressions. Clearly place a "V" in any box where the corresponding expression is valid syntax when used in the
corresponding context.
static method non-static method of method of some
of Tornado class Tornado class other class
name V
MAX_STRENGTH V
V
causeDamage() V
calculateTrajectory() V
V
t.name V V
V
t.MAX_STRENGTH V
V
t.causeDamage() V
V
t.calculateTrajectory() V V
V
Tornado.name
Tornado.MAX_STRENGTH V
V
Tornado.causeDamage()
Tornado.calculateTrajectory() V V
V

3. Where can you use a "continue" statement? Inside of any loop.


4. Describe how a continue statement behaves in a while loop. Goes to top of loop immediately and checks the
boolean condition to see if looping should continue.
5. Describe how a continue statement works in a for-loop. It will execute the statement that is usually processed at
the end of an iteration through the loop, and then check the boolean condition to see if looping should continue.
6. Where can you use a "break" statement? Either in a switch statement or in a loop. (We will learn about "switch"
statements later.)
7. Describe how a break statement behaves. Causes the inner-most loop or switch statement to be exited
immediately.
8. Write some faulty code that generates a null-pointer exception, catch the exception immediately and print out
"exception caught" in your catch block.

String s = null;
try {
int x = s.length(); // throws exception
} catch (NullPointerException e) {
System.out.println("exception caught");
}

9. Write some code that prompts the user for a numerical value, and reads their input into an int variable. Run the
program, and try entering some text (like "cat") instead of a number. Notice what kind of exception is thrown.
Now modify your program so that it catches this exception, and instead of crashing the program, have it tell the
user that he/she must enter a NUMBER, and then prompt them for input again.

Scanner s = new Scanner(System.in);

boolean goodNumberEntered = false;

while (true) {
System.out.println("enter a number: ");
try {
int n = s.nextInt();
} catch(java.util.InputMismatchException e) {
s.nextLine(); //removes previous input from stream
System.out.println("No, you MUST ENTER A NUMBER!");
continue;
}
break;
}

10. Write a method called smallSum that takes two int parameters, x and y. If the absolute value of the sum of the
integers is more than 100, throw an ArithmeticException, passing the String "I don't like big numbers" to the
constructor of the exception. If the sum is less than 100, then return the sum. Write a quick driver to test out your
method. After making sure everything works correctly, modify the driver so that it catches the exception and
prints out the message that was passed to the exception's constructor, but doesn't crash the program.

public static int smallSum(int x, int y) {


if (Math.abs(x + y) > 100) {
throw new ArithmeticException("I don't like big numbers!");
}
return x + y;
}

public void static main(String[] args) {


try {
smallSum(50, 60);
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
}
}

11. Explain the relationship between exception handling and the call stack. What happens if an exception is thrown
but not caught anywhere in your program? When an exception is thrown, Java looks for an appropriate catch
block in the place where the problem occurred. If a catch is not found there, then Java discards the current frame
on the call stack, and looks for an appropriate catch block in the previous frame. If none is found, that frame is
discarded, etc. If the exception is not caught anywhere, then the program terminates, and the exception propagates
to the "outside world", which for us is the Eclipse IDE. Eclipse displays that red and blue error notification with
stack trace in the console.
12. Under what circumstances will the finally block run? As long as the "try" block has been entered, the finally block
will run (no matter how you leave!)

Week 9 Study Questions

1. Define the terms mutable and immutable. The state of a mutable object may change over time. If an object is
immutable, it's state is set when it is constructed and will never vary after that.
2. Are String objects mutable? NO
3. Are Integer objects mutable? (If you're not sure, inspect the online API documentation for the Integer class and
find out!) NO
4. True/False -- Aliasing can lead to problems if the object is mutable. True
5. True/False --Aliasing can lead to problems if the object is immutable. False
6. Suppose you are passing (or returning) an array of primitives to/from a method. Is it safe to make a reference
copy only? NO
7. Suppose you are passing (or returning) an array of references to immutable objects to/from a method. Is it safe to
make a reference copy only? Is it safe to make a shallow copy? NO, YES
8. Suppose you are passing or returning an array of references to mutable objects to/from a method. Is it safe to
make a reference copy only? Is it safe to make a shallow copy? NO, NO
9. How many ints are created by the statement: int[] a = new int[5]; 5 ints are created -- all 0.
10. How many Strings are created by the statement: String[] a = new String[5]; (Hint: The answer to this question
and the previous question are different!) None! (Just 5 null references are created -- no objects are instantiated).
11. Are the elements of an array of primitives automatically initialized? If so, to what values? Yes, 0
12. Are the elements of an array of references to objects initialized? If so, to what values? Yes, null
13. Draw the memory diagram for each of the following code fragments:

int[] a = new int[4];


Should have a variable on the call stack which points to an array on the heap of size 4. Each box in the
array contains a zero.
String[] b = new String[4];
for (int i = 0; i < b.length; i++) {
b[i] = "value " + i;
}
Should have a variable on the call stack which points to an array on the heap of size 4. Each box in the
array points to a String. The strings say "value0", "value1", "value2", and "value3".

14. Write a method with the prototype shown below. The return value will be an exact copy of the parameter, but
each value from the parameter will be represented twice. For example, if the parameter is the array [2, 5, 9] then
the return value will be the array [2, 2, 5, 5, 9, 9]

public static int[] duplicate(int[] a)

int[] r = new int[a.length * 2];


for (int i = 0; i < a.length; i++) {
r[i * 2] = a[i];
r[i * 2 + 1] = a[i];
}
return r;

15. Write a method with the prototype shown below. The return value will be an exact copy of the parameter, but
with the even numbers removed. For example, if the parameter is the array [7, 4, 19, 8, 11] then the return value
will be [7, 19, 11].

public static int[] oddOnly(int[] a)

int oddCount = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] % 2 == 1) {
oddCount++;
}
}
int[] r = new int[oddCount];
int pos = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] % 2 == 1) {
r[pos++] = a[i];
}
}
return r;

16. Write a class that has an instance variable which is an array of Cat objects, called kitties. Write a method that
returns a reference copy of kitties. Write a method that returns a shallow copy of kitties. Write a method that
returns a deep copy of kitties.

public class Circus {

private Cat[] kitties;

public Cat[] referenceCopy() {


return kitties;
}

public Cat[] shallowCopy() {


Cat[] copy = new Cat[kitties.length];
for (int i = 0; i < copy.length; i++) {
copy[i] = kitties[i];
}
return copy;
}

public Cat[] deepCopy() {


Cat[] copy = new Cat[kitties.length];
for (int i = 0; i < copy.length; i++) {
copy[i] = new Cat(kitties[i]);
}
return copy;
}
}

Week 10 Study Questions

1.
A. Write a code fragment that creates a two-dimensional ragged array of ints with 3 rows, initialized with the
following data:

5 8 9
4 11 13 15 17
0 1
int[][] x = {{5, 8, 9}, {4, 11, 13, 15, 17}, {0, 1}};

B. After you have created this array, write code that will print the contents in the same format that you see
above.

for (int row = 0; row < x.length; row++) {


for (int col = 0; col < x[row].length; col++) {
System.out.print(x[row][col] + " ");
}
System.out.println();
}
C. Draw the memory map for this array.

x should appear on the stack.


x should refer to a "row array" on the heap of size 3. The first element of the "row array" will refer to an
array of size 3 that contains 5, 8, and 9. The second element of the "row array" will refer to an array of
size 5 that contains 4, 11, 13, 15, and 17. The third element of the "row array" will refer to an array of size
2 that contains 0 and 1.

2.
A. Write a method called catDuplicator, with the following prototype:

public Cat[][] catDuplicator(int[] rowSizes, Cat c)

The method will create a two-dimensional ragged array, using the array "rowSizes" to determine how
many rows there are, and how long each row must be. Each element of the array that gets created will
refer to the very same cat, c.

For example, if the array rowSizes contains the data: 5 7 2 1 then the return value would be a two-
dimensional ragged array with four rows. The first row would be size 5, the second row would be size 7,
etc. Each element of the two-dimensional array must be a reference to c.

public static Cat[][] catDuplicator(int[] rowSizes, Cat c) {


Cat[][] answer = new Cat[rowSizes.length][];
for (int i = 0; i < rowSizes.length; i++) {
answer[i] = new Cat[rowSizes[i]];
}
for (int i = 0; i < answer.length; i++) {
for (int j = 0; j < answer[i].length; j++) {
answer[i][j] = c;
}
}
return answer;
}

B. Draw the memory map for the method above.

The variable c is on the stack and it refers to ONE cat on the heap. The variable answer is on the stack and
it refers to a "row array" that is the same length as the length of the array rowSizes. Each element of the
"row array" refers to a row. A row is an array of references (the sizes of the rows match the entries in the
array rowSizes). Each element of each row refers to the very same cat that c refers to!

3. Write code that asks the user for a value (n), and then creates an n by n two-dimensional array of ints. Fill the
array with a multiplication table. For example, if n is 3, the table should be:

1 2 3
2 4 6
3 6 9
System.out.println("Enter n: ");
java.util.Scanner s = new java.util.Scanner(System.in);
int size = s.nextInt();
int[][] a = new int[size][size];
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
a[row][col] = (row + 1) * (col + 1);
}
}

4.
A. Write a method which has the following prototype:

public static double[] linearize(double[][] array)

The method linearizes the two-dimensional array by returning a one-dimensional array with all the
elements of the parameter (selected row-by-row). The original array cannot be modified.

public static double[] linearize(double[][] array) {


int size = 0;
for (int i = 0; i < array.length; i++) {
size += array[i].length;
}
double[] answer = new double[size];
int position = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
answer[position++] = array[i][j];
}
}
return answer;
}

B. Write a JUnit test that tests your method.

public void testLinearize() {


double[][] x = {{5, 2, 3}, {8, 9}, {7, 11, 15}};
double[] correctAnswer = {5, 2, 3, 8, 9, 7, 11, 15};
double[] answer = MyClass.linearize(x);
for (int i = 0; i < x.length; i++) {
assertEquals(correctAnswer[i], answer[i]);
}
}

5. Write a method called "deepCopy" that takes a parameter (a two-dimensional array of String objects) and returns
a deep copy. (You must make copies of the Strings themselves, even though they are immutable.)

public static String[][] deepCopy(String[][] a) {


String[][] copy = new String[a.length][];
for (int i = 0; i < copy.length; i++) {
copy[i] = new String[a[i].length];
}
for (int i = 0; i < copy.length; i++) {
for (int j = 0; j < copy[i].length; j++) {
copy[i][j] = new String(a[i][j]);
}
}
return copy;
}

Week 11 Study Questions


1. What is a Java interface? Typically, it is just a collection of method prototypes that are implemented by several
related classes.
2. What is polymorphism? Sometimes a single variable can refer to objects of different types. For example, if you
have an interface called "CanFly", then you can create a variable of type "CanFly" which can refer to any kind of
object that knows how to fly. (In other words, it can refer to an object of any class which implements the
"CanFly" interface.) This kind of variable is "polymorphic".
3. Suppose you have an interface called CanDance, and three classes (Student, Penguin, and Cow) all of which
implement the CanDance interface. Also assume that there is a method available with the following prototype:
public static doSquareDance(CanDance a) Decide which of the following code fragments are reasonable:
a. CanDance x = new CanDance(); NO
b. CanDance y = new Student(); YES
c. Student z = new CanDance(); NO
d. Student z = new Penguin(); NO
e. CanDance a;
a = new Student();
a = new Penguin();
a = new Cow(); YES
f. Penguin b = new Penguin();
doSquareDance(b); YES
g. Student c = new Student();
doSquareDance(c); YES
h. Cow d = new Cow();
doSquareDance(d); YES
i. CanDance e = new Student();
doSquareDance(e); YES

4. Answers to this question will vary!


a. Write a Car class. (Use your imagination.)
b. Now write an interface called "CanFixCars" with two method prototypes:

public void fixFlat(Car c);


public void fixRadiator(Car c);

c. Write three classes: CSMajor, MathMajor, and CEMajor, each of which implements the "CanFixCars"
interface. Be creative when implementing the methods. How do you think a Math Major would fix a flat
tire? :-)
d. In a separate class, write a static method with the following prototype:

public static fixCar(Car c, CanFixCars repairPerson)

The method should somehow determine what is wrong with the car (is it a flat tire, a broken radiator, or
something else) and have the repair person fix the car by calling the repair person's fixFlat or fixRadiator
methods.

e. Finally, write a main method that will create several broken cars, create several students of various kinds,
and have the students fix the cars. (I.e.: make several calls to your fixCar method.)
5. What does "method overloading" mean? Writing more than one method in the same class with the same name.
(This only works if the signatures of the methods are different - i.e. the parameter lists have different types.)
6. For each pair of methods, decide whether or not both methods could be implemented in the same class. If so,
could there ever be a situation where an ambiguity could arise?

void f(int x)
void f(int y)
Won't Work

int f(int x)
void f(int x)
Won't Work

void f(int x)
void f(double x)
FINE

void f(int x, int y)


void f(int y, int x)
Won't Work

void f(int x, String y)


void f(String y, int x)
FINE

void f(int x, double y)


void f(double x, int y)
Works, but method calls could be ambiguous. For example:

f(2, 3)
will not compile.

Week 12 Study Questions

1. Using a switch statement, write a method that accepts one parameter, a char, which is expected to be a capital
letter from A to Z. The method will return the number of "pen-strokes" that are required to draw the letter. For
example, the letter Z requires three strokes (top, bottom, diagonal section) and the letter P requires two (the
straight part, and the curved part). You must avoid duplicative code. If the parameter is not a letter in the range A
through Z, then have the method return 0.

public static int brushStrokes(char c) {


int returnValue;

switch(c) {
case 'C':
case 'O':
case 'S':
case 'U':
returnValue = 1;
break;
case 'D':
case 'G':
case 'J':
case 'L':
case 'P':
case 'Q':
case 'T':
case 'V':
case 'X':
returnValue = 2;
break;
case 'A':
case 'B':
case 'F':
case 'H':
case 'I':
case 'K':
case 'N':
case 'R':
case 'Y':
case 'Z':
returnValue = 3;
break;
case 'E':
case 'M':
case 'W':
returnValue = 4;
break;
default:
returnValue = 0;
}
return returnValue;
}

2. If you write a switch statement like this: switch(x) {...} What types could the variable x be? int, short, byte, char,
String
3. If you are working on a Java project outside of eclipse, what command would you type to compile a file called
"Fish.java"? javac Fish.java
4. If you are working on a Java project outside of eclipse, what command would you type to run the main method of
a bytecode file called "Fish.class"? java Fish
5. What is the purpose of the parameter "arg" in the prototype for the standard main method? It allows data to be
passed to the program at the moment the program is executed.
6. For practice, write a Java program without using Eclipse. The program will take three parameters from the
command line. It will print a substring of the first parameter, using the other two parameters to specify the starting
and ending location. For example, if the user runs the program like this: java SubstringMaker ABCDEFGHIJKL 4
7 then the output would be: EFGH

public class SubstringMaker {


public static void main(String[] args) {
int start = Integer.parseInt(args[1]);
int end = Integer.parseInt(args[2]);
System.out.println(args[0].substring(start, end + 1);
}
}

Week 13 Study Questions

1. If you write a class without specifying a particular package, which package will it become part of? default
package
2. What syntax would you use at the top of a source-code file to specify that the class belongs in a subpackage called
"stuff" that is part of a larger package called "junk"? package junk.stuff;
3.
a. Just for practice, write your own MyStack class which stores Integer objects. Use a private array of
Integer objects to store the data. You should include the methods "push" and "pop". Write a JUnit test to
check if everything is working.
b. Now modify your code so that it uses an ArrayList instead of an array.
c. Now that you've gone to all that trouble, modify your JUnit test so that it works with objects of type
Stack instead of MyStack.
4. Write code that stores 50 randomly generated floating point numbers in an ArrayList. Use a regular for-loop to
cycle through the values and remove any that are less than 0.5. Then use a for-each loop to print out the values
that remain.
ArrayList list = new ArrayList();
for (int i = 0; i < 50; i++) {
list.add(Math.random());
}
for (int i = 0; i < list.size(); i++) {
if (list.get(i) < 0.5) {
list.remove(i);
i--;
}
}
for (Double x : list) {
System.out.println(x);
}

5. Write code that creates an ArrrayList and then uses a for-each to cycle through. Try inserting something into the
arrayList in the loop where you are using the Iterator. What happens? You'll find that your code throws a
"ConcurrentModificationException". You cannot insert or delete things from a list as your are going through the
list with a for-each loop.
6. What do you accomplish by using "extends"? (What does it mean to write: public class A extends B)? "extends"
allows the class A to "inherit" all of the elements from B (variables and methods). A can also have other features
of its own, and it can "over-ride" some of B's features if you want.
7. What does it mean to say a class is derived from another class? "A is derived from B" is the same thing as "A
extends B".
8. What does it mean to say a class "inherits" members from another class? The derived class automatically includes
those features.

Week 14 Study Questions

1. What is method overriding? How is it different from overloading? Over-riding means replacing an inherited
method with a different version. When over-riding, the method prototype in the subclass matches the prototype
from the super class. With overloading, the names of the methods are the same, but the parameter lists must be
different.
2. Draw an inheritance diagram (with the arrows going the correct direction) illustrating how the Animal Kingdom
is organized. (It doesn't have to be very scientific, unless you are an overachiever.) (answers vary)
3. Write a class called Animal that has a few instance variables. Write a correct equals method for your Animal
class. Be sure your parameter is type Object (so that you are over-riding the equals method from the Object class).
Don't forget that you will need to use a casting operator to access the instance variables for the parameter!

If we assume the Animal class has just one instance variable, and int called "size", then the correct answer is:

public boolean equals(Object o) {

if (! (o instanceof Animal)) {
return false;
}
Animal a = (Animal)o;

return a.size == size;


}

4. Fill in the method below, which will return the product of the two parameters. You may assume the parameters
are not negative. You may not use loops. You may not use the multiplication operator. You may create a private
helper method if you think it will help.

public static int multiply(int a, int b) {


public static int multiply(int a, int b) {
if (b == 0) {
return 0;
}
return a + multiply(a, b - 1);
}

5. Write a method called "findLargest". It will take an int array as a parameter and return an int. The method will
return the largest integer in the array. You may not use any loops, and you may not create any arrays. You may
create a private helper method if you think it will help.

public static int findLargest(int[] list) {


return findLargestHelper(list, 0);
}

private static int findLargestHelper(int[] list, int position) {


if (position == list.length - 1) {
return list[position];
}
int largestInTheRest = findLargestHelper(list, position + 1);
return (list[position] > largestInTheRest)? list[position] : largestInTheRest;
}

6. Fill in the method below. It will remove all instances of the second parameter from the list. You may not use any
loops. You may create a private helper method if you think it will help.

public static remove(ArrayList list, String toRemove) {


public static void remove(ArrayList list, String toRemove) {
removeHelper(list, toRemove, 0);
}

private static void removeHelper(ArrayList list, String toRemove, int position) {


if (position == list.size()) {
return;
}
removeHelper(list, toRemove, position + 1);
if (list.get(position).equals(toRemove)) {
list.remove(position);
}
}

S-ar putea să vă placă și