• 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/97

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;

97 Cards in this Set

  • Front
  • Back
float f = 1.0f;
double d = d + f;
System.out.println(d);

What prints?
Compiler complains that d might not have been initialized. This is true even if at the member variable level (vs. the method local level).
float f = 1.0;
double d = f;
System.out.println(d);

What prints?
Compiler complains about loss of precision. 1.0 is a double which is bigger than float f.
Instance variables. Stack or Heap?
Heap.

Because instance variables live inside an object and that object is on the heap, then they too live on the heap!
Objects. Stack or Heap?
Heap.
Local variables. Stack or Heap?
Stack. Each thread has its own stack while all threads in an application share 1 heap.
When do you use the digit 8 in an octal representation of a number?
Never. An octal number begins with the digit 0 and then is followed by a series of digits, each with a range of 0 to 7.
What does a hexidecimal value begin with?
ox or oX.
Is the following a legal?
long temp = 0XDeadCafel;
Yes.
char c = 1248;

Compiles? Runs?
Yes and yes.

Char is an integral type though not an integer (byte, short, int, long).
When can implict narrowing primitive conversions during assignment occur?
When...
1) The source is a constant expression.

2) The source is of type byte, short, char, or int.

3) The target is if type byte, short, or char.

4) The value of the source it determined to be in the range of the target type at compile time.

-------
Also.. using shortcut assignment operators implicitly do narrowing conversions (i.e. +=)
String str = "\\\\u0041";
System.out.println(str);

What prints out?
\u0041

If there has only been 1 slash in the String, then A would have printed out.
(unicode \u0041 = capital A)
Char c = \u0041;

Will this compile?
No. Literal unicode values being assigned to a char must occur inside single quoutes.
Char c = "\u0041";

Will this compile?
No. Double quotes will cause compiler to complain that an assignment of incompatible type is being attempted. Single quoutes are required.
What 2 non-primitives have literal represenations?
String Objects...
String s = "hello";

Array Objects...
int[] i = {1, 2, 3};
Does an object reference always refer to an object on the heap?
No. The reference might have the value of null. But all objects do live on the heap.
byte b1 = 1;
byte b2 = 1;
byte b3;
b3 = b1 + b2;
int total = b3;

Does this compile?
No. The result of integral arithmetic expressions is always type int. The assignment of such an int value to b3 causes compiler to complain that there is a possible loss of precision.
int i = (int)7.9f;

What is the value of i?
7. All decimals are dropped when casting from floating points to integral types.
When casting from larger integral types to smaller integral types, what get's removed?
The high order bits on the left simply get dropped. No adjustment is done to preserve the sign of signed types.
byte b = 128;
Compiler error?

byte b = (byte)128;
Compiler error? If not, what is the value of b?
Yes and No.

In the first case, a byte can only hold up to +127 so the compiler complains.

Adding the explicit cast essentially is a message from the user saying, "I know that that this doesn't quite fit in here but trust me... I know what I'm doing."

In this second case the eigth bit (which was a 1) becomes the high bit which is also the signed bit. This means our number is negative.

b = -128
byte b = 1;
b += 1;

Compiles?
Yes. b += 1 is shorthand for b = (byte)b + 1; These compound operators implicitly add a cast.

b = b + 1 would NOT compile;
What are the 4 basic scopes of variables from longest to shortest scope?
Static
Instance
Local
Block
What is the default value of a char member variable?
'\u0000'

This is the character equivalent of null.
What's the difference between null and the empty string ("")?
null says that a reference does not refer to an object on the heap. When the empty string is assigned to a String reference, there is a String object on the heap with the value of the empty string, and the String reference points to that object.
What are 2 other names for "automatic" variables?
1) local variables
2) stack variables
Is a reference variable that isn't pointing to an object always null?
No. When a reference variable is declared locally it does not get initialized by default. Until an explicit initialization, it is NOT null, it also does NOT point to an object.
What is shadowing?
Shadowing hides variables in higher scopes with declarations of same-named variables in lower scopes.

local/block can shadow static/member variables.

NOTE: a member variable CANNOT shadow a static variable, nor can a local block shadow a local variable.

An initializer block (at the member level) can shadow a static or member variable but after the object is constructed that shadowed variable is no longer available.

Local variables can shadow static and member variables.
Explain Declare-Construct-Initialize in terms of arrays.
Declare is creation of reference variable that will point to an array object at some point.

Construct is the creation of the array object.

Initialize is populating the array object with elements.
int[][]i[][];

legal?
Yes. Not recommended but legal.

int[][][][] i; (preferred)
When creating an array object (construct phase of array generation) what is the technique used to build the array object without setting a limit on the number of slots it will have?
There is no such technique.

You MUST declare, directly or indirectly, how much space an array object will need when placing it on the heap. You set the size indirectly by initializing it with a number of items whose number also becomes the size of the array.
int[][][]i = new int[2][3][];

Legal?
Yes.
int[] i = new int[4];
i[4] = 100;

Does this compile?
Yes. But it throws a runtime ArrayIndexOutOfBoundException.
int[] i = new int[3];
int z = -2;
i[z] = 100;

Does this compile? Run? If not, what exceptions get thrown?
Yes. Compiles fine but causes a runtime exception of type ArrayIndexOutOfBoundsException.
int[] i = new int[4];
System.out.println(i.length());

What prints out?
Compiler error. Arrays have a member variable called "length", not a member method called "length()".
What is the syntax for creating an anonymous array?
new TYPE[] {val1, val2,... valN}

Notice that there is no number inside the square brackets.

When constructing an array object you EITHER:
1) declare a size inside the square brackets OR
2) you let that size be deduced from the number of elements you place inside curly brackets.
3) you use this annoymous array syntax

Only at the time of declaration can you use #2. At all other times, if you want to construct a new array for an existing, already declared array reference -- you have to use #1 or #3
What are the two syntaxes for custom initializing an array object at the same time you declare the array?
int[] x = {1, 2, 3};

OR

int[] x = new int[]{1, 2, 3};

NOTE: This second format is actually using the "anonymous array" syntax to first create an anonymous array - which is then assigned to the array reference.
short[] s = new short[];

Compile?
No. When creating an array object (construct) you MUST tell compiler how much space will be needed on heap. Thus, the second set of square brackets needs a 0 or postive integer inside of it.
short[] s = new short[1];
int[] x = s;

Does this compile?
No.

Think of int[] not as a primitive but as object of type Integer[]. Integer and Short wrapper classes both descend from Number -- they cannot be assigned to each other. This is exactly how arrays of primitives behave.
Car[] cars;
Honda[] hondas = new Honda[5];
cars = hondas;

Will this compile?
Yes.
String[][][] i = new String[3][2][2];
i[1] = new String[7][7];
i[2] = new String[7][7];

Legal?
Yes. While an array reference must honor the dimensions of the array object it points at, it can be set to point to an array of different array size than was initially declared.
String[][][] i = new String[3][2][2];
i[1] = new String[3];

Legal?
No. The assignment to i[1] is an attempt to assign an array of different dimentions than what i[1] knows it should hold. Compiler complains about a type mismatch as String[][] is a different type than String[].
When does a static initialization block get called?
Right after a class get's loaded.

NOTE: If a class has a static main method, the class is fully loaded (including static blocks evaluated) before the main method is called.
When does an instance initialization block get called?
Immediatedly after the call to super(). Any non-default initialization of instance variables and initializers happens at the same time in the order they're encountered
How can an initialization block centralize code?
Code that might occur in many constructors of the same class can be pulled out and written once in a single initialization block.
What are the steps in creating an initial object state?
1. Instance variables are initialized to default values (regardless of whether there exist expressions intended to assign non-default values to these same variables).
2. The constructor is invoked.
3. Local chaining of constructors might take place (this()).
4. At the end of the local chain of constructor invocations, before that constructor's execution resumes, the superclass constructor is either implciitly or explicitly invoked (super()).
5. A chain of superclass constructor calls might be called.
6. All superclass constructor calls are completed and control returns to the local constructor just after the implicit or explicit call to a form of super();
7. instance initialization blocks AND instance variable initialization expressions are both evaluated in the order they occur.
8. The local constructor completes and returns, as does any local constructor it was chained to.
Integer i = 2;
Long l = 2l;
System.out.println(i.equals(l));
System.out.println((int)i == (long)l);

What prints?
false
true
Integer i = 2;
Long l = 2l;
System.out.println(i == l);

What prints?
Compiler error. Incompatible types. Think of this problem as comparing a Cat and a Dog. You might compare a Cat to an Animal, but can't compare Cat & Dog
If a serializable object HAS-A another object that is not serializable, what happens when the code is compiled?
It compiles just fine. Any attempts, though, to serialize the objects out to a ObjectOutputStream will cause a runtime error.
If a serializable object IS-A child of a parent that is not serializable, what happens when the code is compiled? run?
Compiles fine. Runs fine. When a serialized object is unserialized ("brought back to life"), the first ancestor that isn't marked as serializable will simply have it's constructor called (as will all it's ancestors - even if some of its ancestors are serializable!!!). For all below this cutoff ancestor, state is simply restored without any call to constructors.
System.out.printf("%f", 123);

Compiles?
Runs?
Yes (compiles) and No(doesn't run).

Print formatting does not automatically promote int to float. This error does not occur until runtime.
System.out.printf("%f", 123.0);

Compiles?
Runs?
Yes and yes. Though the literal is a double, print formatting can adequately handle it as a float.
Boolean b = new Boolean("TRUE");

Legal?
Yes. While the boolean literal true must be lowercase, this Boolean wrapper constructor is the String version which takes a case-insensitive form of "TRuE" or "fAlSe".
Character c = new Character("c");

Legal?
No. Of all the wrapper classes, only Character does not have an overloaded version of it's constructor that takes a String. Only a char is allowed

(i.e. new Character('c') <--- single quotes!)
Float f = new Float(1.2);

Compile?
Yes. Float constructors not only have verstions that take a String or float, but also have a version that takes a double.

NOTE: float f = 1.2 will NOT compile.
Integer i1 = 10;
Integer i2 = 10;
String s = (i1 == i2 ? "equal" : "not equal");
System.out.println(s);

What prints?
equal. Wrapper objects (not prims) are optimiized to save memory. Wrapper objects of the types and in the ranges stated below will be shared between all instances (instead of each instance generating its own object as is the usual case with objects).

All
*Boolean
*Byte
*Character (\\u0000 to \\u007f)
*Short & Integer (-128 to 127)
What do the wrapper class valueOf() methods do?
Create an object of that same wrapper class.


Takes a String arg (and optional second int arg (base) - i.e. binary is base=2) and convert to appropriate wrapper object.

Integer i = Integer.valueOf("100", 2);

NOTE: i is now reference to an Integer object which holds a value of 4.
What is the big difference between the wrapper class methods: parseXxx() and valueOf()?
parseXxx returns a primitive

valueOf() returns a wrapper object. You could then call xxxValue() on that wrapper abject to then get a primitive.

So parseXxx() is a short way of getting a string to a primitive!
What method do you call on a wrapper object to convert it to a primitive
xxxValue()

NOTE: it's not xxxVal();
What wrapper method do you call to convert a String to a primative?
xxx p = WRAPPER_TYPE.parseXxx(String[, radix]);

where WRAPPER_TYPE is the wrapper name equivalent of Xxx (i.e.
WRAPPER_TYPE = Integer
Xxx = int
)
What class methods in the wrapper classes do you call to convert a String to a wrapper object?
WRAPPER_TYPE obj = WRAPPER_TYPE.valueOf(String[, radix]);
What the heck is boxing and unboxing?
Java 5 trying to help us out. Basically it allows prims and their wrapper objects to be used interchangeably. The compiler automates the conversion the the appropriate wrapper or primitive.
When do you use the wrapper class xxxValue() methods?
When you have an instance of numeric wrapper object and want to convert it to a primitive numeric. THIS DOES NOT APPLY TO BOOLEAN OR CHAR!

i.e.
Integer i = Integer.valueOf("2", 10);
byte b = i.byteValue();
int i_primitive = i.intValue();
float f = i.floatValue();
//char c = i.charValue(); // Nope.

NOTE: When converting to prims, you use intValue(), not integerValue()
Wrapper objects are immutable.

T or F?
True.
Integer i = 2;
float f = Integer.valueOf(i);

Does this compile?
No but not for the reason you might think. The method valueOf() requires a String argument.

valueOf("" + i) would force the conversion of Intger i into a String. The equations would then compile and run fine thanks to autoboxing.
Integer i = 2;
byte b = i.byteValue();
long l = i.byteValue();

Compiles?
Yes and yes.
int[] a;
a = new long[5];

Compile?`
No. There is no conversion between array types. Primitives convert but array types don't.
int[] i;
i = {1, 2, 3};

Compiles?
No. This is an attempt to use special array initialization syntax that can only be used on a declaration line. If an array is declared on another line then one should use an anonymous array syntax to populate the array (there are other ways but that's the shortest).

I.E.
i = new int[]{1, 2, 3};
int i = Byte.parseByte("1");
float f = i.byteValue();

Compiles?
No. The i in i.byteValue() is not autoboxed.
int i = Byte.parseInteger("1");
byte b = i.byteValue();

Compiles?
No. All static parseXxx() methods aren't available for every wrapper.

For example, class Byte has parseByte() but not parseInt()

All xxxValue()instance methods, on the other hand, are available to all wrappers. So Integer.byteValue() is perfectly fine.

Summary: parseXxx() is class specific but xxxValue() works across wrappers.

NOTE: the method is named parseInt(str) NOT parseInteger(str)
Can you shadow a static variable with an instance variable?

static int i;
int i;
No. But you can shadow static and instance variables with:
1) local variables
2) initializer block variables
int[]i = new int[1];
int j = i[1];

What runtime error is thown?
ArrayIndexOutOfBoundsException
public class Generic {
int i = 3;
{int i = 4;}
}

When a Generic object is created, what is the value of i?
3. There is no compiler error. The initializer block is shadowing the instance variable i (not writing to it). Thus the instance version of "i" is not affected.

This version WOULD change the value of "i" to 4:

public class Generic {
int i = 3;
{i = 4;}
void aMethod() {
int i;
if (true) {i = 1;}
System.out.print(i);
}

Compiles? Runs?
Yes and yes.

The compiler can figure out that i will always be initialized (because it knows the boolean expression "true" will always be true. ;P)

If, intstead of the literal true, a boolean variable set to true right before loop was used, compiler would complain.
void aMethod() {
int i;
boolean b = true;
if (b) {i = 1;}
System.out.print(i);
}

Compiles? Runs?
Compile fails. Complains that i might not have been initialized.
byte b = 1;
short s = 1;
char c = 1;
int[] i = {b, s, c};

Compiles?
Yes. While there is no promotion between array types, for primitive elements inside an array implicit promotion does occur.
Constructors for wrapper objects have 2 special cases. What are they?
Genernally, wrapper object constructors take either a String or a primitive version of themselves for an argument.

There are 2 special cases:
1) Character class does NOT have a String version of the constructor

2) Float has an additional constructor where it takes a Double as well as the expected Float version and String version.
When a wrapper constructor using a String argument uses an improper String what exception gets thrown at compile time? runtime?
Compiles fine. At runtime get a NumberFormatException.
What are the wrapper classes?
Boolean
Byte
Character
Short
Integer
Long
Float
Double
Does autoboxing work with class Boolean?
Yes.

In Java 5 the following works:

Boolean b = Boolean(true);
if (b) {
...
}
What 3 wrapper methods have the additional radix argument?
By radix we mean the "base" of the number.

The radix argument describes the nature of the String (either the argument that serves as input or the String that is output).

If the String argument is base 2, then the radix would be set to 2, etc...

DESCRIBE INPUT STRING:
Primitive p = parseXxx(String s, int radix)
WrapperType w = WrapperType.valueOf(String s, int radix)

DESCRIBE OUTPUT STRING
String s = WrapperType.toString(primitive p, int radix)
Which of the wrapper classes are affected by the 3 methods that include radix arguments?
Byte, Short, Integer, and Long are the wrapper classes that have the radix version of parseXxx and valueOf()

Integer and Long are the wrapper classes that have the radix version of toString().

NOTE: This is only describing the radix versions of these methods. For example, All the wrapper clases have at toString(primitive) method, w/out a radix argument.
What are the 3 versions of the toString method in the wrapper classes?
toString() (works on instances)

toString(PRIMITIVE_TYPE p)
toString(PRIMITIVE_TYPE p, int radix)

These last 2 are static methods.
String i = Integer.toString(3.14);

Compiles?
No. Primitive argument must be an integer of some kind and 3.14 is a double.
String b = Byte.toString(2);

Compiles?
No. Btye.toString only takes a byte as a primitive argument. 2 is an int. Need to cast!

String b = Byte.toString((byte)2);
static void go(Integer x) {System.out.print("Integer");}
static void go(long x) {System.out.print("long");}
static public void main (String[] args) {
go(1);
}

What prints?
long. 1 is an int. Its looking for the smallest param wider than the int argument.

WIDENING is considered smaller than AUTOBOXING!

long is picked over Integer(notice this is a wrapper object - not a prim).
When looking for a method match what are the proverbial rock-paper-scissor rules that determine when widening, autoboxing, and var-args are used to determine the right method?
WIDENING beats AUTOBOXING
WIDENING beats VAR-ARGS
AUTOBOXING beats VAR-ARGSz
float fl;
fl = 09f;
System.out.println(fl);

What prints (HINT: notice the octal representation)?
9.0!

The hint is a red herring. There is no such thing as octal or hexidecimal reresentation in regards to decimals. (Notice that the word 'decimal' implies base 10.)

fl = 0x9f;

This will cause compilation errror because, as was just mentioned, there is no such thing as a hex representation of a decimal literal.
boolean b = TRUE;

Compiles?
No. Boolean literal 'true' must be lower cased. Same with boolean literal 'false'.
int[][] a = new int[2][2];
for (int b: a[0]) {
System.out.print(b);
}
a[0] = new int[] {1, 2, 3, 4};
for (int b: a[0]) {
System.out.print(b);
}

What prints?
001234

This does compile and run. Notice that initial multi-dem array that gets created is an array with 2 elements and each of these elements is an array initialized to default ints (0).

Notice also that though space was allocated for only 2 elements in the second dimension, you can easily assign that dimension an array of another size.

Is this compiler dependent? Not sure yet.
int[] a = new int[2];
for (int b: a) {
System.out.print(b);
}
a = new int[] {1, 2, 3, 4};
for (int b: a) {
System.out.print(b);
}

Why does this fail to compile?
It doesn't fail. It compiles and runs just fine. The following is print:

001234
int[] a = new int[2];
int[] b = {1, 2, 3};
for (int c: a) {
System.out.print(c);
}
a = b;
for (int c: a) {
System.out.print(c);
}

What prints?
00123

The point to remember is that the SIZE can be different when assigning a new array to an array reference but that new array MUST HAVE THE SAME DIMENSION as the reference!

SUMMARY:

SIZE of array can be different but DIMENSION must be the same.
public static void main (String[] args) {
try {int x = 2;}
finally {System.out.println(++x);}
}

What prints?
Compiler error. Notice that x goes out of scope at the end of the try block, and thus is not properly declared inside the finally clause.
char c = '\U0000';
System.out.println(c);

What prints?
Comiler error. The 'U' in a unicode version of a char literal must be lower case.

char c = '\u0000';

This is the correct for and would give the variable 'c' the value of the null character.
Date d = new Date(1000000000000);

This date constructor takes a long integer as an argument. Does this compile?
No.

The literal is an integer. As such it is to long to fit into an integer. Notice that this happens before any promotion to long can even occur.

The argument literal needs to be declared as such:
(1000000000000L);
Integer i = new Integer("2");
Short s = new Short("2");
System.out.println(i.equals(s));

Does this compile? Runs? If so, what prints?
Yes and yes.

It prints "false". The numeric wrapper classes will only evaluate "true" in a equals comparison if they are wrappers of the same type and they have the same value.

So if you compare an Integer and a Long of the same value, their equals() will evaluate to false.

NOTICE that a primitive int and long of the same value (2 == 2L) DOES evaluate to "true"
Integer i = new Integer("2");
Short s = new Short("2");
if (s < i) {
System.out.println("Short is less than Integer");
}

Does this compile? Run? What prints?
Yes and yes BUT ONLY IN JAVA 1.5 BECAUSE OF AUTOBOXING!!!!

Relational operators (such as "<") only work on integers, floats, and in chars. In this example the 2 objects are autoboxed to primitives and then compared.

In Java 1.4 this would have been a compiler error because objects cannot be compared with relational operators.
Describe the "holy trinity" of wrapper classes.
Imagine a triangle with the three points being:
1) Primative (p)
2) Wrapper (w)
3) String (s)

The wrapper classes move values between the 3 points of this triangle.

w ----> s:
w.toString();
--use 'w' in String context--

p ----> s:
WrapperType.toString(p);
String.valueOf(p);
--use p in String context--


s ----> p:
WrapperType.parseXxx(s);

w ----> p:
w.xxxValue();


p ----> w
w = new WrapperType(p);


s ----> w
w = new WrapperType(s);
w = WrapperType.valueOf(s);
Can you use unicode chars in a String literal?
Yes.

As a char:
'\u0108'
(capital C with circumflex)


In a String:
"S\u00ED se\u00F1or"
(Sí Señor in Spanish).