What is the difference between an int and an Integer in Java and C#?

前端 未结 26 1732
生来不讨喜
生来不讨喜 2020-11-22 12:00

I was reading More Joel on Software when I came across Joel Spolsky saying something about a particular type of programmer knowing the difference between an i

26条回答
  •  耶瑟儿~
    2020-11-22 12:19

    In Java there are two basic types in the JVM. 1) Primitive types and 2) Reference Types. int is a primitive type and Integer is a class type (which is kind of reference type).

    Primitive values do not share state with other primitive values. A variable whose type is a primitive type always holds a primitive value of that type.

    int aNumber = 4;
    int anotherNum = aNumber;
    aNumber += 6;
    System.out.println(anotherNum); // Prints 4
    

    An object is a dynamically created class instance or an array. The reference values (often just references) are pointers to these objects and a special null reference, which refers to no object. There may be many references to the same object.

    Integer aNumber = Integer.valueOf(4);
    Integer anotherNumber = aNumber; // anotherNumber references the 
                                     // same object as aNumber
    

    Also in Java everything is passed by value. With objects the value that is passed is the reference to the object. So another difference between int and Integer in java is how they are passed in method calls. For example in

    public int add(int a, int b) {
        return a + b;
    }
    final int two = 2;
    int sum = add(1, two);
    

    The variable two is passed as the primitive integer type 2. Whereas in

    public int add(Integer a, Integer b) {
        return a.intValue() + b.intValue();
    }
    final Integer two = Integer.valueOf(2);
    int sum = add(Integer.valueOf(1), two);
    

    The variable two is passed as a reference to an object that holds the integer value 2.


    @WolfmanDragon: Pass by reference would work like so:

    public void increment(int x) {
      x = x + 1;
    }
    int a = 1;
    increment(a);
    // a is now 2
    

    When increment is called it passes a reference (pointer) to variable a. And the increment function directly modifies variable a.

    And for object types it would work as follows:

    public void increment(Integer x) {
      x = Integer.valueOf(x.intValue() + 1);
    }
    Integer a = Integer.valueOf(1);
    increment(a);
    // a is now 2
    

    Do you see the difference now?

提交回复
热议问题