Showing posts with label JAVA. Show all posts
Showing posts with label JAVA. Show all posts

JAVA@COFFEE


JAVA TUTORIALS


JAVA DUMPS
TIPS



TIPS TO CRACK SCJP

1. THE BOOK:
The best reference for SCJP is Head First Java, 2nd Edition.
This books gives all the inside and out of java which is required for SCJP examination.


Caution
Herbert Schildt is a good book in general, but is not a good reference for SCJP and many of the texts in this book are not correct.
So in my opinion Head First Java, 2nd Edition is the Bible for SCJP.



2. SCJP DUMPS
SCJP Dumps are set of mock and previous year papers. Previous year questions are a must.
If one understands and masters all the questions, one can easily score in the range of 75 -100%.
These questions often get repeated and if one goes through the whole set, one is bound to get around 60-80% questions in the test from previous year papers.


3.TEST

First of all, make sure that you mark 'novice' in the survey taken by sun prior to the test(SCJP).
Don't ever mark 'intermediate' or 'expert' because the paper will become quite difficult and might be difficult to pass even.

Secondly, 'Drag and Drop Questions'- these questions have to be attempted very carefully.
Make sure you check before confirming your answer because after confirming if you try to check your answer,it gets refreshed, and your answers disappear.
So better technique is to try and check in the first attempt itself.

SCJP MOCK QUESTIONS - 2

Question 2

Given:
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( x.next());
D. for( int i=0; i< x.length; i++ ) System.out.println(x[i]);


Answer: BD

Answer:


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

SCJP MOCK QUESTIONS - 1

QUESTION

Given:
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




ANS - ABD

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 - II



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.

Example:

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.

Example:

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.

Example:

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.

Example:

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.

Example:

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)

Assignment

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;

CASTING


Primitives

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.

Assignment

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.

Example:

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 DUMPS 19 (SCJP)

QUESTION NO: 6

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


 

QUESTION NO: 7

Given:

1. class A {

2. A() { }

3. }

4.

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


 

QUESTION NO: 8

Given:

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


 

QUESTION NO: 9

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


 

QUESTION NO: 10

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

JAVA DUMPS 18 (SCJP)

QUESTION NO: 1

Given:

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


 

QUESTION NO: 2

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

QUESTION NO: 3

Given:

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


 

QUESTION NO: 4

Given:

1. class Test {

2. private Demo d;

3. void start() {

4. d = new Demo();

5. this.takeDemo(d);

6. }

7.

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

QUESTION NO: 5

Given:

1. interface Animal {

2. void soundOff();

3. }

4.

5. class Elephant implements Animal {

6. public void soundOff() {

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

8. }

9. }

10.

11. class Lion implements Animal {

12. public void soundOff() {

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

14. }

15. }

16.

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

JAVA DUMPS 17 (SCJP)

QUESTION NO: 92

Given:

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


 

QUESTION NO: 93

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


 

QUESTION NO: 94

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


 

QUESTION NO: 95

Given:

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;

do

System.out.println(i++);

} 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

JAVA DUMPS 16 (SCJP)

QUESTION NO: 85

Given:

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


 

QUESTION NO: 86

Given:

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


 

QUESTION NO: 87

Given:

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


 

QUESTION NO: 88

Given:

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


 

QUESTION NO: 89

Given:

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


 

QUESTION NO: 90

Given:

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


 

QUESTION NO: 91

Given:

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

JAVA DUMPS 15 (SCJP)

QUESTION NO: 78

Given:

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


 

QUESTION NO: 79

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

eligible.

Answer: D


 

QUESTION NO: 80I

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

two)

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


 

QUESTION NO: 81

Given:

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


 

QUESTION NO: 82

Given:

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


 

QUESTION NO: 83

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


 

QUESTION NO: 84

Given:

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

JAVA DUMPS 14 (SCJP)

QUESTION NO: 72

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


 

QUESTION NO: 73

Given:

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


 

QUESTION NO: 74

Given:

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


 

QUESTION NO: 75

Given:

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


 

QUESTION NO: 76

Given:

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


 

QUESTION NO: 77

Given:

1. interface Beta {}

2.

3. class Alpha implements Beta {

4. String testIt() {

5. return "Tested";

6. }

7. }

8.

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

JAVA DUMPS 13(SCJP)

Given:

1. class Super {

2. public int i = 0;

3.

4. public Super(String text) {

5. i = 1;

6. }

7. }

8.

9. public class Sub extends Super {

10. public Sub(String text) {

11. i = 2;

12. }

13.

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

15. Sub sub = new Sub("Hello");

16. System.out.println(sub.i);

17. }

18. }

What is the result?

A. 0

B. 1

C. 2

D. Compilation fails.

Answer: D


 

QUESTION NO: 68

Given:

11. int i = 1,j = 10;

12. do{

13. if (i>j) {

14. continue;

15. }

16. j--;

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

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


 

QUESTION NO: 69

Which fragment is an example of inappropriate use of assertions?

A. assert (!(map.contains(x)));

map.add(x);

B. if (x > 0) {

} else {

assert (x==0);

}

C. public void aMethod(int x) {

assert (x > 0);

}

D. assert (invariantCondition());

return retval;

E. switch (x) {

case 1: break;

case 2: creak;

default: assert (x == 0);

Answer: C

QUESTION NO: 70

Given:

1. public class X {

2. public X aMethod() { return this;}

3. }

1. public class Y extends X {

2.

3. }

Which two methods can be added to the definition of class Y? (Choose two)

A. public void aMethod() {}

B. private void aMethod() {}

C. public void aMethod(String s) {}

D. private Y aMethod() { return null; }

E. public X aMethod() { return new Y(); }

Answer: C, E


 

QUESTION NO: 71

Given:

1. public class X {

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

3. try {

4. badMethod();

5. System.out.print("A");

6. }

7. catch (Exception ex) {

8. System.out.print("B");

9. }

10. finally {

11. System.out.print("B");

12. }

13. System.out.print("D");

14. }

15. public static void badMethod() {

16. throw new Error();

17. }

18. }

What is the result?

A. ABCD

B. Compilation fails.

C. C is printed before exiting with an error message.

D. BC is printed before exiting with an error message.

E. BCD is printed before exiting with an error message.

Answer: C

ANONYMOUS CLASSES

Anonymous classes can be declared to extend another class or to implement a single interface. If you declare a class that implements a single explicit interface, then it is a direct subclass of java.lang.Object.

Anonymous classes give you a convenient way to avoid having to think up trivial names for classes. They should be small and easy to understand as they do not contain descriptive names.

You cannot define any specific constructor for an anonymous inner class. This is a direct consequence of the fact that you do not specify a name for the class, and therefore you cannot use that name to specify a constructor. Anonymous Class Declarations

new Identifier() { /* class body */ }

Identifier is a class or interface name. The expression by itself isn't of much use, it returns a reference to an object that you usually assign to a reference variable of the same type of the identifier:

Identifier = new Identifier() { /* class body */ };

Of course you can also pass the resulting reference to a method:

Method(new Identifier() { /* class body *} );

Example:

class Test {

public static void main(String args[]) {

Base o = new Base() {

public void Hi() {

System.out.println("Hi!");

}

public void Bye() {

System.out.println("Bye");

}

};

o.Hi();

}

}

interface Base {

public void Hi();

}

Result:

Hi!

Anonymous classes should provide methods defined by the base class or the interface but not brand new methods although they can be declared without compilation errors.

Passing arguments

You can define a constructor inside a inner class, but if you provide arguments, the matching constructor of base class will be invoked:

class Test {

public static void main(String args[]) {

Base o = new Base(15) {

public void Hi() {

System.out.println("Hi!");

}

public void Bye() {

System.out.println("Bye");

}

};

o.Hi();

// o.Bye(); // ERROR.

}

}

class Base {

Base (int i) {

System.out.println("I've got "+i);

}

public void Hi() { }

}

Result:

I've got 15

Hi!

Initialising Anonymous classes

You can't define constructors for an anonymous class, but you can declare an initialisation block:

class Test {

public static void main(String args[]) {

Object o = new Object() {

{

System.out.println("Init");

}

};

}

}

Result:

Init

This feature is available to all classes, not only anonymous ones.

INNER CLASSES

An inner or nested class is the same as any other class but is declared inside some other class or method. When an instance of an inner class is created, there must normally be a pre-existing instance of the outer class acting as context. An inner class and an outer class belong together; the inner class is not just another member of the outer instance.

Example #1:

class Test {

class Inner {

Inner () {

System.out.println("Hello World");

}

}

public static void main(String args[]) {

Test.Inner i = new Test().new Inner();

}

}

Result:

Hello World

Please note the special syntax used to reference the Inner class from a static context. This is just a shorter approach for this:

Test t = new Test();

Inner i = t.new Inner();

Example #2:

class Test {

String h = "Hello World";

class Inner {

Inner () {

System.out.println(h);

Bye();

}

}

public static void main(String args[]) {

Test.Inner i = new Test().new Inner();

}

void Bye() {

System.out.println("Good bye!");

}

}

Result:

Hello World

Bye

Inner classes have access to all the features of the outer class including also methods.

Access modifiers and Static Inner Classes

Inner classes may be marked with standard access modifiers (private, public, protected) (or default if no modifier is specified). Static inner classes do not have any reference to the enclosing instance. Static methods of inner classes may not access non-static features of the outer class.

Example:

class Test {

private static String h = "Hello World";

static class Inner {

static void MyMethod () {

System.out.println(h);

}

}

public static void main(String args[]) {

Test.Inner.MyMethod();

}

}

Result:

Hello World

The Inner class is an extension of the outer class, so we have access to private members.

Classes defined inside Methods

Anything declared inside a method is not a member of the class but is local to the method. Therefore, classes declared in methods are private to the method and cannot be marked with any access modifier; neither can they be marked as static. However, an object created from an inner class within a method can have some access to the variables of the enclosing method if they declare the final modifier.

Since local variables and method arguments are conventionally destroyed when their method exits, these variables would be invalid for access by inner class methods after the enclosing method exists. By allowing access only to final variables, it becomes possible to copy the values of those variables into the object itself.

Example:

class Test {

public static void main(String args[]) {

Hi("Ernest");

}

static void Hi(String name) {

final String h = "Hello World " + name;

int j = 5;

class Inner {

void MyMethod () {

System.out.println(h);

// j++; // ERROR !!!

}

}

Inner i = new Inner();

i.MyMethod();

}

}

Although the variable name entered the method as normal variable, its contents were added to a final variable.