soandos
soandos

Reputation: 5146

Is int an object in Java?

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 Integer a reference type, but does int inherit from Object anyway?

(I am assuming that in this regard int, long, boolean etc are all similar. int was just chosen for convenience)

Upvotes: 14

Views: 27694

Answers (5)

Prasanth
Prasanth

Reputation: 1

  1. Object has state and behavior
  2. state means fields (variables)
    ex: bicycle (current speed, current gear)
  3. behavior means methods to change that fields ex: changing current speed using methods
  4. Just imagine can you change state of an int if you change you could say that int is an object. we can't change so it not an object

Upvotes: -1

Ryan Stewart
Ryan Stewart

Reputation: 128939

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.

Upvotes: 17

mikek3332002
mikek3332002

Reputation: 3562

  • 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>

Upvotes: 23

Racooon
Racooon

Reputation: 1496

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.

Upvotes: 1

siride
siride

Reputation: 210025

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.

Upvotes: 1

Related Questions