• Shuffle
    Toggle On
    Toggle Off
  • Alphabetize
    Toggle On
    Toggle Off
  • Front First
    Toggle On
    Toggle Off
  • Both Sides
    Toggle On
    Toggle Off
  • Read
    Toggle On
    Toggle Off
Reading...
Front

Card Range To Study

through

image

Play button

image

Play button

image

Progress

1/75

Click to flip

Use LEFT and RIGHT arrow keys to navigate between flashcards;

Use UP and DOWN arrow keys to flip the card;

H to show hint;

A reads text to speech;

75 Cards in this Set

  • Front
  • Back
What can a switch statement expression evaluate to?
byte, short, char, int or, as of Java 5, enum
int x = 2;
final int a;
a = 2;
switch(x) {
default:
System.out.println("Default");
case a:
System.out.print("a");
}

What prints?
Compiler error. Variable a, while final, is not a compile time constant.

final int a = 2; (IS compile constant)
final int a;
a = 2; (is NOT)

COMPILE CONSTANT REQUIREMENTS:
1) Declared final
2) Assignment at same time as declaration
3) The assigned value is a literal OR another compile time constant
Are duplicate labels allowed in switch statements?
...
case 10:
case 10:
...
No.
byte b = 1;
switch(b) {
case 128:
System.out.println("Default");
}

What prints?
Compiler error.

The case label, 128, is of a value too large for the byte type.
Name 5 ways to exit out of a loop.
1. break statement
2. System.exit()
3. Exception thrown
4. return
5. meet the conditional requirement
When does a while statement end with a semicolon?
When it's part of a do-while statement.

i.e.
int x = 0;
do{
x++;
} while (x<2);
int[] arr = {1, 2, 3};
int element;
for (element : arr) {
System.out.println(element);
}

Output?
Complier error. The variable "element" is already declared. A for loop that loops through arrays requires that a newly created block variable be declared.

i.e.
for (int x : arr);
for (int i=0; i<0; i++);

Legal?
Yup. This for loop, instead of a block, simply loops on the first statement following it. In this case that statement is simply a semicolon.
for (int i; i<0; i++);

Legal?
No. i is a local variable and so has not been explicitly initialized. You cannot begin using it as an operand a relation operator or increment operator without first assigning it a value.

i.e.
for (int i=0; i<0; i++);
When does a while statement end with a semicolon?
When it's part of a do-while statement.

i.e.
int x = 0;
do{
x++;
} while (x<2);
Can a try block exist without a catch or finally block?
No. A try block must have at least a catch block or a finally block. Otherwise the code will cause a compiler error.
try{
throw new Exception();
}
System.out.println("End Try.");
catch (Exception e) {
System.out.println("Exception.");
}

What prints?
Compiler error. You cannot have any statements between a try block and a catch block. Compiler assumes a try block has been declared without a catch or finally block when it gets to the intruding statement, and complains that the try statement needs one of its buddies to be legal.
try{}
catch(Exception e) {System.out.println("A");}
catch(RuntimeException e){System.out.println("B");}


Will "B" ever be printed?
Compiler error! It's a compiler error to specify a catch clause based on a Throwable object that's will be caught in a preceeding catch clause.
Can you nest a try/catch/finally block inside a catch block?
Yes. If you take the error caught by the initial catch block, and then throw it in a nested try block, you can then catch it in an accompanying NESTED catch block.

NOTE: Any other un-nested catch blocks (peers to our original, outer catch block) will NOT be reconsidered by any exceptions thrown in the nested try/catch/finally blocks.

Also. If any catch block turns around and throws any error - it will not be caught by itself or any of it's peer catch blocks.
try{
throw new Error();
}
catch(Error e) {
System.out.print("Error ");
try {
throw new RuntimeException();
}
finally {
System.out.print("Finally,Inner ");
}
}
catch (RuntimeException e) { System.out.print("RuntimeException ");
}
finally{
System.out.print("Finally,Outer ");
}

What prints?
Error
Finally,Inner
Finally,Outer
The curly braces are optional in the body of an if statement?

True or False?
True.
boolean doStuff() {return true;}
...
if (doStuff()){}

Compiles? Runs?
Yes and yes. The expression in an if statement must simply be a boolean expression.
What is the format of a switch statement?
switch(expression) {
case const1: 0 to N statements and/or blocks
case const2: 0 to N statements and/or blocks
default: 0 to N statements and/or blocks
}

When the following statement is encountered the switch ends:
break;
You can use expressions that evaluated to a byte, short, char, int, or long in a switch statment.

True or False?
False. Longs cannot be used. As of Java 5 enums can be used.
final int label1 = 2;
final int label2 = 2 * 2;
final int label3 = label1 * label2;
final int label4 = label3 + 2;
final int label5 = -1;

switch(1) {
default:
case label1:
case label2:
case label3:
case label4:
case label5:
System.out.println("Works");
}

What prints?
Works.

All the case labels qualify as compile time constants so this switch statement compiles and runs.

Whena a variable qualifies as a compile time constant, it then itself can be treated as if it were a literal
switch(1) {
default:
case 2: {
break;
System.out.println("Works");
}
}

What prints?
Compiler error. The statement after break; can never be reached and compiler will throw error.
switch(1) {
default:
2: {
System.out.println("Works");
break;
}
}

What prints?
Complier error. Cases actually require the keyword "case". So in this situation 2: should read

case 2:

It would then compile, run, and print "Works"
switch(1) {
default:
case 2: {
System.out.println("Works");
break;
}
}

What prints?
Works
while (true);

Compiles?
Yes. And it will run as an endless loop (boo). Curly braces (block) are not required.

while(boolean)
block or statment
while(1){}

Compiles?
No. The expression in a while statement must be of type boolean, not int.
int i=0;
for (int i=0; i<10; i++) {}

Compiles?
No. Compiler will announce that i is already declared. You cannot shadow in this case.
for (int i=0, String s=""; i<10;i++, s +="+");

Runs?
Compiler error (so no, it doesn't run either).

In the initialization section you can either DECLARE (plus set values) or INITIALIZ (you have to do 1 or the other - can't mix).

Here we are doing DECLARATION. In this case you can NOT mix type. If we had only been INITIALIZING variables defined outside for loop we could have mixed type.
int i=0;
String s = "";
for (i=0, s=""; i<10;i++, s +="+");

Compiles?
Yes.
What are the rules for the initialization section of a traditional for statement?
1. Must be a
a) Declaration statement [where you can also optionally set initial values for the variablese declared]

OR

b) Initialization statement

2) If Initialization, then type can be mixed

3) If Declaration, only 1 type allowed

4) You can't mix Declaration and Initialization kinds of statements
for (int i=0; i<10;i++);
int i = 10;
System.out.println(i);

What prints?
10.

Notice that once for loop ends, it's "i" goes out of scope so it's perfectly legal to then redeclare "i".
for (int i=0; i<10;i++);
System.out.println(i);
Compiler error. "i" goes out of scope at end of for loop so attempting to print an undefined variable.
i:
for (int i=0; i<3; i++){
System.out.println(i);
continue i;
}

What prints?
0
1
2

Albeit poor style, but it works.
How many test expressions can you have in a traditional for statement?
1.
What is the definition of the new for statement?
for (declaration : expression)
statement or block

where

delcaration is a NEWLY DECLARED block variable of a type compatible with the elements of the array being accessed

and

expression evaluates to an array
for (int i=0; i<0; i++){
System.out.println(i);
next;
}

What prints?
Compiler error. next is not a known symbol. continue; is the statement used to skip the current itteration of the loop
Are these 2 the same?

i:
for (int i=0; i<3; i++){
System.out.println(i);
continue i;
}

for (int i=0; i<3; i++){
System.out.println(i);
}
Yes.
for (int i=0; i<10; i++){
continue i;
}

Compiles?
No. By putting "i" after continue, i will be treated like a label. Since there is no label with the title "i" (the string "i" - not the value of the variable i) compiler complains.
Can continue statement be written outside of a loop? How about a break statement?
No and yes. A break statement can also be used in a switch statement.
What constitutes a legal statement label?
A label is just another identifier. It follows the same rules as all other identifiers.

It's followed by a colon and whitespace
What is they syntax of a label declaration? of a break statement using that label?
cats: for(int i=0; i<1;i++){
break cats;
}
cats: for(int i=0; i<10;i++){break dogs;}
dogs: for(int i=0; i<10;i++){}

Compiles?
No.

Labeled continue and break statements must be inside the loop that has the same label name.
What is the hierarchy of Object, Throwable, Error, Exception, and RuntimeException classes?
Object at top.

Throwable descends from Object.

Error and Exception descend from Throwable

RuntimeException descends from Exception.

NOTE 1: Anything that is a Throwable or a subtype can be thrown.

NOTE 2: All Exceptions (except RuntimeException and its subclasses) are "CHECKED" exceptions and must be handled by the programmer.
In regards to checked exceptions, what is "handle or declare"?
A method that MIGHT produce a checked exception must either handle it using a try/catch/finally clause or must add a throws clause with the offending exception to its signature.
When do the following get thrown:
ArrayIndexOutOfBoundsException
ClassCastException
IllegalArgumentException
IllegalStateException
NullPointerException
NumberFormatException
AssertionError
ExceptionInitializerError
StackOverflowError
NoClassDefFoundError
Look it up buddy (page 370).
static String s;
static public void main (String[] args) {
System.out.println(s.length());
}

Compiles?
Yes. But it does not run. At runtime a NullPointerException is thrown.

We easily see that s is null but compiler doesn't. It never looks for what's actually IN s, it's just checking to make sure a thing of type String behaves in ways the programmer is asking it to (in this case, a programmer says that a String has a length() method which the compiler knows to be a perfectly okay behavior).
void go() {
go();
}

What happens?
Compiles fine. StackOverflowError is thrown at runtime.
What's the difference between Exceptions thrown by the JVM and progromatically thrown Exceptions?
programatically means Exceptions thrown by a programmer and/or the API.
An example would be a call to a wrapper object's parseXxx method where the String argument was improperly formatted. (NumberFormatException gets thrown).

JVM is just that - the Java Virtual Machine throws.
An example would be if the JVM was asked to call the length() method on a String variable that was set to null (NullPointerException).
How do assertions work?
You assert something to be true. If it is, no problem. If what you say is true is actually false then a AssertionError is thrown THAT SHOULD NEVER BE CAUGHT! (Whole point is that during development these errors scream out at you so they can get noticed - don't want to handle them away)
What is the syntax of an assertion?
assert(boolean expression);

OR

assert(boolean expression): statement that results in a value;

In the latter form a value would be a primitive or object which will then get converted to a string (much like println() converts prims and objects)).
What happens to a string you add to an assert statement?
It gets added to the stack trace.
When did assertions first appear in Java?
1.4
What if you are compiling legacy code that uses "assert" as an identifier (and not as a keyword)?
You must compile with the following switch
javac -source 1.3

In this case you'll receive WARNINGS (not errors) and the code will still compile
Are these switches different?

javac -source 5
javac -source 1.5
No.
At runtime, how do you enable assertions?
Use the following switches
java -ea
java -ea:XXX
java -ea:XXX...
java -enableassertions
java -enableassertions:XXX
java -enableassertions:XXX...

Where a form of :XXX is NOT present all classes (besides System classes) are assertion enabled.

Where :XXX... IS present then XXX = a package name and assertions are turned on for that package and ANY PACKAGE BELOW THAT PACKAGE IN SAME DIRECTORY HIERARCHY

Where :XXX is used, XXX = a class name and assertion turned on for just that class.
Can you combine enabling and disabling java command line switches?
Yes.
How do you disable assertions
use the following switches:
-da
-disableassertions

Notices that "assertions" is lower case -- no camel case here!

Also you can add :XXX... (package) and :XXX (class) to more specifically target what you disable.
what is the -dsa assertion switch?
It disables assertions in system classes.
static public void checker(int i) {
assert (i>0): "i shouldn't be below zero.";
// do stuff with i
}
...
checker(-1);

Compile? Run? Appropriate?
Yes, compiles. Runtime error ONLY IF ASSERTIONS ARE ENABLED, otherwise runs fine. Thus this is not appropriate usage because this check on the publicly submitted variable should always occur and not just when assertions are enabled.

Similarly you wouldn't use the assert mechanism to validate args sent in via command line.

It IS appropriate to use assertion checks on arguments sent to a private method.
Does it make sense to use assert statements at the start of code that should never be reached?
Yes!
Should your assert boolean expression evaluation, as a side affect, change the state of the application?
No!

assert(foo()){}

boolean foo(){
i++;
return true;
}

This is legal but bad form. It's bad because the state change will or will not happen depending on whether your app is being run with assertions enabled or not.
switch(-1) {
case 1:
case 2:
}

Does this compile? Run?
Yes and yes.
for (int i = 0; i < 1; i++);
int i = 2;
System.out.println(i);

What prints?
2
for (int i = 0; i < 1; i++) {
}
System.out.println(i);

What prints?
Compiler error. "i" goes out of scope once the for loop is completed.
int y = 0;
for (int y : x) {
System.out.print (y + " ");
}
int y = 0;


What changes can be made to make this code compile?
You must comment out the the first line.

For loop declared variables share the scope of where they are declared (so if "var1" already exists - then it can be redeclared in the for loop).

On the other hand, any variable declared in a for loop does go out of scope the moment the loop is over -- in this case the loop acts not as a sharer of the same scope but an even smaller, separate scope.
final Integer x1 = 1;
switch(1) {
case x1: System.out.println("1");
}

What prints?
Compiler error.

The compiler will not see x1 as a constant expression.
When using an enum in a switch statement, what must be true of the case statements?
The case statments should be UNQUALIFIED, ENUM CONSTANT


switch(state) {
//case MachineState.BUSY:// Compile error: Must be unqualified.
case BUSY: System.out.println(state + ": Try later."); break;
case IDLE: System.out.println(state + ": At your service."); break;
case BLOCKED: System.out.println(state + ": Waiting on input."); break;
//case 2: // Compile error: Not unqualified enum constant.
default: assert false: "Unknown machine state: " + state;
}
Select all the incorrect options:
a) Since enums are comparable to traditional classes, they may not be arguments in switch statements.
b) Enums may not extend another class/ enum.
c) Enums inherit the java.lang.Object class.
d) Enums may be extended by another Enum.
a & d are incorrect
Can you run an enum as a standalone application (can you put the following method inside an enum:

public static void main(String[] args) {...}

?
Yes
Can you define a class inside of an enum?
Yes
Does an enum get compiled to a .class file?
Yes
Can you extend with another enum/class?
No
Can you define abstract methods inside an enum?
Yes
Can you define and enum as abstract?
No
Is this legal?

enum Colours {
YELLOW (Personality.EXPRESSIVE),
GREEN (Personality.AMIABLE),
RED (Personality.ASSERTIVE),
BLUE (Personality.ANALYTICAL);

Personality personality;

Colours (Personality personality) {
this.personality = personality;
}

enum Personality {ASSERTIVE, EXPRESSIVE, AMIABLE, ANALYTICAL };
}
Yes
Legal?

enum Rating {
POOR,
AVERAGE,
GOOD,
EXCELLENT;

int raise() {
switch (this) {
case POOR: return 0;
case AVERAGE: return 5;
case GOOD: return 20;
case EXCELLENT: return 45;
}
return 0;
}
}
Yes