Thursday, 20 March 2014

Difference Between String , StringBuilder and StringBuffer Classes

String

String is immutable  ( once created can not be changed )object  . The object created as a String is stored in the  Constant String Pool  .
Every immutable object in Java is thread safe ,that implies String is also thread safe . String can not be used by two threads simultaneously.
String  once assigned can not be changed .

String  demo = " hello " ;
// The above object is stored in constant string pool and its value can not be modified.


demo="Bye" ;     //new "Bye" string is created in constant pool and referenced by the demo variable           
 // "hello" string still exists in string constant pool and its value is not overrided but we lost reference to the  "hello"string 

StringBuffer

StringBuffer is mutable means one can change the value of the object . The object created through StringBuffer is stored in the heap .  StringBuffer  has the same methods as the StringBuilder , but each method in StringBuffer is synchronized that is StringBuffer is thread safe .

Due to this it does not allow  two threads to simultaneously access the same method . Each method can be accessed by one thread at a time .

But being thread safe has disadvantages too as the performance of the StringBuffer hits due to thread safe property . Thus  StringBuilder is faster than the StringBuffer when calling the same methods of each class.

StringBuffer value can be changed , it means it can be assigned to the new value . Nowadays its a most common interview question ,the differences between the above classes .
String Buffer can be converted to the string by using
toString() method.

StringBuffer demo1 = new StringBuffer("Hello") ;
// The above object stored in heap and its value can be changed .

demo1=new StringBuffer("Bye");
// Above statement is right as it modifies the value which is allowed in the StringBuffer

StringBuilder

StringBuilder  is same as the StringBuffer , that is it stores the object in heap and it can also be modified . The main difference between the StringBuffer and StringBuilder is that StringBuilder is also not thread safe. 
StringBuilder is fast as it is not thread safe . 


StringBuilder demo2= new StringBuilder("Hello");
// The above object too is stored in the heap and its value can be modified
demo2=new StringBuilder("Bye");
// Above statement is right as it modifies the value which is allowed in the StringBuilder


----------------------------------------------------------------------------------
                                    String                    StringBuffer         StringBuilder
----------------------------------------------------------------------------------                
Storage Area | Constant String Pool           Heap                       Heap
Modifiable     |  No (immutable)            Yes( mutable )          Yes( mutable )
Thread Safe   |           Yes                                  Yes                              No
 Performance |         Fast                                Very slow                    Fast
-----------------------------------------------------------------------------------


For Example
String s = "Let’s test";
s.concat("if the String object is IMMUTABLE");
System.out.println(s);

O/P:
Let's test.

IF u rewrite the program as below
String s = "Let’s test";
s = s.concat("if the String object is IMMUTABLE");
System.out.println(s);
   
O/P:
Let’s testif the String object is IMMUTABLE

By above example we can say that String is immuatble. It will create new objects every time when ever we assign the values. It will not refer to the old object.


To Overcome this we have StringBuilder  and StringBuffer

    StringBuilder s1 = new StringBuilder("Hello");
    s1.append("Hai");
    System.out.println("StringBuilder : "+s1);
    
    StringBuffer s2 = new StringBuffer("testing");
    s2.append("Hai");
    System.out.println("StringBuffer : "+s2);

O/P:
StringBuilder : HelloHai

StringBuffer : testingHai


Print Friendly and PDF

Wednesday, 19 March 2014

Difference between Hashtable and Collections.synchronizedMap(HashMap)

DifferenceS :

1.The HashMap class is roughly equivalent to Hashtable, except that it is non synchronized and permits 
    nulls. (HashMap allows null values as key and value whereas Hashtable doesn't allow nulls).

2.One of the major differences between HashMap and Hashtable is that HashMap is non 
   synchronized whereas Hashtable is synchronized.
   Which means Hashtable is thread-safe and can be shared between multiple threads but HashMap can not
   be shared between multiple threads without proper synchronization. Java 5 introduces 
   ConcurrentHashMap which is an alternative of Hashtable and provides better scalability than Hashtable in 
   Java.

3.HashTable is legacy class promoted into collection framework. It got its own extra features like enumerators.


NOTE:
HashMap can be synchronized by

Map m = Collections.synchronizeMap(hashMap);

Tuesday, 18 March 2014

How To make an class as an Immutable

Before converting the java class as Immuatable .
I will explain what is Mutable and Immutable

Mutable object - an object that is liable to change.
Immutable object - an object that is unchanging over time or unable to be changed.

For Ex:
IMMUTABLE :
String imm = "abc";
imm = "abc"+"d";

Here we are not adding the value to exist object ("abc"),  
1)"d" will add to "abc",
2) will create new object "abcd" 
3) the reference of "abc" will map to "abcd";

MUTABLE:
StringBuffer mut = new StringBuffer("abc");
mut.append("d");

Here the value of "mut" changing directly.

Guidelines to make a class immutable

1) Don’t provide “setter” methods — methods that modify fields or objects referred to by fields.
2) Make all fields final and private
3) Don’t allow subclasses to override methods
4) Special attention when having mutable instance variables



Print Friendly and PDF

Monday, 17 March 2014

How to remove null in the List (JAVA)

Just add as below
listnameObject.removeAll(Collections.singleton(null));

For Ex:
public class MapTest {
  public static void main(String[] args) {
    List<String> scores = new ArrayList<String>();
    scores.add("100");
    scores.add("90");
    scores.add("80");
    scores.add("97");
    scores.add(null);
    scores.removeAll(Collections.singleton(null));
   
    for(String a : scores){
      System.out.println(a.toString());
    }
  }
}

O/P:
100
90
80
97

Sunday, 16 March 2014

GENERAL DISCUSSIONS

In order to claim a complete 3-Tier architecture, all three layers should be able to run in separate computers.
Diagram 1: 3-Tier Architecture
These three layers are briefly described as below:
Presentation layer: a layer that users can access directly, such as desktop UI, web page and etc. Also called client. 
Application layer: this layer encapsulates the business logic (such as business rules and data validation), domain concept, data access logic and etc. Also called middle layer.  
Data layer: the external data source to store the application data, such as database server, CRM system, ERP system, mainframe or other legacy systems and etc. The one we meet often today is database server. For N-Tier architecture, we need to use the non-embedded database server, such as SQL server, Oracle, DB2, MySQL or PostgreSQL. The non-embedded database server can be run in an individual computer. Whereas, the embedded type databases, such as Microsoft access, dbase and etc, cannot run in an individual computer, and then cannot be used as the data layer of the 3-Tier architecture. 

1, 2, 3 or More Tier Architecture 

1-Tier: all above layers can only run in one computer. In order to achieve 1-Tier, we need to use the embedded database system, which cannot run in an individual process. Otherwise, there will be at least 2-Tier because non-embedded databases usually can run in an individual computer (tier).   
2-Tier: either presentation layer and application layer can only run in one computer, or application layer and data layer can only run in one computer. The whole application cannot run in more than 2 computers. 
3-Tier: the simplest case of N-Tier architecture; all above three layers are able to run in three separate computers. Practically, these three layers can also be deployed in one computer (3-Tier architecture, but deployed as 1-Tier). 
N-Tier: 3 or more tiers architecture. Diagram 2 below depicts a typical N-Tier architecture. Some layers in 3-Tier can be broken further into more layers. These broken layers may be able to run in more tiers. For example, application layer can be broken into business layer, persistence layer or more. Presentation layer can be broken into client layer and client presenter layer. In diagram 2, in order to claim a complete N-Tier architecture, client presenter layer, business layer and data layer should be able to run in three separate computers (tiers). Practically, all these layers can also be deployed in one compute (tier).  
Diagram 2: N-Tier Architecture
Below are brief summaries on all layers in Diagram 2: 
Client layer: this layer is involved with users directly. There may be several different types of clients coexisting, such as WPF, Window form, HTML web page and etc.  
Client presenter layer: contains the presentation logic needed by clients, such as ASP .NET MVC in IIS web server. Also it adapts different clients to the business layer.
Business layer: handles and encapsulates all of business domains and logics; also called domain layer. 
Persistence layer: handles the read/write of the business data to the data layer, also called data access layer (DAL).  
Data layer: the external data source, such as a database. 
Sometimes, the number of tiers is able to be equal or more than 3, but client presenter layer, business layer and data layer cannot run in three separate computers (tiers). Is this a N-Tier architecture? we categorize this N-Tier as an incomplete N-Tier architecture because its client presenter layer, business layer and data layer cannot run in three separate computers (tiers). 

Simplest way to display Server Time in JSP using js

THE BELOW CODE WORKS ONLY IN JSP : <html> <body > <table width="95%" border="1" cellpadding="1...