Java interview questions for 0 to 2 years experience

1. Introduction

This post covers possible java interview questions with answers. Java and J2EE questions are uniquely designed to help experienced developers. You will find the answer to every question just after it. Enjoy learning!

2. Core Java Interview Questions

Question: After invoking the wait method on an object, obj1, thread T1 will remain in the wait set of obj1 until which of the following occurs?

  1. Another thread invokes the notify method on the object, obj1, and T1 is selected to move out of the wait set
  2. Another thread invokes the notifyAll method on the object
  3. Another thread invokes the resume method on thread T1
  4. Another thread interrupts thread T1
  5. The priority of thread T1 is increased

Answer: 1, 2, 4

Question: Consider the following piece of code and select the correct statements: 

class A {
    protected int method() {
    }
}

class B extends A {
    int method() {
    }
}

Options:

  1. The code fails to compile because you can’t override a method to be more private than its parent
  2. The code fails to compile, because method() is declared as protected, and is therefore not available to any subclass
  3. The code compiles correctly but throws a NullPointerException at runtime
  4. The code fails to compile. However, it can be made to compile correctly by prefixing line 7 with the access qualifier public
  5. The code fails to compile. However, it can be made to compile correctly by prefixing line 7 with the access qualifier protected

Answer: 1, 4, 5

Question: Consider the following piece of code and select all statements which yield a boolean value of true as a result. 

Double d1=new Double(10.0);
Double d2=new Double(10.0);
int x=10;
float f=10.0f;
  1. d1 == d2;
  2. d1 == x;
  3. f == x;
  4. d1.equals(d2);
  5. None of the above.

Answer: 3, 4

Question: What is the result of attempting to compile and run the following program?

class Amber {
    public static void main(String[] args) {
        int[][] a = {{1,2},{0,1,2},{-1,0,2}};
        Object[] obj = (Object[])a.clone();
        for(int i = 0;i < obj.length; i++) {
            int[] ia = (int[])obj[i];
            System.out.print(ia[i]);
        }
    }
}
  1. Compiler error at line 3
  2. Compiler error at line 6
  3. Compiler error at line 7
  4. Runtime error
  5. None of the above

Answer: 5

Question: Which of the following pieces of code compiles without any errors?

  1. StringBuffer sb1 = “abcd”;
  2. Boolean b = new Boolean(“abcd”);
  3. byte b = 255;
  4. int x = 0x1234;
  5. float fl = 1.2;

Answer: 2, 4

Question: What are the possible results of attempting to compile and run the program? 

class A extends Thread {
    public void run() {
        try {sleep(10000);} catch (InterruptedException ie){}
    }
    public static void main(String[] args) {
        A a1 = new A();
        long startTime = System.currentTimeMillis();
        a1.start();
        System.out.print(System.currentTimeMillis() - startTime);
    }
}
  1. Prints a number greater than or equal to 0
  2. The number printed must always be higher than 10000
  3. This program will run for at least ten seconds
  4. Compile time error
  5. Runtime error

Answer: 1, 3

Question: The && operator works with which data types?

  1. int
  2. long
  3. double
  4. boolean
  5. float

Answer: 4

Question: What is the result of attempting to compile and run the following program? 

interface I {String s1 = "I";}

class A implements I {String s1 = "A";}

class B extends A {String s1 = "B";}

class C extends B {
    String s1 = "C";
    void printIt() {
        System.out.print(((A)this).s1 + ((B)this).s1 + ((C)this).s1 + ((I)this).s1);
    }
    public static void main (String[] args) {
        new C().printIt();
    }
}
  1. Prints: ABCI
  2. Runtime Exception
  3. Compiler Error
  4. None of the Above

Answer: 1

Question: What is printed out following the execution of the code below:

class Test{
    static String s;
    public static void main(String []args){
        int x = 4;
        if (x < 4)
         System.out.println("Val = " + x);
        else
         System.out.println(s);
    }
}
  1. The code fails to compile because the String s isn’t declared correctly
  2. The text Val = null is displayed
  3. The string Val = is displayed
  4. The text null is displayed
  5. A blank line of text is printed

Answer: 4

Question: What is the result of attempting to compile and run the program? 

class A {
    static int i;
    public static void main(String args[]) {
        for (i=1; i < 3; i++) {System.out.print(i);} // 1
        for (int i=1; i < 3; i++) {System.out.print(i);} // 2
        int i; // 3
        for (i=0; i < 2; i++) {System.out.print(i);} // 4
        System.out.print(JMM125.i);
    }
}
  1. Prints: 1212010
  2. Prints: 1212013
  3. Compile-time error at line 1
  4. Compile-time error at line 2
  5. Compile-time error at line 4

Answer: 2

Question: The StringBuffer class does not have a concat() method?

  1. true
  2. false

Answer: 1

Question: What is the result of attempting to compile and run the following program? 

class C {
    static int m(int i) {
        System.out.print(i + ", ");
        return i;
    }
    public static void main(String s[]) {
        int i = 1;
        m(m(++i) - m(i++) + m(-i) * m(~i));
    }
}
  1. Prints: 2, 2, -3, -4, 8,
  2. Prints: 2, 2, -3, -4, 12,
  3. Prints: 2, 3, -3, -4, 7,
  4. Prints: 1, 1, 1, 1, 0,
  5. Prints: 2, 2, -2, -2, 4,

Answer: 2

Question: Class C has legal implementations of the equals and hashCode methods. On Monday, an instance of the class is created, and the hashCode method is invoked. On Tuesday the program is loaded again, and an instance of class C is created containing the same data that was loaded on Monday.

If the hashCode method is invoked after restarting the program on Tuesday, then the hashCode method must return the same integer value that was returned on Monday.

  1. false
  2. true

Answer: 1

Question: What is the result of attempting to compile and run the program? 

class A implements Runnable {
    public void run() {System.out.print(Thread.currentThread().getName());}
}

class B implements Runnable {
    public void run() {
        new A().run();
        new Thread(new A(),"T2").run();
        new Thread(new A(),"T3").start();
    }
}

class C {
    public static void main (String[] args) {
        new Thread(new B(),"T1").start();
    }
}
  1. Prints: T1T1T1
  2. Prints: T1T1T2
  3. Prints: T1T2T2
  4. Prints: T1T2T3
  5. Prints: T1T1T3

Answer: 5

Question: What is the result of attempting to compile and run the program? 

public class Q8
{
    int i = 20;
    
    static {
        int i = 10;
    }
    
    public static void main(String[] args)
    {
        Q8 a = new Q8();
        System.out.println(a.i);
    }
}
  1. Compilation error, variable i declared twice
  2. Compilation error, static initializers for initialization purpose only
  3. Prints: 10
  4. Prints: 20

Answer: 4

Question: Which of the three objects, A, B, C are eligible for garbage collection when method m2 begins to execute? 

class I
{
    private String name;
    public I(String s) {name = s;}
    private I other;
    public void other(I i) {other = i;}
}
public class Test3
{
    private I i1 = new I("A");
    private I i2 = new I("B");
    private I i3 = new I("C");
    private void m1()
    {
        i1.other(i2);
        i2.other(i1);
        i3.other(i3);
        i1 = i3;
        i2 = i3;
        m2();
    }
    private void m2() {
        // Do amazing things.
    }

    public static void main(String args[])
    {
        new Test3().m1();
    }
}
  1. A
  2. B
  3. C
  4. None
  5. Compiler error

Answer: 1, 2

Question: Analyse the following two classes and select the correct statements. 

class A{
    private int x = 0;
    static int y = 1;
    protected int q = 2;
}
class B extends A{
    void method(){
        System.out.println(x);
        System.out.println(y);
        System.out.println(q);
    }
}
  1. The code fails to compile because the variable x is not available to class B
  2. The code compiled correctly and displayed: 0 1 2
  3. The code fails to compile because you can’t subclass a class with private variables
  4. Removing the line System.out.println(x) will allow the code to compile correctly
  5. The compiler will complain that the variable x in class B is undefined

Answer:1, 4, 5

Question: Which of these words belong to the set of java keywords?

  1. int
  2. decimal
  3. int64
  4. float

Answer: 1, 4

Question: What is the result of attempting to compile and run the following program? 

class L {
    static String m(float i) {return "float";}
    static String m(double i) {return "double";}
    public static void main (String[] args) {
        int a = 1;
        long b = 2;
        System.out.print(m(a)+", "+ m(b));
    }
}
  1. Prints: float, float
  2. Prints: float, double
  3. Prints: double, float
  4. Prints: double, double
  5. Compiler error

Answer: 1

Question: What is the result of attempting to compile and run the program? 

class P{
    public static void main (String[] args) {
        StringBuffer s1 = new StringBuffer(null);
        System.out.print(s1);
    }
}
  1. Prints nothing
  2. Prints: null
  3. Compiler Error
  4. Runtime Error
  5. None of the Above

Answer: 4

Question: What will happen when you try compiling and running this code? 

public class Ref{
    public static void main(String argv[]){
        Ref r = new Ref();
        r.amethod(r);
    }
    public void amethod(Ref r){
        int i=99;
        multi(r);
        System.out.println(i);
    }
    public void multi(Ref r){
        r.i = r.i*2;
    }
}
  1. Error at compile time
  2. An output of 99
  3. An output of 198
  4. An error at runtime

Answer: 1

Question: What is the result of attempting to compile and run the program? 

import java.util.*;

class F {
    public static void main (String[] args) {
        Object v = new Vector();
        System.out.print((v instanceof Collections)+",");
        System.out.print((v instanceof Arrays)+",");
        System.out.print(v instanceof List);
    }
}
  1. Prints: false,false,false
  2. Prints: false,false,true
  3. Prints: false,true,false
  4. Prints: false,true,true
  5. Prints: true,false,false

Answer: 2

Question : Compile-time errors are generated at which lines? 

class A {
    protected float b; // 1
    strictfp float h; // 2
    private float c; // 3
    static float d; // 4
    synchronized float i; // 5
}
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5

Answer: 2, 5

3. Advanced Java Interview Questions

Question: Which of the following files is the correct name and location of deployment descriptor of a web application. Assume that the web application is rooted at \doc-root. Select the one correct answer.

  1. \doc-root\dd.xml
  2. \doc-root\web.xml
  3. \doc-root\WEB-INF\web.xml
  4. \doc-root\WEB_INF\dd.xml
  5. \doc-root\WEB-INF\lib\dd.xml

Answer: 3

Question: Which of these is true about deployment descriptors. Select the one correct answer:

  1. The order of elements in the deployment descriptor is important, and elements must follow a specific order
  2. The elements of deployment descriptor are case insensitive
  3. The servlet-mapping element, if defined, must be included within the servlet element
  4. The web-app element must include the servlet element

Answer: 1

Question: Which of these is a correct fragment within the web-app element of the deployment descriptor.

1. <exception>
<exception-type> mypackage.MyException</exception-type>
<location> /error.jsp</location>
</exception>

2. <error-page>
<exception-type> mypackage.MyException</exception-type>
<location> /error.jsp</location>
</error-page>

3. <error-page>
<exception> mypackage.MyException </exception-type>
<location> /error.jsp </location>
</error-page>

4. <error-page>
<exception-type> mypackage.MyException</exception-type>
</error-page>

5. <error-page>
<servlet-name> myservlet</servlet-name>
<exception-type> mypackage.MyException</exception-type>
</error-page>

Answer: 2

Question: Which of these is a correct fragment within the web-app element of deployment descriptor.

1. <error-page>
<error-code>404</error-code>
<location>/error.jsp</location>
</error-page>

2. <error-page>
<exception-type>mypackage.MyException</exception-type>
<error-code>404</error-code>
<location>/error.jsp</location>
</error-page>

3. <error-page>
<exception-type>mypackage.MyException</exception-type>
<error-code>404</error-code>
</error-page>

4. <error-page>
<exception-type>mypackage.MyException</exception-type>
<location>/error.jsp</location>
</error-page>

Answer: 1, 4

Question: Which of these is a correct example of specifying a listener element resented by MyClass class. Assume myServlet element is defined correctly. Select the one correct answer.

1. <listener>MyClass</listener>

2. <listener>
<listener-class>MyClass</listener-class>
</listener>

3. <listener>
<listener-name>aListener</listener-name>
<listener-class>MyClass</listener-class>
</listener>

4. <listener>
<servlet-name>myServlet</servlet-name>
<listener-class>MyClass</listener-class>
</listener>

Answer: 2

Question: Which statements are correct about character enconding methods?

  1. ServletRequest has setCharacterEncoding method
  2. ServletRequest has getCharacterEncoding method
  3. ServletResponse has getCharacterEncoding method
  4. ServletResponse has setCharacterEncoding method

Answer: 1, 2, 3

Question: Which are mandatory sub-elements of login-config element?

  1. auth-method
  2. realm-name
  3. form-login-config
  4. login-config doesn’t have mandatory sub-elements

Answer: 4

Question: How is it specified that an application is distributable?

  1. By specifying in the DD: <distributable>yes</distributable>
  2. By specifying in the DD: <distributable></distributable>
  3. It is servlet container specific
  4. An application can’t be distributable

Answer: 2

Question: Which statements are true about distributable web applications?

  1. There will be one instance of ServletContext in each VM
  2. There will be only one instance of the default ServletContext in only one VM (the default ServletContext is one created for all servlets not deployed as part of an application are assigned)
  3. One VM must handle all requests that are part of a session at a time
  4. Container must notify any session attributes implementing the HttpSessionActivationListener interface during migration of a session from one VM to another

Answer: 1, 2, 3, 4

Question: Which of the following are valid return values for doEndTag() method?

  1. Tag.SKIP_TAG
  2. Tag.SKIP_BODY
  3. Tag.SKIP_PAGE
  4. Tag.EVAL_BODY
  5. Tag.EVAL_TAG

Answer: 3

Question: Which of the following is a valid lifecycle event listener interface but is NOT configured in the web.xml?

  1. HttpSessionListener
  2. SessionActivationListener
  3. HttpSessionBindingListener
  4. ContextAttributeListener
  5. SessionAttributeListener

Answer: 3

Question: Which of the following is legal JSP syntax to print the value of i.

  1. <%int i = 1;%> <%= i; %>
  2. <%int i = 1; i; %>
  3. <%int i = 1%> <%= i %>
  4. <%int i = 1;%> <%= i %>
  5. <%int i = 1%> <%= i; %>

Answer: 4

Question: Assume that you need to write a JSP page that adds numbers from one to ten, and then print the output. Which statement when placed at the location XXX can be used to compute the sum. 

<% int sum = 0;
for(j = 0; j < 10; j++) { %>
// XXX --- Add j to sum
<% } %>
// YYY --- Display ths sum

Select the one correct statement

  1. <% sum = sum + j %>
  2. <% sum = sum + j; %>
  3. <%= sum = sum + j %>
  4. <%= sum = sum + j; %>

Answer: 2

Question: Consider the following code: 

public void LoggingServlet extends HttpServlet
{
    public void doPost(HttpServletRequest req, HttpServletResponse res)
    {
        String theMessage = "Log test";
        //1
    }
}

Which of the following LOCs when inserted at //1 will put Log test in the log file?

  1. log(theMessage);
  2. req.log(theMessage);
  3. res.log(theMessage);
  4. this.getServletContext().log(theMessage);
  5. this.servletConfig().log(theMessage);

Answer: 1, 4

Question: A JSP page, test.jsp, contains only one directive: <%@ page isErrorPage=”false” errorPage=”error.jsp”%>
Which implicit variable is not available for test.jsp?

  1. exception
  2. session
  3. application
  4. page
  5. All of these

Answer: 1

Question: A JSP page called test.jsp is passed a parameter name in the URL using http://localhost/test.jsp?name=John. The test.jsp contains the following code: 

<%! String myName=request.getParameter();%>
<% String test= "welcome" + myName; %>
<%= test%>
  1. The program prints Welcome John
  2. The program gives a syntax error because of the statement:
    <%! String myName=request.getParameter();%>
  3. The program gives a syntax error because of the statement:
    <% String test= “welcome” + myName; %>
  4. The program gives a syntax error because of the statement:
    <%= test%>

Answer: 2

Question: Which of the given statements are correct regarding the following JSP page code? 

<jsp:useBean id="mystring" class="java.lang.String" />
<jsp:setProperty name="mystring" property="*" />
<%=mystring%>

Assume that the request for this page contains a parameter mystring=hello.

  1. It will print a blank string
  2. It will print hello
  3. It will not compile
  4. It will throw an exception at runtime

Answer: 1

Question: Which statements are correct about load-on-startup elements?

  1. It must be an integer
  2. It can be negative
  3. If it is 0 (zero), it will be loaded at deployment time
  4. Several servlets can have the same value for this element

Answer: 1, 2, 3, 4

Question: What will be the result of this JSP line if the user takes a look at the page source code? 

<!-- Today is <%= new java.util.Date() %>.Hava a nice day -->
  1.  It won’t compile
  2. The user won’t see the comment
  3. The user will see the same JSP line as above
  4. The user will see the comment with the current date because the expression is evaluated at runtime

Answer: 4

Question: Which of the following statements is correct regarding HttpSessionBindingListener interface?

  1. The valueBound() method is called before the object becomes accessible through HttpSession.getAttribute()
  2. The valueUnbound() method is called before the object is removed from the HttpSession
  3. The valueReplaced() method is called before the object is replaced with another object in the session
  4. None of these

Answer: 1

Question: Which of the following represents a correct syntax for usebean. Select the two correct answers.

  1. <jsp:usebean id=”fruit scope =”page”/>
  2. <jsp:usebean id=”fruit type =”String”/>
  3. <jsp:usebean id=”fruit type =”String” beanName=”Fruit”/>
  4. <jsp:usebean id=”fruit class=”Fruit” beanName=”Fruit”/>

Answer: 2, 3

Question: Identify the implicit objects available to EL expressions.

  1. requestScope
  2. application
  3. header
  4. pageScope
  5. pageContext

Answer: 1, 3, 4, 5

Question: A JSP file that uses a tag library must declare the tag library first. The tag library is defined using the taglib directive – 

<%= taglib uri="..." prefix="..."%>

Which of the following specifies the right purpose of prefix attribute. Select the one correct answer.

  1. The prefix defines the name of the tag that may be used for a tag library
  2. The prefix attribute defines the location of the tag library descriptor file
  3. The prefix attribute should refer to the short name attribute of the tag library file that is defined by the URI attribute of taglib directive
  4. The prefix attribute is used in front of a tagname of a tag defined within the tag library

Answer: 4

Question: A JSP file uses a tag as <myTaglib:myTag>. The myTag element here should be defined in the tag library descriptor file in the taglib element using which element.
Select the one correct answer

  1. tagname
  2. name
  3. tag
  4. prefix

Answer: 2

Question: What are the types returned by the ServletContext method getResource and getResourceAsStream?

  1. ServletContext doesn’t have one of these two methods
  2. String and InputStream
  3. URL and InputStream
  4. URL and StreamReader

Answer: 3

Question: Which of the following statements regarding HttpRequest methods are correct?

  1. getHeaderNames returns an Enumeration
  2. getHeaders returns a String[]
  3. getHeaderValues returns a String[]
  4. getIntParameter returns an int

Answer: 1

Question: Which statements are true about the method log?

  1. log is a method GenericServlet class
  2. log is a method of ServletContext interface
  3. log is an overloaded method
  4. There is a log method with the signature log(String, Exception)

Answer: 1, 2, 3

Question: Of the following four valid comment styles that can be used within JSP pages, which can the end user see?

  1. <%–
    My comments
    <% out.println(“Hello World”); %>
    –%>
    –%>”>
  2. <!– (c)2000 cloudtechpro.com –>
  3. <% // For Loop
    for (int i=1; i<=4; i++) {
    %>
    <H<%=i%>>Hello</H<%=i%>>
    <% } %>
  4. <% /** yet another comment */
    JavaDoc Rules
    %>

Answer: 2

Question: The sendRedirect method defined in the HttpServlet class is equivalent to invoking the setStatus method with the following parameter and a Location header in the URL.

Select the one correct answer.

  1. SC_OK
  2. SC_MOVED_TEMPORARILY
  3. SC_NOT_FOUND
  4. SC_INTERNAL_SERVER_ERROR
  5. ESC_BAD_REQUEST

Answer: 2

Question: Which of the following statements regarding <jsp:useBean> action are correct?

  1. It must have an id attribute
  2. If beanName attribute is present, type must also be present
  3. It must have a scope attribute
  4. If class attribute is present, type must also be present

Answer: 1, 2

Question: Which of the following correctly represents the following JSP statement. <%x=1;%>

  1. <jsp:expression x=1;/>
  2. <jsp:expression>x=1;</jsp:expression>
  3. <jsp:statement>x=1;</jsp:statement>
  4. <jsp:declaration>x=1;</jsp:declaration>
  5. <jsp:scriptlet>x=1;</jsp:scriptlet>

Answer: 5

Question: Given the following jsp line select the correct statements: 

<% public void jspInit() { ...java code...} %>
  1. It is a valid line that can be used to initialize the servlet that implements the jsp file
  2. It won’t compile as no identifier can start with jsp not _jsp
  3. It will serve as the servlet initialization if the function’s name is _jspInit
  4. There is no way to initialize a jsp’s implementation class servlet

Answer: 1

Question: Attribute flush of jsp include action is a mandatory attribute?

  1. yes
  2. no
  3. Only the first time a jsp include action appears in a page

Answer: 2

Question: When a JSP page is compiled, what is it turned into?

  1. Applet
  2. Servlet
  3. Application
  4. Mailet

Answer: 2

Question: Which of the following is not a standard method called as part of the JSP life cycle?

  1. jspInit()
  2. jspService()
  3. _jspService()
  4. jspDestroy()

Answer: 2

Question: Are custom tags available in JSP 1.0? If not, how else might you implement iteration from within a JSP?

  1. Yes, but the only tags available relate to database access
  2. No. To iterate over a collection of values, one must use scriptlet code
  3. No, but there is a standard <iterate> tag that may be used
  4. Yes, but custom tags will not help developers create tags for use in iterating over a collection

Answer: 2

Question: You want to be notified whenever there is a change (non-attribute) in your ServletContext. Which listener interface would you implement?

  1. ServletListener
  2. ServletContextListener
  3. ServletContextAttributeListener
  4. HttpServletContextListener
  5. HttpServletListener

Answer: 2

Question: Which of the following design patterns is normally used to reduce the number of remote calls made by the clients to the server?

  1. Business Delegate
  2. Model View Controller
  3. Facade
  4. Factory
  5. Value Objects

Answer: 5

Question: What gets printed when the following JSP code is invoked in a browser. 

<%= if(Math.random() < 0.5) %>
hello
<%= } else { %>
hi
<%= } %>
  1. The browser will print either hello or hi based on the return value of random
  2. The string hello will always get printed
  3. The string hi will always get printed
  4. The JSP file will not compile

Answer: 4

Question: Given:

Bean A with transaction attributes of NotSupported for all its methods.

Bean B with transaction attributes of Mandatory for all its methods.

A method mA in bean A calls a method mB on Bean B.

Assuming that the method invocation is local, which of the following statements is correct?

  1. mA() will get a javax.transaction.TransactionRequiredException
  2. The bean A instance will be discarded
  3. mA() will get a javax.transaction.TransactionRolledbackException
  4. The container will create a new transaction context for executing mB()
  5. None of the above

Answer: 2

Question: Consider the following code snippet appearing in a client of a session Bean. Assuming that it is a valid code, which of the given statements are correct? 

...
Context ctx = new InitialContext();
BeanHome beanHome = (BeanHome) ctx.lookup("java:comp/env/ejb/beanHome"));
Bean bean = beanHome.create();
  1. BeanHome extends from EJBHome
  2. Bean extends from EJBLocalObject beanHome
  3. getMetaData() will return an object of type EJBMetaData
  4. Any method called on bean will be a remote call

Answer: 2

Question: Which of the following may an enterprise bean developer do using any EJB 2.0 compliant container?

  1. Send and receive emails
  2. Use java.transaction.TransactionManager interface to manage transactions
  3. Parse XML input using DOM parser
  4. JMX

Answer: 3

Question: A client of a session bean with container-managed transaction demarcation gets a javax.transaction.TransactionRolledbackException.

Assuming that the session bean executes within the client’s transaction context and that the transaction was not already rolled back before calling the bean method, which of the following statements are correct?

  1. The client is a remote client
  2. The client is a local client
  3. The bean method encountered a system exception
  4. The bean method encountered an application exception
  5. The application was not assembled properly

Answer: 1, 3

Question: Which of the following methods brings a bean from does not exist to a pooled state?

  1. ejbCreate
  2. ejbLoad
  3. setEntityContext
  4. A call to any ejbHome<method>
  5. A call to any ejbFind<method>

Answer: 3

Question: An entity bean provides getAge and setAge methods that manage a CMP field. Which of the following deployment descriptor elements correctly declare this field?

  1. <cmp-field>
    <field-name>age</field-name>
    <field-type>int</field-type>
    </cmp-field>
  2. <cmp-field>
    <name>age</name>
    </cmp-field>
  3. <cmp-field>
    <cmp-field-name>age</cmp-field-name>
    <cmp-field-type>int</cmp-field-type>
    </cmp-field>
  4. <cmp-field>
    <cmp-field-name>age</cmp-field-name>
    </cmp-field>
  5. <cmp-field>
    <field-name>age</field-name>
    </cmp-field>

Answer: 5

Question: What does the method isCallerInRole do?

  1. It tests whether the caller exists in the roles defined by the beans
  2. It tests whether the caller’s role exists in the application’s security domain
  3. It tests whether the role passed in as a parameter exists in the application’s security domain
  4. It tests whether the caller of the bean belongs to the role that is passed as a parameter to this method

Answer: 4

Question: Which of the following code snippets correctly retrieves the local home interface of an entity bean which is bound to the JNDI name of java:comp/env/ejb/accounts?

  1. Context initialContext = new InitialContext();
    AccountHome accountHome = (AccountHome) initialContext.lookup(“java:comp/env/ejb/accounts”);
  2. Context initialContext = new InitialContext();
    AccountHome accountHome = (AccountHome) initialContext.lookup(“java:comp/env/ejb/accounts”, AccountHome.class);
  3. Context initialContext = new InitialContext(“java:comp”);
    AccountHome accountHome = (AccountHome) initialContext.lookup(“/env/ejb/accounts”, AccountHome.class);
  4. Context initialContext = new InitialContext();
    AccountHome accountHome = (AccountHome) initialContext.lookup(AccountHome.class, “java:comp/env/ejb/accounts”);

Answer: 1

Question: Which of the following should be performed in the ejbActivate method of a session bean?

  1. Restore transient fields using the information in non-transient fields
  2. Reacquire resources that were released in the ejbPassivate method
  3. Increase the heap size of the JVM if the bean is data-heavy
  4. Set all non-serializable fields to null
  5. Set all resource manager factory references to null

Answer: 1, 2

Question: Consider the following code written by a developer for a component interface of an entity bean. Identify the correct statements regarding this code. 

import javax.ejb.*;
import java.rmi.*;

public interface Example extends ***Object //EJBObject or EJBLocalObject
{
    public double compute(double price, double tax) throws InvalidPriceException;

    public int getBalance();

}
  1. It may extend EJBObject
  2. It is not valid because it does not define the remove() method
  3. Client may call remove() on a reference to this interface
  4. Client may call remove(Object primaryKey) on a reference to this interface
  5. None of these is correct

Answer: 3

Question: Which of the following nonbusiness exceptions might be thrown to a client that calls a business method on an entity bean’s local component interface?

  1. javax.ejb.EJBException
  2. javax.ejb.TransactionRequiredException
  3. javax.ejb.TransactionRolledbackException
  4. javax.ejb.FinderException
  5. java.rmi.RemoteException

Answer: 1

Question: Consider the following method of a stateless session bean. Which of the given options are correct regarding this method?

public void xxxx()
{
    try{
        InitialContext ctx = new InitialContext();
        QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory) ctx.lookup("java:comp/env/jms/myQueueConnectionFactory");
        ...//other valid code.
    } catch(Exception e) {
        throw new EJBException(e.getMessage());
    }
}
  1. It may be ejbCreate() method
  2. It may be ejbRemove() method
  3. It may be a business method
  4. It may be setSessionContext() method
  5. This code is invalid in any stateless session bean method

Answer: 3

Question: Which of the following is a requirement for an EJB 2.0 compliant container?

  1. Multiuser synchronized access to entity beans
  2. Multiuser simultaneous access to entity beans
  3. Multiuser simultaneous access to stateful session beans
  4. Support for nested transactions

Answer: 1

Question: Which of the following exceptions is considered as an application exception?

  1. javax.ejb.TransactionRequiredLocalException
  2. javax.ejb.TransactionRolledbackLocalException
  3. javax.ejb.DuplicateKeyException
  4. javax.ejb.NoSuchObjectLocalException
  5. None of the above

Answer: 3

Question: Which of the following exceptions are considered as application exceptions?

  1. javax.ejb.CreateException
  2. javax.ejb.RemoveException
  3. javax.ejb.FinderException
  4. javax.ejb.EJBException
  5. java.lang.RuntimeException

Answer: 1, 2, 3

Question: Identify the correct statements about EJBQL.

  1. It can be used for finder methods
  2. It can be used for select methods
  3. It can be used for home business methods
  4. It can be used for creating methods
  5. It can be used for mass update methods

Answer: 1, 2

Question: Which of the following tasks would an application assembler perform?

  1. Configure a resource manager factory
  2. Bind a resource manager connection factory reference used by a bean to actual resource factory
  3. Specify the resource manager connection factory references in the deployment descriptor
  4. None of these

Answer: 4

Question: The remote home interface of an entity bean has the following finder method: 

Hello findByPrimaryKey(Integer id) throws RemoteException, FinderException;

Assuming the existence of the declaration: Integer id = new Integer(10); which of the following client code snippets that use this method is valid?

  1. Object obj = helloHome.findByPrimaryKey(id);
    Hello hello = obj.narrow(Hello.class);
  2. Hello hello = (Hello) helloHome.findByPrimaryKey(id);
  3. Hello hello = PortableRemoteObject.narrow(helloHome.findByPrimaryKey(id));
  4. Hello hello = helloHome.findByPrimaryKey(id);
  5. Hello hello = PortableRemoteObject.narrow(helloHome.findByPrimaryKey(id), Hello.class);

Answer: 2, 4

Question: Which of the following tasks can you do using a reference to EJBHome?

  1. Create and remove a session bean
  2. Create but not remove a session bean
  3. Get a handle on a session bean
  4. None of these

Answer: 1

Question: Which of the following is a valid deployment descriptor snippet?

  1. <run-as>
    <role>admin</role>
    </run-as>
  2. <run-as>
    <security-role>admin</security-role>
    </run-as>
  3. <run-as>
    <role-name>admin</role-name>
    <role-link>administrator</role-link>
    </run-as>
  4. <run-as>
    <role-name>admin</role-name>
    </run-as>

Answer: 4

Question: Which of the method calls shown in the options are valid from within the following methods of a stateful session bean assuming that the bean has remote interfaces?

  1. getEJBHome()
  2. getCallerPrincipal()
  3. getEJBObject()
  4. access to other EJBs
  5. All of these

Answer: 5

Question: Which of the following is a valid deployment descriptor snippet?

  1. <security-identity>
    <use-caller-identity/>
    </security-identity>
  2. <security-identity>use-caller-identity</security-identity>
  3. <security-identity>
    <run-as>
    <use-caller-identity />
    </run-as>
    </security-identity>
  4. <security-identity>
    <run-as>use-caller-identity</run-as>
    </security-identity>
  5. <security-identity>
    <run-as>
    <role-name>admin</role-name>
    </run-as>
    </security-identity>

Answer: 1, 5

Question: An entity bean has moved from pooled state to the ready state. Which methods would have been called on this bean instance?

  1. setEntityContext
  2. ejbActivate
  3. ejbLoad
  4. ejbCreate
  5. A business method

Answer: 2, 4

Question: A bean implements javax.ejb.SessionSysnchronization interface. What can be said about this bean?

  1. It is a stateless session bean
  2. It is a stateful session bean
  3. It uses container-managed transactions
  4. It uses bean-managed transactions
  5. It is an entity bean

Answer: 2, 3

Question: A MDB with container-managed transaction demarcation (CMTD) can call … from within its onMessage() method.

  1. MessageDrivenContext.getUserTransaction()
  2. MessageDrivenContext.setRollbackOnly()
  3. UserTransaction.setRollbackOnly()
  4. MessageDrivenContext.isCallerInRole()
  5. None of the above

Answer: 2

Question: Consider the following code snippet appearing in a client of a session Bean. Assuming that it is a valid code, what does it tell you about the client and the bean? 

...
Context ctx = new InitialContext();
beanHome = (BeanHome) ctx.lookup("java:comp/ejv/ejb/beanHome"), BeanHome.class);
bean = beanHome.create(100);
...
  1. The client could be a local or remote client, and the bean is a stateful session bean
  2. The client is a local client, and the bean could be a stateful or stateless session bean
  3. The client is a local client, and the bean is a stateful session bean
  4. The client is a remote client, and the bean is a stateful session bean
  5. The client is a remote client, and the bean could be a stateful or stateless session bean

Answer: 3

Question: A remote component interface of an entity bean allows a client to…

  1. remove the bean
  2. create a new bean
  3. execute business methods that are not specific to the bean instance
  4. Obtain a handle to the bean’s home interface
  5. None of these

Answer: 1

Question: Which of the following data types can be used to specify the environment entry values for an EJB?

  1. long
  2. java.lang.Boolean
  3. java.lang.Float
  4. float
  5. java.lang.String

Answer: 2, 3, 5

Question: A stateful session EJB needs access to a database. Which of the following tags will be used by the bean provider to specify this requirement?

  1. <resource>
  2. <resource-ref>
  3. <data-resource>
  4. <data-source>
  5. <data-source-ref>

Answer: 2

Question: You are developing a stateless session EJB to calculate sales tax. The rate of sales tax needs to customized by the user (deployer). Which of the following tags will you use to accomplish this?

  1. <resource>
  2. <resource-ref>
  3. <env-entry>
  4. <property>
  5. <config-parameter>

Answer: 3

Question: Your session EJB performs differently depending on what role, admin or employee, is accessing it. Which of the following tags would you use to convey this to the user of your bean (application assembler/deployer)?

  1. <security-role-ref>
  2. <security-role>
  3. <role>
  4. <role-ref>

Answer: 1

Question: Which of the following tasks should be performed by an application assembler?

  1. Link an enterprise bean reference to a target enterprise bean
  2. Make sure that all the resource references used by an EJB are present in the environment
  3. Bind a resource manager connection factory to an actual resource manager factory
  4. Configure the EJB server and EJB container

Answer: 1

Question: A client has successfully called a business method on a stateless session bean. Which of the following statements may be true?

  1. The client’s Principal belongs to a role that has permission to access the method
  2. The client is a trusted client and does not need any permission
  3. The method has been configured as unchecked in the deployment descriptor
  4. The method has been excluded from the security restrictions
  5. The client has been excluded from the security restrictions

Answer: 1,3

Question: Which of the statements are true regarding the following enterprise bean code snippet appearing in a business method? 

...
Context initContext = new InitialContext();

DataSource ds1 = (DataSource)initContext.lookup("java:comp/env/db1");
Connection con1 = ds1.getConnection();
DataSource ds2 = (DataSource)initContext.lookup("java:comp/env/db2");
Connection con2 = ds2.getConnection();

UserTransaction tx = ejbContext.getUserTransaction();
tx.begin();
//use the connection to update database 1.
//use the connection to update database 2.
tx.commit();
con1.close();
con2.close();
...
  1.  This code is invalid in all kinds of EJBs
  2. This code is invalid in Session beans
  3. This code is invalid in Entity beans
  4. This code is invalid in Message driven beans
  5. This code is invalid in Stateful Session beans

Answer: 3

Question: Which of the following statements are true for a stateless session bean?

  1. It must not have any create method in its home interface
  2. It must have only one create() method in its home interface, and that method cannot take any argument
  3. It may have multiple create() methods in its home interface, but it must have one no-args create() method also
  4. The bean implementation class must implement javax.ejb.SessionBean
  5. It may implement javax.ejb.SessionSynchronization interface

Answer: 2, 4

Question: Which of the following client code snippets correctly retrieve a stateless session bean’s remote interface reference?

  1. Context initCtx = new InitialContext();
    TaxHome taxHome = (TaxHome) initCtx.lookup(“java:comp/env/ejb/tax”);
    Tax tax = (Tax) taxHome.create();
  2. Context initCtx = new InitialContext();
    TaxHome taxHome = (TaxHome) PortableRemoteObject.narrow(initCtx.lookup(“java:comp/env/ejb/tax”), TaxHome.class);
    Tax tax = (Tax) PortableRemoteObject.narrow(taxHome.create(), Tax.class);
  3. Context initCtx = new InitialContext();
    TaxHome taxHome = (TaxHome) PortableRemoteObject.narrow(initCtx.lookup(“java:comp/env/ejb/tax”, TaxHome.class));
    Tax tax = (Tax) PortableRemoteObject.narrow(taxHome.create(10), Tax.class);
  4. Context initCtx = new InitialContext();
    TaxHome taxHome = PortableRemoteObject.narrow(initCtx.lookup(“java:comp/env/ejb/tax”), TaxHome.class);
    Tax tax = PortableRemoteObject.narrow(taxHome.create(10), Tax.class);
  5. Context initCtx = new InitialContext();
    TaxHome taxHome = (TaxHome) PortableRemoteObject.narrow(initCtx.lookup(“java:comp/env/ejb/tax”), TaxHome.class);
    Tax tax = (Tax) taxHome.create();

Answer: 5

Question: A stateful session bean has acquired some resources that need to be released before the bean is taken out of service. Which of the following methods should be appropriately coded to release such resources?

  1. finalize()
  2. ejbRemove()
  3. remove()
  4. unsetSessionContext()
  5. ejbPassivate()

Answer: 2,5

Question: Consider the following code snippet appearing in a client of an enterprise JavaBean. Assuming that line 11 always prints the sum of all integers passed in the add() calls by this client, what can be said about the client and the bean?

...
Context ctx = new InitialContext();
beanHome = (BeanHome) PortableRemoteObject.narrow(ctx.lookup("beanHome"), BeanHome.class);
bean = beanHome.create();
bean.add(10);
bean.add(20);
bean.add(30);
System.out.println(bean.getTotal()); //prints 60
...
  1. This code is buggy because it assumes that it is the sole user of the bean
  2. This code is buggy because it is reusing the bean remote reference
  3. This is a valid client code and the bean is an entity bean
  4. This is a valid client code and the bean is a stateful session bean
  5. This is a valid client code and the bean is a stateless session bean

Answer: 4

Question: Which of the following is a valid signature for an ejbSelect method occurring in an entity bean?

  1. public Collection ejbSelectAllOrderedProducts(Customer cust) { }
  2. public abstract Collection ejbSelectAllOrderedProducts(Customer cust);
  3. protected Collection ejbSelectAllOrderedProducts(Customer cust) { }
  4. protected abstract Collection ejbSelectAllOrderedProducts(Customer cust);
  5. public abstract Collection ejbSelectAllOrderedProducts(Customer cust) throws FinderException;

Answer: 5

Question: Which of the following methods can be used by an entity bean to retrieve its primary key?

  1. getPrimaryKey() of EntityContext
  2. An entity bean already has its primary key fields as its instance variables
  3. An entity bean is unaware of its primary key because the container maintains it
  4. An entity bean can call the getter methods of its primary key fields to retrieve the primary key
  5. getPrimaryKey() of EntityBean interface

Answer: 1

More questions

Mail me or comment: If you think there are more java interview questions needs to be added. I will try to add them whenever possible.

Leave a Reply

Your email address will not be published. Required fields are marked *