5

Javaでは、すべてが値によって渡されることを私は知っています。ただし、オブジェクトの場合、渡されるのはオブジェクトへの参照の値です。これは、オブジェクトがパラメータを介して変更される場合があることを意味します。そのため、パラメータを変更しないでください。

しかし、次のコードでは、別のことが起こります。 sに戻ってもinchangeIt()は変わりませんmain()

public class TestClass {

    static String str = "Hello World";

    public static void changeIt( String s ) {
        s = "Good bye world";
    }

    public static void main( String[] args ) {
        changeIt( str );
        System.out.println( str );
    }
}

私は推測しています-そして確認をお願いします-あなたが言うときそれはと言うs = "something"のと同じか同等String s = new String("something")です。これがなぜs変わらないのですか?終了すると破棄されるまったく新しいオブジェクトがローカルに割り当てられていますchangeIt()か?

4

3 に答える 3

4

that when you say s = "something" it's the same or equivalent to saying String s = new String("something")

Yes, pretty much. (though the JVM might do optimizations so that the same string literal used several times refers to the same String object).

Is this why s doesn't change? Is it assigned a whole new object locally which gets thrown away once you exit changeIt()

Yes. As you say, everything is passed by value in Java, even references to object. So the variable s in changeIt( String s ) is a different value from str you use in main(), it's just a local variable within the changeIt method. Setting that reference to reference another object does not affect the caller of changeIt.

Note that the String object s refer to is still the same String as str refers to when entering the changeIt() method before you assign a different object to s

There's another thing you need to be aware of, and that is that Strings are immutable. That means that no method you invoke on a string object will change that string. e.g. calling s.toLowerCase() within your changeIt() method will not affect the caller either. That's because the String.toLowerCase() does not alter the object, but rather returns a new String object.

于 2012-07-20T19:43:31.007 に答える
3

When you write

s = "Good bye world";

you are changing the value of s to be a reference to the new string. You are not changing the value of the string referenced by s.

于 2012-07-20T19:45:52.697 に答える
0

Yes, now 'S' points to brand new object whose scope is limited to that method. String may not be perfect example to understand pass-by-value concept. Instead of string, let us say pass some mutable object reference and make changes to that assign new object inside the method. You don't see them outside of the object.

public class MyMain {

    private static void testMyMethod(MyMain mtest) {
        mtest=new MyMain();
        mtest.x=50;
        System.out.println("Intest method"+mtest.x);
    }
     int x=10;
    public static void main(String... args)
    {
        MyMain mtest = new MyMain();
        testMyMethod(mtest);
        System.out.println("In main method: "+mtest.x);
    }
}

Read second answers in this SO discussion.

于 2012-07-20T19:41:50.273 に答える