String,String Buffer and String Builder in Java

0
String:-  It is predefined Java class which provide immutable object means we can not change value of String from actual address.

In Java We can write String using two different ways:-

1 String as a Object:-

  String s = new String();

2 String as a Reference:-

String s = "hello";

Program Explanation of String:-

public class StringExample {
 
    public static void main(String[] args) {
        String s1 = "hello";
        String s = new String("hello");
     
        String s2=s.concat("world");
        String s3= s.toUpperCase();
        System.out.println(s);
        System.out.println(s1);
        System.out.println(s2);
        System.out.println(s3);
    }
 
}

Program Explanation of String with equals():-


equals() is used to compare two different String object ,it will return value of current address.

public class StringExample {
 
    public static void main(String[] args) {
        String s = "hello";
        String s1 = new String("hello");
        String s2 = new String("hello");
        String s3="hello";
      //  System.out.println(s1.hashCode());
       // System.out.println(s2.hashCode());
        if(s1.equals(s3))
        {
            System.out.println("Equalls");
        }
        else
        {
            System.out.println("Not equalls");
        }
    }
 
}

note:- == operator never use to compare objects ,it's only for value type elements(int,char,float ,double) and String reference.




String Buffer:-

It provide mutable object because we can change value of String object from actual address.

String Buffer provide Synchronized object.

StringBuffer sb = new StringBuffer("hello");
sb.append("manish");
sout(sb);

Solution:-
public class StringExample {
 
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("hello");
        sb.append("world");
        System.out.println(sb);
    }
 
}


String Builder:-


StringBuilder is predefine class ,it also provide mutable object but it can not be synchronized ,StringBuffer is the modified format of StringBuilder class.

StringBuilder sb = new StringBuilder("manish");
sb.append("sharma");
sout(sb);














Post a Comment

0Comments

POST Answer of Questions and ASK to Doubt

Post a Comment (0)