Introduction: String Handling
- A string is a sequence of characters.
- The String objects are immutable(constant), it means their values cannot be changed after they are created.
- Once a String object is created, the characters that comprise the String object will be created but original contents of the object will not be changed.
- String buffers support mutable strings.
- Because String objects are immutable they can be shared.
Object Creation of String:
String str = new String();For Example:
String s=“HeeraBabu”;
It is equivalent to:
char name[] = {‘H,’e’ ,’e’ ,’r’ ,’a’ ,’B’ ,’a’ ,’b’ ,’u’};
String s=new String(name);
Simple Program:
import java.lang.StringBuffer;
import java.lang.String;
public class TestS1 {
public static void main(String args[])
{
String name="Heera";
name.concat("Babu");
System.out.println(name);
StringBuffer sb = new StringBuffer("Heera");
sb.append("Babu");
System.out.println(sb);
}
}
Sample output:
Heera
HeeraBabu
How to assign a new instance of string values?
public class TestS1 {
public static void main(String args[])
{
String name="Heera";
String fullname=name.concat("Babu");
System.out.println(name);
System.out.println(fullname);
name="Singh";
System.out.println(name);
System.out.println(fullname);
StringBuffer sb = new StringBuffer("Heera");
sb.append("Babu");
System.out.println(sb);
}
}
Sample output:
Heera
HeeraBabu
Singh
HeeraBabu
HeeraBabu