Question 2

10. public class Bar {
11.static void foo(int...x) {
12. // insert code here
13. }
14. }
Which two code fragments, inserted independently at line 12, will allow
the class to compile? (Choose two.)
A. foreach(x) System.out.println(z);
B. for(int z : x) System.out.println(z);
C. while( x.hasNext()) System.out.println(;
D. for( int i=0; i< x.length; i++ ) System.out.println(x[i]);

Answer: BD


type... x is used in function arguments where type can be any data type
for example:
int... x

which can take variable arguments
for example a function named var having declarations

var(int... x)

we can pass var(1); , var(1,1); , var(1,2,3);

so it can take 1 to any number of integers as arguments

int... x here x is just like an array and we can iterate over its elements using simple and enhanced for loop

other options are invalid

foreach is a method which is not defined
And hasnext() is used to iterate over collections(sets,lists,maps)

Hence the answer is B,D



11. public interface Status {
12. /* insert code here */ int MY_TRUE_VALUE = 10;
13. }
Which three are valid on line 12? (Choose three.)
A. final
B. static
C. native
D. public
E. private
F. abstract
G. protected


In Interfaces we can define constants for example:

interface you
{ int i=10;

now in interfaces every variable is implicitly public static final
Therefore, though we define int i=10 but for the compiler it is
public static final int i=10;

Now you can even define like this way :

  1. final int i=10;
  2. static int i=10;
  3. public int i=10;
  4. public static int i=10;
  5. public final int i=10;
  6. static final int i=10;
  7. public static final int i=10;
All these declarations are valid but for the compiler all these declarartions lead to the same declaration - public static final int i=10;

Invalid Declarations:

native - can be only applied to methods
private - variables in interfaces are public
protected - variables in interfaces are public
abstract - As the variables are implicitly final and we know final and abstract cannot be together, therefore it is invalid.


Casting to (byte)

Within the range:

A byte is signed and can hold a range of numbers from -128 to 127. If the value of the widest type is within this range, conversion won't produce unexpected results.


int a = -128;

byte x = (byte)a;

float a = -128.0f;

byte x = (byte)a;

Result in both cases: -128

Outside the range but within the signed byte range:

If the value is between 128 and 255, it will be converted to binary and then to the byte decimal representation of that binary pattern. In fact, this bit-level interpretation always occurs, but you have to be conscious about it for this special case.


int a = 128;

byte x = (byte)a;

Result: -128

The bit pattern for 128 is 10000000, but 10000000 is considered to be a signed byte. Thus 10000000 is equal to -128. The next binary number, 10000001, equals to -127. If byte was unsigned, as in C/C++, the decimal value of 1000001 would be 129.


int a = 129;

byte x = (byte)a;

Result: -127

Outside the signed byte range:

If the value is greater than 255 or lower than -128, the lower byte of the value is kept and the rest is just thrown away.

Example #1:

int a = 257;

byte x = (byte)a;

Result: 1

257 = [00000000] [00000000] [00000001] [00000001]

32-bits int value

1 = [00000001]

8-bits byte value

Example #2:

int a = -135;

byte x = (byte)a;

Result: 121

-135 = [11111111] [11111111] [11111111] [01111001]

32-bits int value

121 = [01111001]

8-bits byte value

Casting to (char)

Within the range:

A char is 16-bits wide unsigned type that holds values between 0 and 65535. Conversion will perform as expected if the value is within the valid range.


int a = 65535;

char x = (char)a;

Result: 65535

Outside the range or negative:

If the value is outside the range because it is lower than 0 or greater than 65535, then the lower 2 bytes will be kept.

Example #1:

int a = 65539;

char x = (char)a;

Result: 3

65539 = [00000000] [00000001] [00000000] [00000011]

32-bits int value

3 = [00000000] [00000011]

16-bits char value

Example #2:

int a = -1;

char x = (char)a;

Result: 65535

-1 = [11111111] [11111111] [11111111] [11111111]

32-bits int value

65535 = [11111111] [11111111]

16-bits char value

Casting to (short) and other signed integer values

Values between -32768 and 32767 are converted flawlessly as they are within the valid range. If the value is lower or greater, the lower 2 bytes of the value will be kept to conform a short value. The behaviour is the same as byte casting.

Other integer values will also behave as expected according to what we've seen at the byte examples.

Casting floats or doubles to narrower types

On some programming languages, conversion from floating-point numbers to decimals "round" the value. This is not the Java case, the integer part is kept and the rest is thrown away.


double a = 1.9999999;

int x = (int)a;

Result: 1

Object Reference Conversion

Object reference conversion takes place in:

* Assignment
* Method call
* Casting

(There is no arithmetic promotion)


Object reference assignment conversion happens when you assign an object reference value to a variable of a different type.

There are 3 general kinds of object reference type:

* A class type, such as Button or TextField
* An interface type, such as Clonable or LayoutManager
* An array type, such as int[][] or TextArea[]

Conversion rules for implicit casting on this context:

OLD_Type a = new OLD_Type;

NEW_Type b = a;



Conversion of primitive types may occur in these contexts:

* Assignment
* Method call
* Arithmetic promotion
* Explicit casting

Widening conversions: -

Your browser may not support display of this image.


General rules for primitive assignment conversions:

* A boolean may not be converted to any other type.
* A non-boolean may be converted to another non-boolean type, provided the conversion is a widening conversion.
* A non-boolean may not be converted to another non-boolean type, if the conversion would be a narrowing conversion.

Example #1:

int i = 5;

float j = i;

Method call

Widening conversion takes place on method calls as on assignments. You can pass to a method any primitive narrower than the expected one. Implicit casting will naturally occur.

For instance:

public static void main(String args[]) {

byte x = 126;

System.out.println( DoIt(x) );


static String DoIt(int a) {

return "I've received an int of value "+a;


Result: I've received an int value of 126

The method DoIt(int a) expects an int, but you can throw a char, byte or short there, the value will be promoted to int and the method will IN FACT receive an int.

This special behavior occurs if a method to handle a narrower type hasn't been declared. If you declare a method to handle bytes, then that method will "catch" the call. This is an OOP feature called overloading.


public static void main(String args[]) {

byte x = 126;

System.out.println( DoIt(x) );


static String DoIt(int a) {

return "I've received an int of value "+a;


static String DoIt(byte a) {

return "I've received a byte of value "+a;


Result: I've received a byte value of 126

If the argument type if wider than expected, no implicit casting will occur and you will need to perform an explicit cast:

public static void main(String args[]) {

float x = 1.26f;

System.out.println( DoIt( (int)x ) );


static String DoIt(int a) {

return "I've received an int of value "+a;


Result: I've received an int value of 1

Last example:

public static void main(String args[]) {

char x = 'A';

System.out.println( DoIt(x) );


static String DoIt(int a) {

return "I've received an int of value "+a;


static String DoIt(byte a) {

return "I've received a byte of value "+a;


Result: I've received an int value of 65

As you can see, there's no method to catch char types so the value is promoted to int and caught by DoIt(int a).

Arithmetic Promotion

Arithmetic promotion happens when narrower types need to be promoted to wider types in order to make sense in an operation among other wider types.

Basic rules for binary operators and most of the unary operators:

* All arithmetic expressions are promoted to the wider of the operands.
* The promotion is at least to int, even if no int operand appears.

These rules don't apply to the unary operators: ++ and -- and assignment operators.

Example #1:

byte x = 1;

x++; // Ok. x is now equal to 2.

x = x + 1; // Error. Expression x + 1 is promoted to int.

Example #2:

byte a = 1;

byte x = 23;

x <<= a; // Ok. x is now equal to 46.

x = x << a; // Error. Expression x << a is promoted to int.

Example #3:

char a = 5;

short x = 3;

x *= a; // Ok. x is now equal to 15.

x = x * a; // Error. Expression x = x * a is promoted to int.

Example #4:

byte a = 15;

a = -a; // Error. -a is promoted to int.

a = ~a; // Error. ~a is promoted to int.

Example #5:

float a = 1.0f;

int b = 15;

int x = a * b; // Error. Expression is promoted to float.

int x = (int)(a*b); // Ok. We cast the float result back to int.

Primitives and Casting

Casting means explicitly telling Java to make a conversion. A casting operation may widen or narrow its argument. To cast a value, you need to precede it with the name of the desired type enclosed within parentheses:

byte x = 15;

int r = (int)(x * 3);

Booleans cannot be casted. Don't bother with them, stuff like this doesn't work:

byte a = 1;

boolean status = a;

Narrowing runs the risk of loosing information, in fact, many times you know that you are going to loose information and it is important to know which part information is going to be loosen and naturally, what information will be kept.

Java Video Tutorials

Are you new to java? Then these video tutorials will help you tke a step forward towards learning java programming.

This video gives an example of a very simple program to make a new java file, compile and run and print a cutom text on the screen.

The second video is a tutorial to start using java in Eclipse environment.


Intermediate Arrays

Anonymous arrays

Java 2 added anonymous arrays, which allow you to create a new array of values anywhere in the program, not just in an initialization in a declaration.

// This anonymous array style can also be used in other statements.

String[] days = new String[] {"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"};

You can also use anonymous array syntax in other parts of the program. For example,

// Outside a declaration you can make this assignment.

x = new String[] {"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"};

You must be careful not to create these anonymous arrays in a loop or as local variables because each use of new will create another array.

Dynamic allocation

Because arrays are allocated dynamically, the initialization values may arbitrary expresssions. For example, this call creates two new arrays to pass as parameters to drawPolygon.

g.drawPolygon(new int[] {n, n+45, 188}, new int[] {y/2, y*2, y}, 3);

C-style array declarations

Java also allows you to write the square brackets after the variable name, instead of after the type. This is how you write array declarations in C, but is not a good style for Java. C declaration syntax can get very ugly with part of the declaration before the variable, and part after. Java has a much nicer style where all type information can be written together without the use of a variable, and there are times when only the Java notation is possible to use.

   int[] a;   // Java style -- good

   int a[];   // C style -- legal, but not Java style

Converting between arrays and Collections data structures


Common array problems

Some common array programming mistakes are:

  • Forgetting that array subscripts start with zero.
  • Writing a.length() instead of a.length. The length() method is used with Strings, not arrays.
  • Declaring an array with a size. Eg, int[100] a; instead of int[] a = new int[100];.

Library methods for arrays

Static methods for manipulating arrays are available in the java.util.Arrays class.


Returns a List based on the array.


Returns a readable form of the array.


Performs binary serach of a sorted array.


Compares two arrays for equality.


Fills entire array or subrange with a value.


Sorts an array.

In addition there is System.arrayCopy() method.

Anonymous arrays have to be assigned to the variables at the time of declaration of varaible itself. Assigning to the variable after variable declaration is not possible 
int[] i = {1,2,3} is fine. 
int[] i; 
i = {1,2,3} is compiler error. 
This restriction at the time of method invocation is valid, since we don't know the type of array(overloading issue). But for assignment the left side variable type is known. So, why should it be not possible to cast the anonymous array {1,2,3} to int[] and assign to variable.

i=i++ produces the output "0″ instead of "1″.

The code 
int i = 0; 
i = i++; 
produces the output "0″ instead of "1″.

"i = i++" roughly translates to

int oldValue = i; 
i = i + 1; 
i = oldValue;

Array and ArrayList

In a arrayList of object, any types of object(mixed) can be put. However in an array of objects, once initialized to a particular object type, other type of objects cannot be put.


ArrayList a = new ArrayList(); 

is allowed and will run fine.


Object[] obj = new String[5]; 
obj[0] = new Integer(1);

will throw ArrayStoreException(is a RunTimeException).

With generics, arraylist is also not allowed to store Integer if it is declared as ArrayList of String. Thus, with generics, 
ArrayList<String> a = new ArrayList<String>(); 
a.add(5);  — will be compiler error(unlike array which is at rutime).

But with generics also, one more difference is array  allows polymorphic assignment., i.e.,

Number[] n = new Integer[5];

However, in case of generics, polymorphic assignment holds good only for the base

type and not for the generic type. i.e.,

List<Integer> l = new ArrayList<Integer>;  — for base type hold good

ArrayList<Number> n = new ArrayList<Integer>; — not allowed for generic type



Java arrays are similar to ideas in mathematics

An array can store many similar values in memory. Each value can be accessed by specifying a subscript or index. "Array" in Java means approximately the same thing as array, matrix, or vector does in math.

Unlike math, you must declare the array and allocate a fixed amount of memory for it.

Declaring an array

An array variable is like other variables -- you must declare it, which means you must declare the type of elements that are in an array. All elements must be the same type. Write the element type name, then "[]", then the name of the array variable. The declaration allocates only enough space for a reference to an array (typically 4 bytes), but doesn't create the actual array object.

String[]  args;   // args is an array of Strings

int[]     scores; // scores is an array of ints

JButton[] bs;     // bs is an array of JButtons

No size in declaration. Unlike some languages, never put the size of the array in the declaration because an array declaration specifies only the element type and the variable name.

Allocate an array object with new

Create an array using new. This example creates an array of 100 int elements, from a[0] to a[99].

int[] a;           // Declare a to be an array of ints

a = new int[100];  // Allocate an array of 100 ints

These are often combined in one line.

int[] a = new int[100];  // Declare and allocate.


Subscripts are enclosed in square brackets []. xi in mathematics is x[i] in Java, and is pronounced "x-sub-i".

Subscript ranges always start at zero because Java came largely from C++, which had a good reason for using zero (pointer arithmetic on arrays). It isn't the way that humans normally count; you'll just have to live with it.

Java always checks subscript legality to be sure the subscript is >= 0, and less than the number of elements in the array. If the subscript is outside this range, Java throws ArrayIndexOutOfBoundsException. This is far superior to the behavior of C and C++, which allow out of range references. Consequently, Java programs are far less susceptible to bugs and security flaws than C/C++ programs.

Length of an array

Each array has a constant (final) instance variable that has its length. You can find out how many elements an array can hold by writing the array name followed by .length. In the previous example, a.length would be 100. Remember that this is the number of elements in the array, one more than the maximum subscript.

Java idiom for looping over an array

The most common use of .length is in a for loop test condition. For example, the variable i will go over the entire range of subscripts of the array a.

for (int i=0; i < a.length; i++) {

    . . .


If you only need to reference the value of each of the elements, you can use the somewhat simpler Java 5 for loop, which keeps track of the index and assigns successive values to a variable (v in this example).

for (int v : a) {

    . . .


Example Version 1 -- Adding all elements of an array

These statements create an array and put 1000 random values in it. The second loop adds all 1000 elements. It would have been better to add them in the first loop, but writing it this way allows two examples of loops.

int[] a;           // Declare an array of ints

a = new int[1000]; // Create an array of 1000 ints, a[0]...a[999] 

//... Assign random values to each element.

for (int i=0; i<a.length(); i++) {

    a[i] = (int)(Math.random() * 100000);  // Random number 0-99999


//... Add all values in the array.

int sum = 0;           // Start the total sum at 0.

for (int i=0; i<a.length; i++) {

    sum = sum + a[i];  // Add the next element to the total


Example Version 2 -- Adding all elements of an array in Java 5

This is the the same as above, but uses the Java 5 "for each" loop to do the sum, which frees you from using an index if you simply need to get all successive values. This kind of loop only gets the values, so it couldn't have been used to set the values in the first loop above.

. . .

int sum = 0;        // Start the total sum at 0.

for (int v : a) {

    sum = sum + v;  // Add the next element to the total


Initial array element values -- zero/null/false

When an array is allocated (with new), all elements are set to an initial value. The initial value is 0 if the element type is numeric (int, float, ...), false for boolean, and null for all object types.

Array Initialization

When you declare an array, you can can also allocate a preinitialized array object in the same statement. In this case, do not give the array size because Java counts the number of values to determine the size. For example,

// Java 1.0 style -- shorter, but can be used ONLY IN DECLARATIONS

String[] days = {"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"};

Array variables are references to arrays

When you declare an array variable, Java reserves only enough memory for a reference (Java's name for an address or pointer) to an array object. References typically require only 4 bytes. When an array object is created with new, a reference is returned, and that reference can then be assigned to a variable. When you assign one array variable to another, only the reference is copied. For example,

int[] a = new int[] {100, 99, 98};

int[] b;

// "a" points to an array, and "b" doesn't point to anything

b = a;      // Now b referes to the SAME array as "a"

b[1] = 0;   // Also changes a[1] because a and b refer to the same array.

// Both a and b refer to same array with value {100, 0, 98}

Make Money From Your Mobile

Mginger is a program in India which pays mobile users to receive SMS ads.These Ads are displayed according to the preference of the user and therefore Ads are very relevant.The best thing is that by receiving these ads ,we also get to know about new offers and Latest products and also get to know about discounts on apparels and other shopping items.

Registration is straightforward, you need your name, phone number and a few location details. In addition to this, you must select 5 Interests, such as music, gaming etc, this will “fine tune” your ads that you receive. Sooooo, where’s the money, well for every ad that you receive you get 20 paisa, and for every ad that your friend gets you get 10 paisa, and if your friend’s friend’s gets an ad you get 5 paisa. Now it may not sound like much, but it could add up.
You get paid Per SMS received and when the balance reaches 300 you can request a payment which will be delivered at address specified in your profile.

As these mobile ads can be received on any mobile and one account refers to one mobile.So If you have more than one mobile you can sign one account for each mobile.

To Sign UP visit the link below



Which statement is true?

A. Memory is reclaimed by calling Runtime.gc().

B. Objects are not collected if they are accessible from live threads.

C. Objects that have finalize() methods are never garbage collected.

D. Objects that have finalize() methods always have their finalize() methods called before

the program ends.

E. An OutOfMemory error is only thrown if a single block of memory cannot be found

that is large enough for a particular requirement.

Answer: B




1. class A {

2. A() { }

3. }


5. class B extends A {

6. }

Which two statements are true? (Choose two)

A. Class B's constructor is public.

B. Class B's constructor has no arguments.

C. Class B's constructor includes a call to this().

D. Class B's constructor includes a call to super().

Answer: B, D




11. int i = 1,j = 10;

12. do {

13. if(i>j) {

14. break;

15. }

16. j--;

17. } while (++i <5);

18. System.out.println("i =" +i+" and j = "+j);

What is the result?

A. i = 6 and j = 5

B. i = 5 and j = 5

C. i = 6 and j = 4

D. i = 5 and j = 6

E. i = 6 and j = 6

Answer: D



Which statement is true?

A. Assertions can be enabled or disabled on a class-by-class basis.

B. Conditional compilation is used to allow tested classes to run at full speed.

C. Assertions are appropriate for checking the validity of arguments in a method.

D. The programmer can choose to execute a return statement or to throw an exception if

an assertion fails.

Answer: A



You want a class to have access to members of another class in the same package. Which

is the most restrictive access that accomplishes this objective?

A. public

B. private

C. protected

D. transient

E. default access

Answer: E




1. public class Test {

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

3. class Foo {

4. public int i = 3;

5. }

6. Object o = (Object)new Foo();

7. Foo foo = (Foo)o;

8. System.out.println("i = " + foo.i);

9. }

10. }

What is the result?

A. i = 3

B. Compilation fails.

C. A ClassCastException is thrown at line 6.

D. A ClassCastException is thrown at line 7.

Answer: A



Which two cause a compiler error? (Choose two)

A. float[] = new float(3);

B. float f2[] = new float[];

C. float[] f1 = new float[3];

D. float f3[] = new float[3];

E. float f5[] = { 1.0f, 2.0f, 2.0f };

F. float f4[] = new float[] { 1.0f. 2.0f. 3.0f};

Answer: A, B



11. int i =1,j =10;

12. do {

13. if(i++> --j) {

14. continue;

15. }

16. } while (i <5);

17. System.out.println("i = " +i+ "and j = "+j);

What is the result?

A. i = 6 and j = 5

B. i = 5 and j = 5

C. i = 6 and j = 5

D. i = 5 and j = 6

E. i = 6 and j = 6

Answer: D




1. class Test {

2. private Demo d;

3. void start() {

4. d = new Demo();

5. this.takeDemo(d);

6. }


8. void takeDemo(Demo demo) {

9. demo = null;

10. demo = new Demo();

11. }

12. }

When is the Demo object, created on line 3, eligible for garbage collection?

A. After line 5.

B. After line 9.

C. After the start() method completes.

D. When the takeDemo() method completes.

E. When the instance running this code is made eligible for garbage collection.

Answer: E



1. interface Animal {

2. void soundOff();

3. }


5. class Elephant implements Animal {

6. public void soundOff() {

7. System.out.println("Trumpet");

8. }

9. }


11. class Lion implements Animal {

12. public void soundOff() {

13. System.out.println("Roar");

14. }

15. }


17. class Alpha1 {

18. static Animal get( String choice ) {

19. if ( choice.equalsIgnoreCase( "meat eater" )) {

20. return new Lion();

21. } else {

22. return new Elephant();

23. }

24. }

25. }

Which compiles?

A. new Animal().soundOff();

B. Elephant e = new Alpha1();

C. Lion 1 = Alpha.get("meat eater");

D. new Alpha1().get("veggie").soundOff();

Answer: D




1. abstract class AbstractIt {

2. abstract float getFloat();

3. }

4. public class AbstractTest extends AbstractIt {

5. private float f1 = 1.0f;

6. private float getFloat() { return f1; }

7. }

What is the result?

A. Compilation succeeds.

B. An exception is thrown.

C. Compilation fails because of an error at line 2.

D. Compilation fails because of an error at line 6.

Answer: D



Which four can be thrown using the throw statement? (Choose four)

A. Error

B. Event

C. Object

D. Throwable

E. Exception

F. RuntimeException

Answer: A, D, E, F



What produces a compiler error?

A. class A {

public A(int x) {}


B. class A {


class B extends A {

B() {}


C. class A {

A() {}


class B {

public B() {}


D. class Z {

public Z(int) {}


class A extends Z {


Answer: D




11. for( int i = min; i <max; i++) {

12. System.out.println(i);

13. }

If min and max are arbitrary integers, what gives the same result?

A. init i = min;

while( i < max ) {


B. int i = min;



} while( i< max );

C. for (int i=min; i<max; System.out.println(++I));

D. for (int i=; i++<max; System.out.println(i));

Answer: B




12. float f[][][] = new float[3][][];

13. float f0 = 1.0f;

14. float[][] farray = new float[1][1];

What is valid?

A. f[0] = f0;

B. f[0] = farray;

C. f[0] = farray[0];

D. f[0] = farray[0][0];

Answer: B




11. for (int i =0; i < 4; i +=2) {

12. System.out.print(i + "");

13. }

14. System.out.println(i);

What is the result?

A. 0 2 4

B. 0 2 4 5

C. 0 1 2 3 4

D. Compilation fails.

E. An exception is thrown at runtime.

Answer: D




12. void start() {

13. A a = new A();

14. B b = new B();

15. a.s(b);

16. b = null;

17. a = null;

18. System.out.printIn("start completed");

19. }

When is the B object, created in line 14, eligible for garbage collection?

A. After line 16.

B. After line 17.

C. After line 18 (when the methods ends).

D. There is no way to be absolutely certain.

E. The object is NOT eligible for garbage collection.

Answer: C




1. public class Exception Test {

2. class TestException extends Exception {}

3. public void runTest() throws TestException {}

4. public void test() /* Point X */ {

5. runTest();

6. }

7. }

At Point X on line 4, which code is necessary to make the code compile?

A. No code is necessary.

B. throws Exception

C. catch ( Exception e )

D. throws RuntimeException

E. catch ( TestException e)

Answer: B




11. int i = 0;

12. while (true) {

13. if(i==4) {

14. break;

15. }

16. ++i;

17. }

18. System.out.println("i="+i);

What is the result?

A. i = 0

B. i = 3

C. i = 4

D. i = 5

E. Compilation fails.

Answer: C




11. try {

12. int x = 0;

13. int y = 5 / x;

14. } catch (Exception e) {

15. System.out.println("Exception");

16. } catch (ArithmeticException ae) {

17. System.out.println("Arithmetic Exception");

18. }

19. System.out.println("finished");

What is the result?

A. finished

B. Exception

C. Compilation fails.

D. Arithmetic Exception

Answer: C




1. public class Test { }

What is the prototype of the default constructor?

A. Test()

B. Test(void)

C. public Test()

D. public Test(void)

E. public void Test()

Answer: A




11. public class Test {

12. public void foo() {

13. assert false;

14. assert false;

15. }

16. public void bar(){

17. while(true){

18. assert false;

19. }

20. assert false;

21. }

22. }

What causes compilation to fail?

A. Line 13

B. Line 14

C. Line 18

D. Line 20

Answer: D



Which statement is true?

A. Programs will not run out of memory.

B. Objects that will never again be used are eligible for garbage collection.

C. Objects that are referred to by other objects will never be garbage collected.

D. Objects that can be reached from a live thread will never be garbage collected.

E. Objects are garbage collected immediately after the system recognizes they are


Answer: D



n which two cases does the compiler supply a default constructor for class A? (Choose


A. class A {


B. class A {

public A() {}


C. class A {

public A(int x) {}


D. class Z {}

class A extends Z {

void A() {}


Answer: A, D




1. public class ReturnIt {

2. return Type methodA(byte x, double y) {

3. return (short)x / y * 2;

4. }

5. }

What is the narrowest valid returnType for methodA in line2?

A. int

B. byte

C. long

D. short

E. float

F. double

Answer: F




1. public class Outer{

2. public void someOuterMethod() {

3. // Line 3

4. }

5. public class Inner{}

6. public static void main( String[]argv ) {

7. Outer o = new Outer();

8. // Line 8

9. }

10. }

Which instantiates an instance of Inner?

A. new Inner(); // At line 3

B. new Inner(); // At line 8

C. new o.Inner(); // At line 8

D. new Outer.Inner(); // At line 8

Answer: A



What allows the programmer to destroy an object x?

A. x.delete()

B. x.finalize()

C. Runtime.getRuntime().gc()

D. Explicitly setting the object's reference to null.

E. Ensuring there are no references to the object.

F. Only the garbage collection system can destroy an object.

Answer: F




11. int x = 1, y =6;

12. while (y--) {

13. x++;

14. }

15. System.out.println("x =" + x + "y =" +y);

What is the result?

A. x = 6 y = 0

B. x = 7 y = 0

C. x = 6 y = -1

D. x = 7 y = -1

E. Compilation fails.

Answer: D



You want subclasses in any package to have access to members of a superclass. Which is

the most restrictive access that accomplishes this objective?

A. public

B. private

C. protected

D. transient

E. default access

Answer: C




1. class Exc0 extends Exception { }

2. class Exc1 extends Exc0 { }

3. public class Test {

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

5. try {

6. throw new Exc1();

7. } catch (Exc0 e0) {

8. System.out.println("Ex0 caught");

9. } catch (Exception e) {

10. System.out.println("exception caught");

11. }

12. }

13. }

What is the result?

A. Ex0 caught

B. exception caught

C. Compilation fails because of an error at line 2.

D. Compilation fails because of an error at line 6.

Answer: A




20. public float getSalary(Employee e) {

21. assert validEmployee(e);

22. float sal = lookupSalary(e);

23. assert (sal>0);

24. return sal;

25. }

26. private int getAge(Employee e) {

27. assert validEmployee(e);

28. int age = lookupAge(e);

29. assert (age>0);

30. return age;

31. }

Which line is a violation of appropriate use of the assertion mechanism?

A. line 21

B. line 23

C. line 27

D. line 29

Answer: A




1. public class A {

2. void A() {

3. System.out.println("Class A");

4. }

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

6. new A();

7. }

8. }

What is the result?

A. Class A

B. Compilation fails.

C. An exception is thrown at line 2.

D. An exception is thrown at line 6.

E. The code executes with no output.

Answer: E




1. class Bar { }

1. class Test {

2. Bar doBar() {

3. Bar b = new Bar();

4. return b;

5. }

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

7. Test t = new Test();

8. Bar newBar = t.doBar();

9. System.out.println("newBar");

10. newBar = new Bar();

11. System.out.println("finishing");

12. }

13. }

At what point is the Bar object, created on line 3, eligible for garbage collection?

A. After line 8.

B. After line 10.

C. After line 4, when doBar() completes.

D. After line 11, when main() completes.

Answer: C




1. interface Beta {}


3. class Alpha implements Beta {

4. String testIt() {

5. return "Tested";

6. }

7. }


9. public class Main1 {

10. static Beta getIt() {

11. return new Alpha();

12. }

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

14. Beta b = getIt();

15. System.out.println( b.testIt() );

16. }

17. }

What is the result?

A. Tested

B. Compilation fails.

C. The code runs with no output.

Answer: B