what is the alternative to autoboxing in Java? - java

As any Java programmer knows, you can’t put an int (or other primitive value) into a collection. Collections can only hold object references, so you have to box primitive values into the appropriate wrapper class (which is Integer in the case of int). When you take the object out of the collection, you get the Integer that you put in; if you need an int, you must unbox the Integer using the intValue method. All of this boxing and unboxing is a pain, and clutters up your code. The autoboxing and unboxing feature automates the process, eliminating the pain and the clutter.
Are there other ways to convert primitive types to non-primitive analogs?

No need of intValue() at all:
List<Integer> list = new ArrayList();
list.add(3);
list.add(new Integer(70));
int x = list.get(0) + 600;
if (x > 800) {
x = new Integer(80);
}
(but there can be some pitfalls ...)

Not sure why you want to go away from autoboxing and unboxing features. But this is how it looks like without using those.
int number = 5;
Integer num = new Integer(number);

I think you are looking for a List alternative that actually holds primitive data types instead of knowing that you can avoid intValue calls (it seems like you already know this near the end of your question's text).
In the Java Class Library there is no List implementation that store primitive data types directly but third party libraries essentially do support this, for example Apache Commons' ArrayIntList.
The good news is that it's planned to allow for primitive types to be used as generic type arguments for Java 10. However Java 10 will arrive sometime around 2018.

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

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

Using int vs Integer

I came across a class using Integer variables to capture size to be used in a for loop. Is this good practice or should we use the int primitive data type?
Integer size = something.getFields().size();
for (Integer j = 0; j < size - 1; ++j)
the Integer class is provided so that values can be boxed/unboxed in a pure OO manner. use int where appropriate unless you specifically need to use it in an OO way; in which case Integer is appropriate.
Java Int vs Integer
However, very different things are going on under the covers here. An int is a number; an > Integer is a pointer that can reference an object that contains a number.
...
An int is not an object and cannot passed to any method that requires
objects. A common case is in using the provided collection classes (
List , Map , Set ) - though it is possible to write versions of these
classes that provide similar capabilities to the object versions. The
wrapper classes ( Integer , Double , etc) are frequently required
whenever introspection is used (such as in the reflection API).
A better description of when to use one vs. the other:
Choosing between int and Integer
I'll start with how these types should be used before going into
detail on why.
Prefer int for performance reasons
Methods that take objects (including generic types like List<T>)
will implicitly require the use of Integer
Use of Integer is relatively cheap for low values (-128 to
because of interning - use Integer.valueOf(int) and not new
Integer(int)
Do not use == or != with Integer types
Consider using Integer when you need to represent the
absence of a value (null)
Beware unboxing Integer values to int with null values
If you can use int do so. If the value can be null or is used as an Object e.g. Generics, use Integer
Usually it doesn't matter which one you use but often int performs slightly better.
This approach is not good in practice, use int whenever possible. Usage of Integer indicates that this particular variable can be null (or it was inside a collection, damn generics...) - which is not the case.
Also using Integer introduces an extra overhead of boxing and unboxing.
This is a potential disaster waiting to happen in large projects. The coder here forgot that each Integer is actually a new object, and, to use it as an int, there has to be boxing and unboxing all the time. Not only is it inefficient, it's also not going to run as expected. You are best advised to always use int where possible, and only use Integer for placing these values into lists, containers or for database storage. Remember, comparing Objects using >, < and == means something else than when you are using the same operators to compare primitives.
Promote primitive types always where it is possible.
primitive types can not be used as GenericArgument or a null.
Dont use it only to loop. Use the primitive type int (better performance), which is not the same as the Class 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.
So, use Integer if you need to call the Integer functions or need to assign a null value to it.
You will also need to use Integer instead of int for generics like List
When there is a need of using objects, you have to use the Wrapper classes,
like Integer, Double, Float, etc...
eg:
int n = Integer.parseInt("10");
Here we are converting the string to an integer (Primitive type) ,
but method parseInt(String str) works only on Wrapper classes (ie Object),
so we used it... you will find many more use of it in java.
There can be a performance penalty due to boxing and unboxing, as you incur the overhead of converting between a primitive and a reference type.
However, the Integer class adds additional methods that can be very useful.
You can't use == or != with Integer types as it'll compare their "pointer location".
In order for auto-unboxing to kick off, at least one of the elements must be int.
If you are comparing Integer1 == Integer2, what actually happens is that Object.equals gets called as in: Integer1.equals(Integer2) which (unless overridden) compares the references.
(This is meant to be a reply to #Muhammad Shahab but I cannot add comments yet)
I normally use Integer because of purely OO. Performance of int is definitely far better than its object counterpart but it is noticeable only when you are looping millions time in the loop.
IMHO, If performance is paramount importance in you application and you want to squeeze even single nano second then use int without any brain. But if OO and readability is main concerned then use Integer.

What is the difference between Integer and int in 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")).

using new(Integer) versus an int

In my Java class, the professor uses something like:
integerBox.add(new Integer(10));
Is this the same as just doing:
integerBox.add(10);
?
I've googled a bit but can't find out one way or the other, and the prof was vague.
The closest explanation I can find is this:
An int is a number; an Integer is a pointer that can reference an
object that contains a number.
Basically, Java collection classes like Vector, ArrayList, HashMap, etc. don't take primitive types, like int.
In the olden days (pre-Java 5), you could not do this:
List myList = new ArrayList();
myList.add(10);
You would have to do this:
List myList = new ArrayList();
myList.add(new Integer(10));
This is because 10 is just an int by itself. Integer is a class, that wraps the int primitive, and making a new Integer() means you're really making an object of type Integer. Before autoboxing came around, you could not mix Integer and int like you do here.
So the takeaway is:
integerBox.add(10) and integerBox.add(new Integer(10)) will result in an Integer being added to integerBox, but that's only because integerBox.add(10) transparently creates the Integer for you. Both ways may not necessarily create the Integer the same way, as one is explicitly being created with new Integer, whereas autoboxing will use Integer.valueOf(). I am going by the assumption the tutorial makes that integerBox is some type of collection (which takes objects, and not primitives).
But in this light:
int myInt = 10;
Integer myInteger = new Integer(10);
One is a primitive, the other is an object of type Integer.
integerBox.add(10);
is equivalent to
integerBox.add(Integer.valueOf(10));
So it may return the cached Integer instance.
Read Java Specialist 191 for various way of setting autoboxing cache size.
See also: cache options
In this case, yes. I'm assuming that integerBox is a collection of objects - you can only store objects within integerBox. This means that you cannot have a primitive value, such as an int, within the collection.
After Java 5 was released, however, there came about something called autoboxing. Autoboxing is the process of automatically converting a primitive value to an object. This is done through one of the wrapper classes - Integer, Double, Character, etc (all named with a capital letter and a name pertaining to the primitive value that they represent).
When you added int 10 to the collection(ArrayList, most likely), the Java VIrtual Machine transformed it into an object of type Integer behind the scenes.

Categories

Resources