First of all Sorry For this question. this is very old topic.
Yes i did lots of search that java is pass by value.
But by my program show that out put. i can't understand why?
My program is
class Dog{
static String dogName;
Dog(String name){
dogName=name;
}
public void setName(String newName){
dogName=newName;
}
public String getName(){
return dogName;
}
}
class JavaIsPassByValue{
public static void main(String arr[]){
Dog dog1=new Dog("OldDog");
new JavaIsPassByValue().display(dog1);
System.out.println(dog1.getName());
}
public void display(Dog d){
System.out.println(d.getName());
d = new Dog("NewDog");
System.out.println(d.getName());
}
}
Output isOldDog
NewDog
NewDog
but i am expectingOldDog
NewDog
OldDog
Please anybody tell me where i am thinking wrong.
Your problem is that your using static
for DogName.
Hence when you call the constructor of Dog, you are changing the value of DogName for all Dog objects (as there is only one value actually).
static String dogName;
Dog(String name){
dogName=name;
}
Change your code to this:
String dogName;
Dog(String name){
dogName=name;
}
static String dogName;
should be
String dogName;
Both objects with static share the same dogName (class level field).
Though two objects, and pass-by-value, the single object dogName was changed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With