2

I have a class in theFirst.java file.

public class theFirst {
    private String str = "Hello , i'm here";
    public IntStream get_code_point(){
        return str.codePoints();
    }
    public void str_print(){
        System.out.println(str);
    }
    public String get_str(){
        return str;
    }
}

In another class in for_test.java, I want to get a string to add something to it and have it change too:

public class for_test {
    public static void main(String[] args){

        theFirst tmp = new theFirst();
        String test2 = tmp.get_str();
        test2+= "another one";
        tmp.str_print();
        System.out.println(test2);       
    }
}

But for some reason, when called tmp.str_print();. The line has not changed, but if i print System.out.println(test2); then prints the modified one.

I am new to java and as I understand such classes should pass a reference, but as I understand copying occurs.I'll be glad if you can help me figure it out.

Omegon
  • 387
  • 2
  • 10
  • Does this answer your question? [Is Java "pass-by-reference" or "pass-by-value"?](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – OH GOD SPIDERS Jun 23 '21 at 08:59

1 Answers1

1

Following

test2 += "another one";

doesn't works as you expect it to because tmp.get_str() returns a string to which you concatenate another string: "another one". This concatenation creates a new string: "Hello , i'm hereanother one" which is then assigned to test2 BUT the temp.str is unaffected; it's value isn't changed.

Strings are immutable - you have to create a new string and then assign it to str instance field.

To do this, you first need a setter method:

public String setStr(String str){
    this.str = str;
}

Inside the main method, call this setter method as:

tmp.setStr(tmp.get_str() + "another one");

or you can do it in two steps: first create a string and then pass the new string to the setter method:

test2 += "another one";
tmp.setStr(test2);

Alternatively, you could create a method inside the theFirst class that does the concatenation for you.

public void concatenateStr(String str) {
   this.str += str;
} 

Inside the main method, you can call it as:

tmp.concatenateStr("another one");

Note: Class names should begin with a capital letter: theFirst should be: TheFirst or simply: First.

Yousaf
  • 27,861
  • 6
  • 44
  • 69