0

I struggled coming up with a title for this post but I would love to find a simple explanation why the running the following program gives output of 6,5,5 instead of 5,5,5:

public class TestMethod {
public static void main(String[] args) {

    IntegerObject aInt = new IntegerObject(5);
    objectIncrease(aInt);
    System.out.println(aInt.x);

    int bInt = 5;
    increase(bInt);
    System.out.println(bInt);

    Integer cInt = new Integer(5);
    increase(cInt);
    System.out.println(cInt);
}

public static void objectIncrease(IntegerObject x){
    x.increment();
}

public static void increase(int x){
    ++x;
}}

IntegerObject is just another class that I created to demonstrate my point. Why does the increase(int x) method create a local instance of the int x but the objectIncrease(IntegerObject x) method does not create a local instance of the integerObject x?

  • There is a difference between an "instance" and a "variable". Primitive types (such as `int`) do not have instances at all. Object types can have multiple variables pointing to the same instance. – Thilo Mar 09 '16 at 01:11
  • 1
    The `increase(int x)` method actually doesn't create a local instance of anything. It just modifies the primitive parameter value locally, then discards it – OneCricketeer Mar 09 '16 at 01:12
  • Thanks for the link to that other question. I had never heard of the phrase pass-by-value which is exactly what I needed. – the0dark0one Mar 09 '16 at 01:26

0 Answers0