Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java Integer reference

Tags:

java

I've got a question.

public class Jaba {

    public static void main(String args[]) {
        Integer i = new Integer(0);        
        new A(i);
        System.out.println(i);
        new B(i);
        System.out.println(i);
        int ii = 0;        
        new A(ii);
        System.out.println(ii);
        new B(ii);
        System.out.println(ii);    
    }

}

class A {

    public A(Integer i) { ++i; }

}

class B {

    public B(int i) { ++i; }

}

To my mind passing an int\Integer as Integer to a function and making ++ on that reference should change the underlying object, but the output is 0 in all the cases. Why is that?

like image 325
OneMoreVladimir Avatar asked Jul 03 '11 10:07

OneMoreVladimir


People also ask

Is integer reference type Java?

Java has a two-fold type system consisting of primitives such as int, boolean and reference types such as Integer, Boolean. Every primitive type corresponds to a reference type. Every object contains a single value of the corresponding primitive type.

Is integer a reference type?

int is a value type.

Can we just cast the reference to an int?

Yes, you can cast the reference(object) of one (class) type to other.


2 Answers

Most of the classes such as Integer that derive from Java's abstract Number class are immutable., i.e. once constructed, they can only ever contain that particular number.

A useful benefit of this is that it permits caching. If you call:

Integer i = Integer.valueOf(n);

for -128 <= n < 127 instead of:

Integer i = Integer.new(n)

you get back a cached object, rather than a new object. This saves memory and increases performance.

In the latter test case with a bare int argument, all you're seeing is how Java's variables are passed by value rather than by reference.

like image 81
Alnitak Avatar answered Oct 10 '22 09:10

Alnitak


@Alnitak -> correct. And to add what really happens here. The ++i due to autoboxing works like that:

int val = Integer.intValue(); ++val;

and val is not stored anywhere, thus increment is lost.

like image 36
Jarek Potiuk Avatar answered Oct 10 '22 09:10

Jarek Potiuk