0

I want to know how or if I can set multiple Class fields using one or several Class methods which don't specifically refer to any field?. I made the simplest example I could think of.

My apologies if this is a terribly obvious question which has been answered. I found a couple of questions that seemed similar but they involved several classes and were confusing. I think having this question is beneficial and might be easy for someone to answer.

public class MyClass {

    private String str = "hello";
    private String str2 = "ciao";
    private String str3 = "hola";

    public void changeSomeString(){
        changeString(str);
    }

    private void changeString(String s){
        s = "goodbye";
    }

    public void changeSpecificString(){
        str = "goodbye";
    }

    public void printString(){
        System.out.println(str);
    }

    public static void main(String args[]) {

        MyClass a = new MyClass();
        a.printString();
        a.changeSomeString();
        a.printString();
        a.changeSpecificString();
        a.printString();

    }

}

I can't say I expected, but I wanted

hello
goodbye
goodbye

and I received

hello
hello
goodbye
  • 2
    shouldn't it be `str = "goodbye"` in `changeString` ? – Michał Krzywański Sep 12 '19 at 10:11
  • 1
    Calling `changeString(str)` passes the *value* of `str` to `changeString`, not the actual variable. – Joachim Sauer Sep 12 '19 at 10:13
  • 2
    Java is pass-by-value so no, method like `void change(String s){s="foo";}` used on `String a = "abc"; change(a);` will not change content of `a` variable but `s` variable which is considered as *separate* and *local* variable of `change` method. Alternative solution depends on what you *really* want to achieve. – Pshemo Sep 12 '19 at 10:17
  • I sort of understood scope as the reason why it wasn't working, although I didn't know the terminology like "pass-by-value." I've changed the question to specify my intent. Is there a way of setting let's say 30 String fields without having 30 setters? – Andrea deCandia Sep 12 '19 at 10:30
  • 1
    If you want to iterate over fields of some class you can use *reflection* mechanism (official tutorial: https://docs.oracle.com/javase/tutorial/reflect/index.html), but be aware that it is very slow in comparison of directly assigning values to fields or executing simple setter methods. – Pshemo Sep 12 '19 at 10:43
  • @Pshemo thank you very much. This is definitely my answer, if you want to post it. And I appreciate you explaining it to me. – Andrea deCandia Sep 12 '19 at 13:33

1 Answers1

0

It happens because of Java method parameter object reference. You are changing the value of String s in changeString(str) from hello to goodbye but the value of str still remains the same.

Kavitha Karunakaran
  • 1,340
  • 1
  • 17
  • 32