Saturday, February 2, 2013

Packages and Interfaces programs

                                                          Packages and Interfaces
 
13. Write a java program that illustrates the following:
(a) Creation of simple package.
(b) Accessing a package.
(c) Implementing interfaces.

Packages are a feature of Java that helps you to organize and structure your classes and their relationships to one another. A package is a grouping of related types providing access protection and name space management. Note that types refer to classes, interfaces and others. The types that are part of the Java platform are members of various packages that bundle classes by function: fundamental classes are in java.lang, classes for reading and writing (input and output) are in java.io, and so on. You can put your types in packages too.
For example, consider the following package specification:

package MyPack;

In order for a program to find MyPack, we use one of the two alternatives:

1.Program is executed from a directory immediately above MyPack, or

2.CLASSPATH must be set to include the path to MyPack.
SET CLASSPATH =C:\MyPack\
We create a directory, MyPack below the current development directory, put the .class files into the MyPack directory, and then execute the program from the development directory.

Program (a): A simple package example
 
package MyPack; // A simple package
class Balance
{
String name;
double bal;
Balance(String s, double b) // constructor
{ name = s;
bal = b;
}
void show() // method
  if(bal < 0)
        System.out.print("-->> ");
   System.out.println(name + ": Rs" + bal);
}
}
class AccountBalance
{
public static void main(String args[])
Balance current[] = new Balance[3];
current[0] = new Balance("R. Lepakshi", 15230.50);
current[1] = new Balance("K. Siva Kumar", 350.75);
current[2] = new Balance("Michael Jackson", -120.30);
for(int i = 0; i < 3; i++) current[i].show();
}
}

Let the current development directory be C:\java

Create (make directory: md) MyPack directory as follows:

C:\java>md MyPack
Edit the AccountBalance.java program and compile it from current development directory as follows:

C:\java>edit AccountBalance.java

C:\java>javac AccountBalance.java

Then, copy Balance.class and AccountBalance.class files from the directory C:\java to the directory C:\java\MyPack

Execute the AccountBalance class, using the following command line:
C:\java>java MyPack.AccountBalance

AccountBalance is now part of the package MyPack. This means that it cannot be executed by itself. That is, we cannot use this command line:
C:\java>java AccountBalance

AccountBalance must be qualified with its package name.

In Java, an interface is a reference type, similar to a class that can contain only constants, method signatures, and nested types. There are no method bodies. Interfaces cannot be instantiated - they can only be implemented by classes or extended by other interfaces.
Here is an example of an interface definition (defining an interface is similar to creating a new class). Program 13(b) declares an interface called Items which contains four methods. Note that the method signatures have no braces and are terminated with a semicolon.

Program (b): Defining an interface Items

interface Items
   boolean equal(); // test whether two numbers are equal
  int add(); // sum of two numbers
  int max(); // maximum of two numbers
  void display(); // print two numbers
}

To declare a class that implements an interface, you include an implements clause in the class declaration. Your class can implement more than one interface, so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class. When an instantiable class implements an interface, it provides a method body for each of the methods declared in the interface. Here is an example class Client that implements the Items interface.

Program (c): Implementing an interface Items
 
class Client implements Items
{
int a, b;
Client( int i, int j) // constructor
{ a = i; b = j; }
public boolean equal()
{ return (a == b); }
public int add()
{ return(a + b); }
public int max()
{ if( a > b ) return a;
else return b;
}
public void display()

{
  System.out.println(a + " " + b);
 }
public int multiply() // non-interface method
    return(a * b); }
}

Program (d): Testing a class which implements an interface

class ClientDemo
{
 public static void main(String[] srgs)
{
  Client ob = new Client(5, 7);
 ob.display();
if( ob.equal())
  System.out.println("Two numbers are equal");
else
  System.out.println("Two numbers are not equal");
  System.out.println("Sum of two numbers is " + ob.add());
  System.out.println("Max of two numbers is " + ob.max());
 System.out.println("Product of two numbers is " + ob.multiply());
}
}

Output of this program is:
 
5 7

Two numbers are not equal
Sum of two numbers is 12
Max of two numbers is 7
Product of two numbers is 35

Thursday, January 24, 2013

OCJP tutorials -7

                                        OCJP Encyclopedia Tutorials

Consider the following application:

1. class Q6 {
2. public static void main(String args[]){
3. Holder h = new Holder();
4. h.held = 100;
5. h.bump(h);
6. System.out.println(h.held);
7. }
8. }
9.
10. class Holder {
11. public int held;
12. public void bump(Holder theHolder){theHolder.held++;}
13. }
What value is printed out at line 6?

A. 0.
B. 1.
C. 100.
D. 101.
Answer:  D is correct. A holder is constructed on line 6. A reference to that holder is passed into method bump() on line 5. Within the method call, the holder's held variable is bumped from 100 to 101.


Question: Consider the following application:

1. class Q7 {
2. public static void main(String args[]){
3. double d = 12.3;
4. Decrementer dec = new Decrementer();
5. dec.decrement(d);
6. System.out.println(d);
7. }
8. }
9.
10. class Decrementer {
11. public void decrement(double decMe){decMe = decMe - 1.0;}
12. }
What value is printed out at line 6?
A. 0.0
B. -1.0
C. 12.3
D. 11.3
Answer:C is correct. The decrement() method is passed a copy of the argument d; the copy gets decremented, but the original is untouched.

Question: What does the following code fragment print out at line 10?


1. try{
2. FileOutputStream fos = new FileOutputStream("xx");
3. for (byte b=10; b<50; b++)
4. fos.write(b);
5. fos.close();
6. RandomAccessFile raf = new RandomAccessFile("xx","r");
7. raf.seek(10);
8. int i = raf.read();
9. raf.close();
10. System.out.println("i=" + i);
8. }
9. catch (IOException e) {}


A. The output is i = 30.


B. The output is i = 20.


C. The output is i = 10.


D. There is no output because the code throws an exception at line 1.


E. There is no output because the code throws an exception at line 6.


Answer:B is correct. All the code is perfectly legal, so no exceptions are thrown. The first byte in the file is 10, the next byte is 11, the next is 12 and so on. The byte at file position 10 is 20, so the output is i = 20.

Question: Which of the following signatures are valid for the main() method entry point of an application?


A. public static void main()

B. public static void main(String arg[])

C. public void main(String [] arg)

D. public static void main(String[] args)

E. public static int main(String [] arg)

Answer:B and D are both acceptable


Question: What is the range of values that can be assigned to a variable of type short?


A. It depends on the underlying hardware.


B. 0 through 216-1


C. 0 through 232-1


D. -21515 through 215-1


E. -231 through 231-1.


Answer:D is correct. The range for a 16-bit short is -215 through 215-1. This range is part of the Java specification, regardless of the underlying hardware.


Question: A file is created with the following Code:

1. FileOutputStream fos = new FileOutputStream("datafile");
2. DataOutputstream dos = new DataOutputstream(fos); 
3. for(int i=0; i<500; i++)
4. dos.writeInt(i);

You would like to write code to read back the data from this file. Which solutions listed below will work? (Choose none, some, or all).


A. Construct a FileInputStream, passing the name of the file. Onto the FileInputStream, chain a DataInputStream, and call its readInt() method.


B. Construct a FileReader, passing the name of the file. Call the file reader's readInt() method.


C. Construct a PipedInputStream, passing the name of the file. Call the piped input stream's readInt() method.


D. Construct a RandomAccessFile, passing the name of the file. Call the random access file's readInt() method.


E. Construct a FileReader, passing the name of the file. Onto the FileReader, chain a DataInputStream, and call its readInt() method.


Answer:  A and D are correct. Solution A chains a data input stream onto a file input stream. Solution D simply uses the RandomAccessFile class. B fails because the FileReader class has no readInt() method; readers and writers only handle text. Solution C fails because the PipedInputStream class has nothing to do with file I/O. (Piped inout and output streams are used in inter-thread communication). Solution E fails because you cannot chain a data input stream onto a file reader. Readers read chars, and input streams handle bytes.

Friday, January 11, 2013

Eclipse 30 Key Board Shortcuts

  • This tutorial is about 30 Eclipse keyboard shortcuts, this list is by no means complete and I will suggest you guys to share eclipse shortcuts listed other than here to make this more useful.Eclipse is most used Java development IDE and knowing Eclipse shortcuts not only improve your productivity but also makes you more efficient, you will have more time for things you like to do. 
  • Using keyboard shortcuts also helps to impress colleagues and shows that you have good hold on tools you used for Java Development. 
  • Netbeans provide sophisticated IDE environment to enable you to build, debug and run your Java application in various emulator including some advanced processing options e.g. preprocessing, setting up Exception break-point etc.
  • From that time I love to know keyboard shortcuts on IDE and other tools I used for development including Edit Plus, Microsoft Excel etc.

 Eclipse was most suited for those application given some of cool feature of eclipse e.g. Remote Debugging, Conditional Breakpoints, Exception breakpoints and Ctrl+T and Ctrl+R kind of shortcuts.

 Here I am sharing list of 30 Eclipse keyboard shortcuts which I found most useful and using in my day to day life while writing code, reading code or debugging Java application in Eclipse. 

Eclipse Keyboard Shortcuts 

 1) Ctrl + T for finding class even from jar This keyboard shortcut in Eclipse is my most used and favorite shortcut. While working with high speed trading system which has complex code I often need to find classes with just blink of eye and this eclipse keyboard shortcut is just made for that. No matter whether you have class in your application or inside any JAR, this shortcut will find it.

 2) Ctrl + R for finding any resource (file) including config xml files This is similar to above Eclipse shortcut with only difference that it can find out not only Java files but any files including xml, configs and many others, but this eclipse shortcut only finds files from your workspace and doesn’t dig at jar level. 

3) Ctrl + 1 for quick fix This is another beautiful Eclipse shortcut which can fix up any error for you in Eclipse. Whether it’s missing declaration, missing semi colon or any import related error this eclipse shortcut will help you to quickly short that out. 

4) Ctrl + Shift + o for organize imports Another Eclipse keyboard shortcut for fixing missing imports. Particularly helpful if you copy some code from other file and what to import all dependencies. 

Eclipse Shortcut for Quick Navigation In this section we will see some eclipse keyboard shortcut which helps to quickly navigate within file and between file while reading and writing code in Eclipse.

 7) Ctrl + o for quick outline going quickly to method 

  9) Alt + right and Alt + left for going back and forth while editing.

 12) Alt + Shift + W for show in package explorer

 13) Ctrl + Shift + Up and down for navigating from member to member (variables and methods) 15) Ctrl + k and Ctrl + Shift +K for find next/previous

 24) Go to a type declaration: F3, This Eclipse shortcut is very useful to see function definition very quickly. 


Eclipse Shortcut for Editing Code These Eclipse shortcuts are very helpful for editing code in Eclipse. 

5) Ctrl + / for commenting, un commenting lines and blocks 

6) Ctrl + Shift + / for commenting, un commenting lines with block comment 

8) Selecting class and pressing F4 to see its Type hierarchy 

10) Ctrl + F4 or Ctrl + w for closing current file 

11) Ctrl+Shirt+W for closing all files. 

14) Ctrl + l go to line 

16) Select text and press Ctrl + Shift + F for formatting.

 17) Ctrl + F for find, find/replace 

18) Ctrl + D to delete a line

 19) Ctrl + Q for going to last edited place


 Miscellaneous Eclipse Shortcuts These are different Eclipse keyboard shortcuts which doesn’t fit on any category but quite helpful and make life very easy while working in Eclipse. 

20) Ctrl + T for toggling between super type and subtype 

21) Go to other open editors: Ctrl + E. 

22) Move to one problem (i.e.: error, warning) to the next (or previous) in a file: Ctrl +. For next, and Ctrl +, for previous problem

 23) Hop back and forth through the files you have visited: Alt + ? and Alt + ?, respectively.

 25) CTRL+Shift+G, which searches the workspace for references to the selected method or variable 

26) Ctrl+Shift+L to view listing for all Eclipse keyboard shortcuts.

 27) Alt + Shift + j to add javadoc at any place in java source file. 

28) CTRL+SHIFT+P to find closing brace. Place the cursor at opening brace and use this.

 29) Alt+Shift+X, Q to run Ant build file using keyboard shortcuts in Eclipse.

 30) Ctrl + Shift +F for Auto formating. Please update us if anything is missing or posted wrong.. No related posts.

Saturday, December 29, 2012

OCJP Questions - 4


Given:
1. class Alligator {
2. public static void main(String[] args) {
3. int []x[] = {{1,2}, {3,4,5}, {6,7,8,9}};
4. int [][]y = x;
5. System.out.println(y[2][1]);
6. }
7. }

What is the result?

A. 2
B. 3
C. 4
D. 6
E. 7
F. Compilation fails.


Answer: E

*********************************************************************************

Given:
11. class Converter {
12. public static void main(String[] args) {
13. Integer i = args[0];
14. int j = 12;
15. System.out.println("It is " + (j==i) + " that j==i.");
16. }
17. }

What is the result when the programmer attempts to compile the code and run it with the
command java Converter 12?

A. It is true that j==i.
B. It is false that j==i.
C. An exception is thrown at runtime.
D. Compilation fails because of an error in line 13.

Answer: D

*********************************************************************************


Given:
11. String test = "Test A. Test B. Test C.";
12. // insert code here
13. String[] result = test.split(regex);
Which regular expression, inserted at line 12, correctly splits test into "Test A", "Test B", and "Test
C"?

A. String regex = "";
B. String regex = " ";
C. String regex = ".*";
D. String regex = "\\s";
E. String regex = "\\.\\s*";
F. String regex = "\\w[ \.] +";


Answer: E


*********************************************************************************

OCJP Tutorials - 3


Given:
1. public class Score implements Comparable<Score> {
2. private int wins, losses;
3. public Score(int w, int l) { wins = w; losses = l; }
4. public int getWins() { return wins; }
5. public int getLosses() { return losses; }
6. public String toString() {
7. return "<" + wins + "," + losses + ">";
8. }
9. // insert code here
10. }

Which method will complete this class?

A. public int compareTo(Object o){/*more code here*/}
B. public int compareTo(Score other){/*more code here*/}
C. public int compare(Score s1,Score s2){/*more code here*/}
D. public int compare(Object o1,Object o2){/*more code here*/}

Answer: B

*******************************************************************************


Given:
11. public class Person {
12. private name;
13. public Person(String name) {
14. this.name = name;
15. }
16. public int hashCode() {
17. return 420;
18. }
19. }

Which statement is true?

A. The time to find the value from HashMap with a Person key depends on the size of the map.
B. Deleting a Person key from a HashMap will delete all map entries for all keys of type Person.
C. Inserting a second Person object into a HashSet will cause the first Person object to be removed
as a duplicate.
D. The time to determine whether a Person object is contained in a HashSet is constant and does
NOT depend on the size of the map.


Ans: A

******************************************************************************


Given:
5. import java.util.*;
6. public class SortOf {
7. public static void main(String[] args) {
8. ArrayList<Integer> a = new ArrayList<Integer>();
9. a.add(1); a.add(5); a.add(3);
11. Collections.sort(a);
12. a.add(2);
13. Collections.reverse(a);
14. System.out.println(a);
15. }
16. }

What is the result?

A. [1, 2, 3, 5]
B. [2, 1, 3, 5]
C. [2, 5, 3, 1]
D. [5, 3, 2, 1]
E. [1, 3, 5, 2]
F. Compilation fails.
G. An exception is thrown at runtime.

Answer: C

********************************************************************************


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

Answer: A, B, D

*********************************************************************************


Which two code fragments correctly create and initialize a static array of int elements? (Choose
two.)


A. static final int[] a = { 100,200 };
B. static final int[] a;
static { a=new int[2]; a[0]=100; a[1]=200; }
C. static final int[] a = new int[2]{ 100,200 };
D. static final int[] a;
static void init() { a = new int[3]; a[0]=100; a[1]=200; }

Answer: A, B




Friday, December 28, 2012

OCJP Questions - 2

A company that makes Computer Assisted Design (CAD) software has, within its
application, some utility classes that are used to perform 3D rendering tasks. The
company's chief scientist has just improved the performance of one of the utility classes'
key rendering algorithms, and has assigned a programmer to replace the old algorithm
with the new algorithm. When the programmer begins researching the utility classes, she
is happy to discover that the algorithm to be replaced exists in only one class. The
programmer reviews that class's API, and replaces the old algorithm with the new
algorithm, being careful that her changes adhere strictly to the class's API. Once testing
has begun, the programmer discovers that other classes that use the class she changed are
no longer working properly. What design flaw is most likely the cause of these new
bugs?
A. Inheritance
B. Tight coupling
C. Low cohesion
D. High cohesion
E. Loose coupling

Answer: B

=========================================================================

Given:
5. class Thingy { Meter m = new Meter(); }
6. class Component { void go() { System.out.print("c"); } }
7. class Meter extends Component { void go() { System.out.print("m"); } }
8.
9. class DeluxeThingy extends Thingy {
10. public static void main(String[] args) {
11. DeluxeThingy dt = new DeluxeThingy();
12. dt.m.go();
13. Thingy t = new DeluxeThingy();
14. t.m.go();
15. }
16. }
Which two are true? (Choose two.)
A. The output is mm.
B. The output is mc.
C. Component is-a Meter.
D. Component has-a Meter.
E. DeluxeThingy is-a Component.
F. DeluxeThingy has-a Component.

Answer: A,F


Saturday, December 22, 2012

OCJP QUIZ QUESTIONS

Given the code. What is the output?
public class Test {    
    int a = 10;
   
    public void doStuff(int a) {
        a += 1;
        System.out.println(++a);
    }
    public static void main(String args[]) {
        Test t = new Test();
        t.doStuff(3);
    }
}


0/p :   5 
------------------------------------------------------------------

Given the code. What is the result?
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class HashTest {
   
    private String str;
   
    public HashTest(String str) {
        this.str = str;
    }
   
    @Override
    public String toString() {
        return this.str;
    }
       
    public static void main(String args[]) {
        HashTest h1 = new HashTest("2");       
        String s1 = new String("1");       
       
        List<Object> list = new LinkedList<Object>();
        list.add(h1);
        list.add(s1);
       
        Collections.sort(list);
        for (Object o : list) {
            System.out.print(o + " ");
        }
    }
}
  A) "2 1" is printed.
 B) "1 2" is printed.
 C) Compilation fails.
 D) An exception is thrown at runtime
o/p :
-----------------------------------------------------------------

Given the code. What is the result?
    public static void main(String args[]) {
                String str = "null";
                if (str == null) {
                        System.out.print("1");
                } else if (str.length() == 0) {
                        System.out.print("2");
                } else {
                        System.out.print("3");
                }
        }
       
        A) Compilation fails.
 B) "1" is printed.
 C) "2" is printed.
 D) "3" is printed.
 E) An exception is thrown at runtime.

 --------------------------------------------------------------
 What should be called after the code below to suggest that the JVM expend effort toward recycling the memory used by the object a? (Select two)
BigObject a = MyFactory.createBigObject();
a.doStuff();
a = null;
 A) System.gc()
 B) Runtime.gc()
 C) System.freeMemory()
 D) Runtime.getRuntime().freeMemory()
 E) Runtime.getRuntime().gc()

 --------------------------------------------------------------
 class Hotel {
    public void book() throws Exception {
        throw new Exception();
    }
}

public class SuperHotel extends Hotel  {
    public void book() {
        System.out.print("booked");
    }
   
    public static void main(String args[]) {
        Hotel h = new SuperHotel();
        h.book();
    }  
}
 A) An exception is thrown at runtime.
 B) Compilation fails.
 C) The code runs without any output.
 D) "boked" is printed.
 ------------------------------------------------------------
 class Hotel {
    public void book() throws Exception {
        throw new Exception();
    }
}

public class SuperHotel extends Hotel  {
    public void book() {
        System.out.print("booked");
    }
   
    public static void main(String args[]) {
        Hotel h = new SuperHotel();
        h.book();
    }  
}

-----------------------------------------------------------
Given the code. What is the result?
public class Test {
    private static void doStuff(String str) {
        int var = 4;
        if (var == str.length()) {
            System.out.print(str.charAt(var--) + " ");
        }
        else {
            System.out.print(str.charAt(0) + " ");
        }
    }
    public static void main(String args[]) {
        doStuff("abcd");
        doStuff("efg");
        doStuff("hi");
    }
}
 A) Compilation fails.
 B) An exception is thrown at runtime.
 C) d e h
 D) d f i
 E) c f i
 F) c e h
 --------------------------------------------------------
 Given the code. Which statements are true? (Select two)
public class Hotel {        

        public static void book() {
                //some code goes here
        }
       
        public void cancelBooking() {
                //some code goes here
        }      
}     
 A) Method book() can directly call method cancelBooking()
 B) Method cancelBooking() can directly call method book()
 C) Hotel.book() is a valid invocation of book()
 D) Hotel.cancelBooking() is a valid invocation of cancelBooking()

 expalnation :

                public class StaticEx1 {        

        public static void book() {
              // cancelBooking();         
        }
       
        public void cancelBooking() {
                //some code goes here
   
        }      
}  
 if we call method cancelBooking in book() method we will get the following output:
StaticEx1.java:4: non-static method cancelBooking() cannot be referenced from a
static context
               cancelBooking();
               ^
1 error

so Correct answer is

    public class StaticEx1 {        

        public static void book() {
                
        }
       
        public void cancelBooking() {
                //some code goes here
                book();
        }      
}  
 i.e we can call a static method in non static context. But not a non-static method in static context.


 class StaticEx {        

        public static void book() {
              // cancelBooking();
        System.out.println(" Hi! I am a static method ");

        }
       
        public void cancelBooking() {
                //some code goes here
        book();
        System.out.println(" Hi! I am a non-static method ");
        }      
}     
class StaticEx1
{
    public static void main(String[] args)
    {
        StaticEx.book();
    //    StaticEx.cancelBooking(); //a non-static method cannot be referenced from a static context.
    }

}
 ------------------------------------------------------------------

Given the code. What is the result?
public class Cruiser implements Runnable {
    public static void main(String[] args) {
        Thread a = new Thread(new Cruiser());
        a.start();
       
        System.out.print("Begin");
        a.join();
        System.out.print("End");
    }
   
    public void run() {
        System.out.print("Run");
    }
}
 A) Compilation fails.
 B) An exception is thrown at runtime.
 C) "BeginRunEnd" is printed.
 D) "BeginEndRun" is printed.
 E) "BeginEnd" is printed.
 -----------------------------------------------------------------

 public class TryMe {
   
    public static void printB(String str) {
         System.out.print(Boolean.valueOf(str) ? "true" : "false");
    }
   
    public static void main(String args[]) {
        printB("tRuE");
        printB("false");
    }
}
-------------------------------------------------------------------
Given the code. What is the result?
    public static void main(String args[]) {
        String str = null;
        if (str == null) {
            System.out.print("1");
        } else (str.length() == 0) {
            System.out.print("2");
        } else {
            System.out.print("3");
        }
    }
 A) Compilation fails.
 B) "1" is printed.
 C) "2" is printed.
 D) "3" is printed.
 E) An exception is thrown at runtime.
-----------------------------------------------------------------
Given the code. What is the result?
public class Hotel  {
   
    private static void book() {
        System.out.print("book");
    }
   
    public static void main(String[] args) {
        Thread.sleep(1);
        book();
    }
}
 A) Compilation fails.
 B) An exception is thrown at runtime.
 C) "book" is printed.
 D) The code executes normally, but nothing is printed.
----------------------------------------------------------------
import java.util.HashSet;

public class HashTest {
   
    private String str;
   
    public HashTest(String str) {
        this.str = str;
    }
       
    @Override
    public int hashCode() {            
        return this.str.hashCode();
    }
   
    @Override
    public boolean equals(Object obj) {
        return this.str.equals(obj);
    }
   
    public static void main(String args[]) {
        HashTest h1 = new HashTest("1");
        HashTest h2 = new HashTest("1");
        String s1 = new String("2");
        String s2 = new String("2");
       
        HashSet<Object> hs = new HashSet<Object>();
        hs.add(h1);
        hs.add(h2);
        hs.add(s1);
        hs.add(s2);
       
        System.out.print(hs.size());
    }
}
)
 A)"4" is printed.
 B) "3" is printed.
 C) "2" is printed.
 D) Compilation fails.
 E) An exception is thrown at runtime.
        
------------------------------------------------------------------------

Given the code. What is the result?
    public static void main(String args[]) {
        try {
            String arr[] = new String[10];
            arr = null;
            arr[0] = "one";
            System.out.print(arr[0]);
        } catch(NullPointerException nex) {
            System.out.print("null pointer exception");
        } catch(Exception ex) {
            System.out.print("exception");
        }
    }
 A) "one" is printed.
 B) "exception" is printed.
 C) "null pointer exception" is printed. // correct answer
 D) Compilation fails.
-----------------------------------------------------------------------

.

Which of the following lines will print false?

1.public class MyClass
2.{
3.     static String s1 = "I am unique!";
4.     public static void main(String[] args)
5.     {
6.          String s2 = "I am unique!";
7.          String s3 = new String(s1);
8.          System.out.println(s1 == s2);
9.          System.out.println(s1.equals(s2));
10.         System.out.println(s3 == s1);
11.         System.out.println(s3.equals(s1));
12.     }
13.}
     a.  Line 8   
     b.  Line 9   
     c.  Line 10   
     d.  Line 11   
     e.  None of these
     -------------------------------------------------------------------
     Given the code. What is the result?
import java.util.Collections;
import java.util.LinkedList;

public class TryMe {
    public static void main(String args[]) {
        LinkedList<String> list = new LinkedList<String>();
        list.add("BbB1");
        list.add("bBb2");
        list.add("bbB3");
        list.add("BBb4");
        Collections.sort(list);
        for (String str : list) {
            System.out.print(str + ":");
        }
    }
}
 A) "BbB1:bBb2:bbB3:BBb4:" is printed.
 B) "BBb4:bbB3:bBb2:BbB1:" is printed.
 C) "BBb4:BbB1:bBb2:bbB3:" is printed. // correct answer
 D) "bbB3:bBb2:BbB1:BBb4:" is printed
 E) Compilation fails.
 F) An exception is thrown at runtime.
 --------------------------------------------------------------------
 Give the code. What is the result?
class Hotel {
    public int bookings;
    public void book() {
        bookings++;
    }
}

public class SuperHotel extends Hotel {
    public void book() {
        bookings--;
    }
   
    public void book(int size) {
        book();
        super.book();
        bookings += size;
    }
   
    public static void main(String args[]) {
        SuperHotel hotel = new SuperHotel();
        hotel.book(2);
        System.out.print(hotel.bookings);
    }
}
 A) Compilation fails.
 B) An exception is thrown at runtime.
 C) 0
 D) 1
 E) 2
 F) -1
 -----------------------------------------------------------------------------
 Given the code. What is the result?
public class Cruiser implements Runnable {
   
    public void run() {
        System.out.print("go");
    }
   
    public static void main(String arg[]) {
        Thread t = new Thread(new Cruiser());
        t.run();
        t.run();
        t.start();
    }
}
 A) Compilation fails.
 B) An exception is thrown at runtime.
 C) "go" is printed
 D) "gogogo" is printed   // cORRECT ANSWER
 E) "gogo" is printed
 ================================================================================
 Given the code. What is the result?
class Small {
    public Small() {
        System.out.print("a ");
    }
}

class Small2  extends Small {
    public Small2() {
        System.out.print("b ");
    }
}

class Small3 extends Small2 {
    public Small3() {
        System.out.print("c ");
    }
}

public class Test {    
    public static void main(String args[]) {
        new Small3();
    }
}
 A) a
 B) c
 C) a b c
 D) c b a
 E) The code runs without output.
---------------------------------------------------------------------------------

class Test2{
public static void main(String args[]) {
      Object myObj = new String[]{"one", "two", "three"};
 {
          for (String s : (String[])myObj) System.out.print(s + ".");
      }
  }
}

o/p : Error at line 3  or one.two.three if declaration is ended with semicoaln in line 3.
----------------------------------------------------------------------------------
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class TryMe3 {
    public static void main(String args[]) {
        List list = new LinkedList<String>();
        list.add("one");
        list.add("two");
        list.add("three");
       
        Collections.reverse(list);
        Iterator iter = list.iterator();
       
        for (Object o : list) {
            System.out.print(o + " ");
        }
//    System.out.println(iter);

    }
}
 three two one is output
 -------------------------------------------------------------------------------
 Given the code. What is the result?
import java.io.*;

public class Hotel implements Serializable {
    private transient Room room = new Room();
   
    public static void main(String[] args) {
        Hotel h = new Hotel();
        try {
            FileOutputStream fos = new FileOutputStream("Hotel.dat");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(h);
            oos.close();
        } catch(Exception ex) {
            ex.printStackTrace();
        }
    }
}

class Room {
}
 A) Compilation fails.
 B) An exception is thrown at runtime.
 C) An instance of Hotel is serialized.
 D) An instance of Hotel and an instance of Room are both serialized.
 -----------------------------------------------------------------------------
 Give a piece of code. Which two are possible results? (Select two)
public class Cruiser {
    private int a = 0;
   
    public void foo() {
        Runnable r = new LittleCruiser();
        new Thread(r).start();
        new Thread(r).start();
    }
   
    public static void main(String arg[]) {
        Cruiser c = new Cruiser();
        c.foo();
    }
   
    public class LittleCruiser implements Runnable {
        public void run() {
            int current = 0;
            for (int i = 0; i < 4; i++) {
                current = a;
                System.out.print(current + ", ");
                a = current + 2;
            }
        }
    }
}
 A) 0, 2, 4, 0, 2, 4, 6, 6,
 B) 0, 2, 4, 6, 8, 10, 12, 14,
 C) 0, 2, 4, 6, 8, 10, 2, 4,
 D) 0, 0, 2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 12, 12, 14, 14,
 E) 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14,
 ===============================================================================
 package com.mycompany;

public class Hotel  {
    public int roomNr = 100;
}
 A) Only the Hotel class.
 B) Any class.
 C) Any class in com.mycompany package.
 D) Any class that extends Hotel.
 --------------------------------------------------------------------------------
 Given the exhibit. What is the result?
public class Hotel {
   
    public static void book(short a) {
        System.out.print("short ");
    }
   
    public static void book(Short a) {
        System.out.print("SHORT ");
    }
   
    public static void book(Long a) {
        System.out.print("LONG ");
    }
   
    public static void main(String[] args) {
        short shortRoom = 1;
        int intRoom = 2;
       
        book(shortRoom);
        book(intRoom);
    }
}
 A) SHORT LONG
 B) short LONG
 C) Compilation fails
 D) An exception is thrown at runtime
 -----------------------------------------------------------------------------
 Given the code. What is the output?
public class Hotel {
    private int roomNr;
   
    public Hotel(int roomNr) {
        this.roomNr = roomNr;
    }
   
    public int getRoomNr() {
        return this.roomNr;
    }
   
    static Hotel doStuff(Hotel hotel) {
        hotel = new Hotel(1);
        return hotel;
    }
   
    public static void main(String args[]) {
        Hotel h1 = new Hotel(100);
        System.out.print(h1.getRoomNr() + " ");
        Hotel h2 = doStuff(h1);
        System.out.print(h1.getRoomNr() + " ");
        System.out.print(h2.getRoomNr() + " ");
        h1 = doStuff(h2);
        System.out.print(h1.getRoomNr() + " ");
        System.out.print(h2.getRoomNr() + " ");
    }
}
 A) 100 1 1 1 1
 B) 100 100 1 1 1
 C) 100 100 100 1 1
 D) 100 100 100 100 1
 E) 100 100 100 100 100
-------------------------------------------------------------------------
Given the code. What is the result?
public class Test {
    private static void doStuff(String str) {
        int var = 4;
        if (var == str.length()) {
            System.out.print(str.charAt(--var) + " ");
        }
        else {
            System.out.print(str.charAt(0) + " ");
        }
    }
    public static void main(String args[]) {
        doStuff("abcd");
        doStuff("efg");
        doStuff("hi");
    }
}
 A) Compilation fails.
 B) An exception is thrown at runtime.
 C) d e h
 D) d f i
 E) c f i
 F) c e h
 -----------------------------------------------------------------------
 The code below is executed by "java -Dmyprop=myprop Test". Which two, placed instead of "//some code goes here", will produce the output "myprop"? (Choose two)
public class Test {
    public static void main(String args[]) {
        String prop = //some code goes here//
        System.out.print(prop);
    }
}
 A) System.getEnv("myprop");
 B) System.load("myprop");
 C) System.property("myprop");
 D) System.getProperty("myprop");
 E) System.get("myprop");
 F) System.getProperties().getProperty("myprop");
 ---------------------------------------------------------------------------
 Given the code. Select correct calls of methods. (Select all that apply)
import java.util.*;

class Empty {  
}

class Extended extends Empty { 
}

public class TryMe {   
        public static void doStuff1(List<Empty> list) {
                // some code
        }
        public static void doStuff2(List list) {       
                // some code
        }
        public static void doStuff3(List<? extends Empty> list) {
                // some code           
        }
       
        public static void main(String args[]) {
                List<Empty> list1 = new LinkedList<Empty>();
                List<Extended> list2 = new LinkedList<Extended>();
               
                // more code here
        }
}
 A) doStuff1(list1);
 B) doStuff2(list2);
 C) doStuff2(list1);
 D) doStuff3(list1);
 E) doStuff3(list2);
 F) doStuff1(list2);
---------------------------------------------------------------------------------
Given the code. What is the result after the class TryMe execution?
class A {
    public void doA() {
        B b = new B();
        b.dobB();
        System.out.print("doA");
    }
}

class B {
    public void dobB() {
        C c = new C();
        c.doC();
        System.out.print("doB");
    }
}

class C {
    public void doC() {
        if (true)
            throw new NullPointerException();
        System.out.print("doC");
    }
}

public class TryMe {

    public static void main(String args[]) {
        try {
            A a = new A();
            a.doA();
        } catch (Exception ex) {
            System.out.print("error");
        }
    }
}
 A) "doCdoBdoA" is printed
 B) "doAdoBdoC" is printed
 C) "doBdoAerror" is printed
 D) "error" is printed
 E) nothing is printed
 ---------------------------------------------------------------------
 Given:
System.out.printf("Pi = %f and E = %b", Math.PI, Math.E).
Place values where they would appear in the output
Pi = 3.141593 and E = 2.718282
3 2 true false

--------------------------------------------------------------------
Given the code. What is the result?
public class SomeClass {
    private int value = 1;
   
    public int getValue() {
        return value;
    }
   
    public void changeVal(int value) {
        value = value;
    }

    public static void main(String args[]) {
        int a = 2;
        SomeClass c = new SomeClass();
        c.changeVal(a);
        System.out.print(c.getValue());
    }
}
 A) "1" is printed // correct answer
 B) "2" is printed
 C) Compilation fails
 D) An exception is thrown at runtime
 -------------------------------------------------------------------
Which of the following lines will print false?

1.public class MyClass
2.{
3.     static String s1 = "I am unique!";
4.     public static void main(String[] args)
5.     {
6.          String s2 = "I am unique!";
7.          String s3 = new String(s1);
8.          System.out.println(s1 == s2);
9.          System.out.println(s1.equals(s2));
10.         System.out.println(s3 == s1);
11.         System.out.println(s3.equals(s1));
12.     }
13.}
     a.  Line 8   
     b.  Line 9   
     c.  Line 10// correct answer   
     d.  Line 11   
     e.  None of these   
-------------------------------------------------------------------
What is the result of compiling and running the following code?

public class IntegerTest
{
     public static void main(String[] argv)
     {
          Integer i1 = new Integer("1");
          Integer i2 = new Integer("2");
          Integer i3 = Integer.valueOf("3");
          int i4 = i1 + i2 + i3;
          System.out.println(i4);
     }
}
     a.  Compiler error: Integer class has no constructors which take a String argument   
     b.  Compiler error: Incorrect argument passed to the valueOf method   
     c.  Compiler error: Integer objects cannot work with + operator   
     d.  Prints 6    // CORRECT ANSWER
     e.  Prints 123

EJB Excercise - 1

What exception is thrown for EJB client when you attempt to invoke a method on an object that no longer exists?
Choice 1
    NoSuchEJBException
Choice 2
    FinderException
Choice 3
    EJBException
Choice 4
    ObjectNotFoundException   // answer
Choice 5
    AccessLocalException


During the lifecycle of a Message-driven bean, the container invokes which lifecycle callbacks?
Choice 1

    PrePassivate and PreDestroy
Choice 2
    PostConstruct and PreDestroy
Choice 3
    PostConstruct and PostActivate
Choice 4
    PrePassivate and PostActivate
Choice 5
    PrePassivate and PostConstruct



Which annotation do you use to specify the security roles permitted to access your application, EJB module, EJB, or business methods?
Choice 1
    @DeclareRoles
Choice 2
    @PermitRoles
Choice 3
    @MethodPermissions
Choice 4
    @RolesPermissions
Choice 5
    @RolesAllowed // answer


You have an enterprise application that needs to display a large list of categories in order to let a user select from that list. The average size of the list is 100.
Question     Based on the scenario above, which enterprise bean incurs the least amount of resource overhead?

Choice 1
    Message driven bean
Choice 2
    Stateless session bean
Choice 3
    Standard Java bean
Choice 4
    Entity bean // answer
Choice 5
    Stateful session bean


You implement javax.ejb.SessionSynchronization in:
Choice 1
    stateless session beans with bean-managed transactions.
Choice 2
    message driven beans.
Choice 3
    stateful session beans with container-managed transactions.
Choice 4
    stateless session beans with container-managed transactions.
Choice 5
    entities.


Which method is first called by the EJB container on a stateless session bean?
Choice 1
    postConstruct()
Choice 2
    setSessionContext()
Choice 3
    newInstance()
Choice 4
    initialize()
Choice 5
    create()  // answer



What can you inject by defining the dependency injection through the annotation @Resource?

Choice 1
    Entity beans
Choice 2
    Session beans
Choice 3
    PersistenceContext
Choice 4
    EJB Reference
Choice 5
    DataSource // answer

To facilitate test driven development, the EJB 3.0 specification allows you to use annotations to inject dependencies through annotations on fields or setter methods. Instead of complicated XML ejb-refs or resource refs, you can use the @EJB and @Resource annotations to set the value of a field or to call a setter method within your session bean with anything registered within JNDI. You can use the @EJB annotation to inject EJB references and @Resource to access datasources.