Subscribe

RSS Feed (xml)

Powered By

Skin Design:
Free Blogger Skins

Powered by Blogger

Monday, August 31, 2009

Preparing For SCJP Certification

Hi friends,

Today I would like to share my experience both during my preparation and on the day of the SCJP exam which I took on the previous Saturday(29/08/2009).

POINT TO NOTE:

There are totally seven parts that evaluate a candidate in an SCJP test.

* Declaration,Initialization and scoping
* Flow Control
* API Contents
* Concurrency
* OO Concepts
* Collections/Generics
* Fundamentals

PREPARATION:

First of all I took my certification seriously as this is going to be my first stepping stone.I studied smart and utilized as much time as possible, for the exam.

I started my preparation about five months back. I started with the book
SCJP Sun Certified Programmer for Java 5 Study Guide (Exam 310-055) by Katherine Sierra and Bert Bates

To get my Fundamentals strong, I referred the book,
Head First Java by Katherine Sierra and Bert Bates
Both these books cover all the portions that are needed for the SCJP 1.5 exam.
Head first Java was very helpful to understand the concepts and was a good support when I needed a concept in SCJP book to be explained in more detail.

I also had the help of many of our associates who taught me how to view a problem in the exam.
Two typical examples, 
Before starting, I find out problems that can be easily solved and solve them.I solve the rest when I go through it the next time. This ensures that I have a favourable number questions that help me clear the exam, and in the second pass, I concentrate on the rest to ensure that I get as many questions right as possible and score high.

If I was spending some time on a problem, I make sure that I complete it before proceeding further. This would save a lot of time for going through all the questions again.

Apart from that I referred to various Mock Tests available online and I made sure that I didnt go by their solution if I felt that the answer given to be confusing.
This helped me a lot and I learnt something new each time I attended one.
I used to solve the code snippets and had found some examples which were given wrong solutions.


DURING THE EXAM:

During the exam, I felt the same tension that I had during my degree exam. But I would assure you that you dont have to worry, there is ample time. Three hours for sixty questions and you have choice for the answers too!

There are two type of questions according to my classification,
One type is that we have to judge what is the output from a set of choices, and 
In Second type, you are given some code snippets and are asked to arrange them in a proper sequence so that you get some specific output.
Especially for the second type, the online questions which I had tested myself earlier came to my help and I solved them easily.

Remember that you are not given ant or eclipse in the exam. Everything has to be done by your mind and the paper pad.

I completed my test in about one and a half hours. At the end of one and a half hours, I was confident of fifty five questions out of sixty to be correct.

This confidence made me bold and I tried my best on the other five questions.
At the end, As I submitted I got the result immediately and all my tension got subsided on seeing the result.


MY TOTAL SCORE  93.00%

ASSESMENT SECTION
SECTION ANALYSIS



Declaration,Initialization and scoping  90.00%
Flow Control  81.00%
API Contents  100.00%
Concurrency  100.00%
OO Concepts  90.00%
Collections/Generics  100.00%
Fundamentals  100.00%


Sunday, August 30, 2009

Java Quiz-12

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.

Q: 1 Given

1. // insert code here
2. private N min, max;
3. public N getMin() { return min; }
4. public N getMax() { return max; }
5. public void add(N added) {
6. if (min == null || added.doubleValue() < min.doubleValue()) 
7. min = added;
8. if (max == null || added.doubleValue() > max.doubleValue()) 
9. max = added;
10. }
Which two, inserted at line 1, will allow the code to compile? (Choose two.)

A. public class ClassA {
B. public class ClassA {
C. public class ClassA {
D. public class ClassA {
E. public class ClassA {
F. public class ClassA {

Answer: D, F

Q: 2 Given:
1. import java.util.*;
2.
3. public class ClassA{
4. public static void main(String[] args) {
5. ArrayList strings = new ArrayList();
6. strings.add("aAaA");
7. strings.add("AaA");
8. strings.add("aAa");
9. strings.add("AAaa");
10. Collections.sort(strings);
11. for (String data : strings) { System.out.print(data + " "); }
12. }
13. }
What is the result?

A. Compilation fails.
B. aAaA aAa AAaa AaA
C. AAaa AaA aAa aAaA
D. AaA AAaa aAaA aAa
E. aAa AaA aAaA AAaa
F. An exception is thrown at runtime.

Answer: C

Q: 3 Given:
1. public abstract class ClassA {
2. private int x;
3. private int y;
4. public abstract void quiz();
5. public void test(int x, int y) {
6. this.x = x;
7. this.y = y;
8. }
9. }
Which two classes use the ClassA class correctly? (Choose two.)
A. public class ClassB implements ClassA {
private int data;
}
B. public abstract class ClassB extends ClassA {
private int data;
}
C. public class ClassB extends ClassA {
private int data;
public void quiz();
}
D. public abstract class ClassB implements ClassA {
private int data;
public void quiz();
}
E. public class ClassB extends ClassA {
private int data;
public void quiz() {/* code here */}
F. public abstract class ClassB implements ClassA {
private int data;
public void quiz() { /* code here */ }


Answer: B, E

Q: 4 Given
1. class ClassA {
2. static void questions() { /* more code here */ }
3. void answers() { /* more code here */ }
4. }
Which two statements are true? (Choose two.)

A. ClassA.answers() is a valid invocation of answers().
B. ClassA.questions() is a valid invocation of questions().
C. Method answers() can directly call method questions().
D. Method questions() can directly call method answers().


Answer: B, C

Q: 5 Given:
1. class ClassA {
2. public ClassA() { System.out.print(1); }
3. }
4. class ClassB extends ClassA {
5. public ClassB() { System.out.print(2); }
6. }
7. class ClassC extends ClassB {
8. public ClassC() { System.out.print(3); }
9. }
10. public class ClassNumbers{
11. public static void main( String[] args ) { new ClassC(); }
12. }
What is the result when this code is executed?

A. 1
B. 3
C. 123
D. 321
E. The code runs with no output.


Answer: C

Q: 6 Given:
1. class ClassA{
2. public enum Direction { NORTH, SOUTH, EAST, WEST }
3. }
4. public class ClassB{
5. // insert code here
6. }
Which code, inserted at line 5, allows the ClassB class to compile?

A. Direction data = NORTH;
B. ClassA.Direction data = NORTH;
C. Direction data = Direction.NORTH;
D. ClassA.Direction data = ClassA.Direction.NORTH;


Answer: D

Q: 7 Given:
1. class ClassA {
2. public ClassA classAObj() { return this; }
3. }
4. class ClassB extends ClassA {
5. public ClassA classAObj() { return this; }
6. }
7. class ClassC extends ClassB {
8. // insert method here
9. }
Which ClassB methods, inserted individually, correctly complete the ClassC class? (Choose ClassB.)

A. public void classAObj() {}
B. public int classAObj() { return 3; }
C. public ClassB classAObj() { return this; }
D. public ClassA classAObj() { return this; }
E. public Object classAObj() { return this; }


Answer: C, D

Q: 8 Given:
1. public static void main(String[] args) {
2. Object obj = new int[] { 1, 2, 3 };
3. int[] dataArray = (int[])obj;
4. for (int data : dataArray) System.out.print(data + " ");
5. }
What is the result?

A. 1 2 3
B. Compilation fails because of an error in line 2.
C. Compilation fails because of an error in line 3.
D. Compilation fails because of an error in line 4.
E. A ClassCastException is thrown at runtime.


Answer: A

Q: 9 Given:
1. public class ClassA implements Runnable {
2. public void run() {
3. System.out.print("Answer it yourself");
4. }
5. public static void main(String[] args) {
6. Thread t = new Thread(new ClassA());
7. t.run();
8. t.run();
9. t.start();
10. }
11. }
What is the result?

A. Compilation fails.
B. An exception is thrown at runtime.
C. The code executes and prints "Answer it yourself".
D. The code executes and prints "Answer it yourselfAnswer it yourself".
E. The code executes and prints "Answer it yourselfAnswer it yourselfAnswer it yourself".

Answer: E

Q: 10 Given:
1. public class ClassA {
2. public static void main (String[] args) throws Exception {
3. Thread.sleep(2000);
4. System.out.println("Java Quiz");
5. }
6. }
What is the result?
A. Compilation fails.
B. An exception is thrown at runtime.
C. The code executes normally and prints "Java Quiz".
D. The code executes normally, but nothing is printed.

Answer: C

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! 

Thursday, August 27, 2009

Java Quiz -11

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.

Q: 1 Given:
1. public class ClassA {
2. public static void main(String[] args) {
3. String myProp = /* insert code here */
4. System.out.println(myProp);
5. }
6. }
and the command line:
java -Dprop.custom=apple ClassA
Which two, placed on line 3, will produce the output apple? (Choose two.)
A. System.getProperty("prop.custom");
B. System.property("prop.custom");
C. System.getProperties().getProperty("prop.custom");
D. System.load("prop.custom");
E. System.getenv("prop.custom");

Answer: A, C

Q: 2 Given:
1. class ClassA {
2. ClassB classBobj;
3. public ClassA() { booch = new ClassB(this); }
4. }
5.
6. class ClassB {
7. ClassA classAobj;
8. public ClassB( ClassA s) { classAobj = s; }
9. }
And the statements:
10. public static void main(String[] args) {
11. ClassA classAmainObj = new ClassA();
12. classAmainObj = null;
13. // more code here
14. }
Which statement is true about the objects referenced by classAmainObj, classAobj, and classBobj immediately after line
12 executes?
 
A. Only the object referenced by classAobj is eligible for garbage collection.
B. None of these objects are eligible for garbage collection.
C. The objects referenced by classAobj and classBobj are eligible for garbage collection.
D. Only the object referenced by classBobj is eligible for garbage collection.
E. Only the object referenced by classAmainObj is eligible for garbage collection.

Answer: E

Q: 3 Given:
1. public class ClassA {
2.
3. static public void main(String [] args) {
4. for(int x = 1; x < args.length; x++) {
5. System.out.print(args[x] + " ");
6. }
7. }
8. }
and the command line invocation:
java ClassA a b c
What is the result?

A. a b
B. b c
C. a b c
D. Compilation fails.
E. An exception is thrown at runtime.

Answer: B

Q: 4 A developer is creating a class ClassA, that needs to access class ClassB. The
ClassB class is deployed in a JAR named quiz.jar. Which three, taken independently, will allow the developer to use the ClassB class while compiling the ClassA class? (Choose three.)

A. The JAR file is located at $JAVA_HOME/jre/classes/quiz.jar.
B. The JAR file is located at $JAVA_HOME/jre/lib/ext/quiz.jar.
C. The JAR file is located at /foo/quiz.jar and a classpath environment variable is set that includes
/foo/quiz.jar/ClassB.class.
D. The JAR file is located at /foo/quiz.jar and a classpath environment variable is set that includes
/foo/quiz.jar.
E. The JAR file is located at /foo/quiz.jar and the ClassA class is compiled using javac -cp /foo/quiz.jar/ClassB
ClassA.java.
F. The JAR file is located at /foo/quiz.jar and the ClassA class is compiled using javac -d /foo/quiz.jar
ClassA.java
G. The JAR file is located at /foo/quiz.jar and the ClassA class is compiled using javac -classpath
/foo/quiz.jar ClassA.java

Answer: B, D, G

Q: 5 Given:
enum Example { Questions,Answers,Test }
Which statement is true?
A. The expressions (Questions == Questions) and Questions.equals(Questions) are both guaranteed to be true.
B. The expression (Questions < Answers) is guaranteed to be true and Questions.compareTo(Answers) is guaranteed to be less
than Questions.
C. The Example values cannot be used in a raw java.util.HashMap; instead, the programmer must use a
java.util.EnumMap.
D. The Example values can be used in a java.util.SortedSet, but the set will NOT be sorted because enumerated types do NOT implement java.lang.Comparable.

Answer: A


Q: 6 Given:
1. import java.util.*;
2. public class ClassA {
3. public static void main(String[] args) {
4. PriorityQueue data = new PriorityQueue();
5. data.add("Test");
6. data.add("Questions");
7. data.add("Answers");
8. System.out.println(data.poll() + ":" + data.peek());
9. }
10. }
What is the result?
A. Questions:Questions
B. Test:Questions
C. Questions:Answers
D. Answers:Questions
E. Test:Test
F. Test:Answers


Answer: C

Q: 7 Given:

1. Object [] data = {
2. new Integer(12),
3. new String("foo"),
4. new Integer(5),
5. new Boolean(true)
6. };
7. Arrays.sort(data);
8. for(int i=0; i9. System.out.print(data[i].toString());
10. System.out.print(" ");
11. }
What is the result?
A. Compilation fails due to an error in line 1.
B. Compilation fails due to an error in line 7.
C. A ClassCastException occurs in line 7.
D. A ClassCastException occurs in line 5.
E. The value of all four objects will be printed.


Answer: C

Q: 8 Given:
1. import java.util.*;
2. public class ClassA {
3. private String s;
4. public ClassA(String s) { this.s = s; }
5. public static void main(String[] args) {
6. HashSet test = new HashSet();
7. ClassA classAobj1 = new ClassA("aardvark");
8. ClassA classAobj2 = new ClassA("aardvark");
9. String s1 = new String("aardvark");
10. String s2 = new String("aardvark");
11. test.add(classAobj1); test.add(classAobj2); test.add(s1); test.add(s2);
12. System.out.println(test.size()); } }
What is the result?
A. 0
B. 1
C. 2
D. 3
E. 4
F. Compilation fails.
G. An exception is thrown at runtime.

Answer: D  

Q: 9 Given:
1. public class ClassA {
2. private long data1;
3. private long data2;
4.
5. // class ClassA methods
6. }
A programmer is developing a class ClassA, that will be used as a ClassA in a standard java.util.HashMap.
Which two methods should be overridden to assure that ClassA works correctly as a ClassA? (Choose two.)

A. public int hashCode()
B. public boolean equals(ClassA k)
C. public int compareTo(Object o)
D. public boolean equals(Object o)
E. public boolean compareTo(ClassA k)


Answer: A, D

Q: 10 Given a pre-generics implementation of a method:
1. public static int data(List list) {
2. int data = 0;
3. for ( Iterator iter = list.iterator(); iter.hasNext(); ) {
4. int i = ((Integer)iter.next()).intValue();
5. data += i;
6. }
7. return data;
8. }
Which three changes must be made to the method data to use generics? (Choose three.)

 
A. remove line 4
B. replace line 4 with "int i = iter.next();"
C. replace line 3 with "for (int i : intList) {"
D. replace line 3 with "for (Iterator iter : intList) {"
E. replace the method declaration with "data(List intList)"
F. replace the method declaration with "data(List intList)"

 Answer: A, C, F

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!
 

Wednesday, August 26, 2009

Few Points Related To Design Patterns

Hi friends,

Its been sometime since we shared some information regarding the concepts(For those who missed out, We had been doing Few Java Quizzes! Check It out Here
http://helptotheneeded.blogspot.com/search/label/Java%20Quiz)


Today I would like to present a general hint which would be helpful for people who want to take seminars in Design Patterns.

Without wasting further time, Here We Go!

Before Design Pattern:

Interface – Car and TV remote
Abstract Class – I10
Is a - has a
Aggregation - If the History-Class object is destroyed, the Student objects may continue to exist.
History-Class << --->Student
(Weak relationship)
Composition - If the House object is destroyed, the Room objects will also be destroyed.
(Strong relationship) House << --- > Room

Architecture – Skeletal view
Framework – Implementation

Organizing the patterns:

Creational – Involve object instantiation and all provide a way to decouple a client from the objects
it needs to instantiate.
Behavioral – It is concerned with how classes and objects interact and distribute responsibility.
Structural – It lets you compose classes or objects into larger structures.

GOF – Gang of four (Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides) author’s of the book

There are 250 patterns in oo world where 23 are familiar and well known patterns.

Creational:
Singleton:

“Ensure a class has one instance and provide a global point of access to it”
public class single {
private static single s;
private single() { };

public static synchronized single getInstance()
{
if(s==null)
s = new single();
return s;
}
//other methods continue here

Factory Method:

Based on your data, we are going to instaniate an object of a classes
eg:
Car<- Buick, Chevrolet, Ford, Pontiac and Saturn
public class OrderCars
{
public Car orderCar(String model)
{
Car car;
if(model.equals("Lucerne"))
car = new Buick(model);
else if(model.equals("Corvette"))
car = new Chevrolet(model);
else if(model.equals("Fusion"))
car = new Ford(model);
else if(model.equals("GTO"))
car = new Pontiac(model);
else if(model.equals("Vue"))
car = new Saturn(model);
}
}
When a class does not know which class of objects it must create.

Abstract Factory:

Its a super set of Factory method pattern


public class ComputerType {
private Computer comp;
public static void main(String[] args) {
ComputerType type = new ComputerType();
Computer computer = type.getComputer("Server");
System.out.println("Monitor: "+computer.getMonitor().getSpecification());
System.out.println("RAM: "+computer.getRAM().getSpecification());
System.out.println("Processor: "+computer.getProcessor().getSpecification());
}
/**
* Returns a computer for a type
*
* @param computerType String, PC / Workstation / Server
* @return Computer
*/
public Computer getComputer(String computerType) { if (computerType.equals("PC"))
comp = new PC();
else if(computerType.equals("Workstation"))
comp = new Workstation();
else if(computerType.equals("Server"))
comp = new Server();
return comp;
} }// End of class

Builder and Prototype

Behavioral:

Strategy - It desines a set of algorithm and make them interchangable based on client request (refer ppt )
Observer - Refer ppt It defines a one-to-many dependency between objects so that when one object change state,
all of its dependents are notified and updated automatically (refer ppt)
Chain of Responsibility , Command , Interpreter , Iterator , Mediator, Memento

Structural:

Adapter: It converts the interface of a class into another interface the client expects. Adapter lets
classes work together that couldn’t otherwise because of incompatible interfaces (refer ppt )
Façade: This is nothing but the outlook of an object.It hides the complexity of our implementation
(refer ppt ).

Bridge ,Composite, Decorator, Façade, Flyweight and Proxy

This Information As Said Earlier is only a general hint which would be helpful for people who want to take seminars.
Hope It was useful to you, Please Post your comments!

Tuesday, August 25, 2009

Java Quiz -10

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.

Q: 1 Given:
1.public class TestString3{
2. public static void main(String[] args) {
3.// insert code here
4.System.out.println(s);
5.}
6.} Which two code fragments, inserted
independently at line 3, generate the output 4247? (Choose two.)

A. StringBuffer s = new StringBuffer("123456789");
s.substring(3,6).delete(1,3).insert(1, "24");
B. StringBuffer s = new StringBuffer("123456789");
s.delete(0,3).replace(1,3,"24").delete(4,6);
C. String s = "123456789";
s = (s-"123").replace(1,3,"24") - "89";
D. StringBuilder s = new StringBuilder("123456789");
s.substring(3,6).delete(1,2).insert(1, "24");
E. StringBuilder s = new StringBuilder("123456789");
s.delete(0,3).delete(1,3).delete(2,5).insert(1, "24");

Answer: B, E

Q: 2 When comparing java.io.BufferedWriter to java.io.FileWriter, which
capability exists as a method in only one of the two?

A. writing a line separator to the stream
B. writing to the stream
C. marking a location in the stream
D. flushing the stream
E. closing the stream

Answer: A

Q: 3 Given:
12. Date date = new Date();
13. df.setLocale(Locale.ITALY);
14. String s = df.format(date);
The variable df is an object of type DateFormat that has been initialized in line 11.
What is the result if this code is run on December 14, 2000?

A. The value of s is Dec 14, 2000.
B. The value of s is 14-dec-2004.
C. Compilation fails because of an error in line 13.
D. An exception is thrown at runtime.

Answer: C

Q: 4 Which three statements concerning the use of the java.io.Serializable
interface are true? (Choose three.)

A. An object serialized on one JVM can be successfully deserialized on a different JVM.
B. The values in fields with the transient modifier will NOT survive serialization and deserialization.
C. It is legal to serialize an object of a type that has a supertype that does NOT implement java.io.Serializable.
D. Objects from classes that use aggregation cannot be serialized.
E. The values in fields with the volatile modifier will NOT survive serialization and deserialization.

Answer: A, B, C

Q: 5 Given:
11. String test = "This is a test";
12. String[] tokens = test.split("\s");
13. System.out.println(tokens.length);
What is the result?

A. 10
B. 2
C. 5
D. Compilation fails.
E. An exception is thrown at runtime.

Answer: D

Q: 6 Given:
d is a valid, non-null Date object
df is a valid, non-null DateFormat object set to the current locale
What outputs the current locale's country name and the appropriate version of d's date?

A. Locale loc = Locale.getDefault();
System.out.println(loc.getDisplayCountry()
+ " " + df.format(d));
B. Locale loc = Locale.getLocale();
System.out.println(loc.getDisplayCountry()
+ " " + df.setDateFormat(d));
C. Locale loc = Locale.getDefault();
System.out.println(loc.getDisplayCountry()
+ " " + df.setDateFormat(d));
D. Locale loc = Locale.getLocale();
System.out.println(loc.getDisplayCountry()
+ " " + df.format(d));

Answer: A

Q: 7 Given classes defined in two different files:
1. package util;
2. public class ClassA {
3. private static void process(byte[] b) {}
4. }
1. package app;
2. public class ClassB {
3. public static void main(String[] args) {
4. byte[] byteobj = new byte[256];
5. // insert code here
6. }
7. }
What is required at line 5 in class SomeApp to use the process method of ClassB?

A. process(byteobj);
B. ClassB.process(byteobj);
C. app.ClassB.process(byteobj);
D. util.ClassB.process(byteobj);
E. import util.ClassB.*; process(byteobj);
F. SomeApp cannot use the process method in ClassB.

Answer: F

Q: 8 Given:
1. rbo = new ReallyBigObject();
2. // more code here
3. rbo = null;
4. /* insert code here */
Which statement should be placed at line 4 to suggest that the virtual machine expend effort toward recycling the memory used by the object rbo?

A. Runtime.getRuntime().growHeap();
B. System.freeMemory();
C. Runtime.getRuntime().freeMemory();
D. System.gc();
E. Runtime.gc();

Answer: D

Q: 9 Given classes defined in two different files:
1. package util;
2. public class ClassB {
3. public static void process(byte[]) { /* more code here */ }
4. }
1. package app;
2. public class ClassA {
3. public static void main(String[] args) {
4. byte[] byteobj = new byte[256];
5. // insert code here
6. }
7. }
What is required at line 5 in class ClassA to use the process method of ClassB?

A. ClassB.process(byteobj);
B. util.ClassB.process(byteobj);
C. process(byteobj);
D. import util.ClassB.*; process(byteobj);
E. SomeApp cannot use methods in ClassB.

Answer: B

Q: 10 Given:
11. public static void test(String string) {
12. int value = 4;
13. if ( value = string.length()) {
14. System.out.print(string .charAt( value -= 1) +", ");
15. } else {
16. System.out.print(string .charAt(0) + ", ");
17. }
18. }
and the invocation:
21. test("four");
22. test("tee");
23. test("to");
What is the result?

A. r, e, o,
B. r, t, t,
C. Compilation fails.
D. An exception is thrown at runtime.

Answer: C

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!

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!

Friday, August 21, 2009

Java Quiz -8

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)I have class called GlobalCache in package com.planetsoft.cache.
I want to print the name of the class, without creating an object
of the class.


Ans: GlobalCache.class.getName()

2)What is the output of the following program?

System.out.println("value=" + 08);


Ans: Compilation Error: Octal digit out of range

3)What is the output of the following code

private void display()
{
int ret = catchMe(true);
System.out.println("ret=" + ret);

ret = catchMe(false);
System.out.println("ret=" + ret);

}
private int catchMe(boolean cond)
{

try
{
if (cond) throw new Exception("catch me");
return 1;
}
catch(Exception ex)
{
return 2;
}
finally
{
return 3;
}

}

Ans:

ret=3
ret=3


5)What is wrong in the following code? suggest a solution to fix it

public static void display()
{
final long MICROS_PER_DAY = 24 * 60 * 60 * 1000 * 1000;
final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000;
System.out.println(MICROS_PER_DAY / MILLIS_PER_DAY);
}

Ans:

The problem is arithmetic overflow. Solution is to prefix the
numbers with L, to make the computation in long arithmetic.


6)Mr. Jack has a 15cm gold bar and wants to give Mr. Jill, 1 cm
of gold bar on day 1, 2cms of gold bar on day 2, and so on..., .Finally
Mr. Jack should give away 15 cms of gold bar on day 15.
Following are the rules
a)Mr. Jack can make at the most 3 cuts in the gold bar
b)Mr. Jack can take back the gold bars , given to Mr. Jill, on any
given day.

Ans:
Make 3 cuts at 1,2 and 4 cms

7)A car runs for 10,000 kms. It has one stepney(i.e, extra tyre).
If all tyres has to be used equally, what is the total no. of
kms, each tyre would have run?

Ans:
8000 kms

8)There are 3 fruit baskets - one with full of Apples, one with
full of Oranges and one with both apples and oranges. All boxes
are labelled wrongly. You cannot see what is inside the box.
Given these , you have to pick only one fruit from any one of the
box of your choice, and label the boxes correctly. How do you
solve this?

Ans:

----
Pick one fruit from Box labelled "Mixed"
If it is Apple then

Rename "Mixed" as "Apple".
Rename "Apple" as "Orange"
Rename "Orange" as "Mixed"

else If it is Orange then

Rename "Mixed" as "Orange".
Rename "Orange" as "Apple"
Rename "Apple" as "Mixed"

End if

9)From a List of String , how to get array of Strings
Note: You only have to fill up the blanks in the following code.

private static void display()
{
List l = new ArrayList();

l.add("tom");
l.add("harry");
String [] arr = ------------------;

}

Ans:
(String [])l.toArray(new String[0])


10)What is the output of the following method

private static void display()
{
char x = 'X';
int i = 0;
System.out.print(true ? x : 0);
System.out.print(false ? i : x);

}

Ans:
X88

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!

Thursday, August 20, 2009

JUnit Tests

Hi Friends,
Today Lets see A sample program as to how JUnit test is performed.
For readers who can grasp information if explained using a program, this post is going to be very Informative.

First We Have A Class for which JUnit has to be written

// JUnit test example

public class Rectangle
{
// State variables.
private int height;
private int width;

// Constructors
Rectangle()
{
height=0;
width =0;
}
Rectangle(int h,int w)
{
height=h;
width =w;
}

// Readers
public int getH()
{return height;}
public int getW()
{return width;}
public int getA()
{return height* width;}

// Writers
public void setH(int h)
{height=h;}
public void setW(int w)
{width =w;}

public String toString()
{return "Rectangle: height="+height+"; width="+ width +
"; area="+getA()+".";}

} // End of Rectangle class

Now We Create A TestCase for The Rectangle Class





import static org.junit.Assert.*;
import org.junit.*;

public class RectangleTest extends TestCase
{
Rectangle r;
Rectangle[] rList=new Rectangle[5];

@Before
// Will be performed before each test.
public void testSetup()
{
System.out.println("Setup for test complete.");
}

@After
// Will be performed after each test.
public void testComplete()
{
System.out.println("Test complete.");
}

@Test
public void test1()
{
// Can be run when reader methods and default
// constructor are complete.
r=new Rectangle();
try
{
assertTrue("Test 1: Default values are wrong.",
r.getH()==0 && r.getW()==0);
System.out.println("Test 1 completed successfully.");
}
catch (AssertionError e)
{
System.out.println(e.getMessage());
}
}

@Test
public void test2()
{
// After area reader is written.
r=new Rectangle();
try
{
assertTrue("Test 2: Default values are wrong.",
r.getH()==0 && r.getW()==0 && r.getA()==0);
System.out.println("Test 2 completed successfully.");
}
catch (AssertionError e)
{
System.out.println(e.getMessage());
}
}



@Test
public void test3()
{
// After second constructor is written.
r=new Rectangle();
try
{
r=new Rectangle(10,20);
assertTrue("Test 3: Initial values are wrong.",
r.getH()==10 && r.getW()==20 && r.getA()==200);
System.out.println("Test 3 completed successfully.");
}
catch (AssertionError e)
{
System.out.println(e.getMessage());
}
}

@Test
public void test4()
{
// After second constructor is written.
r=new Rectangle();
try
{
for (int i=0;i<5;i++)
{
rList[i] = new Rectangle(2*i,3*i);
assertTrue("Test 4: Initial values are wrong.",
rList[i].getH()==2*i &&
rList[i].getW()==3*i &&
rList[i].getA()==6*i*i);
}
System.out.println("Test 4 completed successfully.");
}
catch (AssertionError e)
{
System.out.println(e.getMessage());
}
}

@Test
public void test5()
{
// After writers are written.
r=new Rectangle();
try
{
for (int i=0;i<5;i++)
{
rList[i] = new Rectangle(2*i,3*i);
rList[i].setH(11*i);
rList[i].setW(7*i);
assertTrue("Test 5: Modified values are wrong.",
rList[i].getH()==11*i &&
rList[i].getW()==7*i &&
rList[i].getA()==77*i*i);
}
System.out.println("Test 5 completed successfully.");
}
catch (AssertionError e)
{
System.out.println(e.getMessage());
}
}

@Test
public void test6()
{
// toString test.
r=new Rectangle();
try
{
for (int i=0;i<5;i++)
{
rList[i] = new Rectangle(2*i,3*i);
rList[i].setH(11*i);
rList[i].setW(7*i);
assertTrue("Test 6: Modified values are wrong.",
rList[i].getH()==11*i &&
rList[i].getW()==7*i &&
rList[i].getA()==77*i*i);
System.out.println(rList[i]);
}
System.out.println("Test 6 completed successfully.");
}
catch (AssertionError e)
{
System.out.println(e.getMessage());
}
}

public static void main(String[] args)
{
org.junit.runner.JUnitCore.main("RectangleTest");
}
}

Output from correct Rectangle class test:

Setup for test complete.
Test 1 completed successfully.
Test complete.
Setup for test complete.
Test 2 completed successfully.
Test complete.
Setup for test complete.
Test 3 completed successfully.
Test complete.
Setup for test complete.
Test 4 completed successfully.
Test complete.
Setup for test complete.
Test 5 completed successfully.
Test complete.
Setup for test complete.
Rectangle: height=0; width=0; area=0.
Rectangle: height=11; width=7; area=77.
Rectangle: height=22; width=14; area=308.
Rectangle: height=33; width=21; area=693.
Rectangle: height=44; width=28; area=1232.
Test 6 completed successfully.
Test complete.


I changed setH() so that height was set to h*2 and reran the tests.

Setup for test complete.
Test 1 completed successfully.
Test complete.
Setup for test complete.
Test 2 completed successfully.
Test complete.
Setup for test complete.
Test 3 completed successfully.
Test complete.
Setup for test complete.
Test 4 completed successfully.
Test complete.
Setup for test complete.
Test 5: Modified values are wrong.
Test complete.
Setup for test complete.
Rectangle: height=0; width=0; area=0.
Test 6: Modified values are wrong.
Test complete.

Wednesday, August 19, 2009

Java Quiz -7

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.

Q: 1Given:
1. public class Boxer1{
2. Integer i;
3. int x;
4. public Boxer1(int y) {
5. x = i+y;
6. System.out.println(x);
7. }
8. public static void main(String[] args) {
9. new Boxer1(new Integer(4));
10. }
11. }
What is the result?

A. The value "4" is printed at the command line.
B. Compilation fails because of an error in line 5.
C. Compilation fails because of an error in line 9.
D. A NullPointerException occurs at runtime.
E. A NumberFormatException occurs at runtime.
F. An IllegalStateException occurs at runtime.

Answer: D

Q: 2 Given:
11. public static Iterator reverse(List list) {
12. Collections.reverse(list);
13. return list.iterator();
14. }
15. public static void main(String[] args) {
16. List list = new ArrayList();
17. list.add("1"); list.add("2"); list.add("3");
18. for (Object obj: reverse(list))
19. System.out.print(obj + ", ");
20. }
What is the result?

A. 3, 2, 1,
B. 1, 2, 3,
C. Compilation fails.
D. The code runs with no output.
E. An exception is thrown at runtime.

Answer: C

Q: 3 Click the Exhibit button.
Given:
25. try {
26. A a = new A();
27. a.method1();
28. } catch (Exception e) {
29. System.out.print("an error occurred");
30. }
Which two statements are true if a NullPointerException is thrown on line 3 of class C? (Choose two.)

A. The application will crash.
B. The code on line 29 will be executed.
C. The code on line 5 of class A will execute.
D. The code on line 5 of class B will execute.
E. The exception will be propagated back to line 27.

Answer: B, E

Q: 4 Given:
23. int z = 5;
24.
25. public void stuff1(int x) {
26. assert (x > 0);
27. switch(x) {
28. case 2: x = 3;
29. default: assert false; } }
30.
31. private void stuff2(int y) { assert (y < 0); }
32.
33. private void stuff3() { assert (stuff4()); }
34.
35. private boolean stuff4() { z = 6; return false; }
Which statement is true?

A. All of the assert statements are used appropriately.
B. Only the assert statement on line 31 is used appropriately.
C. The assert statements on lines 29 and 31 are used appropriately.
D. The assert statements on lines 26 and 29 are used appropriately.
E. The assert statements on lines 29 and 33 are used appropriately.
F. The assert statements on lines 29, 31, and 33 are used appropriately.
G. The assert statements on lines 26, 29, and 31 are used appropriately.

Answer: C

Q: 5 Given:
25. int x = 12;
26. while (x < 10) {
27. x--;
28. }
29. System.out.print(x);
What is the result?

A. 0
B. 10
C. 12
D. Line 29 will never be reached.

Answer: C

Q: 6 Given:
33. try {
34. // some code here
35. } catch (NullPointerException e1) {
36. System.out.print("a");
37. } catch (RuntimeException e2) {
38. System.out.print("b");
39. } finally {
40. System.out.print("c");
41. }
What is the result if a NullPointerException occurs on line 34?

A. c
B. a
C. ab
D. ac
E. bc
F. abc

Answer: D

Q: 7 Given:
10. public class Foo {
11. static int[] a;
12. static { a[0]=2; }
13. public static void main( String[] args ) {}
14. }
Which exception or error will be thrown when a programmer attempts to run this code?

A. java.lang.StackOverflowError
B. java.lang.IllegalStateException
C. java.lang.ExceptionInInitializerError
D. java.lang.ArrayIndexOutOfBoundsException

Answer: C

Q: 8 Given:
11. public static void main(String[] args) {
12. try {
13. args = null;
14. args[0] = "test";
15. System.out.println(args[0]);
16. } catch (Exception ex) {
17. System.out.println("Exception");
18. } catch (NullPointerException npe) {
19. System.out.println("NullPointerException");
20. }
21. }
What is the result?

A. test
B. Exception
C. Compilation fails.
D. NullPointerException

Answer: C

Q: 9 Given:
12. public class Wow {
13. public static void go(short n) {System.out.println("short");}
14. public static void go(Short n) {System.out.println("SHORT");}
15. public static void go(Long n) {System.out.println(" LONG");}
16. public static void main(String [] args) {
17. Short y = 6;
18. int z = 7;
19. go(y);
20. go(z);
21. }
22. }
What is the result?

A. short LONG
B. SHORT LONG
C. Compilation fails.
D. An exception is thrown at runtime.

Answer: C

Q: 10 Given:
12. import java.io.*;
13. public class Forest implements Serializable {
14. private Tree tree = new Tree();
15. public static void main(String [] args) {
16. Forest f = new Forest();
17. try {
18. FileOutputStream fs = new FileOutputStream("Forest.ser");
19. ObjectOutputStream os = new ObjectOutputStream(fs);
20. os.writeObject(f); os.close();
21. } catch (Exception ex) { ex.printStackTrace(); }
22. } }
23.
24. class Tree { }
What is the result?

A. Compilation fails.
B. An exception is thrown at runtime.
C. An instance of Forest is serialized.
D. An instance of Forest and an instance of Tree are both serialized.

Answer: B

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!

Tuesday, August 18, 2009

Java Quiz -6

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.

Q: 1 Given:
1. public class GC {
2. private Object o;
3. private void doSomethingElse(Object obj) { o = obj; }
4. public void doSomething() {
5. Object o = new Object();
6. doSomethingElse(o);
7. o = new Object();
8. doSomethingElse(null);
9. o = null;
10. }
11. }
When the doSomething method is called, after which line does the Object created in line 5 become
available for garbage collection?

A. Line 5
B. Line 6
C. Line 7
D. Line 8
E. Line 9
F. Line 10

Answer: D

Q: 2 Click the Exhibit button.
Which three code fragments, added individually at line 29, produce the output 100? (Choose three.)

A. n = 100;
B. i.setX( 100 );
C. o.getY().setX( 100 );
D. i = new Inner(); i.setX( 100 );
E. o.setY( i ); i = new Inner(); i.setX( 100 );
F. i = new Inner(); i.setX( 100 ); o.setY( i );

Answer: B, C, F

Q: 3 Given:
15. public class Yippee {
16. public static void main(String [] args) {
17. for(int x = 1; x < args.length; x++) {
18. System.out.print(args[x] + " ");
19. }
20. }
21. } and two separate command line invocations:
java Yippee
java Yippee 1 2 3 4
What is the result?

A. No output is produced.
1 2 3
B. No output is produced.
2 3 4
C. No output is produced.
1 2 3 4
D. An exception is thrown at runtime.
1 2 3
E. An exception is thrown at runtime.
2 3 4
F. An exception is thrown at runtime.
1 2 3 4

Answer: B

Q: 4 Given:
11. public void genNumbers() {
12. ArrayList numbers = new ArrayList();
13. for (int i=0; i<10; i++) {
14. int value = i * ((int) Math.random());
15. Integer intObj = new Integer(value);
16. numbers.add(intObj);
17. }
18. System.out.println(numbers);
19. }
Which line of code marks the earliest point that an object referenced by intObj becomes a candidate for
garbage collection?

A. Line 16
B. Line 17
C. Line 18
D. Line 19
E. The object is NOT a candidate for garbage collection.

Answer: D

Q: 5 Click the Exhibit button.
Given the fully-qualified class names:
com.foo.bar.Dog
com.foo.bar.blatz.Book
com.bar.Car
com.bar.blatz.Sun
Which graph represents the correct directory structure for a JAR file from which those classes can be
used by the compiler and JVM?

A. Jar A
B. Jar B
C. Jar C
D. Jar D
E. Jar E

Answer: A

Q: 6 A class games.cards.Poker is correctly defined in the jar file Poker.jar. A user
wants to execute the main method of Poker on a UNIX system using the command:
java games.cards.Poker
What allows the user to do this?

A. put Poker.jar in directory /stuff/java, and set the CLASSPATH to include /stuff/java
B. put Poker.jar in directory /stuff/java, and set the CLASSPATH to include /stuff/java/*.jar
C. Put Poker.jar in directory /stuff/java, and set the CLASSPATH to include /stuff/java/Poker.jar
D. put Poker.jar in directory /stuff/java/games/cards, and set the CLASSPATH to include /stuff/java
E. put Poker.jar in directory /stuff/java/games/cards, and set the CLASSPATH to include /stuff/java/*.jar
F. put Poker.jar in directory /stuff/java/games/cards, and set the CLASSPATH to include /stuff/java/Poker.jar

Answer: C

Q: 7 Given a class Repetition:
1. package utils;
2.
3. public class Repetition {
4. public static String twice(String s) { return s + s; }
5. }
and given another class Demo:
1. // insert code here
2.
3. public class Demo {
4. public static void main(String[] args) {
5. System.out.println(twice("pizza"));
6. }
7. }
Which code should be inserted at line 1 of Demo.java to compile and run Demo to print "pizzapizza"?

A. import utils.*;
B. static import utils.*;
C. import utils.Repetition.*;
D. static import utils.Repetition.*;
E. import utils.Repetition.twice();
F. import static utils.Repetition.twice;
G. static import utils.Repetition.twice;

Answer: F

Q: 8 Given:
11. public static void main(String[] args) {
12. String str = "null";
13. if (str == null) {
14. System.out.println("null");
15. } else (str.length() == 0) {
16. System.out.println("zero");
17. } else {
18. System.out.println("some");
19. }
20. }
What is the result?

A. null
B. zero
C. some
D. Compilation fails.
E. An exception is thrown at runtime.

Answer: D

Q: 9 Given:
11. static class A {
12. void process() throws Exception { throw new Exception(); }
13. }
14. static class B extends A {
15. void process() { System.out.println("B "); }
16. }
17. public static void main(String[] args) {
18. A a = new B();
19. a.process();
20. }
What is the result?

A. B
B. The code runs with no output.
C. An exception is thrown at runtime.
D. Compilation fails because of an error in line 15.
E. Compilation fails because of an error in line 18.
F. Compilation fails because of an error in line 19.

Answer: F

Q: 10 Given:
11. public void testIfA() {
12. if (testIfB("True")) {
13. System.out.println("True");
14. } else {
15. System.out.println("Not true");
16. }
17. }
18. public Boolean testIfB(String str) {
19. return Boolean.valueOf(str);
20. }
What is the result when method testIfA is invoked?

A. True
B. Not true
C. An exception is thrown at runtime.
D. Compilation fails because of an error at line 12.
E. Compilation fails because of an error at line 19.

Answer: A

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!

Monday, August 17, 2009

Java Quiz -5

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.

Q: 1 Given:
10: public class Hello {
11: String title;
12: int value;
13: public Hello() {
14: title += " World";
15: }
16: public Hello(int value) {
17: this.value = value;
18: title = "Hello";
19: Hello();
20: }
21: }
and:
30: Hello c = new Hello(5);
31: System.out.println(c.title);
What is the result?

A. Hello
B. Hello World
C. Compilation fails.
D. Hello World 5
E. The code runs with no output.
F. An exception is thrown at runtime.

Answer: C

Q: 2 Given:
1. class Super {
2. private int a;
3. protected Super(int a) { this.a = a; }
4. }
...
11. class Sub extends Super {
12. public Sub(int a) { super(a); }
13. public Sub() { this.a = 5; }
14. }
Which two, independently, will allow Sub to compile? (Choose two.)

A. Change line 2 to:
public int a;
B. Change line 2 to:
protected int a;
C. Change line 13 to:
public Sub() { this(5); }
D. Change line 13 to:
public Sub() { super(5); }
E. Change line 13 to:
public Sub() { super(a); }

Answer: C, D

Q: 3 Given:
1. class ClassA {
2. public int numberOfInstances;
3. protected ClassA(int numberOfInstances) {
4. this.numberOfInstances = numberOfInstances;
5. }
6. }
7. public class ExtendedA extends ClassA {
8. private ExtendedA(int numberOfInstances) {
9. super(numberOfInstances);
10. }
11. public static void main(String[] args) {
12. ExtendedA ext = new ExtendedA(420);
13. System.out.print(ext.numberOfInstances);
14. }
15. }
Which statement is true?

A. 420 is the output.
B. An exception is thrown at runtime.
C. All constructors must be declared public.
D. Constructors CANNOT use the private modifier.
E. Constructors CANNOT use the protected modifier.

Answer: A

Q: 4 Given:
1. interface A { public void aMethod(); }
2. interface B { public void bMethod(); }
3. interface C extends A,B { public void cMethod(); }
4. class D implements B {
5. public void bMethod(){}
6. }
7. class E extends D implements C {
8. public void aMethod(){}
9. public void bMethod(){}
10. public void cMethod(){}
11. }
What is the result?

A. Compilation fails because of an error in line 3.
B. Compilation fails because of an error in line 7.
C. Compilation fails because of an error in line 9.
D. If you define D e = new E(), then e.bMethod() invokes the version of bMethod() defined in Line 5.
E. If you define D e = (D)(new E()), then e.bMethod() invokes the version of bMethod() defined in Line 5.
F. If you define D e = (D)(new E()), then e.bMethod() invokes the version of bMethod() defined in Line 9.

Answer: F

Q: 5 Given:
1. public class Base {
2. public static final String FOO = "foo";
3. public static void main(String[] args) {
4. Base b = new Base();
5. Sub s = new Sub();
6. System.out.print(Base.FOO);
7. System.out.print(Sub.FOO);
8. System.out.print(b.FOO);
9. System.out.print(s.FOO);
10. System.out.print(((Base)s).FOO);
11. } }
12. class Sub extends Base {public static final String FOO="bar";}
What is the result?

A. foofoofoofoofoo
B. foobarfoobarbar
C. foobarfoofoofoo
D. foobarfoobarfoo
E. barbarbarbarbar
F. foofoofoobarbar
G. foofoofoobarfoo

Answer: D

Q: 6 Which two statements are true? (Choose two.)
A. An encapsulated, public class promotes re-use.
B. Classes that share the same interface are always tightly encapsulated.
C. An encapsulated class allows subclasses to overload methods, but does NOT allow overriding methods.
D. An encapsulated class allows a programmer to change an implementation without affecting outside code.

Answer: A, D

Q: 7 Given classes defined in two different files:
1. package util;
2. public class BitUtils {
3. public static void process(byte[]) { /* more code here */ }
4. }
1. package app;
2. public class SomeApp {
3. public static void main(String[] args) {
4. byte[] bytes = new byte[256];
5. // insert code here
6. }
7. }
What is required at line 5 in class SomeApp to use the process method of BitUtils?

A. process(bytes);
B. BitUtils.process(bytes);
C. util.BitUtils.process(bytes);
D. SomeApp cannot use methods in BitUtils.
E. import util.BitUtils.*; process(bytes);

Answer: C

Q: 8 Given:
13. public class Pass {
14. public static void main(String [] args) {
15. int x = 5;
16. Pass p = new Pass();
17. p.doStuff(x);
18. System.out.print(" main x = " + x);
19. }
20.
21. void doStuff(int x) {
22. System.out.print(" doStuff x = " + x++);
23. }
24. }
What is the result?

A. Compilation fails.
B. An exception is thrown at runtime.
C. doStuff x = 6 main x = 6
D. doStuff x = 5 main x = 5
E. doStuff x = 5 main x = 6
F. doStuff x = 6 main x = 5

Answer: D

Q: 9 Given:
11. public static void test(String str) {
12. if (str == null | str.length() == 0) {
13. System.out.println("String is empty");
14. } else {
15. System.out.println("String is not empty");
16. }
17. }
And the invocation:
31. test(null);
What is the result?

A. An exception is thrown at runtime.
B. "String is empty" is printed to output.
C. Compilation fails because of an error in line 12.
D. "String is not empty" is printed to output.

Answer: A

Q: 10 Given:
12. public class Yippee2 {
13.
14. static public void main(String [] yahoo) {
15. for(int x = 1; x < yahoo.length; x++) {
16. System.out.print(yahoo[x] + " ");
17. }
18. }
19. }
and the command line invocation:
java Yippee2 a b c
What is the result?

A. a b
B. b c
C. a b c
D. Compilation fails.
E. An exception is thrown at runtime.

Answer: B

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!

Saturday, August 15, 2009

Java Quiz -4

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.

Q: 1 Click the Task button.
Answer: Check TestNows eEngine, Download from Member Center
www.TestNows.com Q: 43 Given:
11. String test = "This is a test";
12. String[] tokens = test.split("\s");
13. System.out.println(tokens.length);
What is the result?

A. 0
B. 1
C. 4
D. Compilation fails.
E. An exception is thrown at runtime.

Answer: D

Q: 2 Given:
11. public class Yikes {
12.
13. public static void go(Long n) {System.out.println("Long ");}
14. public static void go(Short n) {System.out.println("Short ");}
15. public static void go(int n) {System.out.println("int ");}
16. public static void main(String [] args) {
17. short y = 6;
18. long z = 7;
19. go(y);
20. go(z);
21. }
22. }
What is the result?

A. int Long
B. Short Long
C. Compilation fails.
D. An exception is thrown at runtime.

Answer: A

Q: 3 Given:
System.out.format("Pi is approximately %d.", Math.PI);
What is the result?

A. Compilation fails.
B. Pi is approximately 3.
C. Pi is approximately 3.141593.
D. An exception is thrown at runtime.

Answer: D

Q: 4 Given:
33. Date d = new Date(0);
34. String ds = "December 15, 2004";
35. // insert code here
36. try {
37. d = df.parse(ds);
38. }
39. catch(ParseException e) {
40. System.out.println("Unable to parse " + ds);
41. }
42. // insert code here too
What creates the appropriate DateFormat object and adds a day to the Date object?

A. 35. DateFormat df = DateFormat.getDateFormat();
42. d.setTime( (60 * 60 * 24) + d.getTime());
B. 35. DateFormat df = DateFormat.getDateInstance();
42. d.setTime( (1000 * 60 * 60 * 24) + d.getTime());
C. 35. DateFormat df = DateFormat.getDateFormat();
42. d.setLocalTime( (1000*60*60*24) + d.getLocalTime());
D. 35. DateFormat df = DateFormat.getDateInstance();
42. d.setLocalTime( (60 * 60 * 24) + d.getLocalTime());

Answer: B

Q: 5 Given:
12. NumberFormat nf = NumberFormat.getInstance();
13. nf.setMaximumFractionDigits(4);
14. nf.setMinimumFractionDigits(2);
15. String a = nf.format(3.1415926);
16. String b = nf.format(2);
Which two statements are true about the result if the default locale is Locale.US? (Choose two.)

A. The value of b is 2.
B. The value of a is 3.14.
C. The value of b is 2.00.
D. The value of a is 3.141.
E. The value of a is 3.1415.
F. The value of a is 3.1416.
G. The value of b is 2.0000.

Answer: C, F

Q: 6 Given:
12. import java.io.*;
13. public class Forest implements Serializable {
14. private Tree tree = new Tree();
15. public static void main(String [] args) {
16. Forest f = new Forest();
17. try {
18. FileOutputStream fs = new FileOutputStream("Forest.ser");
19. ObjectOutputStream os = new ObjectOutputStream(fs);
20. os.writeObject(f); os.close();
21. } catch (Exception ex) { ex.printStackTrace(); }
22. } }
23.
24. class Tree { }
What is the result?

A. Compilation fails.
B. An exception is thrown at runtime.
C. An instance of Forest is serialized.
D. An instance of Forest and an instance of Tree are both serialized.

Answer: B

Q: 7 Assuming that the serializeBanana() and the deserializeBanana() methods will
correctly use Java serialization and given:
13. import java.io.*;
14. class Food implements Serializable {int good = 3;}
15. class Fruit extends Food {int juice = 5;}
16. public class Banana extends Fruit {
17. int yellow = 4;
18. public static void main(String [] args) {
19. Banana b = new Banana(); Banana b2 = new Banana();
20. b.serializeBanana(b); // assume correct serialization
21. b2 = b.deserializeBanana(); // assume correct
22. System.out.println("restore "+b2.yellow+ b2.juice+b2.good);
24. }
25. // more Banana methods go here 50. }
What is the result?

A. restore 400
B. restore 403
C. restore 453
D. Compilation fails.
E. An exception is thrown at runtime.

Answer: C

Q: 8 Given this method in a class:
21. public String toString() {
22. StringBuffer buffer = new StringBuffer();
23. buffer.append('<');
24. buffer.append(this.name);
25. buffer.append('>');
26. return buffer.toString();
27. }
Which statement is true?

A. This code is NOT thread-safe.
B. The programmer can replace StringBuffer with StringBuilder with no other changes.
C. This code will perform poorly. For better performance, the code should be rewritten:
return "<" + this.name + ">";
D. This code will perform well and converting the code to use StringBuilder will not enhance the performance.

Answer: B

Q: 9 Given:
1. package geometry;
2. public class Hypotenuse {
3. public InnerTriangle it = new InnerTriangle();
4. class InnerTriangle {
5. public int base;
6. public int height;
7. }
8. }
Which statement is true about the class of an object that can reference the variable base?

A. It can be any class.
B. No class has access to base.
C. The class must belong to the geometry package.
D. The class must be a subclass of the class Hypotenuse.

Answer: C

Q: 10 Which two statements are true about has-a and is-a relationships? (Choose
two.)

A. Inheritance represents an is-a relationship.
B. Inheritance represents a has-a relationship.
C. Interfaces must be used when creating a has-a relationship.
D. Instance variables can be used when creating a has-a relationship.

Answer: A, D

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

Friday, August 14, 2009

Java Quiz -3

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.

Q: 1 Given:
11. public class Test {
12. public enum Dogs {collie, harrier, shepherd};
13. public static void main(String [] args) {
14. Dogs myDog = Dogs.shepherd;
15. switch (myDog) {
16. case collie:
17. System.out.print("collie ");
18. case default:
19. System.out.print("retriever ");
20. case harrier:
21. System.out.print("harrier ");
22. }
23. }
24. }
What is the result?

A. harrier
B. shepherd
C. retriever
D. Compilation fails.
E. retriever harrier
F. An exception is thrown at runtime.

Answer: D

Q: 2 Given:
8. public class test {
9. public static void main(String [] a) {
10. assert a.length == 1;
11. }
12. }
Which two will produce an AssertionError? (Choose two.)

A. java test
B. java -ea test
C. java test file1
D. java -ea test file1
E. java -ea test file1 file2
F. java -ea:test test file1

Answer: B, E

Q: 3 Given:
10. interface Foo {}
11. class Alpha implements Foo {}
12. class Beta extends Alpha {}
13. class Delta extends Beta {
14. public static void main( String[] args ) {
15. Beta x = new Beta();
16. // insert code here
17. }
18. }
Which code, inserted at line 16, will cause a java.lang.ClassCastException?

A. Alpha a = x;
B. Foo f = (Delta)x;
C. Foo f = (Alpha)x;
D. Beta b = (Beta)(Alpha)x;

Answer: B

Q: 4 Given:
11. public static Collection get() {
12. Collection sorted = new LinkedList();
13. sorted.add("B"); sorted.add("C"); sorted.add("A");
14. return sorted;
15. }
16. public static void main(String[] args) {
17. for (Object obj: get()) {
18. System.out.print(obj + ", ");
19. }
20. }
What is the result?

A. A, B, C,
B. B, C, A,
C. Compilation fails.
D. The code runs with no output.
E. An exception is thrown at runtime.

Answer: B

Q: 5 Given:
84. try {
85. ResourceConnection con = resourceFactory.getConnection();
86. Results r = con.query("GET INFO FROM CUSTOMER");
87. info = r.getData();
88. con.close();
89. } catch (ResourceException re) {
90. errorLog.write(re.getMessage());
91. }
92. return info;
Which statement is true if a ResourceException is thrown on line 86?

A. Line 92 will not execute.
B. The connection will not be retrieved in line 85.
C. The resource connection will not be closed on line 88.
D. The enclosing method will throw an exception to its caller.

Answer: C

Q: 6 Given:
31. // some code here
32. try {
33. // some code here
34. } catch (SomeException se) {
35. // some code here
36. } finally {
37. // some code here
38. }
Under which three circumstances will the code on line 37 be executed? (Choose Three.)

A. The instance gets garbage collected.
B. The code on line 33 throws an exception.
C. The code on line 35 throws an exception.
D. The code on line 31 throws an exception.
E. The code on line 33 executes successfully.

Answer: B, C, E

Q: 7 Given:
11. class A {
12. public void process() { System.out.print("A,"); }
13. class B extends A {
14. public void process() throws IOException {
15. super.process();
16. System.out.print("B,");
17. throw new IOException();
18. }
19. public static void main(String[] args) {
20. try { new B().process(); }
21. catch (IOException e) { System.out.println("Exception"); }}
What is the result?

A. Exception
B. A,B,Exception
C. Compilation fails because of an error in line 20.
D. Compilation fails because of an error in line 14.
E. A NullPointerException is thrown at runtime.

Answer: D

Q: 8 Given a method that must ensure that its parameter is not null:
11. public void someMethod(Object value) {
12. // check for null value
...
20. System.out.println(value.getClass());
21. }
What, inserted at line 12, is the appropriate way to handle a null value?

A. assert value == null;
B. assert value != null, "value is null";
C. if (value == null) {
throw new AssertionException("value is null");
}
D. if (value == null) {
throw new IllegalArgumentException("value is null");

}

Answer: D

Q: 9 Given:
11. static void test() throws Error {
12. if (true) throw new AssertionError();
13. System.out.print("test ");
14. }
15. public static void main(String[] args) {
16. try { test(); }
17. catch (Exception ex) { System.out.print("exception "); }
18. System.out.print("end ");
19. }
What is the result?

A. end
B. Compilation fails.
C. exception end
D. exception test end
E. A Throwable is thrown by main.
F. An Exception is thrown by main.

Answer: E

Q: 10 Given:
11. Float pi = new Float(3.14f);
12. if (pi > 3) {
13. System.out.print("pi is bigger than 3. ");
14. }
15. else {
16. System.out.print("pi is not bigger than 3. ");
17. }
18. finally {
19. System.out.println("Have a nice day.");
20. }
What is the result?

A. Compilation fails.
B. pi is bigger than 3.
C. An exception occurs at runtime.
D. pi is bigger than 3. Have a nice day.
E. pi is not bigger than 3. Have a nice day.

Answer: A

Hope you found this useful! Kindly give me your comments regarding the same.

Thursday, August 13, 2009

Java Quiz -2

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.

Q: 1 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: B, D

Q: 2 Given:
1. public class Plant {
2. private String name;
3. public Plant(String name) { this.name = name; }
4. public String getName() { return name; }
5. }
1. public class Tree extends Plant {
2. public void growFruit() { }
3. public void dropLeaves() { }
4. }
Which statement is true?
A. The code will compile without changes.
B. The code will compile if public Tree() { Plant(); } is added to the Tree class.
C. The code will compile if public Plant() { Tree(); } is added to the Plant class.
D. The code will compile if public Plant() { this("fern"); } is added to the Plant class.
E. The code will compile if public Plant() { Plant("fern"); } is added to the Plant class.

Answer: D

Q: 3 Which two classes correctly implement both the java.lang.Runnable and the
java.lang.Clonable interfaces? (Choose two.)

A. public class Session
implements Runnable, Clonable {
public void run();
public Object clone();
}
B. public class Session
extends Runnable, Clonable {
public void run() { /* do something */ }

public Object clone() { /* make a copy */ }
C. public class Session
implements Runnable, Clonable {
public void run() { /* do something */ }
public Object clone() { /* make a copy */ }
D. public abstract class Session
implements Runnable, Clonable {
public void run() { /* do something */ }
public Object clone() { /*make a copy */ }
E. public class Session
implements Runnable, implements Clonable {
public void run() { /* do something */ }
public Object clone() { /* make a copy */ }

Answer: C, D

Q: 4 Given:
1. public class Threads2 implements Runnable {
2.
3. public void run() {
4. System.out.println("run.");
5. throw new RuntimeException("Problem");
6. }
7. public static void main(String[] args) {
8. Thread t = new Thread(new Threads2());
9. t.start();
10. System.out.println("End of method.");
11. }
12. }
Which two can be results? (Choose two.)

A. java.lang.RuntimeException: Problem
B. run.
java.lang.RuntimeException: Problem
C. End of method.
java.lang.RuntimeException: Problem
D. End of method.
run.
java.lang.RuntimeException: Problem
E. run.
java.lang.RuntimeException: Problem
End of method.

Answer: D, E

Q: 5 Given:
1. public class TestSeven extends Thread {
2. private static int x;
3. public synchronized void doThings() {
4. int current = x;
5. current++;
6. x = current;
7. }
8. public void run() {
9. doThings();
10. }
11.}
Which statement is true?

A. Compilation fails.
B. An exception is thrown at runtime.
C. Synchronizing the run() method would make the class thread-safe.
D. The data in variable "x" are protected from concurrent access problems.
E. Declaring the doThings() method as static would make the class thread-safe.
F. Wrapping the statements within doThings() in a synchronized(new Object()) { } block would make the class thread-safe.

Answer: E

Q: 6 Given:
1. public class Threads3 implements Runnable {
2. public void run() {
3. System.out.print("running");
4. }
5. public static void main(String[] args) {
6. Thread t = new Thread(new Threads3());
7. t.run();
8. t.run();
9. t.start();
10. }
11. }
What is the result?

A. Compilation fails.
B. An exception is thrown at runtime.
C. The code executes and prints "running".
D. The code executes and prints "runningrunning".
E. The code executes and prints "runningrunningrunning".

Answer: E

Q: 7 Given:
public class NamedCounter {
private final String name;
private int count;
public NamedCounter(String name) { this.name = name; }
public String getName() { return name; }
public void increment() { count++; }
public int getCount() { return count; }
public void reset() { count = 0; }
}
Which three changes should be made to adapt this class to be used safely by multiple threads? (Choose
three.)

A. declare reset() using the synchronized keyword
B. declare getName() using the synchronized keyword
C. declare getCount() using the synchronized keyword
D. declare the constructor using the synchronized keyword
E. declare increment() using the synchronized keyword

Answer: A, C, E

Q: 8 Given:
7. void waitForSignal() {
8. Object obj = new Object();
9. synchronized (Thread.currentThread()) {
10. obj.wait();
11. obj.notify();
12. }
13. }
Which statement is true?

A. This code may throw an InterruptedException.
B. This code may throw an IllegalStateException.
C. This code may throw a TimeoutException after ten minutes.
D. This code will not compile unless "obj.wait()" is replaced with "((Thread) obj).wait()".
E. Reversing the order of obj.wait() and obj.notify() may cause this method to complete normally.
F. A call to notify() or notifyAll() from another thread may cause this method to complete normally.

Answer: B

Q: 9 Which two code fragments will execute the method doStuff() in a separate
thread? (Choose two.)

A. new Thread() {
public void run() { doStuff(); }
};
B. new Thread() {
public void start() { doStuff(); }
};
C. new Thread() {
public void start() { doStuff(); }
}.run();
D. new Thread() {
public void run() { doStuff(); }
}.start();
E. new Thread(new Runnable() {
public void run() { doStuff(); }
}).run();
F. new Thread(new Runnable() {
public void run() { doStuff(); }
}).start();

Answer: D, F

Q: 10 Given:
1. public class TestOne implements Runnable {
2. public static void main (String[] args) throws Exception {
3. Thread t = new Thread(new TestOne());
4. t.start();
5. System.out.print("Started");
6. t.join();
7. System.out.print("Complete");
8. }
9. public void run() {
10. for (int i = 0; i < 4; i++) {
11. System.out.print(i);
12. }
13. }
14. }
What can be a result?

A. Compilation fails.
B. An exception is thrown at runtime.
C. The code executes and prints "StartedComplete".
D. The code executes and prints "StartedComplete0123".
E. The code executes and prints "Started0123Complete".

Answer: E

Hope you found this useful! Kindly give me your comments regarding the same.

Wednesday, August 12, 2009

Java Quiz -1

Hi friends,

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

Q 1:
Given:
11. public class Person {
12. private String name, comment;
13. private int age;
14. public Person(String n, int a, String c) {
15. name = n; age = a; comment = c;
16. }
17. public boolean equals(Object o) {
18. if (! (o instanceof Person)) return false;
19, Person p = (Person)o;
20. return age == p.age && name.equals(p.name);
21. }
22. }
What is the appropriate definition of the hashCode method in class Person?

A. return super.hashCode();
B. return name.hashCode() + age * 7;
C. return name.hashCode() + comment.hashCode() / 2;
D. return name.hashCode() + comment.hashCode() / 2 - age * 3;

Answer: B

Q: 2 Given:
34. HashMap props = new HashMap();
35. props.put("key45", "some value");
36. props.put("key12", "some other value");
37. props.put("key39", "yet another value");
38. Set s = props.keySet();
39. // insert code here
What, inserted at line 39, will sort the keys in the props HashMap?

A. Arrays.sort(s);
B. s = new TreeSet(s);
C. Collections.sort(s);
D. s = new SortedSet(s);

Answer: B

Q: 3 Given:
23. Object [] myObjects = {
24. new Integer(12),
25. new String("foo"),
26. new Integer(5),
27. new Boolean(true)
28. };
29. Arrays.sort(myObjects);
30. for(int i=0; i31. System.out.print(myObjects[i].toString());
32. System.out.print(" ");
33. }
What is the result?

A. Compilation fails due to an error in line 23.
B. Compilation fails due to an error in line 29.
C. A ClassCastException occurs in line 29.
D. A ClassCastException occurs in line 31.
E. The value of all four objects prints in natural order.

Answer: C

Q: 4 Given:
1. public class Person {
2. private String name;
3. public Person(String name) { this.name = name; }
4. public boolean equals(Person p) {
5. return p.name.equals(this.name);
6. }
7. }
Which statement is true?

A. The equals method does NOT properly override the Object.equals method.
B. Compilation fails because the private attribute p.name cannot be accessed in line 5.
C. To work correctly with hash-based data structures, this class must also implement the hashCode method.
D. When adding Person objects to a java.util.Set collection, the equals method in line 4 will prevent duplicates.

Answer: A

Q: 5 Given:
1. import java.util.*;
2. public class Old {
3. public static Object get0(List list) {
4. return list.get(0);
5. }
6. }
Which three will compile successfully? (Choose three.)

A. Object o = Old.get0(new LinkedList());
B. Object o = Old.get0(new LinkedList());
C. String s = Old.get0(new LinkedList());
D. Object o = Old.get0(new LinkedList());
E. String s = (String)Old.get0(new LinkedList());

Answer: A, D, E

Q: 6 Given:
1. import java.util.*;
2. public class Example {
3. public static void main(String[] args) {
4. // insert code here
5. set.add(new Integer(2));
6. set.add(new Integer(1));
7. System.out.println(set);
8. }
9. }
Which code, inserted at line 4, guarantees that this program will output [1, 2]?

A. Set set = new TreeSet();
B. Set set = new HashSet();
C. Set set = new SortedSet();
D. List set = new SortedList();
E. Set set = new LinkedHashSet();

Answer: A

Q: 7 Given
10. class Foo {
11. static void alpha() { /* more code here */ }
12. void beta() { /* more code here */ }
13. }
Which two statements are true? (Choose two.)


A. Foo.beta() is a valid invocation of beta().
B. Foo.alpha() is a valid invocation of alpha().
C. Method beta() can directly call method alpha().
D. Method alpha() can directly call method beta().

Answer: B, C

Q: 8 Given:
11. public static void parse(String str) {
12. try {
13. float f = Float.parseFloat(str);
14. } catch (NumberFormatException nfe) {
15. f = 0;
16. } finally {
17. System.out.println(f);
18. }
19. }
20. public static void main(String[] args) {
21. parse("invalid");
22. }
What is the result?

A. 0.0
B. Compilation fails.
C. A ParseException is thrown by the parse method at runtime.
D. A NumberFormatException is thrown by the parse method at runtime.

Answer: B

Q: 9 Given:
10. class Line {
11. public static class Point {}
12. }
13.
14. class Triangle {
15. // insert code here
16. }
Which code, inserted at line 15, creates an instance of the Point class defined in Line?

A. Point p = new Point();
B. Line.Point p = new Line.Point();
C. The Point class cannot be instatiated at line 15.
D. Line l = new Line() ; l.Point p = new l.Point();

Answer: B

Q: 10 Given:
10. package com.sun.scjp;
11. public class Geodetics {
12. public static final double DIAMETER = 12756.32; // kilometers
13. }
Which two correctly access the DIAMETER member of the Geodetics class? (Choose two.)

A. import com.sun.scjp.Geodetics;
public class TerraCarta {
public double halfway()
{ return Geodetics.DIAMETER/2.0; }
B. import static com.sun.scjp.Geodetics;
public class TerraCarta{
public double halfway() { return DIAMETER/2.0; } }
C. import static com.sun.scjp.Geodetics.*;
public class TerraCarta {
public double halfway() { return DIAMETER/2.0; } }
D. package com.sun.scjp;
public class TerraCarta {
public double halfway() { return DIAMETER/2.0; } }

Answer: A, C

So friends,
I am going to come out with more and more challenging questions.
Hope you find it useful, Your comments are welcome!

Monday, August 10, 2009

Command Pattern In Java

Hi Friends,

Today I would like to show a program for command patterns.

* Client.java

/**
* Creates a ConcreteCommand object and specifies its receiver.
*/

public class Client
{
public Command setup()
{
Command command = new ConcreteCommand();
Receiver receiver = new ConcreteReceiver();
command.setReceiver( receiver );

// We return the command so that the Invoker may use it.

return command;
}
}

* Command.java

/**
* Declares an interface for executing an operation.
*/

public interface Command
{
void setReceiver( Receiver receiver );
Receiver getReceiver();
void execute();
}

* ConcreteCommand.java

/**
* Defines a binding between a Receiver object and an
* action. Implements Execute by invoking the corresponding
* operation on Receiver.
*/

public class ConcreteCommand implements Command
{
private Receiver receiver;

public void setReceiver( Receiver receiver )
{
this.receiver = receiver;
}

public Receiver getReceiver()
{
return receiver;
}

public void execute()
{
receiver.action();
}
}

* ConcreteReceiver

/**
* Implementation of the Receiver interface.
*/

public class ConcreteReceiver implements Receiver
{
public void action()
{
}
}

* Receiver.java

/**
* Knows how to perform the operations associated with
* carrying out a request. Any class may serve as a Receiver.
*/

public interface Receiver
{
void action();
}

* Test.java

/**
* Test driver for the pattern.
*/

public class Test
{
public static void main( String arg[] )
{
try
{
Client client = new Client();
Command command = client.setup();
command.execute();
}
catch( Exception e )
{
e.printStackTrace();
}
}
}

So friends, Hope you found it useful. Please give your valuable feedback.