PhysicsTeacher.in

High School Physics + more

Java program with String and StringBuffer

Here is a Java program that helps you to understand how immutable String and growable StringBuffer classes differ in their behavior and operation.

Java Program showing use of String and StringBuffer

class StringB
{
public static void main(String args[])
{
//immutable String

String s1 = “ABC”;
String s2= s1;
System.out.println(“s2=s1:::”+(s2==s1));
System.out.println(“s2.equals(s1):::”+(s2.equals(s1)));

s1=s1+”CDE”;
System.out.println(“s2=s1:::”+(s2==s1));
System.out.println(“s2.equals(s1):::”+(s2.equals(s1)));

//Growable StringBuffer
StringBuffer sb1=new StringBuffer(“ABC”);
StringBuffer sb2=sb1;

System.out.println(“sb2=sb1:::”+(sb2==sb1));
System.out.println(“sb2.equals(sb1):::”+(sb2.equals(sb1)));
sb1.append(“CDE”);

System.out.println(“sb2=sb1:::”+(sb2==sb1));
System.out.println(“sb2.equals(sb1):::”+(sb2.equals(sb1)));
}
}

See also  Java program - how to access private variable
Scroll to top
error: physicsTeacher.in