0

in this code
Why this prints >> 0 8 instead of >> 5 8 . The method doIt() changes the number of Person p which is already allocated, but the int x is already allocated and is not changed in doIt(). Can anyone give me an theoretic explanation? I'm trying to understand how it works. Thanks.

class Person{
   int number=0;
}

class Student extends Person
{
    int studentNumber;
}

public class Prog{


    public void doIt(int x, Person p)
    {
        x=5;
        p.number=8;
    }

    public static void main(String[] args) {

       Prog p = new Prog();
       p.test();

    }

    public void test()
    {
        int x=0;
        Person p = new Person();
        doIt(x,p);
        System.out.println(x);
        System.out.println(p.number);
    }
} 
PM 77-1
  • 12,933
  • 21
  • 68
  • 111

2 Answers2

3

Java is always pass by value.

Primitives such as int are passed by value, so your x in test is never modified; it's always 0. Only the local copy x in doIt is changed to 5, but that value goes away when the method doIt ends.

There are two x variables in your program:

  • The x in test: initialized to 0 and never changed.
  • The x in doIt: initialized to 0, changed to 5, and never used.

The reference to your Person object is passed by value, but doIt does modify number in the original object, so it changes to 8.

There are two p variables in your program:

  • The p in test: initialized to a new Person object. number is initialized to 0.
  • The p in doIt: it refers to the same Person object as the p in test. So when doIt changes number to 5, it modifies the one and only Person object you have.
Community
  • 1
  • 1
rgettman
  • 176,041
  • 30
  • 275
  • 357
  • So in doIt x is a copy and p is the real object, because x is primitive and Person p isn't ? –  Aug 06 '13 at 00:10
  • Close. In `doIt`, `x` is a copy of the `x` in `test`. `p` is a copy too. But it's a copy of the _reference_ to the object. So both `p` variables, in `doIt` and in `test`, refer to the one and only `Person` object. – rgettman Aug 06 '13 at 00:13
  • Great! Thanks a lot! I'm more accustomed to c++, where i can specify de copys, references.. –  Aug 06 '13 at 00:22
0

Primitive data types, like integers, are based by value instead of by data reference. By setting x=0 in the method, that doesn't set the value of x in the test method to 0, because when x is passed to doIt, it is merely by value. Therefore, anything you do in the method isn't recorded. You would have to pass an object, like Person for the changes to occur.

mattpic
  • 1,277
  • 9
  • 13