Why can Integer and int be used interchangably? - java

I am confused as to why Integer and int can be used interchangeably in Java even though one is a primitive type and the other is an object?
For example:
Integer b = 42;
int a = b;
Or
int d = 12;
Integer c = d;

The first few sentences of the posted article describe it pretty well:
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.
That is basically it in a nutshell. It allows you take advantage of the Collections Framework for primatives without having to do the work yourself.
The primary disadvantage is that it confuses new programmers, and can lead to messy/confusing code if it's not understood and used correctly.

Java supports autoboxing and automatically wraps primitive values into objects and unwraps objects to primitive values for certain types, like char - Character, int - Integer, double - Double, etc.
Note from Oracle Documentation:
So when should you use autoboxing and unboxing? Use them only when there is an “impedance mismatch” between reference types and primitives, for example, when you have to put numerical values into a collection. It is not appropriate to use autoboxing and unboxing for scientific computing, or other performance-sensitive numerical code. An Integer is not a substitute for an int; autoboxing and unboxing blur the distinction between primitive types and reference types, but they do not eliminate it.

Because of autoboxing and autounboxing http://download.oracle.com/javase/1.5.0/docs/guide/language/autoboxing.html

Using an int and an Integer "interchangeably" is called autoboxing. This feature was introduced in Java 5. Before that, your example code wouldn't have compiled. Instead, you would have to write something like this:
Integer b = Integer.valueOf(42); // or new Integer(42);
int a = b.intValue();
or
int d = 12;
Integer c = Integer.valueOf(d); // or new Integer(d);
That's fairly verbose, which is why autoboxing was introduced. It's a bit of compiler magic to make life easier for the coder.
Technically, int and Integer themselves are not interchangeable and one cannot be used where the other is required. However, autoboxing allows implicit conversion between the two.
As a side note, there is one case where autoboxing (specifically unboxing) fails. If your code tries to autounbox a null value, you will get a NullPointerException at runtime, e.g.:
Integer b = null;
int a = b; // NullPointerException here!
Just something to be aware of...

It's called AutoBoxing. That will explain exactly what it is.

In addition to other answers, because Integer is a wrapper class, that lets you box and unbox an int value. Other info here.

The java language specification states that the java virtual machine must perform automatic boxing/unboxing for integers and a few other types.

Related

int or Integer in java [duplicate]

This question already has answers here:
What is the difference between an int and an Integer in Java and C#?
(26 answers)
Closed 2 years ago.
I have seen many times in code that people use int or Integer to declare variable in beans. I know int is datatype and Integer is wrapper class.
My question is, in which condition int or Integer should be used and is there any advantage of either of them over another?
My question is, in which condition int or Integer should be used and is there any advantage of either of them over another?
Well, you should use the reference type Integer whenever you have to. Integer is nothing more than a boxed int. An Object with a single field containing the specified int value.
Consider this example
public class Ex {
int field1;
Integer field2;
public Ex(){}
}
In this case field1 will be initialized with the value 0 while field2 will be initialized with null. Depending on what the fields represent, both approaches might be advantageous. If field1 represents some kind of UUID, would you want it to be initialized with a zero value?
I wouldn't worry too much about the performance implications of Autoboxing. You can still optimize after you get your code running.
For more information take a look at the documentation
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Integer.html
You always use int, pretty much.
Integer should rarely be used; it is an intermediate type that the compiler takes care of for you. The one place where Integer is likely to appear is in generics, as int is simply not legal there. Here is an example:
List<Integer> indices = new ArrayList<Integer>();
int v = 10;
indices.add(v);
The above works: It compiles with no errors and does what you think it would (it adds '10' to a list of integer values).
Note that v is of type int, not Integer. That's the correct usage; you could write Integer here and the code works as well, but it wouldn't be particularly idiomatic java. Integer has no advantages over int, only disadvantages; the only time you'd use it, is if int is straight up illegal. Which is why I wrote List<Integer> and not List<int> as the latter is not legal java code (yet - give it a few versions and it may well be legal then, see Project Valhalla).
Note also that the compiler is silently converting your v here; if you look at the compiled code it is as if javac compiled indices.add(Integer.valueOf(v)) here. But that's fine, let the compiler do its thing. As a rule what the compiler emits and what hotspot optimizes are aligned; trust that what javac emits will be relatively efficient given the situation.
int is a primitive type, a value type for number literals.
it is used whenever and wherever you just want to do some basic arithmetical operation;
it is a value type, so it's stored in the Stack area of the memory, hence operations on it are much faster;
whenever it's needed, compiler implicitly and automatically casts back and forth (a.k.a Boxing and Unboxing) from int to Integer and vice versa;
Integer is a Class, which is a reference type and you instantiate an Object of that type.
you create an object of that class, which means, that you also have some methods and operations on that object;
any time you do some arithmetic operation on the instance of Integer, under the hood, it's still implemented by int primitives, and it's just wrapped into box/container;
it is a reference type / object, which is very important, as you can Serialize or Deserialize it;
it also has some very useful utility factory methods, like Integer.valueOf(..) for example, to parse the String as an integer;
it can be well used into declarations of the generic types and it, as a class, supports the hierarchy as well. For instance, it extends Number, and you can make use of this;
it is stored in the Heap area of the memory.
int is a primitive and Integer is an object .
From an memory footprint point of view , primitive consume less memory than object and also primitives are immutable (since they use pass by value ) .
Here is a good article on when to use what :
https://www.baeldung.com/java-primitives-vs-objects

Unboxing Long in java

In some code I see this:
private void compute(Long a, Long b, Long c) {
long result = a-(b+c);
...
It seems a bit strange that the result is stored in a primitive long instead of a Long object corresponding to its operands.
Are there any reason that a result should be stored as a primitive?
It seems a bit strange that the result is stored in a primitive long instead of a Long object corresponding to its operands.
No, what is "strange" is that you can use the + and - operators on Long objects. Before Java 5, this would have been a syntax error. Then autoboxing/unboxing was introduced. What you're seeing in this code is autounboxing: the operators require primtives, so the compiler automatically inserts a call to longValue() on the objects. The arithmetic is then performed on primitive long values, and the result is also a long that can be stored without further conversion on the variable.
As for why the code does this, the real question is why someone would use the Long type instead of long. Possible reasons:
The values come from some library/API that delivers Long values.
The values are stored in collections (List, Map), which cannot hold primitives.
Sloppiness or cargo cult programming.
The ability to have null values is required, e.g. to signal unavailable or uninitialized data.
Note that the ability of Long to hold null values means that the calculation (or more specifically, the longValue() calls inserted by the compiler) can fail with a NullPointerException - a possibility the code should deal with somehow.
The reason is obvious: result is declared as primitive.
The arithmetic operators + and - are not defined for boxed types (e.g. Long) but for primitive types (e.g. long).
The result is also a long. See Autoboxing and Unboxing tutorial
Autoboxing this into a Long would result in a small performance cost. It is also unnecessary because
We know it will be non-null (if a, b or c were null, a NullPointerException would occur).
It would be autoboxed implicitly if we use it later where a Long is required.
Based on your needs.I mean the decelaration.
Autoboxing and unboxing can happen anywhere where an object is expected and primitive type is available
Usually you should prefer using primitives, especially if you are certain they cannot be null. If you insist on using the boxed types always think extra hard about what happens when it is null.
Java will do the boxing and unboxing automatically for you, but staring at an int and wondering why you got a NullPointerException can be fun.
From Java 1.5 onwards, autoboxing and unboxing occurs implicitly whenever needed.
The following line:
long result = a-(b+c);
...asks Java to take the result of the expression using 3 Longs, and then store it in a primitive long. Before Java 5, it would complain about the types not matching - but these days it just assumes you mean what you say and automatically does the conversion from object to primitive type for you.
In this example however, unless there's some other good reason not presented here, there's absolutely no point having the parameters as the boxed, object type in the first place.
As per the javadoc
Boxing conversion converts expressions of primitive
type to corresponding expressions of reference type.
Specifically, the following nine conversions are called the boxing conversions:
From type boolean to type Boolean
From type byte to type Byte
From type short to type Short
From type char to type Character
From type int to type Integer
From type long to type Long
From type float to type Float
From type double to type Double
From the null type to the null type
Ideally, boxing a given primitive value p, would always yield an identical reference.
In practice, this may not be feasible using existing implementation techniques. The
rules above are a pragmatic compromise. The final clause above requires that certain
common values always be boxed into indistinguishable objects. The implementation may
cache these, lazily or eagerly. For other values, this formulation disallows any
assumptions about the identity of the boxed values on the programmer's part. This would
allow (but not require) sharing of some or all of these references.
This ensures that in most common cases, the behavior will be the desired one, without
imposing an undue performance penalty, especially on small devices. Less memory-limited
implementations might, for example, cache all char and short values, as well as int and
long values in the range of -32K to +32K.`
Here is the Oracle Doc source
The answer for your doubt is
autoboxing and autounboxing in Java which converts from primitive to wrapper class objects and vice versa respectively.
autoboxing means internally compiler uses valueOf() method of primitive classes ans autounboxing means internally compiler uses xxxValue() method.
Suppose for
private void compute(Long a, Long b, Long c) {
long result = a-(b+c);
its makes this conversion a.longValue()-(b.longValue()+c.longValue())
Which means even before your statement performs addition the compiler provides the primitives of long type as input to your operands
Remember that this goes in hand as JAVA is statically and strongly typed language.
Hence you get long type output
I hope i cleared your doubt

Conversions of strings to Integer and to int

Given that String s has been declared, the following 5 lines of code produce the same result:
int i = Integer.valueOf(s);
int y = Integer.parseInt(s);
int j = Integer.valueOf(s).intValue();
Integer x = Integer.valueOf(s);
Integer k = Integer.valueOf(s).intValue();
Are there circumstances where each one would be the preferred code? It appears that int and Integer are interchangeable and that .intValue() is not needed.
If you require an int, use parseInt(), if you require an Integer use valueOf(). Although they're (sort of) interchangeable now, it still makes more sense to use the one that directly returns the data type that you require. (Historically, they weren't interchangeable at all, this was introduced with auto-boxing and unboxing in Java 5.)
The intValue() method you're using is just converting the Integer class type to the int primitive, so using that and valueOf() is the worst possible combination, you never want to use that. (Nothing bad will happen, it's just longer to read, performs slightly worse and is generally more superfluous.)
If you don't care or don't know, then I'd use parseInt(). Especially as a beginner, it's more common that you want the primitive type rather than the class type.
int and Integer are made to look interchangeable by the magic of auto-boxing and auto-unboxing: In many cases where you need one but have the other, the compiler automagically inserts the necessary code to convert them.
This is useful, but if you know about it, you can avoid it in many places which results in slightly faster code (because there's less conversion to do).
Integer.parseInt() returns an int, so you should use it if you need an int
Integer.valueOf() returns an Integer, so you should use it if you need an Integer
Integer.valueOf().intValue() first creates an Integer and then extracts the int value from it. There's no good reason to use this instead of a simple Integer.parseInt().
The decision between int and Integer is easy to do as well:
generally you'd want to use the primitive type (int), if possible
if you need an Object (for example, if you want to put your number in a Collection), then you need to use the wrapper type (Integer), as the primitive type can't be used here.
int and Integer are not interchangeable.Because of Autoboxing feature fron java 5 onwards, int to Integer conversion is taken care by jvm itself.But we should not use Integer class unnecessarily.Primitive data types are always faster.Wrapper classes should be used only required.

How come primitives can skip "new Object" instantiation in Java?

For example if you have an integer:
int i = 9;
How can it do that? I mean the full syntax is:
int i = new Integer(9);
How does it skip the whole new Integer() part and still work?
Thanks.
It doesn't skip it, because primitives aren't objects.
Your second line of code involves auto-unboxing, which was a later addition to the Java language.
new Integer() is not a primitive; it's a boxed primitive.
Actual primitives (int, etc) are not objects and cannot be instantiated.
Note that you can also write Integer x = 9, and the Java compiler will implicitly insert new Integer().
This is called auto-boxing.
Maybe you wanna have a look into AutoBoxing
Primitive : Reference Mapping
byte : Byte
short : Short
int : Integer
long : Long
float : Float
double : Double
bool : Boolean
char : Character
Autoboxing / unboxing is the automated under the covers conversion
between primitive types and their equivalent object types. For
example, the conversion between an int primitive and an Integer object
or between a boolean primitive and a Boolean object. This was
introduced in Java 5.
Primitives and object are two different things. Without primitive you wouldn't be able to create Integer object like new Integer(9) (Integer uses primitive 9 inside constructor).
Your question would have made a lot more sense if it asked why
Integer i = 9;
works without new and then the answer would be "due to auto-boxing of primitives introduced in Java 5". So maybe that's what you really wanted to ask :)

int does not override Integer in Java

I had a function in Java with method signature
public void myMethod (int someInt, String someString)
in my abstract class and I had over-ridden it with method
public void myMethod (Integer someInt, String someString)
The over ride does not work. Is this an inconsistency ? I thought auto-boxing applied to method signature over-ride as well.
int and Integer are two different types. Autoboxing blurs the distinction at the source code level for the convenience of programmers, but does not change the fact that they are in fact two very different types.
As such, you can not #Override a method that takes an int with one that takes an Integer and vice versa.
Note that you should probably think twice before declaring a method to take an Integer instead of an int. Here's an excerpt from Effective Java 2nd Edition, Item 49: Prefer primitives to boxed primitives:
In summary, use primitives in preference to boxed primitive whenever you have the choice. Primitive types are simpler and faster. If you must use boxed primitives, be careful! Autoboxing reduces the verbosity, but not the danger, of using boxed primitives. When your program compares two boxed primitives with the == operator, it does an identity comparison, which is almost certainly not what you want. When your program does mixed-type computations involving boxed and unboxed primitives, it does unboxing, and when your program does unboxing, it can throw NullPointerException. Finally, when your program boxes primitive values, it can result in costly and unnecessary object creations.
There are places where you have no choice but to use boxed primitives, e.g. generics, but otherwise you should seriously consider if a decision to use boxed primitives is justified.
See also
Java Language Guide/Autoboxing
Related questions
What is the difference between an int and an Integer in Java/C#?
Is it guaranteed that new Integer(i) == i in Java? (YES!!! The box is unboxed, not other way around!)
Why does int num = Integer.getInteger("123") throw NullPointerException? (!!!)
Why null == 0 throws NullPointerException in Java?
No, these two signatures define two different methods.
They are absolutely not overridden but overload since the parameters are different. And JVM will choose the method to launch base on this:
widen - boxing - var args...
For example, you have three methods
void add(long n) {} // call this method 1
void add(int... n) {} // call this method 2
void add(Integer n) {} // call this method 3
and when you invoke:
int a = 5;
add(a);
the method 1 will be invoked.
The reason the override doesn't work is because Integerand int are two different things. Integer is an object, whereas int is a primitive type. Java does the implicit typecasting for you. For example:
int myInteger = new Integer(5);
Will create a primitive int type called myInteger with a value of 5. As the Javadoc says,
"The Integer class wraps a value of
the primitive type int in an
object."
You are correct that this scenario will not work because Java provides the functionality of the autoboxing, so at runtime JVM can not decide which method to call because it can call both method as both method fits for the argument type. So I think it will give an error or will choose either method randomly..... Just run it and see.....
int and Integer are two different types in JAVA.Although autoboxing specifies the distinction at the source code level, but does not change the eternal fact that they are in fact two very different types.

Categories

Resources