What is the difference between String and StringBuffer?

This is a common interview question for the fresher as well as experienced persons, here first we need to know what is a string. 


String:



The string can be defined as a sequence of characters. In Java string is immutable that means if you created once that never be modified. The following is an example.

String s=new string("donald")
s.concat("trump")
System.out.println(s)

In the above example, s is pointing to the name donald and where as we creating another one that is trump so the new object donlad trump will be created but is still pointing to the Donald only. Here the output will be donald only.

Where the new object donald trump will be automatically eligible for garbage collector.


StringBuffer:



The StringBuffer is mutable that means we can change the existing object. The following is an example.

Stringbuffer sb=new StringBuffer("donald")
sb.append("trump")
System.out.println(s)

In the above example, the result will be donald trump.



No comments:

Post a Comment

What is Normalization?

Database normalization is a data design and organization process applied to data structures based on rules that help building relational dat...