Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static, Java is pass by value. then why my program show that output?

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 is
OldDog
NewDog
NewDog
but i am expecting
OldDog
NewDog
OldDog
Please anybody tell me where i am thinking wrong.

like image 689
gifpif Avatar asked Sep 12 '13 12:09

gifpif


2 Answers

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;
    }
like image 81
Menelaos Avatar answered Nov 18 '22 17:11

Menelaos


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.

like image 23
Joop Eggen Avatar answered Nov 18 '22 16:11

Joop Eggen