Subscribe

RSS Feed (xml)

Powered By

Skin Design:
Free Blogger Skins

Powered by Blogger

Monday, August 24, 2009

Java Quiz-9

Hi friends,

Today I would like to post few more questions to test your capability.
Dont worry guys, I will give you the answer too! Try to answer it yourself without referring to the answers to test yourself.

1)What is the output of following code

class MyOuter
{
private int x = 7;

public void makeInner()
{
MyInner in = new MyInner();
in.seeOuter();
System.out.println(x);
}

class MyInner
{
public void seeOuter()
{
x += (++x + x++);
System.out.println(x++);
}
}

public static void main(String [] args)
{
MyOuter outer = new MyOuter();
outer.makeInner();
}
}

Ans

23
24

2)Write code to fill up the blanks

class MyOuter
{
private int x = 7;

public void makeInner() {
MyInner in = new MyInner();
in.seeOuter();
}

class MyInner
{
public void seeOuter()
{
System.out.println("Outer x is " + x);
}
}

public static void main(String[] args)
{
MyOuter mo = new MyOuter();
_______ inner = ___________;
inner.seeOuter();
}


}

Ans

MyOuter.MyInner
mo.new MyInner()

3)What is the output of the following code?

class Popcorn
{
public void pop()
{
System.out.println("popcorn");
}
}

class Food
{
Popcorn p = new Popcorn()
{
public void sizzle ()
{
System.out.println("anonymous sizzling popcorn");
}
public void pop()
{
System.out.println("anonymous popcorn");
}
};

public void popIt()
{
p.pop();
p.sizzle();
}
}

Ans

-----
p.sizzle() will result in compilation error: cannot resolve symbol

4) Which are true about a static nested class? (Choose all that apply.)

A. You must have a reference to an instance of the enclosing class in order
to instantiate it.

B. It does not have access to non-static members of the enclosing class.

C. Its variables and methods must be static.

D. If the outer class is named MyOuter, and the nested class is named
MyInner, it can be instantiated using new MyOuter.MyInner();.

E. It must extend the enclosing class.


Ans

B and D

5)What is the problem with the following code?

class FooRunnable implements Runnable
{
public void run()
{
for(int x =1; x < 6; x++)
{
System.out.println("Runnable running");
}
}
}

public class TestThreads
{
public static void main (String [] args)
{
FooRunnable r = new FooRunnable();
r.run();
}
}

Ans

We are not creating Threads here. The programs runs single-threaded.

6)What should you do to make the run() method in the following code
to be thread-safe?

class NameRunnable implements Runnable
{
public void run()
{
for (int x = 1; x <= 3; x++)
{
System.out.println("Run by "
+ Thread.currentThread().getName()
+ ", x is " + x);
}
}
}

Ans

Nothing. The method is already thread-safe.

Hope you found this useful! Kindly give me your comments regarding the same.Many more Quizzes are yet to be posted! Kindly make use of them as much as possible!

No comments: