Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing String objects as arguments Java

Tags:

java

class prog {

      static String display(String s)
      {
         s = "this is a test";
         return s;
      }

   public static void main(String...args) {

     prog p = new prog();
     String s1 = "another";
     System.out.println(display(s1)); //Line 1
     System.out.println(s1);
   }
}

A newbie question.

Can someone explain why s1 is not getting updated to "this is a test" ?.

I thought in Java, object arguments are passed as references and if that is the case, then I am passing String s1 object as reference in Line 1.

And s1 should have been set to "this is a test" via display() method.. Right ?

like image 920
UnderDog Avatar asked Sep 06 '13 16:09

UnderDog


2 Answers

Java is pass-by-value always. For reference types, it passes a copy of the value of the reference.

In your

static String display(String s)
{
    s = "this is a test";
    return s;    
}

The String s reference is reassigned, its value is changed. The called code won't see this change because the value was a copy.

With Strings, it's hard to show behavior because they are immutable but take for example

public class Foo {
    int foo;
}

public static void main(String[] args) {
    Foo f = new Foo();
    f.foo = 3;
    doFoo(f);
    System.out.println(f.foo); // prints 19
}

public static void doFoo(Foo some) {
    some.foo = 19;
}

However, if you had

public static void doFoo(Foo some) {
    some = new Foo();
    some.foo = 19;
}

the original would still show 3, because you aren't accessing the object through the reference you passed, you are accessing it through the new reference.


Of course you can always return the new reference and assign it to some variable, perhaps even the same one you passed to the method.

like image 102
Sotirios Delimanolis Avatar answered Sep 30 '22 18:09

Sotirios Delimanolis


String is a reference which is passed by value. You can change where the reference points but not the caller's copy. If the object were mutable you could change it's content.

In short, Java ALWAYS passed by VALUE, it never did anything else.

like image 39
Peter Lawrey Avatar answered Sep 30 '22 18:09

Peter Lawrey