Go to "Reference Value"? Some clarification required

I know that in Java everything is passed by value. But for objects, this is the value of the reference to the passed object. This means that sometimes an object can change through a parameter, so, I think, people say, never change the parameters.

But in the following code, something else happens. sin changeIt()does not change when you return to 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 );
    }
}

I suppose - and I would like to confirm that when you say s = "something"this is the same or equivalent statement String s = new String("something"). That is why it sdoes not change? Is it an assigned whole new object locally that is discarded after exiting changeIt()?

+5
source share
3

, s = "-", String s = new String ( "something" )

, . ( JVM , , , String).

s ? , changeIt()

. , Java, . , s changeIt( String s ) str, main(), changeIt. changeIt.

, String s, , - , str, changeIt(), s

, , , . , , , . s.toLowerCase() changeIt() . , String.toLowerCase() , String.

+4

s = "Good bye world";

s . , s.

+3

Yes, now "S" indicates a new object whose volume is limited by this method. A line cannot be an ideal example for understanding the concept of “after a while”. Instead of a line, let's say, pass some reference to mutable objects and make changes to assign a new object inside the method. You do not see them outside 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 the second answer in this SO discussion .

0
source

All Articles