What is .intValue() in Java? - java

What is the difference between them?
l is an arraylist of Integer type.
version 1:
int[] a = new int[l.size()];
for (int i = 0; i < l.size(); i++) {
a[i] = l.get(i);
}
return a;
version 2:
int[] a = new int[l.size()];
for (int i = 0; i < l.size(); i++) {
a[i] = l.get(i).intValue();
}
return a;

l.get(i); will return Integer and then calling intValue(); on it will return the integer as type int.
Converting an int to Integer is called boxing.
Converting an Integer to int is called unboxing
And so on for conversion between other primitive types and their corresponding Wrapper classes.
Since java 5, it will automatically do the required conversions for you(autoboxing), so there is no difference in your examples if you are working with Java 5 or later. The only thing you have to look after is if an Integer is null, and you directly assign it to int then it will throw NullPointerException.
Prior to java 5, the programmer himself had to do boxing/unboxing.

As you noticed, intValue is not of much use when you already know you have an Integer. However, this method is not declared in Integer, but in the general Number class. In a situation where all you know is that you have some Number, you'll realize the utility of that method.

The Object returned by l.get(i) is an instance of the Integer class.
intValue() is a instance method of the Integer class that returns a primitive int.
See Java reference doc...
http://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html#intValue()

Java support two types of structures first are primitives, second are Objects.
Method that you are asking, is used to retrieve value from Object to primitive.
All java types that represent number extend class Number. This methods are in someway deprecated if you use same primitive and object type since [autoboxing] was implemented in Java 1.5.
int - primitive
Integer - object
Before Java 1.5 we was force to write
int i = integer.intValue();
since Java 1.5 we can write
int i = integer;
Those methods are also used when we need to change our type from Integer to long
long l = integer.longValue();

Consider this example:
Integer i = new Integer(10);
Integer j = new Integer(10);
if (!(i == j)) {
System.out.println("Surprise, doesn't match!");
}
if (i.intValue() == j.intValue()) {
System.out.println("Cool, matches now!");
}
which prints
Surprise, doesn't match!
Cool, matches now!
That proves that intValue() is of great relevance. More so because Java does not allow to store primitive types directly into the containers, and very often we need to compare the values stored in them. For example:
oneStack.peek() == anotherStack.peek()
doesn't work the way we usually expects it to work, while the below statement does the job, much like a workaround:
oneStack.peek().intValue() == anotherStack.peek().intValue()

get(i) will return Integer object and will get its value when you call intValue().In first case, automatically auto-unboxing happens.

They are exactly the same. As other posters have mentioned, you can put either the Integer object or the int primitive into the array. In the first case, the compiler will automatically convert the Integer object into a primitive. This is called auto-boxing.

It's just a convenience method for getting primitive value from object of Number: http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Number.html
Consider the code:
Integer integerValue = Integer.valueOf(123);
float floatValue = integerValue.floatValue();
The last line is a convenient method to do:
float floatValue = (float)(int)integerValue;
Since any numeric type in Java can be explicitly cast to any other primitive numeric type, Number class implements all these conversions. As usual, some of them don't make much sense:
Integer integerValue = Integer.valueOf(123);
int intValue = integerValue.intValue();
int intValue2 = (int)integerValue;
int intValue3 = integerValue;

Related

Java generics input type vs returned type

I'm learning about generics and am slightly confused.
I'm confused about the difference between the input type and returned type for a class using generics.
Stack<Integer> even = new Stack<>();
// pushing values in stack
even.push(0);
even.push(2);
System.out.println(even.pop().getClass().getSimpleName());
System.out.println("pop => " + even.pop());
We are pushing in an int value of 0 and 2.
But the first print statement will print "Integer".
If the stack is declared with Integer as its generic type, why are we able to push in a primitive "int"?
If we can push in a primitive "int" why is the pop() class returning a wrapper class "Integer"?
I'm clearly misunderstanding something about generics.
It happens because of someting called autoboxing.
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.
The simplest example:
Character ch = 'a';
That is what happens here:
List<Integer> li = new ArrayList<>();
for (int i = 1; i < 50; i += 2)
li.add(i);
The compiler creates an Integer object from i and adds the object to the list.
List<Integer> li = new ArrayList<>();
for (int i = 1; i < 50; i += 2)
li.add(Integer.valueOf(i));
The same thing for you stack.
You cannot have a generics declared as primitive types, because they are not classes. They are other thing (primitive types, of course). Instead, you use the corresponding wrapper class.
When you do the push(int), there is an implicit cast to the wrapper class Integer via the Integer#valueOf(int) method.
stack.push(0);
Is transformed, by the compiler and without asking into this
stack.push(Integer.valueOf(0))
For the same reason, you can do something like this
Integer n = 3;
And get no errors.

Directly casting primitive type to object is fine in Java?

I am directly casting my int primitive type variable to Integer object like below:
int intValue = 0;
Integer value = (Integer) intValue;
Is this fine or will cause some unexpected problems?
Autoboxing is the automatic conversion that the Java compiler makes
between the primitive types and their corresponding object wrapper
classes.
int intValue = 0;
Integer value = intValue; // by Autoboxing
you can also convert it using valueOf method of wrapper class
Integer value = Integer.valueOf(intValue)
Check What code does the compiler generate for autoboxing? if you still have doubts.

ArrayList storing other than specified datatypes

I have an ArrayList with type Long,but i am trying to insert int value in it.I am expecting int should also be stored in ArrayList as int is smaller in size than long.
int i=1;
ArrayList<Long> obj=new ArrayList<Long>();
obj.add(i);//It is showing error that Storing int is not possible
Whereas the below one is possible
List item
long l=0;
int i=5;
l=i;
Please suggest the reason why ArrayList can't store lower value types.
This:
ArrayList<Long> obj=new ArrayList<Long>();
is declaring that the list will store objects of type Long. It's storing references, and you can't put an Integer in, since an Integer is-not a Long (from the point of view of an object hierachy)
Don't think of the issue in term of numbers. Instead, try this. You have a list of Cats. You can't store a Dog in there. But you could if the list was declared as a list of Animals.
You could declare the list to contain a Number (Longs and Integers are both Numbers), but the fundamental issue is why are you mixing integers and longs in this collection ?
You are doing this:
Long l = 0L;
int i = 5;
l=i;//Type mismatch: cannot convert from int to Long
not this:
long l = 0;
int i = 5;
l = i;
It is not an ArrayList matter, look at this for details.
You just need to cast it to a long to make the above code work:
obj.add((long)i);
Because you specified that the ArrayList contains "Long", it forces all objects that go into it to be Long. And since ArrayList can be used to store any type of data, not just numbers, it doesn't have built-in mechanisms to convert ints to longs for example. Different rules apply.
Java primitives, like int and long, allow automatic conversion to comply with the way that C and C++ work, since Java was based on these languages originally. But it doesn't lead to the cleanest/safest code, and so some other more modern languages have removed even this type of fuziness.
The long variable l also can't store lower value types. The assignment of i to l will implicitly do a Widening Primitive Conversion, and the value is stored as a long.
When you try to insert an int value into a List<Long>, you're implicitly trying to do two conversions:
Widening Primitive Conversion (int to long)
Boxing Conversion (long to Long)
That double conversion will not be applied implicitly, so you have to tell the compiler to do it, by forcing the widening primitive conversion using a cast:
obj.add((long)i);
You have declared obj to be a list of Long and thus it restricts you to use add
/**
* Appends the specified element to the end of this list.
*
* #param e element to be appended to this list
* #return <tt>true</tt> (as specified by {#link Collection#add})
*/
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
Note - where E is from the class definition ArrayList<E> extends AbstractList<E>
to primarily add only the type that your list should be consisting of. Hence changing the code as follows should work :
int i=1;
ArrayList<Long> obj=new ArrayList<Long>();
obj.add(Long.valueOf(i));
Also in your latter part the cast is taken care by the = operator as you assign it in following way :
l=i;
An ArrayList<Long> can only store instances of Long.
You can "apparently" store longs in it, because the long is autoboxed to a Long:
list.add(someLong)
gets compiled to
list.add(Long.valueOf(someLong))
Boxing conversion only applies from primitive to corresponding wrapper type: long to Long, int to Integer etc. It doesn't box an int to a Long, however. The compiler isn't that smart/lenient.
And Java doesn't widen an Integer to a Long, because widening isn't defined for those types: it's only defined for primitive numeric types.
You've just got to make the parameter a long, then it can autobox for you:
obj.add((long) i);
or, without autoboxing:
obj.add(Long.valueOf(i));
Note, in the latter case, int is an acceptable parameter for a method taking a long parameter because of widening conversion. Widening + autoboxing just isn't supported.

What is the difference between (Integer)y and new Integer(y) in java?

What is the difference between the following:
Integer in = (Integer)y;
and
Integer in = new Integer(y);
I want to convert int type to Integer type and vice versa. Here is my code for doing that:
public class CompareToDemo {
public static void main(String[] args) {
// Integer x=5;
int y=25;
System.out.println(y+" this is int variable");
Integer in = (Integer)y;
//Integer in = new Integer(y);
if(in instanceof Integer){
System.out.println(in +" this is Integer variable");
}
}
}
If all you want to do is to convert an int primitive to an Integer object,
you have four options
Integer in = (Integer)y; // 1 explicit cast
Integer in = y; // 2 implicit cast (autoboxing)
Integer in = new Integer(y); // 3 explicit constructor
Integer in = Integer.valueOf(y); // 4 static factory method
The most preferable way here is 2 (autoboxing). The explicit constructor (3) is the less preferable, as it might have some small performance hit.
Also, they are not strictly equivalent. Consider:
public static void main(String[] args) {
int x = 25;
Integer a = new Integer(x);
Integer b = new Integer(x);
System.out.println(a == b); // false
Integer c = Integer.valueOf(x);
Integer d = Integer.valueOf(x);
System.out.println(c == d); // true
Integer e = (Integer)x;
Integer f = (Integer)x;
System.out.println(e == f); // true
}
This is because small integers are cached (details here).
Briefly speaking,
The line Integer in = (Integer)y; uses an unnecessary cast.
The line Integer in = new Integer(y); creates an Integer instance.
Each case in detail
First, let's consider the case with explicit casting.
Integer i = (Integer)10;
The compiler understands that 10 is an int primitive type and the fact that it has to be wrapped by its Integer to make it compiles. It seems javac will make the following:
Integer i = (Integer)Integer.valueOf(10);
But the compiler is smart enough to do unnecessary casting, (Integer) just will be omitted:
Integer i = Integer.valueOf(10);
Next, there is the case with instance creation.
Integer i = new Integer(10);
Here is all simply. A new instance of Integer class will be created anyway. But, as the documentation says, usually, it is not appropriate way:
It is rarely appropriate to use these constructors. The static factories valueOf() are generally a better choice, as it is likely to yield significantly better space and time performance.
Conclusion
In everyday code writing, we usually use autoboxing and unboxing. They are automatic conversions between the primitive types and their corresponding object wrapper classes (has been introduced in Java 5). So you needn't think much about Xxx.valueOf(xxx) and .xxxValue() methods. It is so convenient, isn't it?
Integer i = 10; // autoboxing
int j = i; // unboxing
For every primitive type in java, there is a corresponding wrapper class. You can convert between these primitive type and corresponding wrapper class. This is called boxing and unboxing. When you write
Integer in = (Integer)y; //this is unnecessary casting
or
Integer in = new Integer(y); //create a new instance of Integer class
You're mainly converting between primitive type and wrapper class. But Java has a feature called Auto Boxing and Unboxing Where java will do these casting for you. Just write
int iPrimi = 20;
Integer iWrapper = iPrimi; //Autoboxing
int iPrimi2 = iWrapper; //Auto unboxing
Autoboxing and Unboxing decrease performance. Primitives seems to be 2-3 times faster then it’s Integer equivalent. So do not use them if you don't need to.

Difference between int and Integer

What is the difference between int and Integer. Yes, one is primitive and another one is wrapper, what is the situation to use them correctly.
Also what is the difference between :
int i=0;
++i
and
i++
part 1
One example .. you can use Integer as the key of HashMap but you can't use int. Because an Object is needed.
So where you need an int value as an object there you need to use Integer class.
part 2
++i is pre increment
i++ is post increment
for example
i = 0;
System.out.println(i++) //will print 0 then the i will be 1.
and
i = 0;
System.out.println(++i) // here i wil be incremented first then print 1.
Integer is a wrapper class for int which is a primitive data type. Integer is used when int can't suffice. For example: In generics, the type of the generic class, method or variable cannot accept a primitive data type. In that case Integer comes to rescue.
List<int> list; //Doesn't compiles
List<Integer> list; // Compiles
Moreover Integer comes with a plethora of static methods, like toBinaryString, toHexString, numberOfLeadingZeros, etc. which can come in very handy.
As already explained above
An Integer is an object, whereas an int is a primitive. So you can have a null reference to an Integer and a Set or List of them. You can not do that with an int
I find this null reference very useful, when i have to store int values in database. I can store a null value when I use Integer. But cannot do so when I use int.
An Integer is an object, whereas an int is a primitive. So you can have a null reference to an Integer and a Set or List of them. You can not do that with an int.
A basic explanation is an int is a primitive data type and literally is only a value stored in memory. An Integer is a Java object that wraps an int in a Class with lots of nice/helpful methods that can be called to work with that backing int hidden inside. This is the same with most of the primitive data types, such as boolean and Boolean, char and Character, etc. This is refereed to as Boxing a primitive. Unboxing being the opposite, taking an Object and extracting the backing primative.
Here's an example of how one may use Integer to convert a String into an int (boxed to an Integer)
String someString = "10";
Integer intObj = Integer.parseInt(someString);
System.out.println(intObj.toString());
You'll find that some of the data types have more helpful methods than others. Check the JavaDoc's for each of the types you are interested in, there are a lot of goodies in there!

Categories

Resources