J2EE Interview Questions

1) What is J2EE?
J2EE is an environment for developing and deploying enterprise applications. The J2EE platform consists of a set of services, application programming interfaces (APIs), and protocols that provide the functionality for developing multi tiered, and web-based applications.

2) What is the J2EE module?
A J2EE module consists of one or more J2EE components for the same container type and one component deployment descriptor of that type.

3) What are the components of J2EE application?
A J2EE component is a self-contained functional software unit that is assembled into a J2EE application with its related classes and files and communicates with other components. The J2EE specification defines the following J2EE components:

  • Application clients and applets are client components.
  • Java Servlets and Java Server PagesTM (JSPTM) technology components are web components.
  • Enterprise JavaBeansTM (EJBTM) components (enterprise beans) are business components.
  • Resource adapter components provided by EIS and tool vendors.

4) What are the four types of J2EE modules?

  1. Application client module
  2. Web module
  3. Enterprise JavaBeans module
  4. Resource adapter module

5) What does application client module contain?
The application client module contains: class files, an application client deployment descriptor. Application client modules are packaged as JAR files with a .jar extension.

6) What does Enterprise JavaBeans module contain?
The Enterprise JavaBeans module contains: class files for enterprise beans, An EJB deployment descriptor. EJB modules are packaged as JAR files with a .jar extension.

7) What does resource adapt module contain?
The resource adapt module contains: all Java interfaces, classes, native libraries, other documentation,  a resource adapter deployment descriptor. Resource adapter modules are packages as JAR files with a .rar (Resource adapter Archive) extension.

9) What is difference between J2EE 1.3 and J2EE 1.4?

J2EE 1.4 is an enhancement version of J2EE 1.3. It is the most complete Web services platform ever. J2EE 1.4 includes:

  • Java API for XML-Based RPC (JAX-RPC 1.1)
  • SOAP with Attachments API for Java (SAAJ)
  • Web Services for J2EE(JSR 921)
  • J2EE Management Model(1.0)
  • J2EE Deployment API(1.1)
  • Java Management Extensions (JMX)
  • Java Authorization Contract for Containers(JavaACC)
  • Java API for XML Registries (JAXR)
  • Servlet 2.4
  • JSP 2.0
  • EJB 2.1
  • JMS 1.1
  • J2EE Connector 1.5

The J2EE 1.4 features complete Web services support through the new JAX-RPC 1.1 API, which supports service endpoints based on Servlets and enterprise beans. JAX-RPC 1.1 provides interoperability with Web services based on the WSDL and SOAP protocols. The J2EE 1.4 platform also supports the Web Services for J2EE specification (JSR 921), which defines deployment requirements for Web services and utilizes the JAX-RPC programming model. In addition to numerous Web services APIs, J2EE 1.4 platform also features support for the WS-I Basic Profile 1.0. This means that in addition to platform independence and complete Web services support, J2EE 1.4 offers platform Web services interoperability. The J2EE 1.4 platform also introduces the J2EE Management 1.0 API, which defines the information model for J2EE management, including the standard Management EJB (MEJB). The J2EE Management 1.0 API uses the Java Management Extensions API (JMX). The J2EE 1.4 platform also introduces the J2EE Deployment 1.1 API, which provides a standard API for deployment of J2EE applications. The J2EE 1.4 platform includes security enhancements via the introduction of the Java Authorization Contract for Containers (JavaACC). The JavaACC API improves security by standardizing how authentication mechanisms are integrated into J2EE containers. The J2EE platform now makes it easier to develop web front ends with enhancements to Java Servlet and JavaServer Pages (JSP) technologies. Servlets now support request listeners and enhanced filters. JSP technology has simplified the page and extension development models with the introduction of a simple expression language, tag files, and a simpler tag extension API, among other features. This makes it easier than ever for developers to build JSP-enabled pages, especially those who are familiar with scripting languages. Other enhancements to the J2EE platform include the J2EE Connector Architecture, which provides incoming resource adapter and Java Message Service (JMS) plug ability. New features in Enterprise JavaBeans (EJB) technology include Web service endpoints, a timer service, and enhancements to EJB QL and message-driven beans. The J2EE 1.4 platform also includes enhancements to deployment descriptors. They are now defined using XML Schema which can also be used by developers to validate their XML structures.

Note: The above information comes from SUN released notes.

10) Is J2EE application only a web-based?
No. A J2EE application can be web-based or non-web-based. If an application client executes on the client machine, it is a non-web-based J2EE application. The J2EE application can provide a way for users to handle tasks such as J2EE system or application administration. It typically has a graphical user interface created from Swing or AWT APIs, or a command-line interface. When user request, it can open an HTTP connection to establish communication with a Servlet running in the web tier.

Also see : Java Interview Questions and Answers

Java Interview Questions and Answers

1) What is the difference between an Abstract class and Interface?

  • Abstract classes may have some executable methods and methods left unimplemented. Interfaces contain no implementation code.
  • An class can implement any number of interfaces, but subclass at most one abstract class.
  • An abstract class can have nonabstract methods. All methods of an interface are abstract.
  • An abstract class can have instance variables. An interface cannot.
  • An abstract class can define constructor. An interface cannot.
  •  An abstract class can have any visibility: public, protected, private or none (package). An interface’s visibility must be public or none (package).
  • An abstract class inherits from Object and includes methods such as clone() and equals().

2) What are checked and unchecked exceptions?
Java defines two kinds of exceptions :

  • Checked exceptions : Exceptions that inherit from the Exception class are checked exceptions. Client code has to handle the checked exceptions thrown by the API, either in a catch clause or by forwarding it outward with the throws clause. Examples – SQLException, IOxception.
  • Unchecked exceptions : RuntimeException also extends from Exception. However, all of the exceptions that inherit from RuntimeException get special treatment. There is no requirement for the client code to deal with them, and hence they are called unchecked exceptions. Example Unchecked exceptions are NullPointerException, OutOfMemoryError, DivideByZeroException typically, programming errors.

3) What is a user defined exception?
User-defined exceptions may be implemented by

  • defining a class to respond to the exception and
  • embedding a throw statement in the try block where the exception can occur or declaring that the method throws the exception (to another method where it is handled). The developer can define a new exception by deriving it from the Exception class as follows:

The throw statement is used to signal the occurance of the exception within a try block. Often, exceptions are instantiated in the same statement in which they are thrown using the syntax. throw new MyException(“I threw my own exception.”) To handle the exception within the method where it is thrown, a catch statement that handles MyException, must follow the try block. If the developer does not want to handle the exception in the method itself, the method must pass the exception using the syntax: public myMethodName() throws MyException

4) What is the difference between C++ & Java?
Well as Bjarne Stroustrup says “..despite the syntactic similarities, C++ and Java are very different languages. In many ways, Java seems closer to Smalltalk than to C++..”. Here are few I discovered:

  • Java is multithreaded
  • Java has no pointers
  • Java has automatic memory management (garbage collection)
  • Java is platform independent (Stroustrup may differ by saying “Java is a platform”
  • Java has built-in support for comment documentation
  • Java has no operator overloading
  • Java doesn’t provide multiple inheritance
  • There are no destructors in Java

5) What are statements in JAVA ?
Statements are equivalent to sentences in natural languages. A statement forms a complete unit of execution. The following types of expressions can be made into a statement by terminating the expression with a semicolon

  • Assignment expressions
  • Any use of ++ or -• Method calls
  • Object creation expressions These kinds of statements are called expression statements. In addition to these kinds of expression statements, there are two other kinds of statements. A declaration statement declares a variable. A control flow statement regulates the order in which statements get executed. The for loop and the if statement are both examples of control flow statements.

6) What is JAR file?
JavaARchive files are a big glob of Java classes, images, audio, etc., compressed to make one simple, smaller file to ease Applet downloading. Normally when a browser encounters an applet, it goes and downloads all the files, images, audio, used by the Applet separately. This can lead to slower downloads.

7) What is JNI?
JNI is an acronym of Java Native Interface. Using JNI we can call functions which are written in other languages from Java. Following are its advantages and disadvantages. Advantages:

  • You want to use your existing library which was previously written in other language.
  • You want to call Windows API function.
  • For the sake of execution speed.
  • You want to call API function of some server product which is in c or c++ from java client. Disadvantages:
  • You can’t say write once run anywhere.
  • Difficult to debug runtime error in native code.
  • Potential security risk.
  • You can’t call it from Applet.

8) What is serialization?
Quite simply, object serialization provides a program the ability to read or write a whole object to and from a raw byte stream. It allows Java objects and primitives to be encoded into a byte stream suitable for streaming to some type of network or to a file-system, or more generally, to a transmission medium or storage facility. A seralizable object must implement the Serilizable interface. We use ObjectOutputStream to write this object to a stream and ObjectInputStream to read it from the stream.

9) Why there are some null interface in java ? What does it mean ? Give me some null interfaces in JAVA?
Null interfaces act as markers..they just tell the compiler that the objects of this class need to be treated differently..some marker interfaces are : Serializable, Remote, Cloneable

10) Is synchronised a modifier? indentifier?? what is it??
It’s a modifier. Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method’s object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.

11) What is singleton class?where is it used?
Singleton is a design pattern meant to provide one and only one instance of an object. Other objects can get a reference to this instance through a static method (class constructor is kept private). Why do we need one? Sometimes it is necessary, and often sufficient, to create a single instance of a given class. This has advantages in memory management, and for Java, in garbage collection. Moreover, restricting the number of instances may be necessary or desirable for technological or business reasons–for example, we may only want a single instance of a pool of database connections.

12) What is a compilation unit?
The smallest unit of source code that can be compiled, i.e. a .java file.

13) Is string a wrapper class?
String is a class, but not a wrapper class. Wrapper classes like (Integer) exist for each primitive type. They can be used to convert a primitive data value into an object, and viceversa.

14) Why java does not have multiple inheritance?
The Java design team strove to make Java:

  • Simple, object oriented, and familiar
  • Robust and secure
  • Architecture neutral and portable
  • High performance
  • Interpreted, threaded, and dynamic

The reasons for omitting multiple inheritance from the Java language mostly stem from the “simple, object oriented, and familiar” goal. As a simple language, Java’s creators wanted a language that most developers could grasp without extensive training. To that end, they worked to make the language as similar to C++ as possible (familiar) without carrying over C++’s unnecessary complexity (simple). In the designers’ opinion, multiple inheritance causes more problems and confusion than it solves. So they cut multiple inheritance from the language (just as they cut operator overloading). The designers’ extensive C++ experience taught them that multiple inheritance just wasn’t worth the headache.

15) Why java is not a 100% oops?
Many people say this because Java uses primitive types such as int, char, double. But then all the rest are objects. Confusing question..

16) What is a resource bundle?
In its simplest form, a resource bundle is represented by a text file containing keys and a text value for each key.

17) What is transient variable?
Transient variable can’t be serialize. For example if a variable is declared as transient in a Serializable class and the class is written to an ObjectStream, the value of the variable can’t be written to the stream instead when the class is retrieved from the ObjectStream the value of the variable becomes null.

18) What is Collection API?
The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces. Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap. Example of interfaces: Collection, Set, List and Map.

19) Is Iterator a Class or Interface? What is its use?
Iterator is an interface which is used to step through the elements of a Collection.

20) What is similarities/difference between an Abstract class and Interface?
Differences are as follows:

  • Interfaces provide a form of multiple inheritance. A class can extend only one other class.
  • Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc.
  • A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class.
  • Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast. Similarities: • Neither Abstract classes or Interface can be instantiated.

21) What is a transient variable?
A transient variable is a variable that may not be serialized.

22) Which containers use a border Layout as their default layout?
The window, Frame and Dialog classes use a border layout as their default layout.

23) Why do threads block on I/O?
Threads block on i/o (that is enters the waiting state) so that other threads may execute while the i/o Operation is performed.

24) How are Observer and Observable used?
Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.

25) What is synchronization and why is it important?
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object’s value. This often leads to significant errors.

Comparing two locations for accuracy in Android

If you are developing a android application which uses android Location Service and you need to find best estimated location by comparing two locations, where one location is the currently obtained location and other is from the location fix then this post contains answer to your question. The below mentioned code contains a method isBetterLocation which will compare two locations and will return true if current location is more accurate than location fix. You might expect that the most recent location fix is the most accurate. However, because the accuracy of a location fix varies, the most recent fix is not always the best.

isBetterLocation method follows following criteria for choosing location fixes, you vary this criteria depending on the use-cases of the application and field testing.

  • Check if the location retrieved is significantly newer than the previous estimate.
  • Check if the accuracy claimed by the location is better or worse than the previous estimate.
  • Check which provider the new location is from and determine if you trust it more.

Java Programming Question

Q.  Using loops and control statements to draw lines can lead to many interesting designs. Create the
design in the left screen capture of Figure. This design draws lines from the top-left corner, fanning out
the lines until they cover the upper-left half of the panel. One approach is to divide the width and height
into an equal number of steps (we found 15 steps worked well). The first endpoint of a line will always be
in the top-left corner (0, 0). The second endpoint can be found by starting at the bottom-left corner and
moving up one vertical step and right one horizontal step. Draw a line between the two endpoints.
Continue moving up and to the right one step to find each successive end-point. The figure should scale
accordingly as you resize the window.
Java Code:
import javax.swing.JPanel;
import javax.swing.JFrame;
import java.awt.Graphics;
public class q2ans extends JPanel
{
public static void main(String args[])
{
q2ans panel = new q2ans(); //creates a panel
JFrame frameapp = new JFrame(); // create a new frame
frameapp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frameapp.add(panel);
frameapp.setSize(500, 500); //size of frame
frameapp.setVisible(true);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
int x, y;
int total_lines = 15;
int width = getWidth();
int height = getHeight();
int change_ratio_x = width / total_lines;
int change_ratio_y = height / total_lines;
x = width;
y = 0;
for(int i=1; i<=15; i++)
{
g.drawLine(0,0,x,y);
x = width – i*change_ratio_x;
y = i*change_ratio_y;
}
}
}

Remote Procedure Call

Birrell and Nelson (1984) introduced a completely different way of handling communication for Distributed System designing. Initially many distributed systems have been based on explicit message exchange between processes. However it was less transparent. So the new concept introduced that is RPC.

Although the idea of communication in RPC is refreshingly simple.  In a nutshell, what Birrell and Nelson suggested was allowing programs to call procedures located on other machines. When a process on machine A calls’ a procedure on machine B, the calling process on A is suspended, and execution of the called procedure takes place on B. Information can be transported from the caller to the callee in the parameters and can come back in the procedure result. No message passing at all is visible to the programmer. This method is known as Remote Procedure Call, or often just RPC.

While the basic idea sounds simple and elegant, subtle problems exist. To start with, because the calling and called procedures run on different machines, they execute in different address spaces, which causes complications. Parameters and results also have to be passed, which can be complicated, especially if the machines are not identical.

For Example:
Each machine often has its own representation for numbers,characters, and other data items. For example, IRM mainframes use the EBCDIC character code, whereas IBM personal computers use ASCII. As a consequence, it is not possible to pass a character parameter from an IBM PC client to an IBM mainframe server using the simple scheme because the server will interpret the character incorrectly. Similar problems can occur with the representation of integers (one’s complement versus two’s complement) and floating-point numbers. In addition, an even more annoying problem exists because some machines, such as the Intel Pentium, number their bytes from right to left, whereas others, such as the Sun SPARC, number them the other way. The Intel format is called little endian and the
SPARC format is called big endian. As an example, consider a procedure with two parameters, an integer and a four-character string. Each parameter requires one 32-bit word.What I mean that the parameter portion of a message built by a client stub on an Intel Pentium might look like, The first word contains the integer parameter, 5 in this case, and the second contains the string “JILL.”

RPC associated problem

So because of such conflicts either or both machines can crash and each of the possible failures causes different problems. This problems possibly can be avoided by making use of IDL (Interface Definition Language).

Creating multithreaded web server in Java

      Web server is a application which runs on server machine and listens request from various clients on specific port and gives some specific response for each request. Web servers and client machines uses sockets for transferring data between each other. In general if we construct simple web server using single execution instance then it will be able to serve only one client at time, so if multiple clients wants connect to the server then other clients may need to wait. To resolve this problem we can construct multithreaded server, which will create and execute a single thread  for each individual request (may be from same client machine or different client machines). Coding this in Java is very easy as compared to other languages.

 

Java Code of a multithreaded web server available here is able to accept requests from other computers (clients) by using their browser to point towards the server host and, in return displays a web pages or images. Following are steps to create multithreaded web server:

1. Create a Socket to listen webrequest on Port 80.
int port =80;
ServerSocket WebSocket = new ServerSocket(port);
2. Accept a TCP request
Socket connectionSocket = WebSocket.accept();
3. Construct an object to process HTTP request.
HttpRequest request = new HttpRequest(connectionSocket);
    
4. Create a thread to process requests.
Thread thread = new Thread(request);
thread.start(); //start thread

Note:   If you are testing this code with Eclipse or Netbeans IDEs then make one .html file, say index.html in root folder of your project and browse http://127.0.0.1/index.html (similary for other .htlm files).

 

 

Java program for connecting postgreSQL server

 
 

Program to check for palindrome string in java

class Palindrome
{
public static void main(String args[])
{
String original, reverse=””;
//reading arguments from command-line.
original = args[0];
//returns lenght of the string
int length = original.length();
for ( int i = length – 1 ; i >= 0 ; i– )
reverse = reverse + original.charAt(i);
//checking match between original string and reverse //string
if (original.equals(reverse))
System.out.println(“Entered string is a palindrome.”);
else
System.out.println(“Entered string is not a palindrome.”);
}
}
Compiling and running program:
>javac Palindrome.java
>java Palindrome JAVA
Output :
Entered string is not a palindrome.

JAVA program to demonstrate Vector Class