Java
Java
Which is true about an anonymous inner class? A. B. C. D. It can extend exactly one class and implement exactly one interface. It can extend exactly one class and can implement multiple interfaces. It can extend exactly one class or implement exactly one interface. It can implement multiple interfaces regardless of whether it also extends a class.
Answer: Option C Explanation: Option C is correct because the syntax of an anonymous inner class allows for only one named type after the new, and that type must be either a single interface (in which case the anonymous class implements that one interface) or a single class (in which case the anonymous class extends that one class). Option A, B, D, and E are all incorrect because they don't follow the syntax rules described in the response for answer Option C. View Answer Workspace Report Discuss in Forum
2.
class Boo { Boo(String s) { } Boo() { } } class Bar extends Boo { Bar() { } Bar(String s) {super(s);} void zoo() { // insert code here } } which one create an anonymous inner class from within class Bar? A. B. C. D. Boo f = new Boo(24) { }; Boo f = new Bar() { }; Bar f = new Boo(String s) { }; Boo f = new Boo.Bar(String s) { };
Answer: Option B Explanation: Option B is correct because anonymous inner classes are no different from any other class when it comes to polymorphism. That means you are always allowed to declare a reference variable of the superclass type and have that reference variable refer to an instance of a subclass type, which in this case is an anonymous subclass of Bar. Since Bar is a subclass of Boo, it all works. Option A is incorrect because it passes an int to the Boo constructor, and there is no matching constructor in the Boo class. Option C is incorrect because it violates the rules of polymorphismyou cannot refer to a superclass type using a reference variable declared as the subclass type. The superclass is not guaranteed to have everything the subclass has. Option D uses incorrect syntax. View Answer Workspace Report Discuss in Forum
3.
Which is true about a method-local inner class? A. B. C. D. It must be marked final. It can be marked abstract. It can be marked public. It can be marked static.
Answer: Option B Explanation: Option B is correct because a method-local inner class can be abstract, although it means a subclass of the inner class must be created if the abstract class is to be used (so an abstract method-local inner class is probably not useful). Option A is incorrect because a method-local inner class does not have to be declared final (although it is legal to do so). C and D are incorrect because a method-local inner class cannot be made public(remember-you cannot mark any local variables as public), or static.
4.
Which statement is true about a static nested class? A. You must have a reference to an instance of the enclosing class in order to instantiate it. It does not have access to nonstatic members of the enclosing class. It's variables and methods must be static. It must extend the enclosing class.
B. C. D.
Answer: Option B Explanation: Option B is correct because a static nested class is not tied to an instance of the enclosing class, and thus can't access the nonstatic members of the class (just as a static method can't access nonstatic members of a class). Option A is incorrect because static nested classes do not need (and can't use) a reference to an instance of the enclosing class. Option C is incorrect because static nested classes can declare and define nonstatic members. Option D is wrong because it just is. There's no rule that says an inner or nested class has to extend anything. View Answer Workspace Report Discuss in Forum
5.
Which constructs an anonymous inner class instance? A. B. C. D. Runnable r = new Runnable() { }; Runnable r = new Runnable(public void run() { }); Runnable r = new Runnable { public void run(){}}; System.out.println(new Runnable() {public void run() { }});
Answer: Option D
Explanation: D is correct. It defines an anonymous inner class instance, which also means it creates an instance of that new anonymous class at the same time. The anonymous class is an implementer of the Runnable interface, so it must override the run()method of Runnable. A is incorrect because it doesn't override the run() method, so it violates the rules of interface implementation. B and C use incorrect syntax. 6. class Foo { class Bar{ } } class Test { public static void main (String [] args) { Foo f = new Foo(); /* Line 10: Missing statement ? */ } } which statement, inserted at line 10, creates an instance of Bar? A. B. C. D. Foo.Bar b = new Foo.Bar(); Foo.Bar b = f.new Bar(); Bar b = new f.Bar(); Bar b = f.new Bar();
Answer: Option B Explanation: Option B is correct because the syntax is correct-using both names (the enclosing class and the inner class) in the reference declaration, then using a reference to the enclosing class to invoke new on the inner class. Option A, C and D all use incorrect syntax. A is incorrect because it doesn't use a reference to the enclosing class, and also because it includes both names in the new. C is incorrect because it doesn't use the enclosing class name in the reference variable declaration, and because the new syntax is wrong. D is incorrect because it doesn't use the enclosing class name in the reference variable
7.
public class MyOuter { public static class MyInner { public static void foo() { } } } which statement, if placed in a class other than MyOuter or MyInner, instantiates an instance of the nested class? A. B. MyOuter.MyInner m = new MyOuter.MyInner(); MyOuter.MyInner mi = new MyInner(); MyOuter m = new MyOuter(); C. MyOuter.MyInner mi = m.new MyOuter.MyInner(); D. MyInner mi = new MyOuter.MyInner();
MyInner is a static nested class, so it must be instantiated using the fully-scoped name of MyOuter.MyInner.
Option B is incorrect because it doesn't use the enclosing name in the new. Option C is incorrect because it uses incorrect syntax. When you instantiate a nested class by invoking new on an instance of the enclosing class, you do not use the enclosing name. The difference between Option A and C is that Option C is calling new on an instance of the enclosing class rather than just new by itself. Option D is incorrect because it doesn't use the enclosing class name in the variable declaration. What will be the output of the program?
1.
public class Test { public static void main(String[] args) { int x = 0; assert (x > 0) ? "assertion failed" : "assertion passed" ; System.out.println("finished");
} } A. B. C. D. finished Compiliation fails. An AssertionError is thrown and finished is output. An AssertionError is thrown with the message "assertion failed."
Answer: Option B Explanation: Compilation Fails. You can't use the Assert statement in a similar way to the ternary operator. Don't confuse. View Answer Workspace Report Discuss in Forum
2.
public class Test { public void foo() { assert false; /* Line 5 */ assert false; /* Line 6 */ } public void bar() { while(true) { assert false; /* Line 12 */ } assert false; /* Line 14 */ } } What causes compilation to fail? A. B. C. D. Line 5 Line 6 Line 12 Line 14
Answer: Option D Explanation: Option D is correct. Compilation fails because of an unreachable statement at line 14. It is a compile-time error if a statement cannot be executed because it is unreachable. The question is now, why is line 20 unreachable? If it is because of the assert then surely line 6 would also be unreachable. The answer must be something other than assert. Examine the following: A while statement can complete normally if and only if at least one of the following is true: - The while statement is reachable and the condition expression is not a constant expression with value true. -There is a reachable break statement that exits the while statement. The while statement at line 11 is infinite and there is no break statement therefore line 14 is unreachable. You can test this with the following code:
public class Test80 { public void foo() { assert false; assert false; } public void bar() { while(true) { assert false; break; } assert false; } }
View Answer Workspace Report Discuss in Forum
3.
public class Test { public static int y; public static void foo(int x) { System.out.print("foo ");
y = x; } public static int bar(int z) { System.out.print("bar "); return y = z; } public static void main(String [] args ) { int t = 0; assert t > 0 : bar(7); assert t > 1 : foo(8); /* Line 18 */ System.out.println("done "); } } A. B. C. D. bar bar done foo done Compilation fails
Answer: Option D Explanation: The foo() method returns void. It is a perfectly acceptable method, but because it returns void it cannot be used in an assert statement, so line 18 will not compile. View Answer Workspace Report Discuss in Forum
4.
What will be the output of the program (when you run with the -ea option) ?
public class Test { public static void main(String[] args) { int x = 0; assert (x > 0) : "assertion failed"; /* Line 6 */ System.out.println("finished"); } } A. B. finished Compilation fails.
C. D.
Answer: Option C Explanation: An assertion Error is thrown as normal giving the output "assertion failed". The word "finished" is not printed (ensure you run with the -ea option) Assertion failures are generally labeled in the stack trace with the file and line number from which they were thrown, and also in this case with the error's detail message "assertion failed". The detail message is supplied by the assert statement in line 6. View Answer Workspace Report Discuss in Forum
5.
public class Test2 { public static int x; public static int foo(int y) { return y * 2; } public static void main(String [] args) { int z = 5; assert z > 0; /* Line 11 */ assert z > 2: foo(z); /* Line 12 */ if ( z < 7 ) assert z > 4; /* Line 14 */ switch (z) { case 4: System.out.println("4 "); case 5: System.out.println("5 "); default: assert z < 10; } if ( z < 10 ) assert z > 4: z++; /* Line 22 */ System.out.println(z); } } which line is an example of an inappropriate use of assertions? A. B. Line 11 Line 12
C. D.
Line 14 Line 22
Answer: Option D Explanation: Assert statements should not cause side effects. Line 22 changes the value of z if the assert statement is false. Option A is fine; a second expression in an assert statement is not required. Option B is fine because it is perfectly acceptable to call a method with the second expression of an assert statement. Option C is fine because it is proper to call an assert statement conditionally. What will be the output of the program?
1.
public class Foo { public static void main(String[] args) { try { return; } finally { System.out.println( "Finally" ); } } } A. B. C. D. Finally Compilation fails. The code runs with no output. An exception is thrown at runtime.
Answer: Option A
Explanation: If you put a finally block after a try and its associated catch blocks, then once execution enters the try block, the code in that finally block will definitely be executed except in the following circumstances: 1. An exception arising in the finally block itself. 2. The death of the thread. 3. The use of System.exit() 4. Turning off the power to the CPU. I suppose the last three could be classified as VM shutdown. View Answer Workspace Report Discuss in Forum
2.
try { int x = 0; int y = 5 / x; } catch (Exception e) { System.out.println("Exception"); } catch (ArithmeticException ae) { System.out.println(" Arithmetic Exception"); } System.out.println("finished"); A. C. finished Compilation fails. B. D. Exception Arithmetic Exception
Answer: Option C Explanation: Compilation fails because ArithmeticException has already been caught.ArithmeticException is a subclass of java.lang.Exception, by time theArithmeticException has been specified it has already been caught by theException class. If ArithmeticException appears before Exception, then the file will compile. When catching exceptions the more specific exceptions must be listed before the more general (the subclasses
must be caught before the superclasses). View Answer Workspace Report Discuss in Forum
3.
public class X { public static void main(String [] args) { try { badMethod(); System.out.print("A"); } catch (Exception ex) { System.out.print("B"); } finally { System.out.print("C"); } System.out.print("D"); } public static void badMethod() { throw new Error(); /* Line 22 */ } } A. B. C. D. ABCD Compilation fails. C is printed before exiting with an error message. BC is printed before exiting with an error message.
Error is thrown but not recognised line(22) because the only catch attempts to catch an Exception and Exception is not a superclass of Error. Therefore only the code in the finally statement can be run before exiting with a runtime error (Exception in thread "main" java.lang.Error).
View Answer Workspace Report Discuss in Forum
4.
public class X { public static void main(String [] args) { try { badMethod(); System.out.print("A"); } catch (RuntimeException ex) /* Line 10 */ { System.out.print("B"); } catch (Exception ex1) { System.out.print("C"); } finally { System.out.print("D"); } System.out.print("E"); } public static void badMethod() { throw new RuntimeException(); } } A. C. BD BDE B. D. BCD BCDE
Answer: Option C Explanation: A Run time exception is thrown and caught in the catch statement on line 10. All the code after the finally statement is run because the exception has been caught. View Answer Workspace Report Discuss in Forum
5.
System.out.print("throwit "); throw new RuntimeException(); } public static void main(String [] args) { try { System.out.print("hello "); throwit(); } catch (Exception re ) { System.out.print("caught "); } finally { System.out.print("finally "); } System.out.println("after "); } } A. B. C. D. hello throwit caught Compilation fails hello throwit RuntimeException caught after hello throwit caught finally after
Answer: Option D Explanation: The main() method properly catches and handles the RuntimeException in the catch block, finally runs (as it always does), and then the code returns to normal. A, B and C are incorrect based on the program logic described above. Remember that properly handled exceptions do not cause the program to stop executing. View Answer Workspace Report Discuss in Forum 6. What will be the output of the program?
public class Test { public static void aMethod() throws Exception { try /* Line 5 */ { throw new Exception(); /* Line 7 */ }
finally /* Line 9 */ { System.out.print("finally "); /* Line 11 */ } } public static void main(String args[]) { try { aMethod(); } catch (Exception e) /* Line 20 */ { System.out.print("exception "); } System.out.print("finished"); /* Line 24 */ } } A. B. C. D. finally exception finished finally exception finished Compilation fails
Answer: Option C Explanation: This is what happens: (1) The execution of the try block (line 5) completes abruptly because of the throwstatement (line 7). (2) The exception cannot be assigned to the parameter of any catch clause of thetry statement therefore the finally block is executed (line 9) and "finally" is output (line 11). (3) The finally block completes normally, and then the try statement completes abruptly because of the throw statement (line 7). (4) The exception is propagated up the call stack and is caught by the catch in the main method (line 20). This prints "exception". (5) Lastly program execution continues, because the exception has been caught, and "finished" is output (line 24). View Answer Workspace Report Discuss in Forum
7.
public class X { public static void main(String [] args) { try { badMethod(); System.out.print("A"); } catch (Exception ex) { System.out.print("B"); } finally { System.out.print("C"); } System.out.print("D"); } public static void badMethod() {} } A. C. AC ACD B. D. BC ABCD
Answer: Option C Explanation: There is no exception thrown, so all the code with the exception of the catch statement block is run. View Answer Workspace Report Discuss in Forum
8.
public class X { public static void main(String [] args) { try { badMethod(); /* Line 7 */ System.out.print("A"); } catch (Exception ex) /* Line 10 */ {
System.out.print("B"); /* Line 12 */ } finally /* Line 14 */ { System.out.print("C"); /* Line 16 */ } System.out.print("D"); /* Line 18 */ } public static void badMethod() { throw new RuntimeException(); } } A. C. AB ABC B. D. BC BCD
Answer: Option D Explanation: (1) A RuntimeException is thrown, this is a subclass of exception. (2) The exception causes the try to complete abruptly (line 7) therefore line 8 is never executed. (3) The exception is caught (line 10) and "B" is output (line 12) (4) The finally block (line 14) is always executed and "C" is output (line 16). (5) The exception was caught, so the program continues with line 18 and outputs "D". View Answer Workspace Report Discuss in Forum
9.
public class MyProgram { public static void main(String args[]) { try { System.out.print("Hello world "); } finally { System.out.println("Finally executing "); } } }
A. B. C. D.
Nothing. The program will not compile because no exceptions are specified. Nothing. The program will not compile because no catch clauses are specified. Hello world. Hello world Finally executing
Answer: Option D Explanation: Finally clauses are always executed. The program will first execute the try block, printing Hello world, and will then execute the finally block, printing Finally executing. Option A, B, and C are incorrect based on the program logic described above. Remember that either a catch or a finally statement must follow a try. Since the finally is present, the catch is not required. View Answer Workspace Report Discuss in Forum
class Exc0 extends Exception { } class Exc1 extends Exc0 { } /* Line 2 */ public class Test { public static void main(String args[]) { try { throw new Exc1(); /* Line 9 */ } catch (Exc0 e0) /* Line 11 */ { System.out.println("Ex0 caught"); } catch (Exception e) { System.out.println("exception caught"); } } } A. B.
Ex0 caught
exception caught
C. D.
Compilation fails because of an error at line 2. Compilation fails because of an error at line 9.
Answer: Option A Explanation: An exception Exc1 is thrown and is caught by the catch statement on line 11. The code is 1. executed in this block. There is no finally block of code to execute. What is the name of the method used to start a thread execution? A. C. init(); run(); B. D. start(); resume();
Answer: Option B Explanation: Option B is Correct. The start() method causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread. Option A is wrong. There is no init() method in the Thread class. Option C is wrong. The run() method of a thread is like the main() method to an application. Starting the thread causes the object's run method to be called in that separately executing thread. Option D is wrong. The resume() method is deprecated. It resumes a suspended thread. View Answer Workspace Report Discuss in Forum
2.
Which two are valid constructors for Thread? 1. 2. 3. 4. 5. Thread(Runnable r, String name) Thread() Thread(int priority) Thread(Runnable r, ThreadGroup g) Thread(Runnable r, int priority)
A.
1 and 3
B.
2 and 4
C.
1 and 2
D.
2 and 5
Answer: Option C Explanation: (1) and (2) are both valid constructors for Thread. (3), (4), and (5) are not legal Thread constructors, although (4) is close. If you reverse the arguments in (4), you'd have a valid constructor. View Answer Workspace Report Discuss in Forum
3.
Which three are methods of the Object class? 1. 2. 3. 4. 5. 6. 7. 8. notify(); notifyAll(); isInterrupted(); synchronized(); interrupt(); wait(long msecs); sleep(long msecs); yield();
A. C.
1, 2, 4 1, 2, 6
B. D.
2, 4, 5 2, 3, 4
Answer: Option C Explanation: (1), (2), and (6) are correct. They are all related to the list of threads waiting on the specified object. (3), (5), (7), and (8) are incorrect answers. The methods isInterrupted() andinterrupt() are instance methods of Thread. The methods sleep() and yield() are static methods of Thread. D is incorrect because synchronized is a keyword and the synchronized()construct is part of the Java language.
4.
class X implements Runnable { public static void main(String args[]) { /* Missing code? */ } public void run() {} } Which of the following line of code is suitable to start a thread ? A. B. C. D. Thread t = new Thread(X); Thread t = new Thread(X); t.start(); X run = new X(); Thread t = new Thread(run); t.start(); Thread t = new Thread(); x.run();
Answer: Option C Explanation: Option C is suitable to start a thread. View Answer Workspace Report Discuss in Forum
5.
Which cannot directly cause a thread to stop executing? A. B. C. D. Calling the SetPriority() method on a Thread object. Calling the wait() method on an object. Calling notify() method on an object. Calling read() method on an InputStream object.
Answer: Option C Explanation: Option C is correct. notify() - wakes up a single thread that is waiting on this object's monitor.
6.
Which two of the following methods are defined in class Thread? 1. 2. 3. 4. 5. start() wait() notify() run() terminate()
A. C.
1 and 4 3 and 4
B. D.
2 and 3 2 and 4
Answer: Option A Explanation: (1) and (4). Only start() and run() are defined by the Thread class. (2) and (3) are incorrect because they are methods of the Object class. (5) is incorrect because there's no such method in any thread-related class. View Answer Workspace Report Discuss in Forum
7.
Which three guarantee that a thread will leave the running state? 1. 2. 3. 4. 5. 6. 7. yield() wait() notify() notifyAll() sleep(1000) aLiveThread.join() Thread.killThread()
A. C.
1, 2 and 4 3, 4 and 7
B. D.
2, 5 and 6 4, 5 and 7
(2) is correct because wait() always causes the current thread to go into the object's wait pool. (5) is correct because sleep() will always pause the currently running thread for at least the duration specified in the sleep argument (unless an interrupted exception is thrown). (6) is correct because, assuming that the thread you're calling join() on is alive, the thread calling join() will immediately block until the thread you're callingjoin() on is no longer alive. (1) is wrong, but tempting. The yield() method is not guaranteed to cause a thread to leave the running state, although if there are runnable threads of the same priority as the currently running thread, then the current thread will probably leave the running state. (3) and (4) are incorrect because they don't cause the thread invoking them to leave the running state. (7) is wrong because there's no such method. View Answer Workspace Report Discuss in Forum 8.
Which of the following will directly stop the execution of a Thread? A. C. wait() notifyall() B. D. notify() exits synchronized code
Answer: Option A Explanation: Option A is correct. wait() causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. Option B is wrong. notify() - wakes up a single thread that is waiting on this object's monitor. Option C is wrong. notifyAll() - wakes up all threads that are waiting on this object's monitor. Option D is wrong. Typically, releasing a lock means the thread holding the lock (in other words, the thread currently in the synchronized method) exits the synchronized method. At that point, the lock is free until some other thread enters a synchronized method on that object.
Does entering/exiting synchronized code mean that the thread execution stops? Not necessarily because the thread can still run code that is not synchronized. I think the word directly in the question gives us a clue. Exiting synchronized code does not directly stop the execution of a thread. View Answer Workspace Report Discuss in Forum 9.
Which method must be defined by a class implementing the java.lang.Runnableinterface? A. C. void run() public void start() B. D. public void run() void run(int priority)
Answer: Option B Explanation: Option B is correct because in an interface all methods are abstract by default therefore they must be overridden by the implementing class. The Runnableinterface only contains 1 method, the void run() method therefore it must be implemented. Option A and D are incorrect because they are narrowing the access privileges i.e. package(default) access is narrower than public access. Option C is not method in the Runnable interface therefore it is incorrect. View Answer Workspace Report Discuss in Forum 10. Which will contain the body of the thread? A. C. run(); stop(); B. D. start(); main();
Answer: Option A Explanation: Option A is Correct. The run() method to a thread is like the main() method to an application. Starting the thread causes the
object's run method to be called in that separately executing thread. Option B is wrong. The start() method causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread. Option C is wrong. The stop() method is deprecated. It forces the thread to stop executing. Option D is wrong. Is the main entry point for an application. Which method registers a thread in a thread scheduler? A. C. run(); start(); B. D. construct(); register();
11.
Answer: Option C Explanation: Option C is correct. The start() method causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread. Option A is wrong. The run() method of a thread is like the main() method to an application. Starting the thread causes the object's run method to be called in that separately executing thread. Option B is wrong. There is no construct() method in the Thread class. Option D is wrong. There is no register() method in the Thread class. View Answer Workspace Report Discuss in Forum 12. Assume the following method is properly synchronized and called from a thread A on an object B:
wait(2000);
After calling this method, when will the thread A become a candidate to get another turn at the CPU? A. B. C. After thread A is notified, or after two seconds. After the lock on B is released, or after two seconds. Two seconds after thread A is notified.
D.
Answer: Option A Explanation: Option A. Either of the two events (notification or wait time expiration) will make the thread become a candidate for running again. Option B is incorrect because a waiting thread will not return to runnable when the lock is released, unless a notification occurs. Option C is incorrect because the thread will become a candidate immediately after notification, not two seconds afterwards. Option D is also incorrect because a thread will not come out of a waiting pool just because a lock has been released. View Answer Workspace Report Discuss in Forum
13. Which of the following will not directly cause a thread to stop? A. C. notify() InputStream access B. D. wait() sleep()
Answer: Option A Explanation: Option A is correct. notify() - wakes up a single thread that is waiting on this object's monitor. Option B is wrong. wait() causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. Option C is wrong. Methods of the InputStream class block until input data is available, the end of the stream is detected, or an exception is thrown. Blocking means that a thread may stop until certain conditions are met. Option D is wrong. sleep() - Causes the currently executing thread to sleep (temporarily cease execution) for a specified number of milliseconds. The thread does not lose ownership of any monitors. View Answer Workspace Report Discuss in Forum
14. Which class or interface defines the wait(), notify(),and notifyAll() methods? A. C. Object Runnable B. D. Thread Class
Answer: Option A Explanation: The Object class defines these thread-specific methods. Option B, C, and D are incorrect because they do not define these methods. And yes, the Java API does define a class called Class, though you do not need to know it for the exam. View Answer Workspace Report Discuss in Forum
15.
public class MyRunnable implements Runnable { public void run() { // some code here } } which of these will create and start this thread? A. B. C. D. new Runnable(MyRunnable).start(); new Thread(MyRunnable).run(); new Thread(new MyRunnable()).start(); new MyRunnable().start();
Answer: Option C Explanation: Because the class implements Runnable, an instance of it has to be passed to theThread constructor, and then the instance of the Thread has to be started. A is incorrect. There is no constructor like this for Runnable because Runnable is an interface,
and it is illegal to pass a class or interface name to any constructor. B is incorrect for the same reason; you can't pass a class or interface name to any constructor. D is incorrect because MyRunnable doesn't have a start() method, and the onlystart() method that can start a thread of execution is the start() in the Threadclass. 1. What is the value of "d" after this line of code has been executed?
Answer: Option B Explanation: The Math.random() method returns a number greater than or equal to 0 and less than 1 . Since we can then be sure that the sum of that number and 2.5 will be greater than or equal to 2.5 and less than 3.5, we can be sure thatMath.round() will round that number to 3. So Option B is the answer. View Answer Workspace Report Discuss in Forum
2.
Which of the following would compile without error? A. B. C. D. int a = Math.abs(-5); int b = Math.abs(5.0); int c = Math.abs(5.5F); int d = Math.abs(5L);
Answer: Option A Explanation: The return value of the Math.abs() method is always the same as the type of the parameter
passed into that method. In the case of A, an integer is passed in and so the result is also an integer which is fine for assignment to "int a". The values used in B, C & D respectively are a double, a float and a long. The compiler will complain about a possible loss of precision if we try to assign the results to an "int". View Answer Workspace Report Discuss in Forum
3.
Which of the following are valid calls to Math.max? 1. 2. 3. 4. Math.max(1,4) Math.max(2.3, 5) Math.max(1, 3, 5, 7) Math.max(-1.5, -2.8f)
A. B. C. D.
Answer: Option A Explanation: (1), (2), and (4) are correct. The max() method is overloaded to take two arguments of type int, long, float, or double. (3) is incorrect because the max() method only takes two arguments. View Answer Workspace Report Discuss in Forum
4.
public class Myfile { public static void main (String[] args) { String biz = args[1]; String baz = args[2]; String rip = args[3]; System.out.println("Arg is " + rip); }
} Select how you would start the program to cause it to print: Arg is 2 A. B. C. D. java Myfile 222 java Myfile 1 2 2 3 4 java Myfile 1 3 2 2 java Myfile 0 1 2 3
Answer: Option C Explanation: Arguments start at array element 0 so the fourth arguement must be 2 to produce the correct 1. output. Suppose that you would like to create an instance of a new Map that has an iteration order that is the same as the iteration order of an existing instance of a Map. Which concrete implementation of the Map interface should be used for the new instance? A. B. C. D. TreeMap HashMap LinkedHashMap The answer depends on the implementation of the existing instance.
Answer: Option C Explanation: The iteration order of a Collection is the order in which an iterator moves through the elements of the Collection. The iteration order of a LinkedHashMap is determined by the order in which elements are inserted. When a new LinkedHashMap is created by passing a reference to an existing Collection to the constructor of a LinkedHashMap the Collection.addAll method will ultimately be invoked. The addAll method uses an iterator to the existing Collection to iterate through the elements of the existing Collection and add each to the instance of the newLinkedHashMap. Since the iteration order of the LinkedHashMap is determined by the order of insertion, the
iteration order of the new LinkedHashMap must be the same as the interation order of the old Collection. View Answer Workspace Report Discuss in Forum
2.
Which class does not override the equals() and hashCode() methods, inheriting them directly from class Object? A. C. java.lang.String java.lang.StringBuffer B. D. java.lang.Double java.lang.Character
java.lang.StringBuffer is the only class in the list that uses the default methods provided by class Object.
View Answer Workspace Report Discuss in Forum
3.
Which collection class allows you to grow or shrink its size and provides indexed access to its elements, but whose methods are not synchronized? A. C. java.util.HashSet java.util.List B. D. java.util.LinkedHashSet java.util.ArrayList
Answer: Option D Explanation: All of the collection classes allow you to grow or shrink the size of your collection.ArrayList provides an index to its elements. The newer collection classes tend not to have synchronized methods. Vector is an older implementation of ArrayListfunctionality and has synchronized methods; it is slower than ArrayList. View Answer Workspace Report Discuss in Forum
4.
You need to store elements in a collection that guarantees that no duplicates are stored. Which one of the following interfaces provide that capability? A. Java.util.Map
B. C. D.
Answer: Option A Explanation: Option A is correct. A Map cannot contain duplicate keys. Option B is wrong. Lists typically allow duplicate elements. Option C is wrong. Collection allows duplicate elements. View Answer Workspace Report Discuss in Forum
5.
You need to store elements in a collection that guarantees that no duplicates are stored and all elements can be accessed in natural order. Which interface provides that capability? A. C. java.util.Map java.util.List B. D. java.util.Set java.util.Collection
Answer: Option B Explanation: Option B is correct. A set is a collection that contains no duplicate elements. The iterator returns the elements in no particular order (unless this set is an instance of some class that provides a guarantee). A map cannot contain duplicate keys but it may contain duplicate values. List and Collection allow duplicate elements. Option A is wrong. A map is an object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value. The Map interface provides three collection views, which allow a map's contents to be viewed as a set of keys, collection of values, or set of keyvalue mappings. The order of a map is defined as the order in which the iterators on the map's collection views return their elements. Some map implementations, like the TreeMap class, make specific guarantees as to their order (ascending key order); others, like the HashMap class, do not (does not guarantee that the order will remain constant over time). Option C is wrong. A list is an ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access
elements by their integer index (position in the list), and search for elements in the list. Unlike sets, lists typically allow duplicate elements. Option D is wrong. A collection is an ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list. Unlike sets, lists typically allow duplicate elements. Which interface does java.util.HashTable implement? A. C. Java.util.Map Java.util.HashTable B. D. Java.util.List Java.util.Collection
6.
Answer: Option A Explanation: Hash table based implementation of the Map interface. View Answer Workspace Report Discuss in Forum
7.
Which interface provides the capability to store objects using a key-value pair? A. C. Java.util.Map Java.util.List B. D. Java.util.Set Java.util.Collection
Answer: Option A Explanation: An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value. View Answer Workspace Report Discuss in Forum
8.
Which collection class allows you to associate its elements with key values, and allows you to retrieve objects in FIFO (first-in, first-out) sequence? A. C. java.util.ArrayList java.util.HashMap B. D. java.util.LinkedHashMap java.util.TreeMap
LinkedHashMap is the collection class used for caching purposes. FIFO is another way to indicate caching behavior. To retrieve LinkedHashMap elements in cached order, use the values() method and iterate over the resultant collection.
View Answer Workspace Report Discuss in Forum
9.
Which collection class allows you to access its elements by associating a key with an element's value, and provides synchronization? A. C. java.util.SortedMap java.util.TreeSet B. D. java.util.TreeMap java.util.Hashtable
Hashtable is the only class listed that provides synchronized methods. If you need synchronization great; otherwise, use HashMap, it's faster.
View Answer Workspace Report Discuss in Forum
10. Which is valid declaration of a float? A. C. float f = 1F; float f = "1"; B. D. float f = 1.0; float f = 1.0d;
Answer: Option A Explanation: Option A is valid declaration of float. Option B is incorrect because any literal number with a decimal point u declare the computer will implicitly cast to double unless you include "F or f" Option C is incorrect because it is a String.
Option D is incorrect because "d" tells the computer it is a double so therefore you are trying to put a double value into a float variable i.e there might be a loss of precision. 11. /* Missing Statement ? */ public class foo { public static void main(String[]args)throws Exception { java.io.PrintWriter out = new java.io.PrintWriter(); new java.io.OutputStreamWriter(System.out,true); out.println("Hello"); } } What line of code should replace the missing statement to make this program compile? A. B. C. D. No statement required. import java.io.*; include java.io.*; import java.io.PrintWriter;
Answer: Option A Explanation: The usual method for using/importing the java packages/classes is by using an import statement at the top of your code. However it is possible to explicitly import the specific class that you want to use as you use it which is shown in the code above. The disadvantage of this however is that every time you create a new object you will have to use the class path in the case "java.io" then the class name in the long run leading to a lot more typing. View Answer Workspace Report Discuss in Forum 12. What is the numerical range of char? A. C. 0 to 32767 -256 to 255 B. D. 0 to 65535 -32768 to 32767
Answer: Option B Explanation: The char type is integral but unsigned. The range of a variable of type char is from 0 to 2161 or 0 to 65535. Java characters are Unicode, which is a 16-bit encoding capable of
representing a wide range of international characters. If the most significant nine bits of a char are 0, then the encoding is the same as seven-bit ASCII. View Answer Workspace Report Discuss in Forum
13. Which of the following are Java reserved words? 1. 2. 3. 4. run import default implement
A. C.
1 and 2 3 and 4
B. D.
2 and 3 2 and 4
Answer: Option B Explanation: (2) - This is a Java keyword (3) - This is a Java keyword (1) - Is incorrect because although it is a method of Thread/Runnable it is not a keyword (4) - This is not a Java keyword the keyword is implement
`
1. void start() { A a = new A(); B b = new B(); a.s(b); b = null; /* Line 5 */ a = null; /* Line 6 */ System.out.println("start completed"); /* Line 7 */ } When is the B object, created in line 3, eligible for garbage collection? A. B. C. after line 5 after line 6 after line 7
D.
Answer: Option D Explanation: No answer description available for this question. Let us discuss. View Answer Workspace Report Discuss in Forum
2.
class HappyGarbage01 { public static void main(String args[]) { HappyGarbage01 h = new HappyGarbage01(); h.methodA(); /* Line 6 */ } Object methodA() { Object obj1 = new Object(); Object [] obj2 = new Object[1]; obj2[0] = obj1; obj1 = null; return obj2[0]; } } Where will be the most chance of the garbage collector being invoked? A. B. C. D. After line 9 After line 10 After line 11 Garbage collector never invoked in methodA()
Answer: Option D Explanation: Option D is correct. Garbage collection takes place after the method has returned its reference to the object. The method returns to line 6, there is no reference to store the return value. so garbage collection takes place after line 6. Option A is wrong. Because the reference to obj1 is stored in obj2[0]. The Objectobj1 still exists on the heap and can be accessed by an active thread through the reference stored
in obj2[0]. Option B is wrong. Because it is only one of the references to the object obj1, the other reference is maintained in obj2[0]. Option C is wrong. The garbage collector will not be called here because a reference to the object is being maintained and returned in obj2[0]. View Answer Workspace Report Discuss in Forum
3.
class Bar { } class Test { Bar doBar() { Bar b = new Bar(); /* Line 6 */ return b; /* Line 7 */ } public static void main (String args[]) { Test t = new Test(); /* Line 11 */ Bar newBar = t.doBar(); /* Line 12 */ System.out.println("newBar"); newBar = new Bar(); /* Line 14 */ System.out.println("finishing"); /* Line 15 */ } } At what point is the Bar object, created on line 6, eligible for garbage collection? A. B. C. D. after line 12 after line 14 after line 7, when doBar() completes after line 15, when main() completes
Answer: Option B Explanation: Option B is correct. All references to the Bar object created on line 6 are destroyed when a new reference to a new Bar object is assigned to the variable newBar on line 14. Therefore the Bar object, created on line 6, is eligible for garbage collection after line 14. Option A is wrong. This actually protects the object from garbage collection. Option C is wrong. Because the reference in the doBar() method is returned on line 7 and is
stored in newBar on line 12. This preserver the object created on line 6. Option D is wrong. Not applicable because the object is eligible for garbage collection after line 14. View Answer Workspace Report Discuss in Forum
4.
class Test { private Demo d; void start() { d = new Demo(); this.takeDemo(d); /* Line 7 */ } /* Line 8 */ void takeDemo(Demo demo) { demo = null; demo = new Demo(); } } When is the Demo object eligible for garbage collection? A. B. C. D. After line 7 After line 8 After the start() method completes When the instance running this code is made eligible for garbage collection.
Answer: Option D Explanation: Option D is correct. By a process of elimination. Option A is wrong. The variable d is a member of the Test class and is never directly set to null. Option B is wrong. A copy of the variable d is set to null and not the actual variabled. Option C is wrong. The variable d exists outside the start() method (it is a class member). So, when the start() method finishes the variable d still holds a reference. View Answer Workspace Report Discuss in Forum
5.
public class X
{ public static void main(String [] args) { X x = new X(); X x2 = m1(x); /* Line 6 */ X x4 = new X(); x2 = x4; /* Line 8 */ doComplexStuff(); } static X m1(X mx) { mx = new X(); return mx; } } After line 8 runs. how many objects are eligible for garbage collection? A. C. 0 2 B. D. 1 3
Answer: Option B Explanation: By the time line 8 has run, the only object without a reference is the one generated as a result of line 6. Remember that "Java is pass by value," so the reference variable x is not affected by the m1() method. Ref: http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html 6. public Object m() { Object o = new Float(3.14F); Object [] oa = new Object[l]; oa[0] = o; /* Line 5 */ o = null; /* Line 6 */ oa[0] = null; /* Line 7 */ return o; /* Line 8 */ } When is the Float object, created in line 3, eligible for garbage collection? A. C. just after line 5 just after line 7 B. D. just after line 6 just after line 8
Answer: Option C
Explanation: Option A is wrong. This simply copies the object reference into the array. Option B is wrong. The reference o is set to null, but, oa[0] still maintains the reference to the Float object. Option C is correct. The thread of execution will then not have access to the object. View Answer Workspace Report Discuss in Forum
7.
class X2 { public X2 x; public static void main(String [] args) { X2 x2 = new X2(); /* Line 6 */ X2 x3 = new X2(); /* Line 7 */ x2.x = x3; x3.x = x2; x2 = new X2(); x3 = x2; /* Line 11 */ doComplexStuff(); } } after line 11 runs, how many objects are eligible for garbage collection? A. C. 0 2 B. D. 1 3
Answer: Option C Explanation: This is an example of the islands of isolated objects. By the time line 11 has run, the objects instantiated in lines 6 and 7 are referring to each other, but no live thread can reach either of them. View Answer Workspace Report Discuss in Forum
8.
C. D.
Answer: Option D Explanation: Option D is correct. When an object is no longer referenced, it may be reclaimed by the garbage collector. If an object declares a finalizer, the finalizer is executed before the object is reclaimed to give the object a last chance to clean up resources that would not otherwise be released. When a class is no longer needed, it may be unloaded. Option A is wrong. I found 4 delete() methods in all of the Java class structure. They are: 1. delete() - Method in class java.io.File : Deletes the file or directory denoted by this abstract pathname. 2. delete(int, int) - Method in class java.lang.StringBuffer : Removes the characters in a substring of this StringBuffer. 3. delete(int, int) - Method in interfacejavax.accessibility.AccessibleEditableText : Deletes the text between two indices 4. delete(int, int) - Method in class :javax.swing.text.JTextComponent.AccessibleJTextComponent; Deletes the text between two indices None of these destroy the object to which they belong. Option B is wrong. I found 19 finalize() methods. The most interesting, from this questions point of view, was the finalize() method in class java.lang.Objectwhich is called by the garbage collector on an object when garbage collection determines that there are no more references to the object. This method does not destroy the object to which it belongs. Option C is wrong. But it is interesting. The Runtime class has many methods, two of which are: 1. getRuntime() - Returns the runtime object associated with the current Java application. 2. gc() - Runs the garbage collector. Calling this method suggests that the Java virtual machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the virtual machine has made its best effort to recycle all discarded objects. Interesting as this is, it doesn't destroy the object.
1.
What are the basic functions of an operating system? - Operating system controls and coordinates the use of the hardware among the various applications programs for various uses. Operating system acts as resource allocator and manager. Since there are many possibly conflicting requests for resources the operating system must decide which requests are allocated resources to operating the computer system efficiently and fairly. Also operating system is control program which controls the user programs to prevent errors and improper use of the computer. It is especially
2.
concerned with the operation and control of I/O devices. Why paging is used? - Paging is solution to external fragmentation problem which is to permit the logical address space of a process to be noncontiguous, thus allowing a process to be allocating physical memory wherever the latter is available. While running DOS on a PC, which command would be used to duplicate the entire diskette? diskcopy What resources are used when a thread created? How do they differ from those when a process is created? - When a thread is created the threads does not require any new resources to execute the thread shares the resources like memory of the process to which they belong to. The benefit of code sharing is that it allows an application to have several different threads of activity all within the same address space. Whereas if a new process creation is very heavyweight because it always requires new address space to be created and even if they share the memory then the inter process
3. 4.
5.
communication is expensive when compared to the communication between the threads. What is virtual memory? - Virtual memory is hardware technique where the system appears to have more memory that it actually does. This is done by time-sharing, the physical memory and storage parts of the memory one disk when they are not actively being used. What is Throughput, Turnaround time, waiting time and Response time? - Throughput number of processes that complete their execution per time unit. Turnaround time amount of time to execute a particular process. Waiting time amount of time a process has been waiting in the ready queue. Response time amount of time it takes from when a request was submitted until the first response is produced, not output (for time-sharing environment). What is the state of the processor, when a process is waiting for some event to occur? Waiting state What is the important aspect of a real-time system or Mission Critical Systems? - A real time operating system has well defined fixed time constraints. Process must be done within the defined constraints or the system will fail. An example is the operating system for a flight control computer or an advanced jet airplane. Often used as a control device in a dedicated application such as controlling scientific experiments, medical imaging systems, industrial control systems, and some display systems. Real-Time systems may be either hard or soft real-time. Hard real-time: Secondary storage limited or absent, data stored in short term memory, or read-only memory (ROM), Conflicts with time-sharing systems, not supported by general-purpose operating systems. Soft real-time: Limited utility in industrial control of robotics, Useful in applications (multimedia, virtual reality) requiring advanced operating-system features. What is the difference between Hard and Soft real-time systems? - A hard real-time system guarantees that critical tasks complete on time. This goal requires that all delays in the system be bounded from the retrieval of the stored data to the time that it takes the operating system to finish any request made of it. A soft real time system where a critical real-time task gets priority over other tasks
6.
7. 8.
9.
and retains that priority until it completes. As in hard real time systems kernel delays need to be bounded 10. What is the cause of thrashing? How does the system detect thrashing? Once it detects thrashing, what can the system do to eliminate this problem? - Thrashing is caused by under allocation of the minimum number of pages required by a process, forcing it to continuously page fault. The system can detect thrashing by evaluating the level of CPU utilization as compared to the level of multiprogramming. It can be eliminated by reducing the level of multiprogramming. 11. What is multi tasking, multi programming, multi threading? - Multi programming: Multiprogramming is the technique of running several programs at a time using timesharing. It allows a computer to do several things at the same time. Multiprogramming creates logical parallelism. The concept of multiprogramming is that the operating system keeps several jobs in memory simultaneously. The operating system selects a job from the job pool and starts executing a job, when that job needs to wait for any i/o operations the CPU is switched to another job. So the main idea here is that the CPU is never idle. Multi tasking: Multitasking is the logical extension of multiprogramming .The concept of multitasking is quite similar to multiprogramming but difference is that the switching between jobs occurs so frequently that the users can interact with each program while it is running. This concept is also known as time-sharing systems. A time-shared operating system uses CPU scheduling and multiprogramming to provide each user with a small portion of time-shared system. Multi threading: An application typically is implemented as a separate process with several threads of control. In some situations a single application may be required to perform several similar tasks for example a web server accepts client requests for web pages, images, sound, and so forth. A busy web server may have several of clients concurrently accessing it. If the web server ran as a traditional singlethreaded process, it would be able to service only one client at a time. The amount of time that a client might have to wait for its request to be serviced could be enormous. So it is efficient to have one process that contains multiple threads to serve the same purpose. This approach would multithread the webserver process, the server would create a separate thread that would listen for client requests when a request was made rather than creating another process it would create another thread to service the request. To get the advantages like responsiveness, Resource sharing economy and utilization of multiprocessor architectures multithreading concept can be used. 12. What is hard disk and what is its purpose? - Hard disk is the secondary storage device, which holds the data in bulk, and it holds the data on the magnetic medium of the disk.Hard disks have a hard platter that holds the magnetic medium, the magnetic medium can be easily erased and rewritten, and a typical desktop machine will have a hard disk with a capacity of between 10 and 40 gigabytes. Data is stored onto the disk in the form of files. 13. What is fragmentation? Different types of fragmentation? - Fragmentation occurs in a dynamic memory allocation system when many of the free blocks are too small to satisfy any request. External Fragmentation: External Fragmentation happens when a dynamic memory allocation algorithm allocates some memory and a small piece is left over that cannot be effectively used. If too much external fragmentation occurs, the amount of usable memory is drastically reduced. Total memory space exists to satisfy a request, but it is not contiguous. Internal Fragmentation: Internal fragmentation is the space wasted inside of allocated memory blocks because of restriction on the allowed sizes of allocated blocks. Allocated memory may be slightly larger than requested memory; this size difference is memory internal to a partition, but not being used 14. What is DRAM? In which form does it store data? - DRAM is not the best, but its cheap, does the job, and is available almost everywhere you look. DRAM data resides in a cell made of a capacitor and a transistor. The capacitor tends to lose data unless its recharged every couple of milliseconds, and this recharging tends to slow down the performance of DRAM compared to speedier RAM types. 15. What is Dispatcher? - Dispatcher module gives control of the CPU to the process selected by the
short-term scheduler; this involves: Switching context, Switching to user mode, Jumping to the proper location in the user program to restart that program, dispatch latency time it takes for the 16. dispatcher to stop one process and start another running. What is CPU Scheduler? - Selects from among the processes in memory that are ready to execute, and allocates the CPU to one of them. CPU scheduling decisions may take place when a process: 1.Switches from running to waiting state. 2.Switches from running to ready state. 3.Switches from waiting to ready. 4.Terminates. Scheduling under 1 and 4 is non-preemptive. All other scheduling is preemptive. What is Context Switch? - Switching the CPU to another process requires saving the state of the old process and loading the saved state for the new process. This task is known as a context switch. Contextswitch time is pure overhead, because the system does no useful work while switching. Its speed varies from machine to machine, depending on the memory speed, the number of registers which must be copied, the existed of special instructions(such as a single instruction to load or store all registers). What is cache memory? - Cache memory is random access memory (RAM) that a computer microprocessor can access more quickly than it can access regular RAM. As the microprocessor processes data, it looks first in the cache memory and if it finds the data there (from a previous reading of data), it does not have to do the more time-consuming reading of data from larger memory. What is a Safe State and what is its use in deadlock avoidance? - When a process requests an available resource, system must decide if immediate allocation leaves the system in a safe state. System is in safe state if there exists a safe sequence of all processes. Deadlock Avoidance: ensure that a system will never enter an unsafe state. What is a Real-Time System? - A real time process is a process that must respond to the events within a certain time period. A real time operating system is an operating system that can run real time processes successfully
17.
18.
19.
20.
1.
Whats relationship between JavaScript and ECMAScript? - ECMAScript is yet another name for JavaScript (other names include LiveScript). The current JavaScript that you see supported in browsers is ECMAScript revision 3. What are JavaScript types? - Number, String, Boolean, Function, Object, Null, Undefined. How do you convert numbers between different bases in JavaScript? - Use the parseInt() function, that takes a string as the first parameter, and the base as a second parameter. So to convert hexadecimal 3F to decimal, use parseInt ("3F", 16); What does isNaN function do? - Return true if the argument is not a number. What is negative infinity? - Its a number in JavaScript, derived by dividing negative number by zero. What boolean operators does JavaScript support? - &&, || and ! What does "1"+2+4 evaluate to? - Since 1 is a string, everything is a string, so the result is 124. How about 2+5+"8"? - Since 2 and 5 are integers, this is number arithmetic, since 8 is a string, its concatenation, so 78 is the result. What looping structures are there in JavaScript? - for, while, do-while loops, but no foreach. How do you create a new object in JavaScript? - var obj = new Object(); or var obj = {}; How do you assign object properties? - obj["age"] = 17 or obj.age = 17. Whats a way to append a value to an array? - arr[arr.length] = value;
2. 3.
Thanks to Sachin Rastogi for contributing these. 1. What makes J2EE suitable for distributed multitiered Applications? - The J2EE platform uses a multitiered distributed application model. Application logic is divided into components according to function, and the various application components that make up a J2EE application are installed on different machines depending on the tier in the multitiered J2EE environment to which the application component belongs. The J2EE application parts are:
2.
Client-tier components run on the client machine. Web-tier components run on the J2EE server. Business-tier components run on the J2EE server. Enterprise information system (EIS)-tier software runs on the EIS server.
3.
What is J2EE? - J2EE is an environment for developing and deploying enterprise applications. The J2EE platform consists of a set of services, application programming interfaces (APIs), and protocols that provide the functionality for developing multitiered, web-based applications. What are the components of J2EE application? - A J2EE component is a self-contained functional software unit that is assembled into a J2EE application with its related classes and files and communicates with other components. The J2EE specification defines the following J2EE components: Application clients and applets are client components. B. Java Servlet and JavaServer Pages technology components are web components. C. Enterprise JavaBeans components (enterprise beans) are business components. D. Resource adapter components provided by EIS and tool vendors. What do Enterprise JavaBeans components contain? - Enterprise JavaBeans components
A.
contains Business code, which is logic that solves or meets the needs of a particular business domain such as banking, retail, or finance, is handled by enterprise beans running in the business tier. All the business code is contained inside an Enterprise Bean which receives data from client programs, processes it (if necessary), and sends it to the enterprise information system tier for storage. An enterprise bean also retrieves data from storage, processes it (if necessary), and sends it back to the client program. Is J2EE application only a web-based? - No, It depends on type of application that client wants. A J2EE application can be web-based or non-web-based. if an application client executes on the client machine, it is a non-web-based J2EE application. The J2EE application can provide a way for users to handle tasks such as J2EE system or application administration. It typically has a graphical user interface created from Swing or AWT APIs, or a command-line interface. When user request, it can open an HTTP connection to establish communication with a servlet running in the web tier. Are JavaBeans J2EE components? - No. JavaBeans components are not considered J2EE components by the J2EE specification. They are written to manage the data flow between an application client or applet and components running on the J2EE server or between server components and a database. JavaBeans components written for the J2EE platform have instance variables and get and set methods for accessing the data in the instance variables. JavaBeans components used in this way are typically simple in design and implementation, but should conform to the naming and design conventions outlined in the JavaBeans component architecture. Is HTML page a web component? - No. Static HTML pages and applets are bundled with web components during application assembly, but are not considered web components by the J2EE specification. Even the server-side utility classes are not considered web components, either. What can be considered as a web component? - J2EE Web components can be either servlets or
JSP pages. Servlets are Java programming language classes that dynamically process requests and construct responses. JSP pages are text-based documents that execute as servlets but allow a more natural approach to creating static content. What is the container? - Containers are the interface between a component and the low-level platform specific functionality that supports the component. Before a Web, enterprise bean, or application client component can be executed, it must be assembled into a J2EE application and deployed into its container. What are container services? - A container is a runtime support of a system-level entity. Containers provide components with services such as lifecycle management, security, deployment, and threading. What is the web container? - Servlet and JSP containers are collectively referred to as Web containers. It manages the execution of JSP page and servlet components for J2EE applications. Web components and their container run on the J2EE server. What is Enterprise JavaBeans (EJB) container? - It manages the execution of enterprise beans for J2EE applications. Enterprise beans and their container run on the J2EE server. What is Applet container? - IManages the execution of applets. Consists of a Web browser and Java Plugin running on the client together. How do we package J2EE components? - J2EE components are packaged separately and bundled into a J2EE application for deployment. Each component, its related files such as GIF and HTML files or serverside utility classes, and a deployment descriptor are assembled into a module and added to the J2EE application. A J2EE application is composed of one or more enterprise bean,Web, or application client component modules. The final enterprise solution can use one J2EE application or be made up of two or more J2EE applications, depending on design requirements. A J2EE application and each of its modules has its own deployment descriptor. A deployment descriptor is an XML document with an .xml extension that describes a components deployment settings. What is a thin client? - A thin client is a lightweight interface to the application that does not have such operations like query databases, execute complex business rules, or connect to legacy applications. What are types of J2EE clients? - Following are the types of J2EE clients: Applets Application clients Java Web Start-enabled rich clients, powered by Java Web Start technology. Wireless clients, based on Mobile Information Device Profile (MIDP) technology. What is deployment descriptor? - A deployment descriptor is an Extensible Markup Language (XML) text-based file with an .xml extension that describes a components deployment settings. A J2EE application and each of its modules has its own deployment descriptor. For example, an enterprise bean module deployment descriptor declares transaction attributes and security authorizations for an enterprise bean. Because deployment descriptor information is declarative, it can be changed without modifying the bean source code. At run time, the J2EE server reads the deployment descriptor and acts upon the component accordingly. What is the EAR file? - An EAR file is a standard JAR file with an .ear extension, named from Enterprise ARchive file. A J2EE application with all of its modules is delivered in EAR file. What is JTA and JTS? - JTA is the abbreviation for the Java Transaction API. JTS is the abbreviation for the Jave Transaction Service. JTA provides a standard interface and allows you to demarcate transactions in a manner that is independent of the transaction manager implementation. The J2EE SDK implements the transaction manager with JTS. But your code doesnt call the JTS methods directly. Instead, it invokes the JTA methods, which then call the lower-level JTS routines. Therefore, JTA is a high level transaction interface that your application uses to control transaction. and JTS is a low level transaction interface and ejb uses behind the scenes (client code doesnt directly interact with JTS. It is based on object transaction service(OTS) which is part of CORBA.
What is JAXP? - JAXP stands for Java API for XML. XML is a language for representing and describing text-based data which can be read and handled by any program or tool that uses XML APIs. It provides standard services to determine the type of an arbitrary piece of data, encapsulate access to it, discover the operations available on it, and create the appropriate JavaBeans component to perform those operations. What is J2EE Connector? - The J2EE Connector API is used by J2EE tools vendors and system integrators to create resource adapters that support access to enterprise information systems that can be plugged into any J2EE product. Each type of database or EIS has a different resource adapter. Note: A resource adapter is a software component that allows J2EE application components to access and interact with the underlying resource manager. Because a resource adapter is specific to its resource manager, there is typically a different resource adapter for each type of database or enterprise information system. What is JAAP? - The Java Authentication and Authorization Service (JAAS) provides a way for a J2EE application to authenticate and authorize a specific user or group of users to run it. It is a standard Pluggable Authentication Module (PAM) framework that extends the Java 2 platform security architecture to support user-based authorization. What is Java Naming and Directory Service? - The JNDI provides naming and directory functionality. It provides applications with methods for performing standard directory operations, such as associating attributes with objects and searching for objects using their attributes. Using JNDI, a J2EE application can store and retrieve any type of named Java object. Because JNDI is independent of any specific implementations, applications can use JNDI to access multiple naming and directory services, including existing naming and directory services such as LDAP, NDS, DNS, and NIS. What is Struts? - A Web page development framework. Struts combines Java Servlets, Java Server Pages, custom tags, and message resources into a unified framework. It is a cooperative, synergistic platform, suitable for development teams, independent developers, and everyone between. How is the MVC design pattern used in Struts framework? - In the MVC design pattern, application flow is mediated by a central Controller. The Controller delegates requests to an appropriate handler. The handlers are tied to a Model, and each handler acts as an adapter between the request and the Model. The Model represents, or encapsulates, an applications business logic or state. Control is usually then forwarded back through the Controller to the appropriate View. The forwarding can be determined by consulting a set of mappings, usually loaded from a database or configuration file. This provides a loose coupling between the View and Model, which can make an application significantly easier to create and maintain. Controller: Servlet controller which supplied by Struts itself; View: what you can see on the screen, a JSP page and presentation components; Model: System state and a business logic JavaBeans.
1.
What is garbage collection? What is the process that is responsible for doing that in java? - Reclaiming the unused memory by the invalid objects. Garbage collector is responsible for this process What kind of thread is the Garbage collector thread? - It is a daemon thread. What is a daemon thread? - These are the threads which can run without user intervention. The JVM can exit when there are daemon thread by killing them abruptly. How will you invoke any external process in Java? - Runtime.getRuntime().exec(.) What is the finalize method do? - Before the invalid objects get garbage collected, the JVM give the user a chance to clean up some resources before it got garbage collected. What is mutable object and immutable object? - If a object value is changeable then we can call it as Mutable object. (Ex., StringBuffer, ) If you are not allowed to change the value of an object, it is
2. 3. 4. 5. 6.
7. 8. 9.
immutable object. (Ex., String, Integer, Float, ) What is the basic difference between string and stringbuffer object? - String is an immutable object. StringBuffer is a mutable object. What is the purpose of Void class? - The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the primitive Java type void. What is reflection? - Reflection allows programmatic access to information about the fields, methods and constructors of loaded classes, and the use reflected fields, methods, and constructors to operate on their underlying counterparts on objects, within security restrictions. What is the base class for Error and Exception? - Throwable What is the byte range? -128 to 127 What is the implementation of destroy method in java.. is it native or java code? - This method is not implemented. What is a package? - To group set of classes into a single unit is known as packaging. Packages provides wide namespace ability. What are the approaches that you will follow for making a program very efficient? - By avoiding too much of static methods avoiding the excessive and unnecessary use of synchronized methods Selection of related classes based on the application (meaning synchronized classes for multiuser and non-synchronized classes for single user) Usage of appropriate design patterns Using cache methodologies for remote invocations Avoiding creation of variables within a loop and lot more. What is a DatabaseMetaData? - Comprehensive information about the database as a whole. What is Locale? - A Locale object represents a specific geographical, political, or cultural region How will you load a specific locale? - Using ResourceBundle.getBundle(); What is JIT and its use? - Really, just a very fast compiler In this incarnation, pretty much a onepass compiler no offline computations. So you cant look at the whole method, rank the expressions according to which ones are re-used the most, and then generate code. In theory terms, its an on-line problem. Is JVM a compiler or an interpreter? - Interpreter When you think about optimization, what is the best way to findout the time/memory consuming process? - Using profiler What is the purpose of assert keyword used in JDK1.4.x? - In order to validate certain expressions. It effectively replaces the if block and automatically throws the AssertionError on failure. This keyword should be used for the critical arguments. Meaning, without that the method does nothing. How will you get the platform dependent values like line separator, path separator, etc., ? - Using Sytem.getProperty() (line.separator, path.separator, ) What is skeleton and stub? what is the purpose of those? - Stub is a client side representation of the server, which takes care of communicating with the remote server. Skeleton is the server side representation. But that is no more in use it is deprecated long before in JDK. What is the final keyword denotes? - final keyword denotes that it is the final implementation for that method or variable or class. You cant override that method/variable/class any more. What is the significance of ListIterator? - You can iterate back and forth. What is the major difference between LinkedList and ArrayList? - LinkedList are meant for sequential accessing. ArrayList are meant for random accessing. What is nested class? - If all the methods of a inner class is static then it is a nested class. What is inner class? - If the methods of the inner class can only be accessed via the instance of the inner class, then it is called inner class. What is composition? - Holding the reference of the other class within some other class is known as composition.
22. 23.
30. What is aggregation? - It is a special type of composition. If you expose all the methods of a composite class and route the method call to the composite method through its reference, then it is 31. 32. 33. called aggregation. What are the methods in Object? - clone, equals, wait, finalize, getClass, hashCode, notify, notifyAll, toString Can you instantiate the Math class? - You cant instantiate the math class. All the methods in this class are static. And the constructor is not public. What is singleton? - It is one of the design pattern. This falls in the creational pattern of the design pattern. There will be only one instance for that entire JVM. You can achieve this by having the private constructor in the class. For eg., public class Singleton { private static final Singleton s = new Singleton(); private Singleton() { } public static Singleton getInstance() { return s; } // all non static methods } What is DriverManager? - The basic service to manage set of JDBC drivers. What is Class.forName() does and how it is useful? - It loads the class into the ClassLoader. It returns the Class. Using that you can get the instance ( class-instance.newInstance() ). Inq adds a question: Expain the reason for each keyword of