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

前端 未结 26 1517
生来不讨喜
生来不讨喜 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:37

    Well, in Java an int is a primitive while an Integer is an Object. Meaning, if you made a new Integer:

    Integer i = new Integer(6);
    

    You could call some method on i:

    String s = i.toString();//sets s the string representation of i
    

    Whereas with an int:

    int i = 6;
    

    You cannot call any methods on it, because it is simply a primitive. So:

    String s = i.toString();//will not work!!!
    

    would produce an error, because int is not an object.

    int is one of the few primitives in Java (along with char and some others). I'm not 100% sure, but I'm thinking that the Integer object more or less just has an int property and a whole bunch of methods to interact with that property (like the toString() method for example). So Integer is a fancy way to work with an int (Just as perhaps String is a fancy way to work with a group of chars).

    I know that Java isn't C, but since I've never programmed in C this is the closest I could come to the answer. Hope this helps!

    Integer object javadoc

    Integer Ojbect vs. int primitive comparison

提交回复
热议问题