Is int an object in Java?

前端 未结 4 1347
旧时难觅i
旧时难觅i 2020-12-19 00:26

More precisely, is int a part of the Integer class (a stripped down version or something) or is it something else entirely?

I am aware that int is a value type and I

相关标签:
4条回答
  • 2020-12-19 00:39

    If you talk about Integer:

    The Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int.

    In addition, this class provides several methods for converting an int to a String and a String to an int, as well as other constants and methods useful when dealing with an int.

    int is not object, its a primitive type.

    0 讨论(0)
  • 2020-12-19 00:56

    From "Primitive Data Types": "Primitive types are special data types built into the language; they are not objects created from a class." That, in turn, means that no, int doesn't inherit from java.lang.Object in any way because only "objects created from a class" do that. Consider:

    int x = 5;
    

    In order for the thing named x to inherit from Object, that thing would need to have a type. Note that I'm distinguishing between x itself and the thing it names. x has a type, which is int, but the thing named x is the value 5, which has no type in and of itself. It's nothing but a sequence of bits that represents the integral value "5". In contrast, consider:

    java.lang.Number y = new java.lang.Integer(5);
    

    In this case, y has the type Number, and the thing named y has the type Integer. The thing named y is an object. It has a distinct type irrespective of y or anything else.

    0 讨论(0)
  • 2020-12-19 00:58
    • The basic types in Java are not objects and does not inherit from Object.

    • Since Java 1.5 introduced allowed auto boxing between int and Integer(and the other types).

    • Because ints aren't Objects that can't be used as generic type parameters eg the T in list<T>

    0 讨论(0)
  • 2020-12-19 01:03

    Primitive types aren't objects, but are stored directly in whatever context they are needed. If they need to be treated like an object, they can be boxed in an Integer.

    0 讨论(0)
提交回复
热议问题