Java Serialization concept | Most asked Serialization Interview Questions and Answers in MNC software company

Java Serialization is very important topic in interview . in every java interview question in MNC software company i face java serialization topic . below list of question you should remember well before going to interview


1) What is the difference between Serializable and Externalizable interface in Java?
This is most frequently asked question in java serialization interview. Here is my version Externalizable provides us writeExternal () and readExternal () method which gives us flexibility to control java serialization mechanism instead of relying on java's default serialization. Correct implementation of Externalizable interface can improve performance of application drastically.

2) How many methods Serializable has? If no method then what is the purpose of Serializable interface?
Serializable interface exists in java.io  package and forms core of java serialization mechanism. It doesn't have any method and also called Marker Interface. When your class implements Serializable interface it becomes Serializable in Java and gives compiler an indication that useJava Serialization mechanism to serialize this object.

3) What is serialVersionUID? What would happen if you don't define this?
SerialVersionUID is an ID which is stamped on object when it get serialized usually hashcode of object, you can use tool serialver to see serialVersionUID of a serialized object . serialVersionUID is used for version control of object. you can specify serialVersionUIDin your class file also.  Consequence of not specifying  serialVersionUID is that when you add or modify any field in class then already serialized class will not be able to recover because serialVersionUID generated for new class and for old serialized object will be different. Java serialization process relies on correct serialVersionUID for recovering state of serialized object and throws java.io.InvalidClassException in case of serialVersionUID mismatch.



4) While serializing you want some of the members not to serialize? How do you achieve it?
this is sometime also asked as what is the use of transient variable, does transient and static variable gets serialized or not etc. so if you don't want any field to be part of object's state then declare it either static or transient based on your need and it will not be included during java serialization process.

5) What will happen if one of the members in the class doesn't implement Serializable interface?
If you try to serialize an object of a class which implements Serializable, but the object includes a reference to an non- Serializable class then a ‘NotSerializableException’ will be thrown at runtime and this is why I always put a SerializableAlert (comment section in my code) to instruct developer to remember this fact while adding a new field in a Serializable class.


6) If a class is Serializable but its super class in not, what will be the state of the instance variables inherited from super class after deserialization?

Java serialization process  only continues in object hierarchy till the class is Serializable i.e. implements Serializable interface in Java And values of the instance variables inherited from super class will be initialized by calling constructor of Non-Serializable Super class during deserialization process . once the constructor chaining will started it wouldn't be possible to stop that , hence even if classes higher in hierarchy implements Serializableinterface , there constructor will be executed.

7) Can you Customize Serialization process or can you override default Serialization process in Java?
The answer is yes you can. We all know that for serializing an object objectOutputStream.writeObject (saveThisobject) is invoked and for reading object ObjectInputStream.readObject () is invoked but there is one more thing which Java Virtual Machine provides you is to define these two method in your class. If you define these two methods in your class then JVM will invoke these two methods instead of applying default serialization mechanism. You can customize behavior of object serialization or deserialization here by doing any kind of pre or post processing task. Important point to note is making these methods private to avoid being inherited, overridden or overloaded. Since onlyJava Virtual Machine can call private method integrity of your class will remain and Java Serialization will work as normal.

8) Suppose super class of a new class implement Serializable interface, how can you avoid new class to being serialized?
If Super Class of a Class already implements Serializable interface in Java then its already serializable in Java, since you can not unimplemented an interface its not really possible to make it Non Serializable class but yes there is a way to avoid serialization of new class. To avoid java serialization you need to implement writeObject () and readObject () method in your Class and need to throw NotSerializableException from those method. This is another benefit of customizing java serialization process as described in above question and normally it asked as follow-up question as interviewprogresses.

9) Which methods are used during Serialization and DeSerialization process in java?
This is quite a common question basically interviewer is trying to know that whether you are familiar with usage of readObject (), writeObject (), readExternal () and writeExternal () or not. Java Serialization is done by java.io.ObjectOutputStream class. That class is a filter stream which is wrapped around a lower-level byte stream to handle the serialization mechanism. To store any object via serialization mechanism we call objectOutputStream.writeObject (saveThisobject) and to deserialize that object we call ObjectInputStream.readObject () method. Call to writeObject () method trigger serialization process in java. one important thing to note about readObject() method is that it is used to read bytes from the persistence and to create object from those bytes and its return an Object which needs to be casted on correct type.

10) Suppose you have a class which you serialized it and stored in persistence and later modified that class to add a new field. What will happen if you deserialize the object already serialized?
It depends on whether class has its own serialVersionUID or not. As we know from above question that if we don't provide serialVersionUID in our code java compiler will generate it and normally it’s equal to hash code of object. by adding any new field there is chance that new serialVersionUID generated for that class version is not the same of already serialized object and in this case Java Serialization API will throw java.io.InvalidClassException and this is the reason its recommended to have your own serialVersionUID in code and make sure to keep it same always for a single class.

11)What are the ways to speed up Object Serialization? How to improve Serialization performance?
The default Java Serialization mechanism is really useful, however it can have a really bad performance based on your application and business requirements. The serialization process performance heavily depends on the number and size of attributes you are going to serialize for an object. Below are some tips you can use for speeding up the marshaling and un-marshaling of objects during Java serialization process.

  •     Mark the unwanted or non Serializable attributes as transient. This is a straight forward benefit since your attributes for serialization are clearly marked and can be easily achieved using Serialzable interface itself.
  •     Save only the state of the object, not the derived attributes. Some times we keep the derived attributes as part of the object however serializing them can be costly. Therefore consider calcualting them during de-serialization process.
  •     Serialize attributes only with NON-default values. For examples, serializing a int variable with value zero is just going to take extra space however, choosing not to serialize it would save you a lot of performance. This approach can avoid some types of attributes taking unwanted space. This will require use of Externalizable interface since attribute serialization is determined at runtime based on the value of each attribute.

12) What are the alternatives to Serialization? If Serialization is not used, is it possible to persist or transfer an object using any other approach?
In case, Serialization is not used, Java objects can be serialized by many ways, some of the popular methods are listed below:

    Saving object state to database, this is most common technique used by most applications. You can use ORM tools (e.g. hibernate) to save the objects in a database and read them from the database.
    Xml based data transfer is another popular mechanism, and a lot of XML based web services use this mechanism to transfer data over network. Also a lot of tools save XML files to persist data/configurations.
    JSON Data Transfer - is recently popular data transfer format. A lot of web services are being developed in JSON due to its small footprint and inherent integration with web browser due to JavaScript format.
    Use Externalizable interface and implement the readObject and writeObject methods to dynamically identify the attributes to be serialized. Some times there can be a custom logic used for serialization of various attributes.


13)What changes are compatible and incompatible to the mechanism of java Serialization?
This is one of a difficult tricky questions and answering this correctly would mean you are an expert in Java Serialization concept. In an already serialized object, the most challenging task is to change the structure of a class when a new field is added or removed. As per the specifications of Java Serialization, addition of any method or field is considered to be a compatible change whereas changing of class hierarchy or non-implementation of Serializable interface is considered to be a non-compatible change. You can go through the Java serialization specification for the extensive list of compatible and non-compatible changes. If a serialized object need to be compatible with an older version, it is necessary that the newer version follows some rules for compatible and incompatible changes. A compatible change to the implementing class is one that can be applied to a new version of the class, which still keeps the object stream compatible with older version of same class. Some Simple Examples of compatible changes are:

  •     Addition of a new field or class will not affect serialization, since any new data in the stream is simply ignored by older versions. the newly added field will be set to its default values when the object of an older version of the class is un marshaled.
  •     The access modifiers change (like private, public, protected or default) is compatible since they are not reflected in the serialized object stream.
  •     Changing a transient field to a non-transient field is compatible change since it is similar to adding a field.
  •     Changing a static field to a non-static field is compatible change since it is also similar to adding a field.

Some Simple Examples of incompatible changes are:

  •     Changing implementation from Serializable to Externalizable interface can not be done since this will result in the creation of an incompatible object stream.
  •     Deleting a existing Serializable fields will cause a problem.
  •     Changing a non-transient field to a transient field is incompatible change since it is similar to deleting a field.
  •     Changing a non-static field to a static field is incompatible change since it is also similar to deleting a field.
  •     Changing the type of a attribute within a class would be incompatible, since this would cause a failure when attempting to read and convert the original field into the new field.
  •     Changing the package of class is incompatible. Since the fully-qualified class name is written as part of the object byte stream.

JSESSIONID concept | what is JSESSIONID working concept in J2EE web application | JSESSIONID interview Question

JSESSIONID is generated by server (which contains servlet container) used for session management for web application because we allready know that HTTP protocal is sataless.

Many applications require a series of requests from a client to be associated with one another.Web-based applications are responsible for maintaining such state, called a session, because the HTTP protocol is stateless. 

Java EE (or Web) developer should know, while browsing on a server, it keeps trace of some data about the browsing session in a server-side HttpSession object. For example an ecommerce web application needs to store somewhere the information about the shopping cart of non registered users.
 How the server can associate the remote session data with the specific navigation session? This is done through a cookie (or via a GET parameter in the URL) that gives to the server the session ID value.

In Java EE applications, the cookie name to identify the sessions is JSESSIONID.



Condition where  JSESSIONID created

JSESSIONID cookie is created/sent when session is created. Session is created when your code calls request.getSession() or request.getSession(true) for the first time. If you just want get session, but not create it if it doesn't exists, use request.getSession(false) -- this will return you a session or null. In this case, new session is not created, and JSESSIONID cookie is not sent. (This also means that session isn't necessarily created on first request... you and your code is in control when the session is created)

Sessions are per-context:


SRV.7.3 Session Scope

HttpSession objects must be scoped at the application (or servlet context) level. The underlying mechanism, such as the cookie used to establish the session, can be the same for different contexts, but the object referenced, including the attributes in that object, must never be shared between contexts by the container.
 
(Servlet 2.4 specification)

Update: Every call to JSP page implicitly creates new session if there is no session yet. This can be turned off by session='false' page directive, in which case session variable is not available on JSP page at all.

JSESSIONID and session management very popular J2EE interview question .Apart from What is JSESSIONID interviewer are also interested in below interview question
How do you avoid using jsessionid?

  • Is it possible to disable jsessionid in tomcat servlet?
  • Under what conditions is a JSESSIONID created?
  • how to refresh JSESSIONID cookie after login?
  • How to monitor HTTP request to check JSESSIONID ?

JMS tutorial | Configuration JMS in Weblogic Application Server

steps to configure a sample JMS server that supports JTA. Suppose a weblogic server or cluster has already been created. Let's call it SampleServer.

  •     Create a Non-XA DataSouce
  •     Create a persistent JDBCStore. Use the non-XA DataSource created above. Don't forget to assign the store a prefix name, say 'Example'. A table ExampleWLStore should be created in the database if the configuration will be successful. Target the JDBCStore to SampleServer.
  •     Create a JMS server. Use the JDBCStore created above. Target it to SampleServer
  •     Create a JMS module. Target it to SampleServer
  •     In the JMS module, create subdeployment. Target the subdeployment to the JMS server.
  •     Create a Queue and a Queue Connection Factory in the JMS module and associate them with the subdeployment. Assign a JNDI name to the queue and the factory. Notice that when creating the queue connection factory, the xa-connection-factory-enabled flag should be set to 'true'.


Notes. It may be necessary to create the queue and the subdeployment and to target it to a JMS server. But you do not have to do this for connection factory. In the webblogic10 sample application medrec, you can see from the admin console that three queues are configured. But there is no connection factory. But JMS won't work without a factory. So where is the factory? The medrec source code reveals the secret. It turns out that weblogic has two predefined factories that can be used. The JmsClientImpl.java in medrec defines the following:

private String connectionFactoryName = "weblogic.jms.XAConnectionFactory";

Then the code uses this name as the JNDI name to look up the connection factory. For more information, look at the weblogic document on it.

Junit tutorial | Best Practices to write JUnit test cases in Java | Junit interview question

Introduction to JUnit Test

Uses
A framework for unit test. Used mainly to test individual classes and methods.

JUnit Library
In maven pom.xml:

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>

The scope is "test". So the junit.jar will not be packaged into the application for deployment.
Configure Maven for Running JUnit
In maven pom.xml:

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<!--<skipTests>true</skipTests>-->
<testFailureIgnore>false</testFailureIgnore>
</configuration>
</plugin>

If skipTests is true, no unit tests will be run.
If testFailureIgnore is true, the tests will be run and the build maven will succeed even if some tests fail.
If testFailureIgnore is false, the tests will be run and build will fail if a test fails.

The test results will go to the directory:
project_base_directory\target\surefire-reports

Traditional JUnit Test
The test class must extend the JUnit class TestCase or its subclasses.

    Use setUp() to initialize resources.
    Use tearDown() to release resources
    Every test method must start with the lowercase "test".

The lifecycle of a TestCase
The lifecycle of a TestCase used by the JUnit framework is as follows:

    Execute setUp().
    Call a test-prefixed method.
    Execute tearDown().
    Repeat these steps for each test method. This will occur even if setUp() or tearDown() throws an exception

Notes:
If setUp() throws an Exception, the test method and tearDown() will not be executed.
If the test method fails and throws an error or exception, tearDown() will still be executed.

Utility Methods from Assert

    assertTrue(String message, boolean condition)
    assertFalse(String message, boolean condition)
    fail(String message)
    assertEquals(String message, Object expected, Object actual)
    assertEquals(String message, String expected, String actual)
    assertEquals(String message, double expected, double actual, double delta)
    assertEquals(String message, int expected, int actual)
    assertSame(String message, Object expected, Object actual)
    assertNotNull(String message, Object object)
    assertNull(String message, Object object)

See the class junit.framework.Assert for more methods.

A Sample Class for Testing

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class Sound {
 private Map<String, String> voicemap = new HashMap<String, String>() {
  {
   put("bee", "buzz");
   put("cow", "moo");
   put("dog", "woof");
   put("cat", "meow");
   put("snake", "hiss");
   put("bird", "chir");
   put("goose", "honk");
  }
 };

 public String speak(String animal) throws Exception {
  if (animal == null) {
   throw new Exception("animial is not specified.");
  }
  String name = animal.toLowerCase();
  Set<String> animals = voicemap.keySet();
  if (!animals.contains(name)) {
   throw new Exception("not implemented yet for this animal.");
  }
  return voicemap.get(name);
 }

 public String yell(String animal) throws Exception {
  String sound = speak(animal);
  return sound.toUpperCase();
 }
}


A Sample JUnit Test Class

import junit.framework.TestCase;

public class SoundTest extends TestCase {

/* This is for demo only. In real life, you won’t need to initialize a simple object such as Sound here. The objects that need to be initialized  in the setUp() method are usually more complex resources such as database connection.
*/
 private Sound sound = null;

 @Override
 protected void setUp() throws Exception {
  super.setUp();
  sound = new Sound(); 
 }

 @Override
 protected void tearDown() throws Exception {
  sound = null;
  super.tearDown();
 }

 public void testSpeak() throws Exception {
  String beeSound = sound.speak("bee");
  assertEquals("buzz", beeSound);
  try {
   String temp = sound.speak("fish");
   fail("Failed for fish. This statemente should not have been executed");
  } catch (Exception e) {
   return; // excepted
  }
 }

 public void testYell() {
  try {
   String gooseYell = sound.yell("goose");
   assertEquals("The sound of goose is not right", "HONK", gooseYell);
  } catch (Exception e) {
   fail("Test failed. This statement should not have been reached.");
  }
 }
}


Run JUnit in Eclipse


Run JUnit Test On CommandLine
JUnit provides the TestRunner classes for running all the tests. The two most popular test runners are a text-based one, junit.textui.TestRunner, and a Swing-based one, junit.swingui.TestRunner

Example:
java junit.textui.TestRunner org.example.SampleTest

TestSuite
JUnit tests can be grouped together by using the TestSuite class.
Example:

import junit.framework.Test;
import junit.framework.TestSuite;

public class GroupTests extends TestSuite {
      static public Test suite() {
            TestSuite suite = new TestSuite();
             suite.addTestSuite(SimpleTest1.class);
             suite.addTestSuite(SimpleTest2.class);
             return suite;
    }
}


When this test is run, both SimpleTest1 and SimpleTest2 will be invoked.

Junit Test Using Annotation in JUnit4

    No need to extend the class TestCase
    No need to use setUp() or tearDown(). Use @Before and @After instead.
    The test method name does not need to start with "test". But you need to put the @Test annotation before each test method.
    Use @Test(expected = YourException.class) to test exception
    Can use @Test(timeout = ?) for performance testing. Here "?" is time in milliseconds.
    Can use @Ignore to ignore a test

Example Using Annotation

import junit.framework.Assert;

import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

public class SoundAnnotationTest {

/** This is for demo only. In real life, you won’t need to initialize a simple object such as Sound here. The objects that need to be initialized  in the @Before method are usually more complex resources such as database connection.
*/
 private Sound sound = null;

 /**
  * The method name does not have to be setUp. You can have multiple such
  * methods with the "Before" annotattion, each of which is run before each
  * test
  */
 @Before
 public void setUp() {
  sound = new Sound();
 }

 /**
  * The method name does not have to be tearDown. You can have multiple such
  * methods with teh "After" annotation, each of which is run after each
  * test.
  */
 @After
 public void tearDown() {
  sound = null;

 }

 @Test
 public void speak() {
  try {
   String beeSound = sound.speak("bee");
   Assert.assertEquals("buzz", beeSound);
  } catch (Exception e) {
   Assert.fail("Test failed.");
  }

  try {
   sound.speak("fish");
   Assert.fail("Failed for fish. This statemente should not have been executed");
  } catch (Exception e) {
   return; // excepted
  }
 }

 @Test
 public void testYell() {
  try {
   String gooseYell = sound.yell("goose");
   Assert.assertEquals("The sound of goose is not right", "HONK",
     gooseYell);
  } catch (Exception e) {
   Assert.fail("Test failed. This statement should not have been reached.");
  }
 }

 @Test(expected = Exception.class)
 // IndexOutOfBoundsException.class
 public void testFish() throws Exception {
  sound.speak("fish");
 }

 @Test(timeout = 700)
 public void testPerformance() throws Exception {
  Thread.currentThread().sleep(600);
 }

 @Ignore
 public void foo() throws Exception {
  for (int i = 0; i < 10; i++) {
   // no-op
  }
 }
}


Use EasyMock in JUnit

    Create Mock object using EasyMock.createMock
    Mock expected results using EasyMock's expect and the andReturn()/andThrow() method
    You can use andReturn to return the value you want.
    You can use andThrow to throw any kind of exception you like.
    Call the EasyMock replay() method.
    Do test and check results.


Example Using EasyMock

(MyServiceEndpointTest)
fooServiceMock = createMock(FooService.class);
barServiceMock = createMock(BarService.class);
endPoint = new MarshallingCommonServiceEndpoint(barServiceMock,
    fooServiceMock);
expect(barServiceMock.getSomeInput(arg1, arg2)).andReturn(Boolean.TRUE);
replay(barServiceMock);
GetBarResponse response = endPoint.getBar(request);
assertTrue("Invalid status", response.isStatus());

IBM DB2 Tutorial : Db2 SQL Replication Steps with example . How to replicate data in db2 step by step

One of the very helpful and important feature in db2 is Replication technique. Replication technique allows you to copy data from one location to another location making the second location data identical to the first location. Data can be copied either in the local or remote machine .Replication is useful1. To consolidate data from multiple sources in a distributed environment
2. to support basic load balancing when your server is running many more read queries (SELECT) than write queries (insert / update / delete) .
3. Makes a backup of data in the local / remote which helps for disaster recovery
4. to reduce delay and bring the data closer to the user.

DB2 Universal Database (UDB), supports two types of replication.
SQL Replication can be done using Control center and Scripting language called ansclp .SQL replication capability is included in the base product. From the Control Center you can access the Replication Center, a graphical interface for the setup of replication. There is also a scripting language for replication called ansclp which allows you to create scripts to automate replication setup.

This tutorial overs that how to setup replication using the the Replication Center . You can access the Replication Center using Control Center -> Tools -> Replication Center.

What happens when we do replication.
Two programs are involved. Capture Program and Apply Program .Capture program capture the data changes in the source table to the CD Table . Changes of data in the source tables are captured in a CD Tables . When we insert new rows in the source table , new rows are captured in the CD Tables with flag "I" . When we update data in the source table , the updated rows are captured in the CD Tables with the flag "U" . SImilarly , When we delete data in the source table , the deleted rows are captured in the CD Tables with the flag "D" . Apply Program , replicate the the data changes captured in the CD table to the target tables.

Major Steps for replication :

1. Create control tables for the Capture program

2. Enable the source database for replication (i.e. to enable logretain on for archival log)

3. Register source tables

4. Create control tables for the Apply program

5. Create a subscription set and member

6. Start the operation to capture and apply

7. Testing the Replication


1. Create control tables for the Capture program
To Create table space and control tables do the following step
1. Right click on the Create Control Servers -> Select Create Capture Control Tables -> Select Custom
2. Select Capture control server (Source database) to create Capture Control Tables
Give user name and password and select Run then OK.

Now Capture control tables are created

2. Enable the source database for replication
Right click on the Source database name (Capture control server ) to enable database for replication . that means to enable archive logging .

Press ok button to set the LOGRETAIN value for the database to RECOVERY and initiate offline backup for the db and take full backup of db


3. Register a replication source

a) Before registering source tables , specify the schema and table name and table space to be used for the CD (Capture Data) tables

Right click on the Capture control server and Source database name and select Manage Source Object Profile

You can specify here
i) table schema and table name to be used as the defaults for the CD tables
ii) table space & its properties for the CD tables and naming convention for table spaces
iii) schema and name for the CD table indexes & naming convention for the the index name.


b) To register source tables
1. Select Capture control servers - > Source database -> capture schemas -> schema name.
2. Right click on the schema name and select Register tables
3. Select Retrive All to retrive all source tables and select the table you want to register. Now CD (Capture Data) table name and table space details appeared automatically based on the settings in the previous steps (i.e. 3 a)

4. Then Ok which will run the query .

4. Create control tables for apply program

To create control tables for apply program , Right click on Apply Control Server -> Create Apply Control Tables -> custom

Select the target database where the data to be replicated . Then Ok.

5. Create Subscription Sets
A subscription set defines a relationship between the source database (ORI_DB in our example) and a target database (DUP_DB in our example). A subscription-set member defines a relationship between the source table (SALES) and one or more target tables (TGSALES).

Here you have to specify , set information , source to target mapping , schedule time to replicate data.

Steps to do :
To create subscription sets , Expand Apply control server -> Right click on the newly created Apply control server ( target data base) -> Subscritption sets
Now you have to fill / select all the details like Apply control server , Set Name , Apply Qualifier , Capture control server and target server (Target database)
Check on the activate the subscription set

Now do the source to target mapping , which maps the source colums to target columns to replicate the data .

Now Set the replication schedule (Time based / event based) , Then Ok.

Now let us Add Members

Right click on the newly created set , select the member information tab and add the member using retrive all option . Use change to do column mapping and etc... Please add the column for index for target table using target table table . Then Ok.

Now the target table is created in the target server where the data to be replicated .

6. Finally Let us start the operation to capture and apply

To start Capture , Expand the operations on SQL replication under Replication center

Right click on the capture control servers and select add and give the capture control server already created (target database) , userid and password which adds capture control servers for operations

Right click on the capture control servers which is added now , then select start capture , then select capture schema , then Ok.
Now give user name and password for the database server to access

Similarly you can stop , resume or suspend capture later.

To start Apply Program
Similarly Expand the apply control servers under operations , Right click on the apply control server -> Apply qualifiers , then refresh .

Now right click on the apply qualifiers already created and the select start Apply , give Host Name or IP Address , then Ok. Now give your target server details by clicking Add New System ..


Similarly you can stop apply , if you need ..


7. Now test the replication ....
Insert any record to the source table

Now the new record is captured in the CD Table (In our example : CDSALES) with the flag (IBMSNAP_OPERATION) with following values

'I' - Insert operation tbe done on the target table.
'U' - Update operation to be done
'D' - Delete Operation to be done

Finally the changes captured in the CD table is applied in the target table by the apply program.



Note : I have created Capture control server and Apply control server on the same system.

Converting InputStream to String | Java IO tutorial InputStream to String Conversion Example | Java interview topic


Read full Article before leave thr blog.  It will really helpfull for Java Interview on IO topic 


 If you like the post please do comments 
 
Converting InputStream to String in Java has become very easy after introduction of Scanner class in Java 5 and due to development of several open source libraries like Apache commons IOUtils and Google Open source guava-libraries which provides excellent support to convert InputStream to String in Java program. we often need to convert InputStream to String  while working in Java for example if you are reading XML files from InputStream and later performing XSLT transformation on it or if InputStream is reading data from text file or text input Source and we either want to log  Strings in log file or want to operate on whole String. Before Java 5 you would have to write lots of boiler plate code to read String line by line or byte by byte depending upon whether you are using either BufferedReader or not but as I said since JDK 5 added Scanner for reading input, its fairly easy to convert InputStream into String.


Before Converting any InputStream or ByteStream into String don't forget to provide character encoding or charSet which tells Java Which characters to expect from those streams of bytes. in the absence of correct character encoding you might alter the output because same bytes can be used to represent different character in different encoding. Another thing to keep in mind is that if you don't provide character encoding, Default character encoding in Java will be used which can be specified from System property "file.encoding" or "UTF-8" if file.encoding is not specified. In this Java tutorial we will see 5 different example of converting InputStream to String in Java both by using standard JDK libraries and using open source libraries.

How to convert InputStream to String in Java – 5 Examples
here are different ways to convert InputStream to String in Java, first we will see most simple way of reading InputStream as String.

InputStream to String -  Using Java 5 Scanner
Convert InputStream to String in Java - 5 Example tutorialjava.util.Scanner has constructor which accept an InputStream, a character encoding and a delimiter to read String from InputStream. Here we have used delimiter as "\A" which is boundary match for beginning of  the input as declared in java.util.regex.Pattern and that's why Scanner is returning whole String form InputStream. I frequently use this technique to read input from user in Java using System.in which is most common example of InputStream in Java, but as demonstrated here this can also be used to read text file in Java.

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

/**
 * Java program example to demonstrate How to convert InputStream into String by using JDK
 * Scanner utility. This program will work Java 5 onwards as Scanner was added in Java 5.
 */       
public class InputStreamTest {

    public static void main(String args[]) throws FileNotFoundException {
        FileInputStream fis = new FileInputStream("c:/sample.txt");
        String inputStreamString = new Scanner(fis,"UTF-8").useDelimiter("\\A").next();
        System.out.println(inputStreamString);
    }
}

Output:
This String is read from InputStream by changing InputStream to String in Java.

If you want to see how an incorrect character encoding completely changes the String just change the character encoding form "UTF-8" to "UTF-16" and you see Chinese(may be) characters instead of English.

Output:
?????????????!???????????!??????^(4)????????

Convert InputStream to String - Plain old JDK4 Example
If you still need to do it on plain old Java on JDK4 without including any additional dependency in your PATH and Classpath than here is quick example using BufferedReader in Java, Remember you can also do this by reading byte by byte from InputStream but that's very slow so consider using BufferedReader for better performance even if you code on JDK4 . For more performance tips see my post 4 JDBC performance tips in Java program. Let’s see example of converting InputStream to String using BufferedReader in Java.

/**
 * Java program to demonstrate How to read InputStream as String
 * using BufferedReader and StringBuilder in Java.
 * This is old and standard way of converting an InputStream into String in Java
 */
public static void main(String args[]) throws FileNotFoundException, UnsupportedEncodingException, IOException {
        FileInputStream fis = new FileInputStream("c:/sample.txt");
        StringBuilder inputStringBuilder = new StringBuilder();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
        String line = bufferedReader.readLine();
        while(line != null){
            inputStringBuilder.append(line);inputStringBuilder.append('\n');
            line = bufferedReader.readLine();
        }
        System.out.println(inputStringBuilder.toString());

}
Output:
This String is read from InputStream by changing InputStream to String in Java.
second line


This is good plain old Java method of converting InputStream to String without adding any extra dependency but remember its converting \r to \n because we are reading line by line, which in most cases fine.

Read InputStream to String - Using Apache IOUtils library
As I said earlire there are many open source library in Java which makes coding lot more easier than any other language. Here is code example for How to convert InputStream to String in Java using Apache IOUtils

/**
 * Example of How to read InputStream into String by using Apache IOUtils library.
 * Nice and clean way of getting InputStream as String in Java
 */

FileInputStream fis = new FileInputStream("c:/sample.txt");
String StringFromInputStream = IOUtils.toString(fis, "UTF-8");
System.out.println(StringFromInputStream);

Isn't it a compact way of converting InputStream to String in Java, just one line of code and that does take care of character encoding as well..

InputStream to String - Using Google's guava-libraries
Google has open source its own set of Java libraries they use for Java development inside Google. it has lots of utility function and also complements Apache commons package. Here is a quick way of converting InputStream to String using Google libraries:

String stringFromStream = CharStreams.toString(new InputStreamReader(fis, "UTF-8"));

Regarding dependency, You need to include guava library i.e. guava-11.0.1.jar in your project classpath. here is full code example:

import com.google.common.io.CharStreams;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

/**
 * How to convert InputStream into String in Java using Google's Guava library
 */
public class InputStreamToString{

    public static void main(String args[]) throws UnsupportedEncodingException, IOException {
        FileInputStream fis = new FileInputStream("c:/sample.txt");
        String stringFromStream = CharStreams.toString(new InputStreamReader(fis, "UTF-8"));
        System.out.println(stringFromStream);
    }   
}

How to read InputStream into String with IOUtils.copy and StringWriter class
java.io.StringWriter is another convenient way of reading writing Strings and by using IOUtils.copy() you can copy contents form InputStream to reader, Here is a complete code example of reading InputStream as String using StringWriter:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import org.apache.commons.io.IOUtils;

/**
  * Java Program to demonstrate reading of InputStream as String
  * using StringWriter and Apache IOUtils
  */
public class InputStreamToStringConversion{

    public static void main(String args[]) throws FileNotFoundException, UnsupportedEncodingException, IOException {
        FileInputStream fis = new FileInputStream("c:/sample.txt");
        StringWriter writer = new StringWriter();
        String encoding = "UTF-8";
        IOUtils.copy(fis, writer, encoding);
        System.out.println(writer.toString());
    }
}

That's all on converting InputStream to String in Java by using standard core java library and by using open source Apache commons IOUtils and Google's guava libraries. Don't forget Character encoding when converting bytes to String which is case here also make a convenient choice as sometime adding additional library for one functionality is not the best option. let us know if you know any other way of converting InputStream to String in Java.

Core concept of Volatile keyword in java multithreading | Java concurrency tutorial

Read full Article before leave thr blog.  It will really helpfull for Java Interview on multithreading topic

First, you have to understand a little something about the Java memory model. I've struggled a bit over the years to explain it briefly and well. As of today, the best way I can think of to describe it is if you imagine it this way:


  •     Each thread in Java takes place in a separate memory space (this is clearly untrue, so bear with me on this one).

  •     You need to use special mechanisms to guarantee that communication happens between these threads, as you would on a message passing system.

  •     Memory writes that happen in one thread can "leak through" and be seen by another thread, but this is by no means guaranteed. Without explicit communication, you can't guarantee which writes get seen by other threads, or even the order in which they get seen.

The Java volatile modifier is an example of a special mechanism to guarantee that communication happens between threads. When one thread writes to a volatile variable, and another thread sees that write, the first thread is telling the second about all of the contents of memory up until it performed the write to that volatile variable.

At this point, I usually rely on a visual aid, which we call the "two cones" diagram, but which my officemate insists on calling the "two trapezoids" diagram, because he is picky. ready is a volatile boolean variable initialized to false, and answer is a non-volatile int variable initialized to 0.




The first thread writes to ready, which is going to be the sender side of the communications. The second thread reads from ready and sees the value the first thread wrote to it. It therefore becomes a receiver. Because this communication occurs, all of the memory contents seen by Thread 1, before it wrote to ready, must be visible to Thread 2, after it reads the value true for ready.

This guarantees that Thread 2 will print "42", if it prints anything at all.

If ready were not volatile, what would happen? Well, there wouldn't be anything explicitly communicating the values known by Thread 1 to Thread 2. As I pointed out before, the value written to the (now non-volatile) ready could "leak through" to Thread 2, so Thread 2 might see ready as true. However, the value for answer might not leak through. If the value for ready does leak through, and the value for answer doesn't leak through, then this execution will print out 0.

We call the communications points "happens-before" relationships, in the language of the Java memory model.

(Minor niggle: The read of ready doesn't just ensure that Thread 2 sees the contents of memory of Thread 1 up until it wrote to ready, it also ensures that Thread 2 sees the contents of memory of any other thread that wrote to ready up until that point.)



With this in mind, let's look at the Double-Checked Locking example again. To refresh your memory, it goes like this:


class Foo {
  private volatile Helper helper = null;
  public Helper getHelper() {
    if (helper == null) {
      synchronized(this) {
        if (helper == null) {
          helper = new Helper();
        }
      }
    }
  return helper;
}

The object of the double-checked locking pattern is to avoid synchronization when reading a lazily constructed singleton that is shared between threads. If you have already constructed the object, the helper field will not be null, so you won't have to perform the synchronization.

However, this is only part of the solution. If one thread creates the object, it has to communicate the contents of its memory to another thread. Otherwise, the object will just sit in the first thread's memory. How do we communicate the contents of memory to another thread? Well, we can use volatile variables. That's why helper has to be volatile -- so that other threads see the fully constructed object.

Locking in Java also forms these "happens-before" communication points. An unlock is the sender side, and a lock on the same variable is the receiver side. The reason that doesn't work for (non-volatile) double-checked locking is that only the writing thread ever performs the locking. The whole point of the idiom is that the reader side doesn't do the locking. Without the explicit communication in the form of the volatile variable, the reading thread will never see the update performed by the writer thread.