Pavalesh
Pavalesh

Reputation: 257

Object type in java

I learnt that Java is not a 100% OOP language and that this is because of data types which are not objects. But according to me, int is of type Integer and Integer belongs to Number and Number belongs to Object. So java is a 100% OOP language. Am I correct?

Upvotes: 0

Views: 304

Answers (3)

avpaderno
avpaderno

Reputation: 29679

int is not an object of the class Integer. In Java, not all the data types are objects.

Upvotes: 1

Mac
Mac

Reputation: 14791

To add to the previous answers (which I think may have missed the point a little) - yes, int and Integer are two completely different (but related) concepts - one is a primitive, the other an equivalent class. More importantly however, that distinction has absolutely no bearing whatsoever on whether Java is an object-oriented language.

Every single Java program uses objects at some point (even if it is just the String[] args parameter to your main method). As such, Java is unequivocally an object-oriented language, simply because it relies on classes as a primary means of program development. The fact that it supports non-object primative types has nothing to do with that at all.

Upvotes: 1

David Z
David Z

Reputation: 131580

No, int and Integer are different. Integer is a regular class, which as you know is a subclass of Number which itself is a subclass of Object. But int is a primitive type. It is not a class, so obviously not a subclass of anything; it has no methods or attributes, and generally there is nothing you can do with int itself, except declare variables of that type, e.g.

int x = 3;

Since int is not a class, the values of int variables are not objects. They have no methods or attributes or properties, and there's not much you can do with them except certain mathematical operations which are handled specially by the compiler.

Note that the Java compiler (recent versions) will automatically insert code to convert an int into an Integer, or vice-versa, where necessary. So it might look like they're the same thing when you write your program, but they are actually not. For instance, if you write

Integer y = 5;

javac translates that into

Integer y = Integer.valueOf(5);

Or

Map<Integer,Integer> m = ...;
m.put(4, 8);
int z = m.get(4);

becomes

Map<Integer,Integer> m = ...;
m.put(Integer.valueOf(4), Integer.valueOf(8));
int z = m.get(Integer.valueOf(4)).intValue();

Upvotes: 10

Related Questions