String in java

In Java, string is basically an object that represents sequence of char values. An array of characters works same as Java string. For example:

char[] ch={'j','a','v','a'};  
String s=new String(ch);
Output
String s="java";  

Memory allotment of String

Whenever a String Object is created as a literal, the object will be created in String constant pool. This allows JVM to optimize the initialization of String literal

Interfaces and Classes in Strings in Java

CharBuffer: This class implements the CharSequence interface. This class is used to allow character buffers to be used in place of CharSequences. An example of such usage is the regular-expression package java.util.regex.
 
String: String is a sequence of characters. In java, objects of String are immutable which means a constant and cannot be changed once created.

Creating a string
By string literal : Java String literal is created by using double quotes.
For Example: String s=“Welcome”;  

By new keyword : Java String is created by using a keyword “new”.
For example: String s=new String(“Welcome”);  
It creates two objects (in String pool and in heap) and one reference variable where the variable ‘s’ will refer to the object in the heap.


Posted on by