-2
Dog.setName("Kutta"); // this is how you call a setter method
String Naam = Dog.getName();
System.println(Naam);  //Kutta
Naam = "Kutte ki Ma";
System.println(Dog.getName()); // Is this *Kutte ki Ma* or is it *Kutta*?

And Why? If Java passes references by value, shouldn't Naam point to Dog.getName()? If that is the case, shouldn't the Name variable of Dog object (which may be private to the class used here) be directly modified if Naam is modified? Isn't that a flaw?

Alboz
  • 1,833
  • 20
  • 29
hrishi1990
  • 325
  • 3
  • 12
  • 6
    `Dog.getName() = "Kutta";` will it compile? – Rustam Oct 04 '14 at 10:13
  • You need to post code that compiles before it's possible to talk about the execution-time behaviour... Please post a short but complete program that demonstrates the problem. – Jon Skeet Oct 04 '14 at 10:16
  • @hrishirc take a look to this thread: http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value Pay attention especially to the second best answer, it explains in detail all you need to know. – Alboz Oct 04 '14 at 10:20
  • Also change Dog.setName() = "Kutta"; to Dog.setName("Kutta"); – Alboz Oct 04 '14 at 10:21
  • The dog's name is "dog"? How creative :-( – Kerrek SB Oct 04 '14 at 10:22

2 Answers2

1

None of the above, because your code posted here never sets the Dog's name. If you did call

Dog.setName("Kutta");

Java is pass by value (but the value of an Object is it's reference). But, String is immutable in Java and you cannot update the reference to a String held by a different instance.

If you were to use a StringBuilder you might do something like,

public static void main(String args[]) {
    Dog d = new Dog();
    d.getName().append("Kutta");
    StringBuilder Naam = d.getName();
    System.out.println(Naam);  //Kutta
    Naam.setLength(0);
    Naam.append("Kutte ki Ma");
    System.out.println(d.getName());
}

static class Dog {
    private StringBuilder sb = new StringBuilder();
    StringBuilder getName() {
        return sb;
    }
}

Which does as you seem to expect.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

Because strings are immutable, when you type Naam = "Kutte ki Ma"; you are not changing the existing string object, you are creating a new one and assigning to your Naam variable.

What this means is that the assignment never actually goes anywhere near the dog's name, which still references the previous string. Hence, it doesn't change.

Ant P
  • 24,820
  • 5
  • 68
  • 105