What is the difference between Integer and int in Java? - java

For example why can you do:
int n = 9;
But not:
Integer n = 9;
And you can do:
Integer.parseInt("1");
But not:
int.parseInt("1");

int is a primitive type. Variables of type int store the actual binary value for the integer you want to represent. int.parseInt("1") doesn't make sense because int is not a class and therefore doesn't have any methods.
Integer is a class, no different from any other in the Java language. Variables of type Integer store references to Integer objects, just as with any other reference (object) type. Integer.parseInt("1") is a call to the static method parseInt from class Integer (note that this method actually returns an int and not an Integer).
To be more specific, Integer is a class with a single field of type int. This class is used where you need an int to be treated like any other object, such as in generic types or situations where you need nullability.
Note that every primitive type in Java has an equivalent wrapper class:
byte has Byte
short has Short
int has Integer
long has Long
boolean has Boolean
char has Character
float has Float
double has Double
Wrapper classes inherit from Object class, and primitive don't. So it can be used in collections with Object reference or with Generics.
Since java 5 we have autoboxing, and the conversion between primitive and wrapper class is done automatically. Beware, however, as this can introduce subtle bugs and performance problems; being explicit about conversions never hurts.

An Integer is pretty much just a wrapper for the primitive type int. It allows you to use all the functions of the Integer class to make life a bit easier for you.
If you're new to Java, something you should learn to appreciate is the Java documentation. For example, anything you want to know about the Integer Class is documented in detail.
This is straight out of the documentation for the Integer class:
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.

An int variable holds a 32 bit signed integer value. An Integer (with capital I) holds a reference to an object of (class) type Integer, or to null.
Java automatically casts between the two; from Integer to int whenever the Integer object occurs as an argument to an int operator or is assigned to an int variable, or an int value is assigned to an Integer variable. This casting is called boxing/unboxing.
If an Integer variable referencing null is unboxed, explicitly or implicitly, a NullPointerException is thrown.
(In the above text, the term "variable" means local variable, field or parameter)

Integer refers to wrapper type in Java whereas int is a primitive type. Everything except primitive data types in Java is implemented just as objects that implies Java is a highly qualified pure object-oriented programming language. If you need, all primitives types are also available as wrapper types in Java. You can have some performance benefit with primitive types, and hence wrapper types should be used only when it is necessary.
In your example as below.
Integer n = 9;
the constant 9 is being auto-boxed (auto-boxing and unboxing occurs automatically from java 5 onwards) to Integer and therefore you can use the statement like that and also Integer n = new Integer(9). This is actually achieved through the statement Integer.valueOf(9).intValue();

Integer is an wrapper class/Object and int is primitive type. This difference plays huge role when you want to store int values in a collection, because they accept only objects as values (until jdk1.4). JDK5 onwards because of autoboxing it is whole different story.

This is taken from Java: The Complete Reference, Ninth Edition
Java uses primitive types (also called simple types),
such as int or double, to hold the basic data types supported by the
language. Primitive types, rather than objects, are used for these
quantities for the sake of performance. Using objects for these values
would add an unacceptable overhead to even the simplest of
calculations. Thus, the primitive types are not part of the object
hierarchy, and they do not inherit Object.
Despite the performance
benefit offered by the primitive types, there are times when you will
need an object representation. For example, you can’t pass a primitive
type by reference to a method. Also, many of the standard data
structures implemented by Java operate on objects, which means that
you can’t use these (object specific) data structures to store primitive types. To
handle these (and other) situations, Java provides type wrappers,
which are classes that encapsulate a primitive type within an object.
Wrapper classes relate directly to Java’s autoboxing
feature. The type wrappers are Double, Float, Long, Integer, Short,
Byte, Character, and Boolean. These classes offer a wide array of
methods that allow you to fully integrate the primitive types into
Java’s object hierarchy.

int is a primitive type and not an object. That means that there are no methods associated with it. Integer is an object with methods (such as parseInt).
With newer java there is functionality for auto boxing (and unboxing). That means that the compiler will insert Integer.valueOf(int) or integer.intValue() where needed. That means that it is actually possible to write
Integer n = 9;
which is interpreted as
Integer n = Integer.valueOf(9);

In Java int is a primitive data type while Integer is a Helper class, it is use to convert for one data type to other.
For example:
double doubleValue = 156.5d;
Double doubleObject = new Double(doubleValue);
Byte myByteValue = doubleObject.byteValue ();
String myStringValue = doubleObject.toString();
Primitive data types are store the fastest available memory where the Helper class is complex and store in heap memory.
reference from "David Gassner" Java Essential Training.

int is a primitive type that represent an integer. whereas Integer is an Object that wraps int. The Integer object gives you more functionality, such as converting to hex, string, etc.
You can also use OOP concepts with Integer. For example, you can use Integer for generics (i.e. Collection<Integer>).

int is a primitive data type while Integer is a Reference or Wrapper Type (Class) in Java.
after java 1.5 which introduce the concept of autoboxing and unboxing you can initialize both int or Integer like this.
int a= 9
Integer a = 9 // both valid After Java 1.5.
why Integer.parseInt("1"); but not int.parseInt("1"); ??
Integer is a Class defined in jdk library and parseInt() is a static method belongs to Integer Class
So, Integer.parseInt("1"); is possible in java. but int is primitive type (assume like a keyword) in java. So, you can't call parseInt() with int.

To optimize the Java code runtime, int primitive type(s) has been added including float, bool etc. but they come along with there wrapper classes so that if needed you can convert and use them as standard Java object along with many utility that comes as their member functions (such as Integer.parseInt("1")).

Related

Relation between Integer Class and int [duplicate]

Autoboxing is the automatic conversion that the Java compiler makes
between the primitive types and their corresponding object wrapper
classes. For example, converting an int to an Integer, a double to a
Double, and so on. If the conversion goes the other way, this is
called unboxing.
So why do we need it and why do we use autoboxing and unboxing in Java?
Some context is required to fully understand the main reason behind this.
Primitives versus classes
Primitive variables in Java contain values (an integer, a double-precision floating point binary number, etc). Because these values may have different lengths, the variables containing them may also have different lengths (consider float versus double).
On the other hand, class variables contain references to instances. References are typically implemented as pointers (or something very similar to pointers) in many languages. These things typically have the same size, regardless of the sizes of the instances they refer to (Object, String, Integer, etc).
This property of class variables makes the references they contain interchangeable (to an extent). This allows us to do what we call substitution: broadly speaking, to use an instance of a particular type as an instance of another, related type (use a String as an Object, for example).
Primitive variables aren't interchangeable in the same way, neither with each other, nor with Object. The most obvious reason for this (but not the only reason) is their size difference. This makes primitive types inconvenient in this respect, but we still need them in the language (for reasons that mainly boil down to performance).
Generics and type erasure
Generic types are types with one or more type parameters (the exact number is called generic arity). For example, the generic type definition List<T> has a type parameter T, which can be Object (producing a concrete type List<Object>), String (List<String>), Integer (List<Integer>) and so on.
Generic types are a lot more complicated than non-generic ones. When they were introduced to Java (after its initial release), in order to avoid making radical changes to the JVM and possibly breaking compatibility with older binaries, the creators of Java decided to implement generic types in the least invasive way: all concrete types of List<T> are, in fact, compiled to (the binary equivalent of) List<Object> (for other types, the bound may be something other than Object, but you get the point). Generic arity and type parameter information are lost in this process, which is why we call it type erasure.
Putting the two together
Now the problem is the combination of the above realities: if List<T> becomes List<Object> in all cases, then T must always be a type that can be directly assigned to Object. Anything else can't be allowed. Since, as we said before, int, float and double aren't interchangeable with Object, there can't be a List<int>, List<float> or List<double> (unless a significantly more complicated implementation of generics existed in the JVM).
But Java offers types like Integer, Float and Double which wrap these primitives in class instances, making them effectively substitutable as Object, thus allowing generic types to indirectly work with the primitives as well (because you can have List<Integer>, List<Float>, List<Double> and so on).
The process of creating an Integer from an int, a Float from a float and so on, is called boxing. The reverse is called unboxing. Because having to box primitives every time you want to use them as Object is inconvenient, there are cases where the language does this automatically - that's called autoboxing.
Auto Boxing is used to convert primitive data types to their wrapper class objects.
Wrapper class provide a wide range of function to be performed on the primitive types. The most common example is :
int a = 56;
Integer i = a; // Auto Boxing
It is needed because of programmers easy to be able to directly write code and JVM will take care of the Boxing and Unboxing.
Auto Boxing also comes in handy when we are working with java.util.Collection types. When we want to create a Collection of primitive types we cannot directly create a Collection of a primitive type , we can create Collection only of Objects. For Example :
ArrayList<int> al = new ArrayList<int>(); // not supported
ArrayList<Integer> al = new ArrayList<Integer>(); // supported
al.add(45); //auto Boxing
Wrapper Classes
Each of Java's 8 primitive type (byte,short,int,float,char,double,boolean,long) hava a seperate Wrapper class Associated with them. These Wrapper class have predefined methods for preforming useful operations on primitive data types.
Use of Wrapper Classes
String s = "45";
int a = Integer.parseInt(s); // sets the value of a to 45.
There are many useful functions that Wrapper classes provide. Check out the java docs here
Unboxing is opposite of Auto Boxing where we convert the wrapper class object back to its primitive type. This is done automatically by JVM so that we can use a the wrapper classes for certain operation and then convert them back to primitive types as primitives result int faster processing. For Example :
Integer s = 45;
int a = s; auto UnBoxing;
In case of Collections which work with objects only auto unboxing is used. Here's how :
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(45);
int a = al.get(0); // returns the object of Integer . Automatically Unboxed .
The primitive (non-object) types have there justification in efficiency.
The primitive types int, boolean, double are immediate data, whereas Objects are references. Hence fields (or variables)
int i;
double x;
Object s;
would need local memory 4+8+8? where for the object only the reference (address) to memory is stored.
Using the Object wrappers Integer, Double and others, one would introduce an indirection, reference to some Integer/Double instance in the heap memory.
Why boxing is needed?
That is a question of relative scope. In a future java it is planned to be able to have an ArrayList<int>, lifting primitive types.
Answer: For now an ArrayList only works for Object, reserving room for an object reference, and managing garbage collection likewise. Hence generic types are Object children.
So if one wanted an ArrayList of floating point values, one needed to wrap a double in a Double object.
Here Java differs from the traditional C++ with its templates: C++ classes vector<string>, vector<int> would create two compilation products. Java design went for having one ArrayList.class, not needing for every parameter type a new compiled product.
So without boxing to Object one would need to compile classes for every occurrence of a parameter type. In concreto: every collection or container class would need a version for Object, int, double, boolean. The version for Object would handle all child classes.
In fact, the need for such diversification already existed in Java SE for IntBuffer, CharBuffer, DoubleBuffer, ... which operate on int, char, double. It was solved in a hacky way by generating these sources from a common one.
Starting with JDK 5, java has added two important functions: autoboxing and autounboxing. AutoBoxing is the process for which a primitive type is automatically encapsulated in the equivalent wrapper whenever such an object is needed. You do not have to explicitly construct an object. Auto-unboxing is the process whereby the value of an encapsulated object is automatically extracted from a type wrapper when its value is required. You do not need to call a method such as intValue() or doubleValue().
The addition of autoboxing and auto-unboxing greatly simplifies writing algorithms, eliminating the bait manually boxing and unboxing of values. It is also helpful to avoid mistakes. It is also very important for generics, who only operate on objects. Lastly, autoboxing facilitates work with the Collections Framework.
Some data structures can accept only objects, no primitive types.
Example: the key in a HashMap.
See this question for more: HashMap and int as key
There are other good reasons, such as a "int" field in a database, which could be NULL as well.
An int in Java cannot be null ; an Integer reference can. Autoboxing and unboxing provide with a facility to avoid writing extraneous code in the conversions back and forth.
why do we have (un)boxing?
to make writing code where we mix primitives and their Object Oriented (OO) alternatives more comfortable/less verbose.
why do we have primitives and their OO alternatives?
primitive types are not classes (unlike in C#), thus they are not subclasses of Object and can not be overridden.
we have primitives like int for performance reasons, and the Object alternatives like Integer for the benefits of OO programming, and as a minor point, to have a good location for utility constants and methods (Integer.MAX_VALUE and Integer.toString(int)).
The OO benefits are visible most easily with Generics (List<Integer>), but are not limited to that, for example:
Number getMeSome(boolean wantInt) {
if (wantInt) {
return Integer.MAX_VALUE;
} else {
return Long.MAX_VALUE;
}
}
ArrayList does not support primitive types only support class. but we need to use primitive types e.g int, double etc.
ArrayList<String> strArrayList = new ArrayList<String>(); // is accepted.
ArrayList<int> intArrayList = new ArrayList<int>(); // not accepted.
The Integer class wraps a value of the primitive type int in an object.so bellow code is accepted.
ArrayList<Integer> intArrayList = new ArrayList<Integer>(); // is accepted.
we can add a value with add(value) method.
To add a String value say "Hello" in strArrayList code is just
strArrayList.add("Hello");
and add a int value say 54 we can write
intArrayList.add(54);
but when we write intArrayList.add(54); compiler convert to the following line
intArrayList.add(Integer.valueOf(54));
As intArrayList.add(54) is easy and more acceptable from user side so compiler does the hard job which is `intArrayList.add(Integer.valueOf(54)); it is autoBoxing.
Similarly to retrieve value we just type
intArrayList.get(0) and compiler convert to <code>intArrayList.get(0).intValue(); which is autoUnboxing.
Because they are different types, and as a convenience. Performance is likely the reason for having primitive types.
Autoboxing: Converting a primitive value into an object of the corresponding wrapper class.
Unboxing: Converting an object of a wrapper type to its corresponding primitive value
// Java program to illustrate the concept
// of Autoboxing and Unboxing
import java.io.*;
class GFG
{
public static void main (String[] args)
{
// creating an Integer Object
// with value 10.
Integer i = new Integer(10);
// unboxing the Object
int i1 = i;
System.out.println("Value of i: " + i);
System.out.println("Value of i1: " + i1);
//Autoboxing of char
Character gfg = 'a';
// Auto-unboxing of Character
char ch = gfg;
System.out.println("Value of ch: " + ch);
System.out.println("Value of gfg: " + gfg);
}
}
Another Special Case is,
Integer intval = null;
int toPrimitive = intval;
System.out.println(toPrimitive);
We are getting NullPointerException for above scenario. that means we can catch NPE

How is int implemented in Java?

According to the docs on Integer class:
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.
and the docs on int :
By default, the int data type is a 32-bit signed two's complement integer, which has a minimum value of -2^31 and a maximum value of 2^31-1.
also, according to this Answer:
In Java, every variable has a type declared in the source code. There are two kinds of types: reference types and primitive types. Reference types are references to objects. Primitive types directly contain values.
So, my question is : How is the int primitive type implemented in Java? Integer being a class can imagine creating its object. However again Integer class uses int. In what way is int implemented to java so that we are allowed to use it and allowed to perform all its arithmetic operations. An insight onto this would be much helpful.
I tried many existing answers and articles, however did not find an answer to my question, that include:
Primitive Data types
Class Integer
Java: Primitive Data types
Can an int be null in Java?
Primitive data type
PS:
If any part of my question is unclear/incorrect, kindly let me know in the comments section.
int and other primitive types are implemented directly by the Java compiler and the JVM. They are not classes. They are value types, not reference types.
The compiler emits byte codes like iload, iadd, and istore, with no method dispatch involved.
Integer is pretty much an ordinary class. Its instances are allocated on the heap. Each instance contains an int value.

Why do we use autoboxing and unboxing in Java?

Autoboxing is the automatic conversion that the Java compiler makes
between the primitive types and their corresponding object wrapper
classes. For example, converting an int to an Integer, a double to a
Double, and so on. If the conversion goes the other way, this is
called unboxing.
So why do we need it and why do we use autoboxing and unboxing in Java?
Some context is required to fully understand the main reason behind this.
Primitives versus classes
Primitive variables in Java contain values (an integer, a double-precision floating point binary number, etc). Because these values may have different lengths, the variables containing them may also have different lengths (consider float versus double).
On the other hand, class variables contain references to instances. References are typically implemented as pointers (or something very similar to pointers) in many languages. These things typically have the same size, regardless of the sizes of the instances they refer to (Object, String, Integer, etc).
This property of class variables makes the references they contain interchangeable (to an extent). This allows us to do what we call substitution: broadly speaking, to use an instance of a particular type as an instance of another, related type (use a String as an Object, for example).
Primitive variables aren't interchangeable in the same way, neither with each other, nor with Object. The most obvious reason for this (but not the only reason) is their size difference. This makes primitive types inconvenient in this respect, but we still need them in the language (for reasons that mainly boil down to performance).
Generics and type erasure
Generic types are types with one or more type parameters (the exact number is called generic arity). For example, the generic type definition List<T> has a type parameter T, which can be Object (producing a concrete type List<Object>), String (List<String>), Integer (List<Integer>) and so on.
Generic types are a lot more complicated than non-generic ones. When they were introduced to Java (after its initial release), in order to avoid making radical changes to the JVM and possibly breaking compatibility with older binaries, the creators of Java decided to implement generic types in the least invasive way: all concrete types of List<T> are, in fact, compiled to (the binary equivalent of) List<Object> (for other types, the bound may be something other than Object, but you get the point). Generic arity and type parameter information are lost in this process, which is why we call it type erasure.
Putting the two together
Now the problem is the combination of the above realities: if List<T> becomes List<Object> in all cases, then T must always be a type that can be directly assigned to Object. Anything else can't be allowed. Since, as we said before, int, float and double aren't interchangeable with Object, there can't be a List<int>, List<float> or List<double> (unless a significantly more complicated implementation of generics existed in the JVM).
But Java offers types like Integer, Float and Double which wrap these primitives in class instances, making them effectively substitutable as Object, thus allowing generic types to indirectly work with the primitives as well (because you can have List<Integer>, List<Float>, List<Double> and so on).
The process of creating an Integer from an int, a Float from a float and so on, is called boxing. The reverse is called unboxing. Because having to box primitives every time you want to use them as Object is inconvenient, there are cases where the language does this automatically - that's called autoboxing.
Auto Boxing is used to convert primitive data types to their wrapper class objects.
Wrapper class provide a wide range of function to be performed on the primitive types. The most common example is :
int a = 56;
Integer i = a; // Auto Boxing
It is needed because of programmers easy to be able to directly write code and JVM will take care of the Boxing and Unboxing.
Auto Boxing also comes in handy when we are working with java.util.Collection types. When we want to create a Collection of primitive types we cannot directly create a Collection of a primitive type , we can create Collection only of Objects. For Example :
ArrayList<int> al = new ArrayList<int>(); // not supported
ArrayList<Integer> al = new ArrayList<Integer>(); // supported
al.add(45); //auto Boxing
Wrapper Classes
Each of Java's 8 primitive type (byte,short,int,float,char,double,boolean,long) hava a seperate Wrapper class Associated with them. These Wrapper class have predefined methods for preforming useful operations on primitive data types.
Use of Wrapper Classes
String s = "45";
int a = Integer.parseInt(s); // sets the value of a to 45.
There are many useful functions that Wrapper classes provide. Check out the java docs here
Unboxing is opposite of Auto Boxing where we convert the wrapper class object back to its primitive type. This is done automatically by JVM so that we can use a the wrapper classes for certain operation and then convert them back to primitive types as primitives result int faster processing. For Example :
Integer s = 45;
int a = s; auto UnBoxing;
In case of Collections which work with objects only auto unboxing is used. Here's how :
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(45);
int a = al.get(0); // returns the object of Integer . Automatically Unboxed .
The primitive (non-object) types have there justification in efficiency.
The primitive types int, boolean, double are immediate data, whereas Objects are references. Hence fields (or variables)
int i;
double x;
Object s;
would need local memory 4+8+8? where for the object only the reference (address) to memory is stored.
Using the Object wrappers Integer, Double and others, one would introduce an indirection, reference to some Integer/Double instance in the heap memory.
Why boxing is needed?
That is a question of relative scope. In a future java it is planned to be able to have an ArrayList<int>, lifting primitive types.
Answer: For now an ArrayList only works for Object, reserving room for an object reference, and managing garbage collection likewise. Hence generic types are Object children.
So if one wanted an ArrayList of floating point values, one needed to wrap a double in a Double object.
Here Java differs from the traditional C++ with its templates: C++ classes vector<string>, vector<int> would create two compilation products. Java design went for having one ArrayList.class, not needing for every parameter type a new compiled product.
So without boxing to Object one would need to compile classes for every occurrence of a parameter type. In concreto: every collection or container class would need a version for Object, int, double, boolean. The version for Object would handle all child classes.
In fact, the need for such diversification already existed in Java SE for IntBuffer, CharBuffer, DoubleBuffer, ... which operate on int, char, double. It was solved in a hacky way by generating these sources from a common one.
Starting with JDK 5, java has added two important functions: autoboxing and autounboxing. AutoBoxing is the process for which a primitive type is automatically encapsulated in the equivalent wrapper whenever such an object is needed. You do not have to explicitly construct an object. Auto-unboxing is the process whereby the value of an encapsulated object is automatically extracted from a type wrapper when its value is required. You do not need to call a method such as intValue() or doubleValue().
The addition of autoboxing and auto-unboxing greatly simplifies writing algorithms, eliminating the bait manually boxing and unboxing of values. It is also helpful to avoid mistakes. It is also very important for generics, who only operate on objects. Lastly, autoboxing facilitates work with the Collections Framework.
Some data structures can accept only objects, no primitive types.
Example: the key in a HashMap.
See this question for more: HashMap and int as key
There are other good reasons, such as a "int" field in a database, which could be NULL as well.
An int in Java cannot be null ; an Integer reference can. Autoboxing and unboxing provide with a facility to avoid writing extraneous code in the conversions back and forth.
why do we have (un)boxing?
to make writing code where we mix primitives and their Object Oriented (OO) alternatives more comfortable/less verbose.
why do we have primitives and their OO alternatives?
primitive types are not classes (unlike in C#), thus they are not subclasses of Object and can not be overridden.
we have primitives like int for performance reasons, and the Object alternatives like Integer for the benefits of OO programming, and as a minor point, to have a good location for utility constants and methods (Integer.MAX_VALUE and Integer.toString(int)).
The OO benefits are visible most easily with Generics (List<Integer>), but are not limited to that, for example:
Number getMeSome(boolean wantInt) {
if (wantInt) {
return Integer.MAX_VALUE;
} else {
return Long.MAX_VALUE;
}
}
ArrayList does not support primitive types only support class. but we need to use primitive types e.g int, double etc.
ArrayList<String> strArrayList = new ArrayList<String>(); // is accepted.
ArrayList<int> intArrayList = new ArrayList<int>(); // not accepted.
The Integer class wraps a value of the primitive type int in an object.so bellow code is accepted.
ArrayList<Integer> intArrayList = new ArrayList<Integer>(); // is accepted.
we can add a value with add(value) method.
To add a String value say "Hello" in strArrayList code is just
strArrayList.add("Hello");
and add a int value say 54 we can write
intArrayList.add(54);
but when we write intArrayList.add(54); compiler convert to the following line
intArrayList.add(Integer.valueOf(54));
As intArrayList.add(54) is easy and more acceptable from user side so compiler does the hard job which is `intArrayList.add(Integer.valueOf(54)); it is autoBoxing.
Similarly to retrieve value we just type
intArrayList.get(0) and compiler convert to <code>intArrayList.get(0).intValue(); which is autoUnboxing.
Because they are different types, and as a convenience. Performance is likely the reason for having primitive types.
Autoboxing: Converting a primitive value into an object of the corresponding wrapper class.
Unboxing: Converting an object of a wrapper type to its corresponding primitive value
// Java program to illustrate the concept
// of Autoboxing and Unboxing
import java.io.*;
class GFG
{
public static void main (String[] args)
{
// creating an Integer Object
// with value 10.
Integer i = new Integer(10);
// unboxing the Object
int i1 = i;
System.out.println("Value of i: " + i);
System.out.println("Value of i1: " + i1);
//Autoboxing of char
Character gfg = 'a';
// Auto-unboxing of Character
char ch = gfg;
System.out.println("Value of ch: " + ch);
System.out.println("Value of gfg: " + gfg);
}
}
Another Special Case is,
Integer intval = null;
int toPrimitive = intval;
System.out.println(toPrimitive);
We are getting NullPointerException for above scenario. that means we can catch NPE

Can a primitive value be considered an object in java?

When I started out using Java, it was implied to me that we have two different types:
Objects (strings, from classes, println, etc)
primitive values (int, double, char)
I just got back an exam from a Professor where this difference would mean the difference between two choices as answers. When I asked my professor to clarify, he told me that primitive values can be objects.
Who is right here and can anyone give me any proof?
Proof would be something official sounding and I would choose that as the answer as well as awarding you some proverbial internets.
Primitives are not objects. Which is to say, an int is not an Integer.
However, with any vaguely-recent Java compiler, a primitive can be auto-boxed as an associated object type (int autoboxes as Integer) and auto-unboxed (Integer unboxes as int), and the instances of the object types related to primitives (Integer, Long, etc.) are immutable (which is important for behaving like their primitive counterparts), and so the distinction becomes blurry. That may have been what the professor was alluding to.
That is, a method (for instance) accepting an int can be given an Integer and the compiler just handles unboxing it; similarly, a method accepting an Object (maps come to mind) can accept a primitive, and the compiler boxes it into the corresponding object type.
Can a primitive value be considered an object?
The answer is No.
The JLS states
There are two kinds of types in the Java programming language: primitive types (§4.2) and reference types (§4.3). There are, correspondingly, two kinds of data values that can be stored in variables, passed as arguments, returned by methods, and operated on: primitive values (§4.2) and reference values (§4.3).
Those are Primitive Types and Values which are
predefined by the Java programming language and named by its reserved keyword
and Reference Types and Values which can be one of
class types (§8), interface types (§9), type variables (§4.4), and array types (§10).
Note also that there is a special type which is the null type and its corresponding value the null reference
There is also a special null type, the type of the expression null (§3.10.7, §15.8.1), which has no name.
...
The null reference is the only possible value of an expression of null type.
For the primitive types the JLS has defined a mechanism called Boxing Conversion for converting them into the corresponding reference types.
Boxing conversion converts expressions of primitive type to corresponding expressions of reference type.
So since there is the need for a conversion to go from a primitive type to a corresponding reference type one cannot say that primitives can be considered as objects and vice versa. But one can say they are convertible.
There is an implicit mapping between primitives and objects, so an int can be used where an Integer is expected. It is a feature called autoboxing.
For example:
Integer foo = 4; // 4 is really an int
Also, primitives have things in common with objects. They have a Class, such as int.class.
It should also be noted that all arrays are objects.
However, the notion of Object vs primitive is one of the worst thing there is in Java. A lot of modern languages simply don't make too much difference between them, or even don't have any primitives. (In java as well, you can do everything without ever using explicitly a primitive).
ONE LINE, QUOTING THE SPEC!!!!
https://docs.oracle.com/javase/specs/jls/se8/jls8.pdf
An object is a class instance or an array.
Conclusion:
value/primitive types are __NOT__ objects.
reference/class types are objects.
Also, all objects extend class object.
And the instanceof operator does not work with value types:
int a; //:<-- int is [value/primitive] type version
//: of Integer [reference/class] type.
if( a instanceof Object ){ ... } //:<-- SYNTAX ERROR

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)
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>
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.
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.
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.
Object has state and behavior
state means fields (variables)
ex: bicycle (current speed, current gear)
behavior means methods to change that fields
ex: changing current speed using methods
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

Categories

Resources