Wednesday, April 02, 2008

Sample SCBCD 5.0 Questions

To get all 300 SCBCD 5.0 Questions, click here.

1) Consider the following Stateless Session Bean,


@Stateless
public class MyTestBean implements MyTestLocal
{

public void cleanResources( )
{
}

}

You want to annotate the method cleanResources() with @PreDestroy Annotation using XML Deployment Descriptor. Which of the following will correctly do that? 1.



MyTestBean

cleanResources



2.



MyTestBean

cleanResources



3.




MyTestBean
cleanResources


4. None of the above.

2) A Stateful Session Bean by name 'ResourceAllocatorBean' has a business method by name 'allocate' along with a number of methods. You have developed an interceptor class 'net.javabeat.ejb3.LoggingInterceptor' which you want to apply to the method 'allocate' of the 'ResourceAllocatorBean'. Which of the following is the correct way to achieve that?
1.





ResourceAllocatorBean
net.javabeat.ejb3.LoggingInterceptor
allocate



2.





ResourceAllocatorBean
net.javabeat.ejb3.LoggingInterceptor
allocate



3.





ResourceAllocatorBean
net.javabeat.ejb3.LoggingInterceptor



4. None of the above.

3) Given the following session bean,


@Stateful
public class CounterBean implements CounterRemote
{
// Line 'A'
public int count()
{
// Line 'B'.
userTransaction.begin();
// Do something here
userTransaction.commit();
}
}

Which of the following code snippets can be inserted into the lines marked by identifiers A and B so that the above bean code will compile without any compilation errors? 1.



@Resource
private SessionContext sessionContext; // Line 'A'
Transaction userTransaction = sessionContext.getTransaction(); // Line 'B'

2.



@Resource
private SessionContext sessionContext; // Line 'A'
UserTransaction userTransaction = sessionContext.getUserTransaction(); // Line 'B'

3.



@Resource
private ApplicationTransaction transaction; // Line 'A'
UserTransaction userTransaction = transaction.getUserTransaction(); // Line 'B'

4. None of the above.

4) Which of the following is not a life-cycle method for a Stateful Session Bean?
1. Post Construction
2. Pre Destruction
3. Post Activation
4. Pre Construction
5. Pre Passivation
6. All the Above

5) Imagine that you have a business interface by name 'Template'. Which of the following ways can be used by the Client Application to acquire a reference to the business interface (assuming that this interface is bound in the JNDI Context)?
1.



@Resource
SessionContext context;
รข€¦
Template template = (Template)context.lookup("template");

2.


@EJB
Template template;

3.



Template template = null;
InitialContext context = new InitialContext();
template = (Template)Context.lookup("java:comp/ejb/template");

4. All the above.

6) Which of the following code snippets correctly declares a Message-Driven Bean by name 'TestMessageDrivenBean'?
1.



public class TestMessageDrivenBean implements javax.jms.MessageListener
{
public void onMessage(Message message)
{
// Business logic here.
}
}

2.



public class TestMessageDrivenBean implements javax.ejb.MessageListener
{
public void onMessage(Message message)
{
// Business logic here.
}
}

3.


public class TestMessageDrivenBean implements javax.ejb.MessageListener
{
public void ejbRemove()
{
}


public void setMessageDrivenContext(MessageDrivenContext context)
{
}
}

4. All the above.

7) Imagine that the Application you develop periodically sends some events to some other parts of the Application at some defined intervals. Which of the following enterprise bean(s) can be used in this scenario?
1. Entity Bean
2. Stateful Session Bean
3. Stateless Session Bean
4. Message Driven Bean
5. Timer Bean
6. None of the above.

8) Assume that your Application has created as instance of EntityManager with the following piece of code,
EntityManagerFactory factory = Persistence.createEntityManagerFactory("...");
EntityManager manager = factory.createEntityManager();
Which of the following methods can be used to check whether the handle of the EntityManager instance is valid?
1. EntityManager.isValid()
2. EntityManager.isHandleValid()
3. EntityManager.isOpen()
4. None of the above.

9) Which of the following way is used for creating an extended persistence context?
1.



EntityManager entityManager = ...;
PersistenceContext context = entityManager.createExtendedPersistenceContext();

2.



EntityManagerFactory factoy = Persistence.createEntityManagerFactory();
EntityManager entityManager = factory.createEntityManager();
PersistenceContext context =
entityManager.createPersistenceContext(PersistenceContextType.EXTENDED);

3.



@PersistenceContext(unitName = "...", type=PersistenceContextType.EXTENDED)
private EntityManager entityManager;

4. None of the above.

10) Which of the following criteria is needed to make a plain java class by name 'Employer' as an entity and that can also be transferred and accessible by a remote application?
1.



@Entity
public class Employer
{
}

2.



public class Employer extends javax.persistence.Entity
{
}

3.



@Entity
public class Employer implements Serializable
{
}

4. All the above.
Answers

1) b.
Option b is correct. The element 'lifecycle-callback-method' must be used specifying the name of the method and this element should be included within the element 'pre-destroy'.

2)4) a.
Option a is correct. This option correctly defines the elements for associating an enterprise bean and the interceptor class along with the method that should be intercepted.

3) b.
Option b is correct. The business method 'count' is trying to explicitly start a transaction, then do some business logic and finally commit the transaction. Here, since the transaction is controlled at the Application level, this transaction should be of type 'UserTransaction'. A UserTransaction object can be obtained a reference by calling the method getUserTransaction() on the Session Context object which is already initialized by the Container by applying the Annotation '@Resource'.

4) d.
Option d is correct. The life-cycle method Pre Construction is not valid for a Stateful Session Bean (as well as for any Enterprise Bean).

5) d.
All the options are correct. Options a and b using the dependency injection mechanism for initializing the business interface (from EJB 3.0). Option c uses the older style (EJB 2.1) for acquiring the reference to the business interface.

6) a.
Option a is correct. It is mandatory for a Message-Driven Bean to implement the MessageListener interface thereby overriding the onMessage() method.

7) c and d.
Options c and d are correct. It should be noted that only Stateless Session Beans and Message Driven Beans can make use of the Timer Service provided by the Container.

8) c.
Option c is correct. The method isOpen() will return true if the handle of the EntityManager is valid and it is not closed.

9) c.
Option c is correct. There is no such interface called PersistenceContext defined by the JPA Specification. A Persistence context is a virtual object that comes into existence whenever an EntityManager instance is created.

10) c.
Option c is correct. The class must be annotated with @Entity and must implement the Serializable interface (or the Externalizable interface).

To get all 300 SCBCD 5.0 Questions, click here.

List of Certification Exams Released by Javabeat

350 SCJP 1.5 Mock Exam Questions

400 SCJP 1.6 Mock Exam Questions

300 SCWCD 5.0 Mock Exam Questions

300 SCWCD 1.4 Mock Exam Questions

300 SCBCD 5.0 Mock Exam Questions

SCBCD 5.0 Mock Exam Questions


JavaBeat has released 300 mock exam questions for SCBCD 5.0 exam. The cost of this kit is JUST $12 or 300 INR. You can buy these mock exams here.


Thursday, March 01, 2007

Sun Updates Mobile Java Platform

Sun Microsystems announced the availability of the Mobile Services Architecture (MSA), the next generation Java platform for mobile phones and other handheld devices. MSA is available now for mobile devices and Sun's NetBeans development platform.

Sun developed the MSA along with 13 other companies, including operators, OEMs and software vendors. The MSA is the next step in the evolution of Sun's mobile API set, Java Technology for the Wireless Industry (JTWI).

"What we did with JTWI was make a compilation of a number of specs together to create a standard platform developer could count on being in handsets. MSA is the next generation. It supersedes JTWI with much more features and functionality than what we had," John Muhlner, group manager for Java ME product marketing at Sun (Quote), told internetnews.com at an event to announce the new platform.


The new APIs (define) in MSA allow for the creation of mobile applications and services that use 3D graphics, personal information management, Bluetooth, animation, Web services, location services and payment services.

MSA also adds a Wireless Client optimized to support multiple, concurrent wireless applications, the Device Test Suite 2.0 for testing the quality and compliance of APIs to the specs, and the NetBeans Mobility Pack 5.5 for building applications in the NetBeans environment.


Finally, there is the Java Wireless Toolkit 2.5 for Connected Limited Device Configuration (CLDC), a collection of tools for building applications and a wireless platform emulator for testing the applications.

Java ME was severely fragmented for the longest time, and MSA will bring it some unity, said Muhlner. "These platform specs take the specific technologies and clarify or define certain options within the spec. It reduces fragmentation and makes for a more consistent application environment."


Jeff Griffin, MSA Expert Group representative for cell phone maker Sony Ericsson, agreed. "MSA is critical for us in the next phase of making Java more usable in mobile phones. The technology continues to grow, new JSRs are added to the mix. This means imp fragmentation. What umbrella JSRs like this are good is setting a baseline and saying everyone needs to start here," he said.

Thursday, January 18, 2007

SCJP 5.0 Mock Exams - Generics


SCJP 5.0 Mock Exams - Generics


  1. what is the result compiling and running the following piece of code?

import java.util.*;

class Test {

public static void main(String [] args) {

Set vals = new TreeSet<String>();

vals.add("one");

vals.add(1);

vals.add("two");

System.out.println(vals);

}

}


Options :

  1. Does not Compile

  2. Compiles with warning and prints output [one, 1, two]

  3. Compiles without warning and prints output [one, 1, two]

  4. Compiles with warning and throws exception at runtime

  5. Compiles without warning and throws exception at runtime


Answer :

D are correct Answers.

Compiles with warning due to un-safe assignment List vals = new ArrayList<String>();

Since TreeSet<String> is used, it will try to sort by natural order. Due to the presence of Integer (vals.add(1);) in the collection, it will throw ClassCastException at runtime(While try to cast Integer in to String).


  1. which of the following piece of code can be inserted to make the following code to compile?

import java.util.*;

class PickThePiece {

public static void main(String [] args) {

//insert the first line here

datas.add("delhi")

datas.add(new Object());

//insert the second line here

}

}

Options :

  1. List<Object> datas = new LinkedList<Object>();

String data = datas.get(0);

  1. List<Object> datas = new LinkedList<Object>();

String data = (String)datas.get(0);

  1. List<String> datas = new LinkedList<String>();

String data = (String)datas.get(0);

  1. List<String> datas = new LinkedList<String>();

String data = datas.get(0);

  1. all the above


Answer :

B,C, and D are the correct answers.

A is wrong because datas.get(0) will return a Object which cannot be directly assigned to a String without casting.


  1. What is the result of compiling and running the following code?

import java.util.*;

class SampleTest {

public static void main(String [] args) {

List samples = new ArrayList();

samples.add("100");

samples.add(200);

samples.add("300");

printData(samples);

}


static void printData(List<String> samples) {

for(String sample : samples) {

System.out.print(sample + “ “);

}

}

}


Options :


  1. Prints 100 200 300

  2. Compile time error

  3. Compiles without warning

  4. Compiles with warning

  5. Runtime Exception


Answer :

D, E are correct answers.

D) It produces warning since un-safe List samples is passed to a type safe collections(as a method argument).

E) Since samples.add(200), adds a Integer in to collection. While iterating through enhanced for loop, Integer is tried to cast to String causes ClassCastException.


  1. Consider the following code, select the valid options given below.

class Fruit {}

class Apple extends Fruit {}

class Orange extends Fruit {}


Options :

  1. List<? extends Fruit> stmt = new ArrayList<Fruit>();

  2. List<? super Apple> stmt = new ArrayList<Fruit>();

  3. List<? extends Fruit> stmt = new ArrayList<Apple>();

  4. List<? super Orange> stmt = new ArrayList<Orange>();

  5. All the above

  6. None of these


Answer :

E is the correct answer. All these options are valid.

Keyword “super “ – allows the type followed by keyword and its super type(parent ).

Keyword “extends” – allows the type followed by keyword and its sub type(child).


  1. What is the output of the following code?

import java.util.*;

class Color {}

class Blue extends Color {}

class Red extends Color {}


class TestColor {

public static void main(String [] args) {

1) List<Color> colors = new ArrayList<Color>();

2) colors.add(new Color());

3) colors.add(new Blue());

4) colors.add(new Red());

5) List<Color> newClr = alterColor(colors);

6) System.out.println(newClr);

}


static void alterColor(List clrs) {

7) clrs.add(new Object());

}

}


Options :

  1. Compile time error due to lines 3 and 4.

  2. Compile time error due to line 5.

  3. Compile time error due to line 7.

  4. Compiles with warning and produces some output.

  5. Compiles without warning and produces some output.

  6. Compiles fine and Exception is thrown at runtime.


Answers :

D is the correct answer.

Warning is due to non-type safe method call. Within the alterColor() method adding a new Object is not a issue because the collection becomes non-type safe.


  1. what is the result of the following code ?

import java.util.*;


class Bird {}

class Duck extends Bird {}

class Hen extends Bird {}


class FuzzyTest {

public static void main(String [] args) {

Map<String, Bird> birds = new HashMap<String, Bird>();

birds.put("bird", new Bird());

birds.put("hen", new Hen());

birds.put("duck", new Duck());

Map bs = addBirds(birds);

for(String b : bs.keySet())

System.out.print(b + " ");

}

static Map addBirds(Map brds) {

brds.put("bird", new Object());

return brds;

}

}


Options :

  1. Compiles and prints output “bird hen duck”.

  2. Compiles and prints output “bird duck hen”.

  3. Compiles and prints some output order cannot be determined.

  4. Run time Exception.

  5. Compilation fails.


Answer :

E is the correct answer.

Since bs is non-typesafe collection, bs.keySet() returns Object. But in enhanced for loop string is used to catch the returned values, that leads to compilation error.


  1. what are the valid statements can be filled in the blank, to make the code to compile and run?

import java.util.*;

interface Eat{}

class Animal implements Eat{}

class Dog extends Animal {}

class Cat extends Animal {}


class AnimalTest {

public static void main(String[] args) {

List<Animal> a = new ArrayList<Animal>();

List<Dog> d = new ArrayList<Dog>();

List<Cat> c = new ArrayList<Cat>();

checkAnimal(a);

checkAnimal(d);

checkAnimal(c);

}

static void checkAnimal( ________________ pets) {

System.out.print(“animals checked here”);

}

}


Options :

  1. List<? extends Animal>

  2. List<? super Animal>

  3. List<? extends Eat>

  4. List<? super Eat>

  5. List<?>

  6. All of the above


Answer :

A , C and E are the correct answers.

Keyword “super “ – allows the type followed by keyword and its super type(parent ).

Keyword “extends” – allows the type followed by keyword and its sub type(child).

Wild card ? – allows everything.


  1. what is the output of the following code?

import java.util.*;

class Example {

public static void main(String [] args) {

Set<String> values = new TreeSet<String>();

values.add(“yet”);

values.add(“get”);

values.add(“bet”);

displayValues(values);

}

static void displayValues(Set<?> values) {

values.add(“wet”)

for(Object v : values) ;

System.out.print(v + “ “);

}

}


Options :

  1. Compiles and gives output “yet get bet wet”.

  2. Compiles and gives output “bet get wet yet”.

  3. Compilation fails

  4. Compiles with warning and Exception thrown at runtime.

  5. Compiles without warning and Exception thrown at runtime.


Answer :

C is the correct answer.

When we use wildcard(?) to catch the collection , then modifications are not allowed in that collection. Here values.add(“wet”) will throw error at compilation time.


  1. Choose the valid ways to create an object for the following class.

class GenTest<T super Number> {

T num;

public T checkNumber(T n) {

return n;

}

}


Options :

  1. Compilation fails.

  2. GenTest<Number> gt = new GenTest<Number>();


  1. GenTest<Integer> gt = new GenTest<Integer>();


  1. GenTest<Object> gt = new GenTest<Object>();


  1. None of the above.



Answer :

A is the correct answer.

Since <T super Number> is an invalid syntax. If super keyword is replaced by extends, then B and C will be the valid answers.


  1. Choose the valid constructors for the following class.

class Generics<T>{}


Options :

  1. public Generics(){}

  2. public Generics<T>(){}

  3. public <T> Generics(T t){}

  4. public <T> Generics(){}

  5. All the above.


Answer :

A,C and D are correct answers.

B is incorrect because of improper syntax.













Servlets Interview Questions

Servlet Interview Questions

1. What is the servlet?
Servlet is a script, which resides and executes on server side, to create dynamic HTML. In servlet programming we will use java language. A servlet can handle multiple requests concurrently

2. What is the architechture of servlet package?
Servlet Interface is the central abstraction. All servlets implements this Servlet 
Interface either direclty or indirectly
( may implement or extend Servlet Interfaces sub classes or sub interfaces)


Servlet
|
Generic Servlet
|
HttpServlet ( Class ) -- we will extend this class to handle GET / PUT HTTP requests
|
MyServlet

3. What is the difference between HttpServlet and GenericServlet?
A GenericServlet has a service() method to handle requests.
HttpServlet extends GenericServlet added new methods
doGet()
doPost()
doHead()
doPut()
doOptions()
doDelete()
doTrace() methods
Both these classes are abstract.

4. What's the difference between servlets and applets?
Servlets executes on Servers. Applets executes on browser. Unlike applets, however, servlets have no graphical user interface.

5. What are the uses of Servlets?
A servlet can handle multiple requests concurrently, and can synchronize requests. Servlets can forward requests to other servers and servlets. Thus servlets can be used to balance load among several servers.

6. When doGET() method will going to execute?
When we specified method='GET' in HTML
Example : < form name='SSS' method='GET'>

7. When doPOST() method will going to execute?
When we specified method='POST' in HTML
< form name='SSS' method='POST' >

8. What is the difference between Difference between doGet() and doPost()?
GET Method : Using get method we can able to pass 2K data from HTML
All data we are passing to Server will be displayed in URL (request string).

POST Method : In this method we does not have any size limitation.
All data passed to server will be hidden, User cannot able to see this info
on the browser.

9. What is the servlet life cycle?
When first request came in for the servlet , Server will invoke init() method of the servlet. There after if any user request the servlet program, Server will directly executes the service() method. When Server want to remove the servlet from pool, then it will execute the destroy() method

Which code line must be set before any of the lines that use the PrintWriter?
setContentType() method must be set.

10. Which protocol will be used by browser and servlet to communicate ?
HTTP




Source : www.javabeat.net











Servlets Interview Questions

Servlet Interview Questions


11. In how many ways we can track the sessions?
Method 1) By URL rewriting

Method 2) Using Session object

Getting Session form HttpServletRequest object
HttpSession session = request.getSession(true);

Get a Value from the session
session.getValue(session.getId());

Adding values to session
cart = new Cart();
session.putValue(session.getId(), cart);


At the end of the session, we can inactivate the session by using the following command
session.invalidate();

Method 3) Using cookies

Method 4) Using hidden fields


12. How Can You invoke other web resources (or other servelt / jsp ) ?
Servelt can invoke other Web resources in two ways: indirect and direct.

Indirect Way : Servlet will return the resultant HTML to the browser which will point to another Servlet (Web resource)

Direct Way : We can call another Web resource (Servelt / Jsp) from Servelt program itself, by using RequestDispatcher object.

You can get this object using getRequestDispatcher("URL") method. You can get this object from either a request or a Context.

Example :
RequestDispatcher dispatcher = request.getRequestDispatcher("/jspsample.jsp");
if (dispatcher != null)
dispatcher.forward(request, response);
}

13. How Can you include other Resources in the Response?
Using include method of a RequestDispatcher object.

Included WebComponent (Servlet / Jsp) cannot set headers or call any method (for example, setCookie) that affects the headers of the response.

Example : RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/banner");
&nbspif (dispatcher != null)
&nbspdispatcher.include(request, response);
}

14. What is the difference between the getRequestDispatcher(String path) ServletRequest interface and ServletContext interface?
The getRequestDispatcher(String path) method of ServletRequest interface accepts parameter the path to the resource to be included or forwarded to, which can be relative to the request of the calling servlet. If the path begins with a "/" it is interpreted as relative to the current context root.

The getRequestDispatcher(String path) method of ServletContext interface cannot accepts relative paths. All path must sart with a "/" and are interpreted as relative to curent context root. If the resource is not available, or if the server has not implemented a RequestDispatcher object for that type of resource, getRequestDispatcher will return null. Your servlet should be prepared to deal with this condition.

15. What is the use of ServletContext ?
Using ServletContext, We can access data from its environment. Servlet context is common to all Servlets so all Servlets share the information through ServeltContext.

16. Is there any way to generate PDF'S dynamically in servlets?
We need to use iText. A open source library for java. Please refer sourceforge site for sample servlet examples.

17. What is the difference between using getSession(true) and getSession(false) methods?
getSession(true) - This method will check whether already a session is existing for the user. If a session is existing, it will return that session object, Otherwise it will create new session object and return taht object.

getSession(false) - This method will check existence of session. If session exists, then it returns the reference of that session object, if not, this methods will return null.

Source : www.javabeat.net