Servlet Simple Example

 

Create the HTML file: index.html


<html>
 <head>
 <title>The servlet example </title>
 </head>
 <body>
  <h1>A simple web application</h1>
  <form method="POST" action="WelcomeServlet">
   <label for="name">Enter your name </label>
   <input type="text" id="name" name="name"/><br><br>
   <input type="submit" value="Submit Form"/>
   <input type="reset" value="Reset Form"/>
  </form>
 </body>
</html>

The welcome Servlet class

package nkpack.servletexample;
 
import java.io.IOException;
import java.io.PrintWriter;
 
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class WelcomeServlet extends HttpServlet {
 
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
 
 
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*
* Get the value of form parameter
*/
String name = request.getParameter("name");
String welcomeMessage = "Welcome "+name;
/*
* Set the content type(MIME Type) of the response.
*/
response.setContentType("text/html");
 
PrintWriter out = response.getWriter();
/*
* Write the HTML to the response
*/
out.println("<html>");
out.println("<head>");
out.println("<title> A very simple servlet example</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>"+welcomeMessage+"</h1>");
out.println("<a href="/servletexample/index.html">"+"Click here to go back to input page "+"</a>");
out.println("</body>");
out.println("</html>");
out.close();
 
}
 
 
public void destroy() {
 
}
} 

The deployment descriptor (web.xml) file.

Copy the following code into web.xml file and save it directly under servlet-example/WEB-INF directory.
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 
 <servlet>
  <servlet-name>WelcomeServlet</servlet-name>
  <servlet-class>nkpack.servletexample.WelcomeServlet</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>WelcomeServlet</servlet-name>
  <url-pattern>/WelcomeServlet</url-pattern>
 </servlet-mapping>
 <welcome-file-list>
  <welcome-file> /index.html </welcome-file>
 </welcome-file-list>
</web-app>
 
Know deploy and run

Thread


Introduction to Threads

Multithreading refers to two or more tasks executing concurrently within a single program. A thread is an independent path of execution within a program. Many threads can run concurrently within a program. Every thread in Java is created and controlled by the java.lang.Thread class. A Java program can have many threads, and these threads can run concurrently, either asynchronously or synchronously.
Multithreading has several advantages over Multiprocessing such as;
  • Threads are lightweight compared to processes
  • Threads share the same address space and therefore can share both data and code
  • Context switching between threads is usually less expensive than between processes
  • Cost of thread intercommunication is relatively low that that of process intercommunication
  • Threads allow different tasks to be performed concurrently.
The following figure shows the methods that are members of the Object and Thread Class.





Thread Creation

There are two ways to create thread in java;
  • Implement the Runnable interface (java.lang.Runnable)
  • By Extending the Thread class (java.lang.Thread)

Implementing the Runnable Interface

The Runnable Interface Signature
public interface Runnable {
void run();
}
One way to create a thread in java is to implement the Runnable Interface and then instantiate an object of the class. We need to override the run() method into our class which is the only method that needs to be implemented. The run() method contains the logic of the thread.
The procedure for creating threads based on the Runnable interface is as follows:
1. A class implements the Runnable interface, providing the run() method that will be executed by the thread. An object of this class is a Runnable object.
2. An object of Thread class is created by passing a Runnable object as argument to the Thread constructor. The Thread object now has a Runnable object that implements the run() method.
3. The start() method is invoked on the Thread object created in the previous step. The start() method returns immediately after a thread has been spawned.
4. The thread ends when the run() method ends, either by normal completion or by throwing an uncaught exception.
Below is a program that illustrates instantiation and running of threads using the runnable interface instead of extending the Thread class. To start the thread you need to invoke the start() method on your object.
class RunnableThread implements Runnable {

 Thread runner;
 public RunnableThread() {
 }
 public RunnableThread(String threadName) {
  runner = new Thread(this, threadName); // (1) Create a new thread.
  System.out.println(runner.getName());
  runner.start(); // (2) Start the thread.
 }
 public void run() {
  //Display info about this particular thread
  System.out.println(Thread.currentThread());
 }
}

public class RunnableExample {

 public static void main(String[] args) {
  Thread thread1 = new Thread(new RunnableThread(), "thread1");
  Thread thread2 = new Thread(new RunnableThread(), "thread2");
  RunnableThread thread3 = new RunnableThread("thread3");
  //Start the threads
  thread1.start();
  thread2.start();
  try {
   //delay for one second
   Thread.currentThread().sleep(1000);
  } catch (InterruptedException e) {
  }
  //Display info about the main thread
  System.out.println(Thread.currentThread());
 }
}
The procedure for creating threads based on extending the Thread is as follows:
1. A class extending the Thread class overrides the run() method from the Thread class to define the code executed by the thread.
2. This subclass may call a Thread constructor explicitly in its constructors to initialize the thread, using the super() call.
3. The start() method inherited from the Thread class is invoked on the object of the class to make the thread eligible for running.
Below is a program that illustrates instantiation and running of threads by extending the Thread class instead of implementing the Runnable interface. To start the thread you need to invoke the start() method on your object.
class XThread extends Thread {

 XThread() {
 }
 XThread(String threadName) {
  super(threadName); // Initialize thread.
  System.out.println(this);
  start();
 }
 public void run() {
  //Display info about this particular thread
  System.out.println(Thread.currentThread().getName());
 }
}

public class ThreadExample {

 public static void main(String[] args) {
  Thread thread1 = new Thread(new XThread(), "thread1");
  Thread thread2 = new Thread(new XThread(), "thread2");
  //     The below 2 threads are assigned default names
  Thread thread3 = new XThread();
  Thread thread4 = new XThread();
  Thread thread5 = new XThread("thread5");
  //Start the threads
  thread1.start();
  thread2.start();
  thread3.start();
  thread4.start();
  try {
 //The sleep() method is invoked on the main thread to cause a one second delay.
   Thread.currentThread().sleep(1000);
  } catch (InterruptedException e) {
  }
  //Display info about the main thread
  System.out.println(Thread.currentThread());
 }
}

Different ways to create an object in Java?


There are four different ways to create objects in java:
A. Using new keyword This is the most common way to create an object in java. Almost 99% of objects are created in this way.
 MyObject object = new MyObject();
B. Using Class.forName() If we know the name of the class & if it has a public default constructor we can create an object in this way.
MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance();
C. Using clone() The clone() can be used to create a copy of an existing object.
MyObject anotherObject = new MyObject();
MyObject object = anotherObject.clone();
D. Using object deserialization Object deserialization is nothing but creating an object from its serialized form.
ObjectInputStream inStream = new ObjectInputStream(anInputStream );
MyObject object = (MyObject) inStream.readObject();

java.io

 

Create a StringWriter object



The default constructor allows us to create a StringWriter with default string buffer size.
  1. import java.io.StringWriter;  
  2.   
  3. /** 
  4.  * StringWriter class examples. 
  5.  */  
  6. public class StringWriterExample {  
  7.     public static void main(String[] args){  
  8.         // Create a stringWriter object.  
  9.         StringWriter writer = new StringWriter();  
  10.     }  
  11. }  
  12. Compare two files using java
    The compareTo method of File class helps us to create a temporary file. This method returns an integer. If the value of the integer is greater than zero, the file will be greater than the argument, if the file is less than zero, the file will be less than the argument and a value of zero means both the files are equal.
    1. import java.io.File;  
    2. /** 
    3.  * File class examples. 
    4.  * 
    5.  */  
    6. public class FileExample  {  
    7.     public static void main(String[] args) {  
    8.         // Create file object representing the source file/directory  
    9.         File file = new File("d:\\temp\\test.txt");  
    10.   
    11.         // Create another file for comparison.  
    12.         File cFile = new File("d:\\temp\\Copy of test.txtt");  
    13.   
    14.         // Compare two files.  
    15.         int value = file.compareTo(cFile);  
    16.   
    17.         System.out.println("File comparison result :  "+value);  
    18.     }  
    19. }  

    Create a temp file using java



    Create a temp file using java
    The createTempFile method of File class helps us to create a temporary file.
    1. import java.io.File;  
    2. import java.io.IOException;  
    3. /** 
    4.  * File class examples. 
    5.  * 
    6.  */  
    7. public class FileExample  {  
    8.     public static void main(String[] args) throws IOException{  
    9.         // Create file object representing the source file/directory  
    10.         File file = new File("d:\\temp");  
    11.   
    12.         // Create the temporary file.  
    13.         File tempFile = File.createTempFile("test"".tmp",file);  
    14.     }  
    15. }  

    Finds out total used space in a partition using java



    Finds out total used space in a partition using java
    In Java we can find the total used space of any drive or partition using getTotalSpace and getFreeSpace methods.
    1. import java.io.File;  
    2. /** 
    3.  * File class examples. 
    4.  * 
    5.  */  
    6. public class FileExample  {  
    7.     public static void main(String[] args){  
    8.         // Create file object representing the source file/directory  
    9.         File file = new File("d:\\temp\\test.txt");  
    10.   
    11.         // Get the total space available in current drive  
    12.         long totalSpace = file.getTotalSpace();  
    13.   
    14.         // Get the total free space available in current partition  
    15.         long freeSpace = file.getFreeSpace();  
    16.   
    17.         // Finds the total used space  
    18.         long value = totalSpace - freeSpace;  
    19.   
    20.         // Convert it to GigaBytes  
    21.         double valueGB = (double) value / 1024 / 1024 / 1024;  
    22.   
    23.         System.out.println("Total used space in the current partition is "+valueGB);  
    24.     }  
    25. }  

    Finds out total usable space available in a partition using java



    Finds out total usable space available in a partition using java
    The getUsableSpace method of File class can be used for getting the total usable space available in a partition or drive using java.
    1. import java.io.File;  
    2. /** 
    3.  * File class examples. 
    4.  * 
    5.  */  
    6. public class FileExample  {  
    7.     public static void main(String[] args){  
    8.         // Create file object representing the source file/directory  
    9.         File file = new File("d:\\temp\\test.txt");  
    10.   
    11.         // Get the total usable space available in current drive  
    12.         long value = file.getUsableSpace();  
    13.   
    14.         // Convert it to GigaBytes  
    15.         double valueGB = (double) value / 1024 / 1024 / 1024;  
    16.   
    17.         System.out.println("Total free space available in the current partition is "+valueGB);  
    18.     }  
    19. }  

    Finds out total free space available in a partition using java



    Finds out total free space available in a partition using java
    The getFreeSpace method of File class can be used for getting the total free space available in a partition or drive using java.
    1. import java.io.File;  
    2. /** 
    3.  * File class examples. 
    4.  * 
    5.  */  
    6. public class FileExample  {  
    7.     public static void main(String[] args){  
    8.         // Create file object representing the source file/directory  
    9.         File file = new File("d:\\temp\\test.txt");  
    10.   
    11.         // Get the total free space available in current drive  
    12.         long value = file.getFreeSpace();  
    13.   
    14.         // Convert it to GigaBytes  
    15.         double valueGB = (double) value / 1024 / 1024 / 1024;  
    16.   
    17.         System.out.println("Total free space available in the current partition is "+valueGB);  
    18.     }  
    19. }  

    Finds out total space available in a partition using java



    Finds out total space available in a partition using java
    The getTotalSpace method of File class can be used for getting the total space available in a partition or drive using java.
    1. import java.io.File;  
    2. /** 
    3.  * File class examples. 
    4.  * 
    5.  */  
    6. public class FileExample  {  
    7.     public static void main(String[] args){  
    8.         // Create file object representing the source file/directory  
    9.         File file = new File("d:\\temp\\test.txt");  
    10.   
    11.         // Get the total space available in current drive  
    12.         long value = file.getTotalSpace();  
    13.   
    14.         // Convert it to GigaBytes  
    15.         double valueGB = (double) value / 1024 / 1024 / 1024;  
    16.   
    17.         System.out.println("Total space available in the current partition is "+valueGB);  
    18.     }  
    19. }  

    Lists all the drives present in Windows using java



    Lists all the drives present in Windows using java
    The listRoots method of File class is used for finding out all the drives available in Windows.
    1. import java.io.File;  
    2. /** 
    3.  * File class examples. 
    4.  * 
    5.  */  
    6. public class FileExample  {  
    7.     public static void main(String[] args){  
    8.         // Get all the drives  
    9.         File drives[] = File.listRoots();  
    10.   
    11.         // Loop through the drive list and display the drives.  
    12.         for (int index = 0; index < drives.length; index++) {  
    13.             System.out.println(drives[index]);  
    14.         }  
    15.     }  
    16. }  
    Note: Since Linux does not have any drives concept, the output of the above program in Linux operating system will be "/"

    Checks whether a file or directory has executable permission or not.



    Checks whether a file or directory has executable permission or not.
    The canExecute method of File class can be used for finding out whether the given file has executable permission or not.
    1. import java.io.File;  
    2. /** 
    3.  * File class examples. 
    4.  * 
    5.  */  
    6. public class FileExample  {  
    7.     public static void main(String[] args){  
    8.         // Create file object representing the source file/directory  
    9.         File file = new File("d:\\temp");  
    10.   
    11.         // Check whether the file has executable permission or not.  
    12.         boolean value = file.canExecute();  
    13.   
    14.         System.out.println("File executable permission status : "+value);  
    15.     }  
    16. }  

    Change file or directory permission only to owner using java



    Change file or directory permission only to owner using java
    The setReadOnly, setWritable,setReadable and setExecutable methods of the file class is used for changing the permissions on a file only to owner of the file or directory.
    1. import java.io.File;  
    2. /** 
    3.  * File class examples. 
    4.  * 
    5.  * The class sets read only, writable, executable and readable permissions 
    6.  * for a file or directory. This permissions will be applied to the owner of 
    7.  * the file or directory only. Not everyone will get the permissions. 
    8.  */  
    9. public class FileExample  {  
    10.     public static void main(String[] args){  
    11.         // Create file object representing the source file/directory  
    12.         File file = new File("d:\\temp\\test.txt");  
    13.   
    14.         // Given below are the different file permissions  
    15.         // operations that can be performed on java.  
    16.   
    17.         // Give executable permission to a file or directory  
    18.         file.setExecutable(truetrue);  
    19.   
    20.         // Set read only property to a file or a directory  
    21.         file.setReadOnly();  
    22.   
    23.         // Give write permission to the file  
    24.         file.setWritable(truetrue);  
    25.   
    26.         // Make the file or directory as readable  
    27.         file.setReadable(truetrue);  
    28.     }  
    29. }  



     

Swing AWT Interview Questions

1 Q What is JFC?
A JFC stands for Java Foundation Classes. The Java Foundation Classes (JFC) are a set of Java class libraries provided as part of Java 2 Platform, Standard Edition (J2SE) to support building graphics user interface (GUI) and graphics functionality for client applications that will run on popular platforms such as Microsoft Windows, Linux, and Mac OSX.
2 Q What is AWT?
A AWT stands for Abstract Window Toolkit. AWT enables programmers to develop Java applications with GUI components, such as windows, and buttons. The Java Virtual Machine (JVM) is responsible for translating the AWT calls into the appropriate calls to the host operating system.
3 Q What are the differences between Swing and AWT?
A AWT is heavy-weight components, but Swing is light-weight components. AWT is OS dependent because it uses native components, But Swing components are OS independent. We can change the look and feel in Swing which is not possible in AWT. Swing takes less memory compared to AWT. For drawing AWT uses screen rendering where Swing uses double buffering.
4 Q What are heavyweight components ?
A A heavyweight component is one that is associated with its own native screen resource (commonly known as a peer).
5 Q What is lightweight component?
A A lightweight component is one that “borrows” the screen resource of an ancestor (which means it has no native resource of its own — so it’s “lighter”).
6 Q What is double buffering ?
A Double buffering is the process of use of two buffers rather than one to temporarily hold data being moved to and from an I/O device. Double buffering increases data transfer speed because one buffer can be filled while the other is being emptied.
7 Q What is an event?
A Changing the state of an object is called an event.
8 Q What is an event handler ?
A An event handler is a part of a computer program created to tell the program how to act in response to a specific event.
9 Q What is a layout manager?
A A layout manager is an object that is used to organize components in a container.
10 Q What is clipping?
A Clipping is the process of confining paint operations to a limited area or shape.
11 Q Which containers use a border Layout as their default layout?
A The window, Frame and Dialog classes use a border layout as their default layout.
12 Q What is the preferred size of a component?
A The preferred size of a component is the minimum component size that will allow the component to display normally.
13 Q What method is used to specify a container’s layout?
A The setLayout() method is used to specify a container’s layout.
14 Q Which containers use a FlowLayout as their default layout?
A The Panel and Applet classes use the FlowLayout as their default layout.

JDBC Interview questions

1. What is JDBC?
JDBC technology is an API (included in both J2SE and J2EE releases) that provides cross-DBMS connectivity to a wide range of SQL databases and access to other tabular data sources, such as spreadsheets or flat files. With a JDBC technology-enabled driver, you can connect all corporate data even in a heterogeneous environment
2. What are stored procedures?
A stored procedure is a set of statements/commands which reside in the database. The stored procedure is precompiled. Each Database has it’s own stored procedure language,
3. What is JDBC Driver ?
The JDBC Driver provides vendor-specific implementations of the abstract classes provided by the JDBC API. This driver is used to connect to the database.
4. What are the steps required to execute a query in JDBC?
First we need to create an instance of a JDBC driver or load JDBC drivers, then we need to register this driver with DriverManager class. Then we can open a connection. By using this connection , we can create a statement object and this object will help us to execute the query.
5. What is DriverManager ?
DriverManager is a class in java.sql package. It is the basic service for managing a set of JDBC drivers.
6. What is a ResultSet ?
A table of data representing a database result set, which is usually generated by executing a statement that queries the database.
A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. The next method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result set.
7. What is Connection?
Connection class represents a connection (session) with a specific database. SQL statements are executed and results are returned within the context of a connection.
A Connection object’s database is able to provide information describing its tables, its supported SQL grammar, its stored procedures, the capabilities of this connection, and so on. This information is obtained with the getMetaData method.
8. What does Class.forName return?
A class as loaded by the classloader.
9. What is Connection pooling?
Connection pooling is a technique used for sharing server resources among requesting clients. Connection pooling increases the performance of Web applications by reusing active database connections instead of creating a new connection with every request. Connection pool manager maintains a pool of open database connections.
10. What are the different JDB drivers available?
There are mainly four type of JDBC drivers available. They are:
Type 1 : JDBC-ODBC Bridge Driver – A JDBC-ODBC bridge provides JDBC API access via one or more ODBC drivers. Note that some ODBC native code and in many cases native database client code must be loaded on each client machine that uses this type of driver. Hence, this kind of driver is generally most appropriate when automatic installation and downloading of a Java technology application is not important. For information on the JDBC-ODBC bridge driver provided by Sun.
Type 2: Native API Partly Java Driver- A native-API partly Java technology-enabled driver converts JDBC calls into calls on the client API for Oracle, Sybase, Informix, DB2, or other DBMS. Note that, like the bridge driver, this style of driver requires that some binary code be loaded on each client machine.
Type 3: Network protocol Driver- A net-protocol fully Java technology-enabled driver translates JDBC API calls into a DBMS-independent net protocol which is then translated to a DBMS protocol by a server. This net server middleware is able to connect all of its Java technology-based clients to many different databases. The specific protocol used depends on the vendor. In general, this is the most flexible JDBC API alternative. It is likely that all vendors of this solution will provide products suitable for Intranet use. In order for these products to also support Internet access they must handle the additional requirements for security, access through firewalls, etc., that the Web imposes. Several vendors are adding JDBC technology-based drivers to their existing database middleware products.
Type 4: JDBC Net pure Java Driver – A native-protocol fully Java technology-enabled driver converts JDBC technology calls into the network protocol used by DBMSs directly. This allows a direct call from the client machine to the DBMS server and is a practical solution for Intranet access. Since many of these protocols are proprietary the database vendors themselves will be the primary source for this style of driver. Several database vendors have these in progress.
11. What is the fastest type of JDBC driver?
Type 4 (JDBC Net pure Java Driver) is the fastest JDBC driver. Type 1 and Type 3 drivers will be slower than Type 2 drivers (the database calls are make at least three translations versus two), and Type 4 drivers are the fastest (only one translation).
12. Is the JDBC-ODBC Bridge multi-threaded?
No. The JDBC-ODBC Bridge does not support multi threading. The JDBC-ODBC Bridge uses synchronized methods to serialize all of the calls that it makes to ODBC. Multi-threaded Java programs may use the Bridge, but they won’t get the advantages of multi-threading.
13. What is cold backup, hot backup, warm backup recovery?
Cold backup means all these files must be backed up at the same time, before the database is restarted. Hot backup (official name is ‘online backup’ ) is a backup taken of each tablespace while the database is running and is being accessed by the users
14. What is the advantage of denormalization?
Data denormalization is reverse procedure, carried out purely for reasons of improving performance. It maybe efficient for a high-throughput system to replicate data for certain data.
15. How do you handle your own transaction ?
Connection Object has a method called setAutocommit ( boolean flag) . For handling our own transaction we can set the parameter to false and begin your transaction . Finally commit the transaction by calling the commit method.

JMS interview question

1. What is JMS?
The Java Message Service (JMS) API is a messaging standard that allows application components based on the Java 2 Platform, Enterprise Edition (J2EE) to create, send, receive, and read messages. It enables distributed communication that is loosely coupled, reliable, and asynchronous
2. What type messaging is provided by JMS
Both synchronous and asynchronous are provided by JMS.
3. What is messaging?
Messaging is a mechanism by which data can be passed from one application to another application.
4. What are the advantages of JMS?
One of the principal advantages of JMS messaging is that it’s asynchronous. Thus not all the pieces need to be up all the time for the application to function as a whole.
5. What is synchronous messaging?
Synchronous messaging involves a client that waits for the server to respond to a message. So if one end is down the entire communication will fail.
6. What is asynchronous messaging?
Asynchronous messaging involves a client that does not wait for a message from the server. An event is used to trigger a message from a server. So even if the client is down , the messaging will complete successfully.
7. What is the difference between queue and topic ?
A topic is typically used for one to many messaging , while queue is used for one-to-one messaging. Topic .e. it supports publish subscribe model of messaging where queue supports Point to Point Messaging.
8. What is Stream Message ?
Stream messages are a group of java primitives. It contains some convenient methods for reading the data. However Stream Message prevents reading a long value as short. This is so because the Stream Message also writes the type information along with the value of the primitive type and enforces a set of strict conversion rules which actually prevents reading of one primitive type as another.
9. What is Map message?
Map message contains name value Pairs. The values can be of type primitives and its wrappers. The name is a string.
10. What is text message?
Text messages contains String messages (since being widely used, a separate messaging Type has been supported) . It is useful for exchanging textual data and complex character data like XML.
11. What is object message ?
Object message contains a group of serializeable java object. So it allows exchange of Java objects between applications. sot both the applications must be Java applications.
12. What is Byte Message ?
Byte Messages contains a Stream of uninterrupted bytes. Byte Message contains an array of primitive bytes in it’s payload. Thus it can be used for transfer of data between two applications in their native format which may not be compatible with other Message types. It is also useful where JMS is used purely as a transport between two systems and the message payload is opaque to the JMS client.
13. What is the difference between Byte Message and Stream Message?
Bytes Message stores data in bytes. Thus the message is one contiguous stream of bytes. While the Stream Message maintains a boundary between the different data types stored because it also stores the type information along with the value of the primitive being stored. Bytes Message allows data to be read using any type. Thus even if your payload contains a long value, you can invoke a method to read a short and it will return you something. It will not give you a semantically correct data but the call will succeed in reading the first two bytes of data. This is strictly prohibited in the Stream Message. It maintains the type information of the data being stored and enforces strict conversion rules on the data being read.
14. What is the Role of the JMS Provider?
The JMS provider handles security of the messages, data conversion and the client triggering. The JMS provider specifies the level of encryption and the security level of the message, the best data type for the non-JMS client.
15. What are the different parts of a JMS message ?
A JMS message contains three parts. a header, an optional properties and an optional body.

Core Java Interview Question

Question: How could Java classes direct program messages to the system console, but error messages, say to a file?
Answer: The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This how the standard output could be re-directed:
Stream st = new Stream(new FileOutputStream("output.txt")); System.setErr(st); System.setOut(st);  
Question: What's the difference between an interface and an abstract class?
Answer: An abstract class may contain code in method bodies, which is not allowed in an interface. With abstract classes, you have to inherit your class from it and Java does not allow multiple inheritance. On the other hand, you can implement multiple interfaces in your class.
Question: Why would you use a synchronized block vs. synchronized method?
Answer: Synchronized blocks place locks for shorter periods than synchronized methods.
Question: Explain the usage of the keyword transient?
Answer: This keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers).

Question: How can you force garbage collection?
Answer: You can't force GC, but could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.

Question: How do you know if an explicit object casting is needed?
Answer: If you assign a superclass object to a variable of a subclass's data type, you need to do explicit casting. For example:
Object a; Customer b; b = (Customer) a;
When you assign a subclass to a variable having a supeclass type, the casting is performed automatically. 
Question: What's the difference between the methods sleep() and wait()
Answer: The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.
Question: Can you write a Java class that could be used both as an applet as well as an application?
Answer: Yes. Add a main() method to the applet.
Question: What's the difference between constructors and other methods?
Answer: Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times.
Question: Can you call one constructor from another if a class has multiple constructors
Answer: Yes. Use this() syntax.
Question: Explain the usage of Java packages.
Answer: This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names. Packages access level also allows you to protect data from being used by the non-authorized classes.
Question: If a class is located in a package, what do you need to change in the OS environment to be able to use it?
Answer: You need to add a directory or a jar file that contains the package directories to the CLASSPATH environment variable. Let's say a class Employee belongs to a package com.xyz.hr; and is located in the file c:\dev\com\xyz\hr\Employee.java. In this case, you'd need to add c:\dev to the variable CLASSPATH. If this class contains the method main(), you could test it from a command prompt window as follows:
c:\>java com.xyz.hr.Employee
Question: What's the difference between J2SDK 1.5 and J2SDK 5.0?
Answer:  There's no difference, Sun Microsystems just re-branded this version.

Question: What would you use to compare two String variables - the operator == or the method equals()?
Answer:  I'd use the method equals() to compare the values of the Strings and the == to check if two variables point at the same instance of a String object.