int or Integer in java [duplicate] - java

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

Related

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

primitives vs wrapper class initialization

What is the Difference between declaring int's as Below. What are the cases which suits the usage of different Types
int i = 20;
Integer i = 20;
Integer i = new Integer(20);
Please Note : I have goggled and found that first is going to create primitive int.Second is going to carry out auto boxing and Third is going to create reference in memory.
I am looking for a Scenario which clearly explains when should I use first, second and third kind of integer initialization.Does interchanging the usage is going to have any performance hits
Thanks for Reply.
The initialization in the 1st case is a simple assignment of a constant value. Nothing interesting... except that this is a primitive value that is being assigned, and primitive values don't have "identity"; i.e. all "copies" of the int value 20 are the same.
The 2nd and 3rd cases are a bit more interesting. The 2nd form is using "boxing", and is actually equivalent to this:
Integer i = Integer.valueOf(20);
The valueOf method may create a new object, or it may return a reference to an object that existed previously. (In fact, the JLS guarantees that valueOf will cache the Integer values for numbers in the range -128..+127 ...)
By contrast new Integer(20) always creates a new object.
This issue with new object (or not) is important if you are in the habit of comparing Integer wrapper objects (or similar) using ==. In one case == may be true if you compare two instances of "20". In the other case, it is guaranteed to be false.
The lesson: use .equals(...) to compare wrapper types not ==.
On the question of which to use:
If i is int, use the first form.
If i is Integer, the second form is best ... unless you need an object that is != to other instances. Boxing (or explicitly calling valueOf) reduces the amount of object allocation for small values, and is a worthwhile optimization.
Primitives will take default values when declared without assignment.
But wrapper classes are reference types, so without assignment they will be null. This may cause a NullPointerException to be thrown if used without assignment.
One such scenario I can think of is when you are mapping DB types in Hibernate. If you use Integer you can check for null (assuming the column allows null values). If you use primitive and if the value is null in the database, I guess it throws an error.

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.

Why can Integer and int be used interchangably?

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.

Object type in java

I learnt that Java is not a 100% OOP language and that this is because of data types which are not objects. But according to me, int is of type Integer and Integer belongs to Number and Number belongs to Object. So java is a 100% OOP language. Am I correct?
No, int and Integer are different. Integer is a regular class, which as you know is a subclass of Number which itself is a subclass of Object. But int is a primitive type. It is not a class, so obviously not a subclass of anything; it has no methods or attributes, and generally there is nothing you can do with int itself, except declare variables of that type, e.g.
int x = 3;
Since int is not a class, the values of int variables are not objects. They have no methods or attributes or properties, and there's not much you can do with them except certain mathematical operations which are handled specially by the compiler.
Note that the Java compiler (recent versions) will automatically insert code to convert an int into an Integer, or vice-versa, where necessary. So it might look like they're the same thing when you write your program, but they are actually not. For instance, if you write
Integer y = 5;
javac translates that into
Integer y = Integer.valueOf(5);
Or
Map<Integer,Integer> m = ...;
m.put(4, 8);
int z = m.get(4);
becomes
Map<Integer,Integer> m = ...;
m.put(Integer.valueOf(4), Integer.valueOf(8));
int z = m.get(Integer.valueOf(4)).intValue();
To add to the previous answers (which I think may have missed the point a little) - yes, int and Integer are two completely different (but related) concepts - one is a primitive, the other an equivalent class. More importantly however, that distinction has absolutely no bearing whatsoever on whether Java is an object-oriented language.
Every single Java program uses objects at some point (even if it is just the String[] args parameter to your main method). As such, Java is unequivocally an object-oriented language, simply because it relies on classes as a primary means of program development. The fact that it supports non-object primative types has nothing to do with that at all.
int is not an object of the class Integer. In Java, not all the data types are objects.

Categories

Resources