Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String vs StringBuffer returned value [duplicate]

Can you please explain why in the following code String and StringBuffer are treated differently and when value is appended in StringBuffer but not in String.

public class MyClass {
    
    public static void main(String args[]) {
        String str = new String("String Rohan ");
    StringBuffer strBfr = new StringBuffer("String Buffer Rohan "); 
        
        strUpdate(str);
        strBfrUpdate(strBfr);
        
        System.out.println(str);
        System.out.println(strBfr);
        
    }
    
    private static void strBfrUpdate(StringBuffer strBfr){
        strBfr.append("Kushwaha");
    }
    
    private static void  strUpdate(String str){
        str += "Kushwaha";
    }
}

Output is as follows:

String Rohan

String Buffer Rohan Kushwaha

like image 977
Rohan Kushwaha Avatar asked Dec 24 '22 09:12

Rohan Kushwaha


2 Answers

In the main method

String str = new String("String Rohan ");

str is a reference(pointer) pointing to some place in the Heap-memory of the Java-JVM. Lets call this place A

str->A

private static void  strUpdate(String str){
    //str here is still pointing to A, but technically this parameter
    //is a copy of the reference of the str pointer in the main-method
    //pointing to the same place in the heap
    //str->A
    str += "Kushwaha";
    // this line is short for str = str + "Kushwaha"
    //what happens here that you create a new String-Object in the heap (B)
    //and assigne the new value "String Rohan Kushwaha" to the new pointer
    //if you print it out now (within this method) you get what you would 
    //expect
    System.out.println(str);
    //will result in "String Rohan Kushwaha"
}

But the str-pointer of the main-method is still pointing to place A in the Heap where still only "String Rohan" is. So once you leave the scope of the method strUpdate(...) the copied pointer (which was reassigned to place B) is deleted.

Hope this helped a bit...

I guess this here is some helpfull input for your understanding

Is Java "pass-by-reference" or "pass-by-value"?

like image 84
Rainer Avatar answered Feb 21 '23 21:02

Rainer


In strUpdate method you keep a reference to a String called str:

private static void  strUpdate(String str){
    str += "Kushwaha";
}

When you write str += "..."; It means:

    str = new String(str + "...");

At this point str references the new String, but only in strUpdate method. It's not "taken back" to main.

like image 29
Gavriel Avatar answered Feb 21 '23 21:02

Gavriel