Step 20:String Handling -13th hour + code


Generally string is a sequence of characters, but in java, strings are immutable objects. Immutable simply means  unmodifiable/unchangeable.

Creation of String object:-

1:- By string literal2:- By new keyword

1:- String literal:-

String s1=”Welcome”; //1 object createdString s2=”Welcome”; //no object will be created

Description:- When a String is created, JVM checks it in string constant pool if it exists it returns reference else string object is submitted to pool.


2:- By new keyword:-

String s=new String(“Welcome”);     //Creates 2 objectsString s1=new String(“Welcome”);   //1 object

Description:- new String object is created in nonpool(heap memory) and literal “Welcome” is created in string constant pool. The variable s is reference variable for object created in nonpool.


Methods of String class– There are many functions which can be performed on string such as concatenation,trim,split,substring etc.

String Buffer & String Builder –

Both classes are used to create mutable strings.

Unlike Strings these are stored in heap memory.

Both classes have same methods, but each method in StringBuffer is synchronized so StringBuffer is thread safe.

StringBuilder is fast in performance.

code samples are here
1-Mostly Used String methods-

package strn;
public class ExStrings {
public static void main(String[] args) {
String nameLiteral = "kuldeep"; // 1 object creation
String nameobject = new String("kaushik"); // 2 object creation
String[] arr1 = nameLiteral.split("d");
System.out.println(arr1[0] + " and " + arr1[1]);
String fortrim = " deep ";
System.out.println(nameLiteral.equals(nameobject)); System.out.println(nameLiteral.indexOf("e"));
System.out.println(nameLiteral.substring(2, 5));
System.out.println(nameLiteral.replace("ul", "lu"));

Run this Program ▶️
2-Mostly Used StringBuilder/StringBuffer methods-(both classes have same methods)

package strn;
public class ExStringB {
public static void main(String[] args) {
StringBuilder sb1=new StringBuilder("java");
StringBuffer sb2=new StringBuffer("core");

Run this Program ▶️

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.