Module 1 Flashcards
Which of the following are valid Java identifiers? (Choose all that apply)
A. A$B
B. _helloWorld
C. true
D. java.lang
E. Public
F. 1980_s
A, B, E
What is the output of the following program?
1: public class WaterBottle {
2: private String brand;
3: private boolean empty;
4: public static void main(String[] args) {
5: WaterBottle wb = new WaterBottle();
6: System.out.print(“Empty = “ + wb.empty);
7: System.out.print(“, Brand = “ + wb.brand);
8: } }
A. Line 6 generates a compiler error.
B. Line 7 generates a compiler error.
C. There is no output.
D. Empty = false, Brand = null
E. Empty = false, Brand =
F. Empty = null, Brand = null
D. Boolean fields initialize to false and references initialize to null, so empty is false
and brand is null. Brand = null is output.
Which of the following are true? (Choose all that apply)
4: short numPets = 5;
5: int numGrains = 5.6;
6: String name = “Scruffy”;
7: numPets.length();
8: numGrains.length();
9: name.length();
A. Line 4 generates a compiler error.
B. Line 5 generates a compiler error.
C. Line 6 generates a compiler error.
D. Line 7 generates a compiler error.
E. Line 8 generates a compiler error.
F. Line 9 generates a compiler error.
G. The code compiles as is
B, D, E. Option A (line 4) compiles because short is an integral type. Option B (line
5) generates a compiler error because int is an integral type, but 5.6 is a floating-point
type. Option C (line 6) compiles because it is assigned a String. Options D and E (lines
7 and 8) do not compile because short and int are primitives. Primitives do not allow
methods to be called on them. Option F (line 9) compiles because length() is defined
on String
Given the following class, which of the following is true? (Choose all that apply)
1: public class Snake {
2:
3: public void shed(boolean time) {
4:
5: if (time) {
6:
7: }
8: System.out.println(result);
9:
10: }
11: }
A. If String result = “done”; is inserted on line 2, the code will compile.
B. If String result = “done”; is inserted on line 4, the code will compile.
C. If String result = “done”; is inserted on line 6, the code will compile.
D. If String result = “done”; is inserted on line 9, the code will compile.
E. None of the above changes will make the code compile.
A, B. Adding the variable at line 2 makes result an instance variable. Since instance
variables are in scope for the entire life of the object, option A is correct. Option B is
correct because adding the variable at line 4 makes result a local variable with a scope
of the whole method. Adding the variable at line 6 makes result a local variable with
a scope of lines 6–7. Since it is out of scope on line 8, the println does not compile and
option C is incorrect. Adding the variable at line 9 makes result a local variable with
a scope of lines 9 and 10. Since line 8 is before the declaration, it does not compile and
option D is incorrect. Finally, option E is incorrect because the code can be made to
compile
Given the following classes, which of the following can independently replace INSERT
IMPORTS HERE to make the code compile? (Choose all that apply)
package aquarium;
public class Tank { }
package aquarium.jellies;
public class Jelly { }
package visitor;
INSERT IMPORTS HERE
public class AquariumVisitor {
public void admire(Jelly jelly) { } }
A. import aquarium.;
B. import aquarium..Jelly;
C. import aquarium.jellies.Jelly;
D. import aquarium.jellies.;
E. import aquarium.jellies.Jelly.;
F. None of these can make the code compile.
C, D. Option C is correct because it imports Jelly by classname. Option D is correct because it imports all the classes in the jellies package, which includes Jelly.
Option A is incorrect because it only imports classes in the aquarium package—Tank
in this case—and not those in lower-level packages. Option B is incorrect because you
cannot use wildcards anyplace other than the end of an import statement. Option E is
incorrect because you cannot import parts of a class with a regular import statement.
Option F is incorrect because options C and D do make the code compile.
Given the following classes, what is the maximum number of imports that can be removed
and have the code still compile?
package aquarium; public class Water { }
package aquarium;
import java.lang.;
import java.lang.System;
import aquarium.Water;
import aquarium.;
public class Tank {
public void print(Water water) {
System.out.println(water); } }
A. 0
B. 1
C. 2
D. 3
E. 4
F. Does not compile.
E. The first two imports can be removed because java.lang is automatically imported.
The second two imports can be removed because Tank and Water are in the same package, making the correct answer E. If Tank and Water were in different packages, one of
these two imports could be removed. In that case, the answer would be option D.
Given the following classes, which of the following snippets can be inserted in place of
INSERT IMPORTS HERE and have the code compile? (Choose all that apply)
package aquarium;
public class Water {
boolean salty = false;
}
package aquarium.jellies;
public class Water {
boolean salty = true;
}
package employee;
INSERT IMPORTS HERE
public class WaterFiller {
Water water;
}
A. import aquarium.;
B. import aquarium.Water;
import aquarium.jellies.;
C. import aquarium.;
import aquarium.jellies.Water;
D. import aquarium.;
import aquarium.jellies.*;
E. import aquarium.Water;
import aquarium.jellies.Water;
F. None of these imports can make the code compile.
A, B, C. Option A is correct because it imports all the classes in the aquarium package
including aquarium.Water. Options B and C are correct because they import Water by
classname. Since importing by classname takes precedence over wildcards, these compile. Option D is incorrect because Java doesn’t know which of the two wildcard Water classes to use. Option E is incorrect because you cannot specify the same classname in
two imports.
Given the following class, which of the following calls print out Blue Jay? (Choose all that
apply)
public class BirdDisplay {
public static void main(String[] name) {
System.out.println(name[1]);
} }
A. java BirdDisplay Sparrow Blue Jay
B. java BirdDisplay Sparrow “Blue Jay”
C. java BirdDisplay Blue Jay Sparrow
D. java BirdDisplay “Blue Jay” Sparrow
E. java BirdDisplay.class Sparrow “Blue Jay”
F. java BirdDisplay.class “Blue Jay” Sparrow
G. Does not compile
B. Option B is correct because arrays start counting from zero and strings with spaces
must be in quotes. Option A is incorrect because it outputs Blue. C is incorrect because
it outputs Jay. Option D is incorrect because it outputs Sparrow. Options E and F are
incorrect because they output Error: Could not find or load main class BirdDisplay.class.
Which of the following legally fill in the blank so you can run the main() method from the
command line? (Choose all that apply)
public static void main( )
A. String[] _names
B. String[] 123
C. String abc[]
D. String _Names[]
E. String… $n
F. String names
G. None of the above.
A, C, D, E. Option A is correct because it is the traditional main() method signature
and variables may begin with underscores. Options C and D are correct because the
array operator may appear after the variable name. Option E is correct because
varargs are allowed in place of an array. Option B is incorrect because variables are
not allowed to begin with a digit. Option F is incorrect because the argument must be
an array or varargs. Option F is a perfectly good method. However, it is not one that
can be run from the command line because it has the wrong parameter type
Which of the following are legal entry point methods that can be run from the command
line? (Choose all that apply)
A. private static void main(String[] args)
B. public static final main(String[] args)
C. public void main(String[] args)
D. public static void test(String[] args)
E. public static void main(String[] args)
F. public static main(String[] args)
G. None of the above.
E. Option E is the canonical main() method signature. You need to memorize it.
Option A is incorrect because the main() method must be public. Options B and F
are incorrect because the main() method must have a void return type. Option C is
incorrect because the main() method must be static. Option D is incorrect because the
main() method must be named main.
Which of the following are true? (Choose all that apply)
A. An instance variable of type double defaults to null.
B. An instance variable of type int defaults to null.
C. An instance variable of type String defaults to null.
D. An instance variable of type double defaults to 0.0.
E. An instance variable of type int defaults to 0.0.
F. An instance variable of type String defaults to 0.0.
G. None of the above.
C, D. Option C is correct because all non-primitive values default to null. Option D is
correct because float and double primitives default to 0.0. Options B and E are incorrect because int primitives default to 0
- Which of the following are true? (Choose all that apply)
A. A local variable of type boolean defaults to null.
B. A local variable of type float defaults to 0.
C. A local variable of type Object defaults to null.
D. A local variable of type boolean defaults to false.
E. A local variable of type boolean defaults to true.
F. A local variable of type float defaults to 0.0.
G. None of the above
G. Option G is correct because local variables do not get assigned default values. The
code fails to compile if a local variable is not explicitly initialized. If this question
were about instance variables, options D and F would be correct. A boolean primitive
defaults to false and a float primitive defaults to 0.0.
Which of the following are true? (Choose all that apply)
A. An instance variable of type boolean defaults to false.
B. An instance variable of type boolean defaults to true.
C. An instance variable of type boolean defaults to null.
D. An instance variable of type int defaults to 0.
E. An instance variable of type int defaults to 0.0.
F. An instance variable of type int defaults to null.
G. None of the above.
A, D. Options A and D are correct because boolean primitives default to false and
int primitives default to 0.
Given the following class in the file /my/directory/named/A/Bird.java:
INSERT CODE HERE
public class Bird { }
Which of the following replaces INSERT CODE HERE if we compile from /my/directory?
(Choose all that apply)
A. package my.directory.named.a;
B. package my.directory.named.A;
C. package named.a;
D. package named.A;
E. package a;
F. package A;
G. Does not compile.
D. The package name represents any folders underneath the current path, which is
named.A in this case. Option B is incorrect because package names are case sensitive,
just like variable names and other identifiers.
Which of the following lines of code compile? (Choose all that apply)
A. int i1 = 1_234;
B. double d1 = 1234.0;
C. double d2 = 1_234._0;
D. double d3 = 1234.0;
E. double d4 = 1_234.0;
F. None of the above.
A, E. Underscores are allowed as long as they are directly between two other digits.
This means options A and E are correct. Options B and C are incorrect because the
underscore is adjacent to the decimal point. Option D is incorrect because the underscore is the last character.
Given the following class, which of the following lines of code can replace INSERT CODE
HERE to make the code compile? (Choose all that apply)
public class Price {
public void admission() {
INSERT CODE HERE
System.out.println(amount);
} }
A. int amount = 9L;
B. int amount = 0b101;
C. int amount = 0xE;
D. double amount = 0xE;
E. double amount = 12.0_0;
F. int amount = 12;
G. None of the above.
B, C, D. 0b is the prefix for a binary value and is correct. 0x is the prefix for a hexadecimal value. This value can be assigned to many primitive types, including int and
double, making options C and D correct. Option A is incorrect because 9L is a long
value. long amount = 9L would be allowed. Option E is incorrect because the underscore is immediately before the decimal. Option F is incorrect because the underscore is
the very last character.
Which of the following are true? (Choose all that apply)
public class Bunny {
public static void main(String[] args) {
Bunny bun = new Bunny();
} }
A. Bunny is a class.
B. bun is a class.
C. main is a class.
D. Bunny is a reference to an object.
E. bun is a reference to an object.
F. main is a reference to an object.
G. None of the above.
A, E. Bunny is a class, which can be seen from the declaration: public class Bunny. bun
is a reference to an object. main() is a method.
Which represent the order in which the following statements can be assembled into a program that will compile successfully? (Choose all that apply)
A: class Rabbit {}
B: import java.util.*;
C: package animals;
A. A, B, C
B. B, C, A
C. C, B, A
D. B, A
E. C, A
F. A, C
G. A, B
C, D, E. package and import are both optional. If both are present, the order must
be package, then import, then class. Option A is incorrect because class is before
package and import. Option B is incorrect because import is before package. Option
F is incorrect because class is before package. Option G is incorrect because class is
before import.
Suppose we have a class named Rabbit. Which of the following statements are true?
(Choose all that apply)
1: public class Rabbit {
2: public static void main(String[] args) {
3: Rabbit one = new Rabbit();
4: Rabbit two = new Rabbit();
5: Rabbit three = one;
6: one = null;
7: Rabbit four = one;
8: three = null;
9: two = null;
10: two = new Rabbit();
11: System.gc();
12: } }
A. The Rabbit object from line 3 is first eligible for garbage collection immediately
following line 6.
B. The Rabbit object from line 3 is first eligible for garbage collection immediately
following line 8.
C. The Rabbit object from line 3 is first eligible for garbage collection immediately
following line 12.
D. The Rabbit object from line 4 is first eligible for garbage collection immediately
following line 9.
E. The Rabbit object from line 4 is first eligible for garbage collection immediately
following line 11.
F. The Rabbit object from line 4 is first eligible for garbage collection immediately
following line 12.
B, D. The Rabbit object from line 3 has two references to it: one and three. The references are nulled out on lines 6 and 8, respectively. Option B is correct because this
makes the object eligible for garbage collection after line 8. Line 7 sets the reference
four to the now null one, which means it has no effect on garbage collection. The Rabbit object from line 4 only has a single reference to it: two. Option D is correct because
this single reference becomes null on line 9. The Rabbit object declared on line 10
becomes eligible for garbage collection at the end of the method on line 12. Calling
System.gc() has no effect on eligibility for garbage collection.
What is true about the following code? (Choose all that apply)
public class Bear {
protected void finalize() {
System.out.println(“Roar!”);
}
public static void main(String[] args) {
Bear bear = new Bear();
bear = null;
System.gc();
} }
A. finalize() is guaranteed to be called.
B. finalize() might or might not be called
C. finalize() is guaranteed not to be called.
D. Garbage collection is guaranteed to run.
E. Garbage collection might or might not run.
F. Garbage collection is guaranteed not to run.
G. The code does not compile.
B, E. Calling System.gc() suggests that Java might wish to run the garbage collector.
Java is free to ignore the request, making option E correct. finalize() runs if an object
attempts to be garbage collected, making option B correct.
What does the following code output?
1: public class Salmon {
2: int count;
3: public void Salmon() {
4: count = 4;
5: }
6: public static void main(String[] args) {
7: Salmon s = new Salmon();
8: System.out.println(s.count);
9: } }
A. 0
B. 4
C. Compilation fails on line 3.
D. Compilation fails on line 4.
E. Compilation fails on line 7.
F. Compilation fails on line 8.
A. While the code on line 3 does compile, it is not a constructor because it has a return
type. It is a method that happens to have the same name as the class. When the code
runs, the default constructor is called and count has the default value (0) for an int.
Which of the following are true statements? (Choose all that apply)
A. Java allows operator overloading.
B. Java code compiled on Windows can run on Linux.
C. Java has pointers to specific locations in memory.
D. Java is a procedural language.
E. Java is an object-oriented language.
F. Java is a functional programming language.
B, E. C++ has operator overloading and pointers. Java made a point of not having
either. Java does have references to objects, but these are pointing to an object that can
move around in memory. Option B is correct because Java is platform independent.
Option E is correct because Java is object oriented. While it does support some parts of
functional programming, these occur within a class.
Which of the following are true? (Choose all that apply)
A. javac compiles a .class file into a .java file.
B. javac compiles a .java file into a .bytecode file.
C. javac compiles a .java file into a .class file.
D. Java takes the name of the class as a parameter.
E. Java takes the name of the .bytecode file as a parameter.
F. Java takes the name of the .class file as a parameter.
C, D. Java puts source code in .java files and bytecode in .class files. It does not use
a .bytecode file. When running a Java program, you pass just the name of the class
without the .class extension.
- Which of the following Java operators can be used with boolean variables? (Choose all that
apply)
A. ==
B. +
C. –
D. !
E. %
F. <=
A, D. Option A is the equality operator and can be used on numeric primitives, boolean values, and object references. Options B and C are both arithmetic operators and
cannot be applied to a boolean value. Option D is the logical complement operator
and is used exclusively with boolean values. Option E is the modulus operator, which
can only be used with numeric primitives. Finally, option F is a relational operator that
compares the values of two numbers
What data type (or types) will allow the following code snippet to compile? (Choose all that
apply)
byte x = 5;
byte y = 10;
_____ z = x + y;
A. int
B. long
C. boolean
D. double
E. short
F. byte
A, B, D. The value x + y is automatically promoted to int, so int and data types that
can be promoted automatically from int will work. Options A, B, D are such data
types. Option C will not work because boolean is not a numeric data type. Options E
and F will not work without an explicit cast to a smaller data type.
What is the output of the following application?
1: public class CompareValues {
2: public static void main(String[] args) {
3: int x = 0;
4: while(x++ < 10) {}
5: String message = x > 10 ? “Greater than” : false;
6: System.out.println(message+”,”+x);
7: }
8: }
A. Greater than,10
B. false,10
C. Greater than,11
D. false,11
E. The code will not compile because of line 4.
F. The code will not compile because of line 5.
F. In this example, the ternary operator has two expressions, one of them a String and
the other a boolean value. The ternary operator is permitted to have expressions that
don’t have matching types, but the key here is the assignment to the String reference.
The compiler knows how to assign the first expression value as a String, but the second boolean expression cannot be set as a String; therefore, this line will not compile.
What change would allow the following code snippet to compile? (Choose all that apply)
3: long x = 10;
4: int y = 2 * x;
A. No change; it compiles as is.
B. Cast x on line 4 to int.
C. Change the data type of x on line 3 to short.
D. Cast 2 * x on line 4 to int.
E. Change the data type of y on line 4 to short.
F. Change the data type of y on line 4 to long.
B, C, D, F. The code will not compile as is, so option A is not correct. The value 2 * x
is automatically promoted to long and cannot be automatically stored in y, which is
in an int value. Options B, C, and D solve this problem by reducing the long value to
int. Option E does not solve the problem and actually makes it worse by attempting
to place the value in a smaller data type. Option F solves the problem by increasing the
data type of the assignment so that long is allowed.
What is the output of the following code snippet?
3: java.util.List<Integer> list = new java.util.ArrayList<Integer>();
4: list.add(10);
5: list.add(14);
6: for(int x : list) {
7: System.out.print(x + ", ");
8: break;
9: }
A. 10, 14,
B. 10, 14
C. 10,
D. The code will not compile because of line 7.
E. The code will not compile because of line 8.
F. The code contains an infinite loop and does not terminate</Integer></Integer>
C. This code does not contain any compilation errors or an infinite loop, so options D,
E, and F are incorrect. The break statement on line 8 causes the loop to execute once
and finish, so option C is the correct answer.
What is the output of the following code snippet?
3: int x = 4;
4: long y = x * 4 - x++;
5: if(y<10) System.out.println(“Too Low”);
6: else System.out.println(“Just right”);
7: else System.out.println(“Too High”);
A. Too Low
B. Just Right
C. Too High
D. Compiles but throws a NullPointerException.
E. The code will not compile because of line 6.
F. The code will not compile because of line 7.
F. The code does not compile because two else statements cannot be chained together
without additional if-then statements, so the correct answer is option F. Option E is
incorrect as Line 6 by itself does not cause a problem, only when it is paired with Line
7. One way to fix this code so it compiles would be to add an if-then statement on
line 6. The other solution would be to remove line 7.
What is the output of the following code?
1: public class TernaryTester {
2: public static void main(String[] args) {
3: int x = 5;
4: System.out.println(x > 2 ? x < 4 ? 10 : 8 : 7);
5: }}
A. 5
B. 4
C. 10
D. 8
E. 7
F. The code will not compile because of line 4.
D. As you learned in the section “Ternary Operator,” although parentheses are not
required, they do greatly increase code readability, such as the following equivalent
statement:
System.out.println((x > 2) ? ((x < 4) ? 10 : 8) : 7)
We apply the outside ternary operator fi rst, as it is possible the inner ternary expression
may never be evaluated. Since (x>2) is true, this reduces the problem to:
System.out.println((x < 4) ? 10 : 8)
Since x is greater than 2, the answer is 8, or option D in this case.
What is the output of the following code snippet?
3: boolean x = true, z = true;
4: int y = 20;
5: x = (y != 10) ^ (z=false);
6: System.out.println(x+”, “+y+”, “+z);
A. true, 10, true
B. true, 20, false
C. false, 20, true
D. false, 20, false
E. false, 20, true
F. The code will not compile because of line 5.
B. This example is tricky because of the second assignment operator embedded in line
5. The expression (z=false) assigns the value false to z and returns false for the
entire expression. Since y does not equal 10, the left-hand side returns true; therefore,
the exclusive or (^) of the entire expression assigned to x is true. The output reflects
these assignments, with no change to y, so option B is the only correct answer. The
code compiles and runs without issue, so option F is not correct.
How many times will the following code print “Hello World”?
3: for(int i=0; i<10 ; ) {
4: i = i++;
5: System.out.println(“Hello World”);
6: }
A. 9
B. 10
C. 11
D. The code will not compile because of line 3.
E. The code will not compile because of line 5.
F. The code contains an infinite loop and does not terminate.
F. In this example, the update statement of the for loop is missing, which is fine as the
statement is optional, so option D is incorrect. The expression inside the loop increments i but then assigns i the old value. Therefore, i ends the loop with the same value that it starts with: 0. The loop will repeat infinitely, outputting the same statement over
and over again because i remains 0 after every iteration of the loop
What is the output of the following code?
3: byte a = 40, b = 50;
4: byte sum = (byte) a + b;
5: System.out.println(sum);
A. 40
B. 50
C. 90
D. The code will not compile because of line 4.
E. An undefined value.
D. Line 4 generates a possible loss of precision compiler error. The cast operator has
the highest precedence, so it is evaluated first, casting a to a byte. Then, the addition is
evaluated, causing both a and b to be promoted to int values. The value 90 is an int
and cannot be assigned to the byte sum without an explicit cast, so the code does not
compile. The code could be corrected with parentheses around (a + b), in which case
option C would be the correct answer
What is the output of the following code?
1: public class ArithmeticSample {
2: public static void main(String[] args) {
3: int x = 5 * 4 % 3;
4: System.out.println(x);
5: }}
A. 2
B. 3
C. 5
D. 6
E. The code will not compile because of line 3.
A. The * and % have the same operator precedence, so the expression is evaluated
from left-to-right. The result of 5 * 4 is 20, and 20 % 3 is 2 (20 divided by 3 is 18, the
remainder is 2). The output is 2 and option A is the correct answer.
What is the output of the following code snippet?
3: int x = 0;
4: String s = null;
5: if(x == s) System.out.println(“Success”);
6: else System.out.println(“Failure”);
A. Success
B. Failure
C. The code will not compile because of line 4.
D. The code will not compile because of line 5
D. The variable x is an int and s is a reference to a String object. The two data types
are incomparable because neither variable can be converted to the other variable’s type.
The compiler error occurs on line 5 when the comparison is attempted, so the answer
is option D.
What is the output of the following code snippet?
3: int x1 = 50, x2 = 75;
4: boolean b = x1 >= x2;
5: if(b = true) System.out.println(“Success”);
6: else System.out.println(“Failure”);
A. Success
B. Failure
C. The code will not compile because of line 4.
D. The code will not compile because of line 5.
A. The code compiles successfully, so options C and D are incorrect. The value of b
after line 4 is false. However, the if-then statement on line 5 contains an assignment,
not a comparison. The variable b is assigned true on line 3, and the assignment operator returns true, so line 5 executes and displays Success, so the answer is option A
What is the output of the following code snippet?
3: int c = 7;
4: int result = 4;
5: result += ++c;
6: System.out.println(result);
A. 8
B. 11
C. 12
D. 15
E. 16
F. The code will not compile because of line 5.
C. The code compiles successfully, so option F is incorrect. On line 5, the pre-increment operator is used, so c is incremented to 4 and the new value is returned to the
expression. The value of result is computed by adding 4 to the original value of 8,
resulting in a new value of 12, which is output on line 6. Therefore, option C is the
correct answer
What is the output of the following code snippet?
3: int x = 1, y = 15;
4: while x < 10
5: y––;
6: x++;
7: System.out.println(x+”, “+y);
A. 10, 5
B. 10, 6
C. 11, 5
D. The code will not compile because of line 3.
E. The code will not compile because of line 4.
F. The code contains an infinite loop and does not terminate.
E. This is actually a much simpler problem than it appears to be. The while statement
on line 4 is missing parentheses, so the code will not compile, and option E is the correct answer. If the parentheses were added, though, option F would be the correct
answer since the loop does not use curly braces to include x++ and the boolean expression never changes. Finally, if curly braces were added around both expressions, the
output would be 10, 6 and option B would be correct.
What is the output of the following code snippet?
3: do {
4: int y = 1;
5: System.out.print(y++ + “ “);
6: } while(y <= 10);
A. 1 2 3 4 5 6 7 8 9
B. 1 2 3 4 5 6 7 8 9 10
C. 1 2 3 4 5 6 7 8 9 10 11
D. The code will not compile because of line 6.
E. The code contains an infinite loop and does not terminate.
D. The variable y is declared within the body of the do-while statement, so it is out of
scope on line 6. Line 6 generates a compiler error, so option D is the correct answer
What is the output of the following code snippet?
3: boolean keepGoing = true;
4: int result = 15, i = 10;
5: do {
6: i–;
7: if(i==8) keepGoing = false;
8: result -= 2;
9: } while(keepGoing);
10: System.out.println(result);
A. 7
B. 9
C. 10
D. 11
E. 15
F. The code will not compile because of line 8.
D. The code compiles without issue, so option F is incorrect. After the first execution of the loop, i is decremented to 9 and result to 13. Since i is not 8, keepGoing is
false, and the loop continues. On the next iteration, i is decremented to 8 and result
to 11. On the second execution, i does equal 8, so keepGoing is set to false. At the
conclusion of the loop, the loop terminates since keepGoing is no longer true. The
value of result is 11, and the correct answer is option D.
What is the output of the following code snippet?
3: int count = 0;
4: ROW_LOOP: for(int row = 1; row <=3; row++)
5: for(int col = 1; col <=2 ; col++) {
6: if(row * col % 2 == 0) continue ROW_LOOP;
7: count++;
8: }
9: System.out.println(count);
A. 1
B. 2
C. 3
D. 4
E. 6
F. The code will not compile because of line 6.
A. The expression on line 5 is true when row * col is an even number. On the first
iteration, row = 1 and col = 1, so the expression on line 6 is false, the continue is
skipped, and count is incremented to 1. On the second iteration, row = 1 and col = 2, so the expression on line 6 is true and the continue ends the outer loop with
count still at 1. On the third iteration, row = 2 and col = 1, so the expression on line
6 is true and the continue ends the outer loop with count still at 1. On the fourth
iteration, row = 3 and col = 1, so the expression on line 6 is false, the continue is
skipped, and count is incremented to 2. Finally, on the fifth and final iteration, row
= 3 and col = 2, so the expression on line 6 is true and the continue ends the outer
loop with count still at 2. The result of 2 is displayed, so the answer is option B.
What is the result of the following code snippet?
3: int m = 9, n = 1, x = 0;
4: while(m > n) {
5: m–;
6: n += 2;
7: x += m + n;
8: }
9: System.out.println(x);
A. 11
B. 13
C. 23
D. 36
E. 50
F. The code will not compile because of line 7
D. Prior to the first iteration, m = 9, n = 1, and x = 0. After the iteration of the first
loop, m is updated to 8, n to 3, and x to the sum of the new values for m + n, 0 + 11 =
11. After the iteration of the second loop, m is updated to 7, n to 5, and x to the sum
of the new values for m + n, 11 + 12 = 23. After the iteration of the third loop, m is
updated to 6, n to 7, and x to the sum of the new values for m + n, 23 + 13 = 36. On
the fourth iteration of the loop, m > n evaluates to false, as 6 < 7 is not true. The
loop ends and the most recent value of x, 36, is output, so the correct answer is option
D.
What is the result of the following code snippet?
3: final char a = ‘A’, d = ‘D’;
4: char grade = ‘B’;
5: switch(grade) {
6: case a:
7: case ‘B’: System.out.print(“great”);
8: case ‘C’: System.out.print(“good”); break;
9: case d:
10: case ‘F’: System.out.print(“not good”);
11: }
A. great
B. greatgood
C. The code will not compile because of line 3.
D. The code will not compile because of line 6.
E. The code will not compile because of lines 6 and 9.
B. The code compiles and runs without issue, so options C, D, and E are not correct. The
value of grade is ‘B’ and there is a matching case statement that will cause “great” to
be printed. There is no break statement after the case, though, so the next case statement will be reached, and “good” will be printed. There is a break after this case statement, though, so the switch statement will end. The correct answer is thus option B.
Static member functions are not allowed to access non-static members. Why?
Static member functions don’t have access to a specific instance (this pointer) and are associated with the class itself. As a result, they cannot directly access non-static (instance) members to avoid ambiguity in the absence of a specific instance. Static functions operate at the class level, while non-static functions work with specific instances and have access to both static and non-static members. This separation helps maintain clarity in the design and prevents potential issues related to undefined behavior. If necessary, static functions can still interact with non-static members through explicit parameters or by creating instances within the function.
What is numeric promotion in Java? Provide examples.
Numeric promotion in Java is the automatic conversion of lower-ranked numeric data types to higher-ranked types to avoid data loss during mixed-type expressions. It ensures that operands of different types in an expression are compatible. For example, when combining an int and a double in an operation, the int is promoted to a double before the operation.
int and long in an addition operation:
int intValue = 5;
long longValue = 10L;
long result = intValue + longValue; // int is promoted to long
What is the String pool in Java and how is it used?
The String pool in Java is a pool of unique String objects stored in memory to optimize memory usage and improve performance. When a String is created using a literal (e.g., “example”), Java checks the pool. If a String with the same value already exists, the existing reference is returned instead of creating a new object. This reduces memory overhead by reusing existing String instances. String pool usage can be controlled using the intern() method, which adds the String to the pool if it’s not already present. Explicitly adding Strings to the pool can be beneficial in scenarios where many identical strings are created.
Explain the concept of Inheritance and how is it useful in OOP?
Inheritance in Object-Oriented Programming (OOP) is a mechanism that allows a class (subclass or derived class) to inherit properties and behaviors from another class (superclass or base class). The subclass can reuse and extend the functionality of the superclass, promoting code reuse and modularity. This relationship establishes an “is-a” connection between the subclass and superclass, facilitating a hierarchy of classes. Inheritance promotes the creation of more specialized classes by inheriting common features from a more general class, leading to a more organized and scalable code structure. It enhances code readability, maintenance, and reduces redundancy by encapsulating shared functionality in a common ancestor.
Polymorphism is one of the core concepts of OOP. What is Object Polymorphism and what are the three ways we can refer to an object?
Object Polymorphism in Object-Oriented Programming (OOP) allows objects of different types to be treated as objects of a common base type. It enables a single interface to represent various types of objects and supports dynamic method binding. The three ways to refer to an object are:
By its own class type: Referring to an object using its declared class type.
By its superclass type: Treating an object as an instance of its superclass, allowing for more general and abstract handling.
By an interface type: Referring to an object through an interface it implements, allowing for interaction based on shared behaviors defined by the interface.
These approaches facilitate flexibility, code extensibility, and the ability to write more generic and reusable code.
public class QuestionOne {
public static String concatStringMethod(StringBuilder sb1, StringBuilder sb2) {
String s1 = sb1.append(sb2).toString().trim().toLowerCase().concat(“HELLO”);
return s1;
}
public static void main(String[] args) { StringBuilder stringFoo = new StringBuilder("FoO"); StringBuilder stringBar = new StringBuilder("bAr"); QuestionOne.concatStringMethod(stringFoo, stringBar); System.out.println(stringFoo.append(stringBar)); } }
FoObArbAr
class Pyramid {
private double baseLength;
private double baseWidth;
private double height;
private double volume;
public Pyramid(double baseLength, double baseWidth, double height) { this.baseLength = baseLength; this.baseWidth = baseWidth; this.height = height; this(); } public Pyramid() { volume = this.baseLength * this.baseWidth * this.height; this.volume /= 3; } public double getVolume() { return volume; } }
public class QuestionTwo {
public static void main(String[] args) {
Pyramid p1 = new Pyramid(1, 2, 3);
Pyramid p2 = new Pyramid(2, 4, 6);
Pyramid p3 = new Pyramid();
System.out.println(p1.getVolume()); System.out.println(p2.getVolume()); System.out.println(p3.getVolume()); } }
Constructor call must be the first statement in a constructor. There is an error in the Pyramid class constructor where the volume calculation is attempted in the no-argument constructor. In the no-argument constructor, this.baseLength, this.baseWidth, and this.height are used, but they may not have been initialized at this point, leading to potential issues in the volume calculation.
public class QuestionThree {
public static void main(String[] args) {
int x = 0;
int y = 0;
int z = 0;
for (;; x++) { z = x % 5 == 0 ? x++ : y++; if (8 == x) { continue; } y += ++y; System.out.println("y: ", +y); if (y >= 20) { break; } System.out.println(x); } } }
y: 1
1
y: 5
2
y: 13
3
y: 29
What is output by the following code? (Choose all that apply)
1: public class Fish {
2: public static void main(String[] args) {
3: int numFish = 4;
4: String fishType = “tuna”;
5: String anotherFish = numFish + 1;
6: System.out.println(anotherFish + “ “ + fishType);
7: System.out.println(numFish + “ “ + 1);
8: } }
A. 4 1
B. 41
C. 5
D. 5 tuna
E. 5tuna
F. 51tuna
G. The code does not compile.
G. Line 5 does not compile. This question is checking to see if you are paying attention
to the types. numFish is an int and 1 is an int. Therefore, we use numeric addition and
get 5. The problem is that we can’t store an int in a String variable. Supposing line 5
said String anotherFish = numFish + 1 + “”;. In that case, the answer would be
options A and D. The variable defined on line 5 would be the string “5”, and both output statements would use concatenation
Which of the following are output by this code? (Choose all that apply)
3: String s = “Hello”;
4: String t = new String(s);
5: if (“Hello”.equals(s)) System.out.println(“one”);
6: if (t == s) System.out.println(“two”);
7: if (t.equals(s)) System.out.println(“three”);
8: if (“Hello” == s) System.out.println(“four”);
9: if (“Hello” == t) System.out.println(“five”);
A. one
B. two
C. three
D. four
E. five
F. The code does not compile.
A, C, D. The code compiles fine. Line 3 points to the String in the string pool. Line 4
calls the String constructor explicitly and is therefore a different object than s. Lines 5
and 7 check for object equality, which is true, and so print one and three. Line 6 uses
object reference equality, which is not true since we have different objects. Line 7 also
compares references but is true since both references point to the object from the string
pool. Finally, line 8 compares one object from the string pool with one that was explicitly constructed and returns false.
Which are true statements? (Choose all that apply)
A. An immutable object can be modified.
B. An immutable object cannot be modified.
C. An immutable object can be garbage collected.
D. An immutable object cannot be garbage collected.
E. String is immutable.
F. StringBuffer is immutable.
G. StringBuilder is immutable
B, C, E. Immutable means the state of an object cannot change once it is created.
Immutable objects can be garbage collected just like mutable objects. String is immutable. StringBuilder can be mutated with methods like append(). Although StringBuffer isn’t on the exam, you should know about it anyway in case older questions haven’t been removed.
What is the result of the following code?
7: StringBuilder sb = new StringBuilder();
8: sb.append(“aaa”).insert(1, “bb”).insert(4, “ccc”);
9: System.out.println(sb);
A. abbaaccc
B. abbaccca
C. bbaaaccc
D. bbaaccca
E. An exception is thrown.
F. The code does not compile.
B. This example uses method chaining. After the call to append(), sb contains “aaa”.
That result is passed to the first insert() call, which inserts at index 1. At this point
sb contains abbbaa. That result is passed to the final insert(), which inserts at index
4, resulting in abbaccca.
What is the result of the following code?
2: String s1 = “java”;
3: StringBuilder s2 = new StringBuilder(“java”);
4: if (s1 == s2)
5: System.out.print(“1”);
6: if (s1.equals(s2))
7: System.out.print(“2”);
A. 1
B. 2
C. 12
D. No output is printed.
E. An exception is thrown.
F. The code does not compile
F. The question is trying to distract you into paying attention to logical equality versus
object reference equality. It is hoping you will miss the fact that line 4 does not compile. Java does not allow you to compare String and StringBuilder using ==.
What is the result of the following code?
public class Lion {
public void roar(String roar1, StringBuilder roar2) {
roar1.concat(“!!!”);
roar2.append(“!!!”);
}
public static void main(String[] args) {
String roar1 = “roar”;
StringBuilder roar2 = new StringBuilder(“roar”);
new Lion().roar(roar1, roar2);
System.out.println(roar1 + “ “ + roar2);
} }
A. roar roar
B. roar roar!!!
C. roar!!! roar
D. roar!!! roar!!!
E. An exception is thrown.
F. The code does not compile
B. A String is immutable. Calling concat() returns a new String but does not change
the original. A StringBuilder is mutable. Calling append() adds characters to the
existing character sequence along with returning a reference to the same object.
Which are the results of the following code? (Choose all that apply)
String letters = “abcdef”;
System.out.println(letters.length());
System.out.println(letters.charAt(3));
System.out.println(letters.charAt(6));
A. 5
B. 6
C. c
D. d
E. An exception is thrown.
F. The code does not compile.
B, D, E. length() is simply a count of the number of characters in a String. In this
case, there are six characters. charAt() returns the character at that index. Remember
that indexes are zero based, which means that index 3 corresponds to d and index 6
corresponds to 1 past the end of the array. A StringIndexOutOfBoundsException is
thrown for the last line.
Which are the results of the following code? (Choose all that apply)
String numbers = “012345678”;
System.out.println(numbers.substring(1, 3));
System.out.println(numbers.substring(7, 7));
System.out.println(numbers.substring(7));
A. 12
B. 123
C. 7
D. 78
E. A blank line.
F. An exception is thrown.
G. The code does not compile.
A, D, E. substring() has two forms. The first takes the index to start with and the
index to stop immediately before. The second takes just the index to start with and
goes to the end of the String. Remember that indexes are zero based. The first call
starts at index 1 and ends with index 2 since it needs to stop before index 3. The second call starts at index 7 and ends in the same place, resulting in an empty String.
This prints out a blank line. The final call starts at index 7 and goes to the end of the
String.
What is the result of the following code? (Choose all that apply)
13: String a = “”;
14: a += 2;
15: a += ‘c’;
16: a += false;
17: if ( a == “2cfalse”) System.out.println(“==”);
18: if ( a.equals(“2cfalse”)) System.out.println(“equals”);
A. Compile error on line 14.
B. Compile error on line 15.
C. Compile error on line 16.
D. Compile error on another line.
E. ==
F. equals
G. An exception is thrown.
F. a += 2 expands to a = a + 2. A String concatenated with any other type gives
a String. Lines 14, 15, and 16 all append to a, giving a result of “2cfalse”. The if
statement on line 18 returns false because the values of the two String objects are the
same using object equality. The if statement on line 17 returns false because the two
String objects are not the same in memory. One comes directly from the string pool
and the other comes from building using String operations.