Difference between int and Integer - java

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!

Related

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.

Integer vs int types, which is better? [duplicate]

This question already has answers here:
Which one to use, int or Integer
(11 answers)
When to use wrapper class and primitive type
(11 answers)
Closed 9 years ago.
Why does Java have these Integer, Character types and classes
while they are also adapting C's int, char etc
Sometimes when people are creating arrays, they tend to
use Integer[] i = {......}
rather than int[] i = {....};
what is the difference then?
Integer is an object, while int is a primitive. Whenever we pass an int into a function, we pass it as-is.
Integer wraps an int. In its case it is immutable so editing it via reference isn't going to work, but it can be put into generics. This can be set to null while int does not have a possibility of anything beyond 0 or a special value you interpret as a null condition, such as -1 or Integer.MAX_VALUE.
For instance, ArrayList<int> is completely invalid while ArrayList<Integer> must be used with ints being wrapped.
With autoboxing, however, we can immediately add an int to an ArrayList without manually wrapping it, and if we need a primitive when we get() the entry, it'll automatically unwrap it transparently.
In the end if you're doing calculations with a limited number of distinct variables or a fixed array, you should generally use int. When dealing with sets, lists, or maps, you should declare the collection as FooCollection<Integer> then add( an int directly allowing for autoboxing.
Integer, Character and others like this are Objects while int, char and others like this are primitives.
The biggest difference is that an Object can be null while a primitive value can't.
It's recommended to use primitive values where you can because they use less memory.
The only difference we can tell generally is Wrapper is objective representation of primitive.
Wrapper classes are used to represent primitive values when an Object is required.
In java,
Integer is a wrapper class i.e. it is an object while int is a primitive.
Integer default value is null while for int it is 0
There is a concept of autoboxing and auto-unboxing for these two types.
An integer can be converted to an int and vice versa
Followign program demonstrates this
public class TestClass {
int num;
Integer number;
public static void main(String[] args) {
TestClass testClass = new TestClass();
System.out.println(testClass.num);
System.out.println(testClass.number);
testClass.autoBoxInt(testClass.num);
}
public void autoBoxInt(Integer number){
System.out.println(number);
}
}
The output is
0
null
0
The statement System.out.println(testCkass,num) prints int default value i.e. 0. System.out.println(testClass.number) prints Integer default value i.e. null. When you pass testClass.num to a method with parameter Integer, int is automatically converted into and Integer object. so the method prints out 0.
The java collections framework uses autoboxing to convert primitives into Wrapper classes because they cannot take primitive values. They help fast retrieval and storing of objects into collections using hashing and hashcodes. Following example demonstrates this
Set<Integer> numbers = new HashSet<Integer>();
numbers.add(new Integer(10));
numbers.add(new Integer(4));
numbers.add(6);
numbers.add(-9);
numbers.add(new Integer(65));
System.out.println(numbers);
This prints out the set
[4, 65, 6, -9, 10]
To know what hashing is and how hashcodes are used, you can look these links
http://www.thejavageek.com/2013/06/27/what-are-hashcodes/
http://www.thejavageek.com/2013/06/26/what-is-the-significance-of-equals-method-in-java/

What is .intValue() in 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;

How can I store an int array into a number array?

Integer extends Number so in that sense Number becomes the superclass of int. I want to store an int array into a Number array..
I have the following code.However, it seems it is not allowed in java.
int[] b = {1,2};
Number[] a = b;
Why java does not allow me to store an int array in number array and how do I store this out ?
You can't do that directly, because an "array-of-primitives" is not an "array-of-objects". Autoboxing does not occur with arrays.
But you can use ArrayUtils.toObject(b) (from commons-lang). This will create a new array of the wrapper type (Integer) and fill it with the values from the primitive array:
int[] a = {1,2};
Number[] n = ArrayUtils.toObject(a);
Because int and Integer are two separate types. The first one is a primitive type, and the second one is an object type. Integer extends Number, but int is not even a class, and it thus can't extend anything.
I would guess this has something to do with Number being an abstract class (API Page), meaning the it cannot be used to represent an item, but allows other classes to share functionality. If you could store items in a Number array, they would lose their type, and become instances of Number, which is impossible as it's abstract.

Can an int be null in Java?

Can an int be null in Java?
For example:
int data = check(Node root);
if ( data == null ) {
// do something
} else {
// do something
}
My goal is to write a function which returns an int. Said int is stored in the height of a node, and if the node is not present, it will be null, and I'll need to check that.
I am doing this for homework but this specific part is not part of the homework, it just helps me get through what I am doing.
Thanks for the comments, but it seems very few people have actually read what's under the code, I was asking how else I can accomplish this goal; it was easy to figure out that it doesn't work.
int can't be null, but Integer can. You need to be careful when unboxing null Integers since this can cause a lot of confusion and head scratching!
e.g. this:
int a = object.getA(); // getA returns a null Integer
will give you a NullPointerException, despite object not being null!
To follow up on your question, if you want to indicate the absence of a value, I would investigate java.util.Optional<Integer>
No. Only object references can be null, not primitives.
A great way to find out:
public static void main(String args[]) {
int i = null;
}
Try to compile.
In Java, int is a primitive type and it is not considered an object. Only objects can have a null value. So the answer to your question is no, it can't be null. But it's not that simple, because there are objects that represent most primitive types.
The class Integer represents an int value, but it can hold a null value. Depending on your check method, you could be returning an int or an Integer.
This behavior is different from some more purely object oriented languages like Ruby, where even "primitive" things like ints are considered objects.
Along with all above answer i would like to add this point too.
For primitive types,we have fixed memory size i.e for int we have 4 bytes and char we have 2 bytes. And null is used only for objects because there memory size is not fixed.
So by default we have,
int a=0;
and not
int a=null;
Same with other primitive types and hence null is only used for objects and not for primitive types.
The code won't even compile. Only an fullworthy Object can be null, like Integer. Here's a basic example to show when you can test for null:
Integer data = check(Node root);
if ( data == null ) {
// do something
} else {
// do something
}
On the other hand, if check() is declared to return int, it can never be null and the whole if-else block is then superfluous.
int data = check(Node root);
// do something
Autoboxing problems doesn't apply here as well when check() is declared to return int. If it had returned Integer, then you may risk NullPointerException when assigning it to an int instead of Integer. Assigning it as an Integer and using the if-else block would then indeed have been mandatory.
To learn more about autoboxing, check this Sun guide.
instead of declaring as int i declare it as Integer i then we can do i=null;
Integer i;
i=null;
Integer object would be best. If you must use primitives you can use a value that does not exist in your use case. Negative height does not exist for people, so
public int getHeight(String name){
if(map.containsKey(name)){
return map.get(name);
}else{
return -1;
}
}
No, but int[] can be.
int[] hayhay = null; //: allowed (int[] is reference type)
int hayno = null; //: error (int is primitive type)
//: Message: incompatible types:
//: <null> cannot be converted to int
As #Glen mentioned in a comment, you basically have two ways around this:
use an "out of bound" value. For instance, if "data" can never be negative in normal use, return a negative value to indicate it's invalid.
Use an Integer. Just make sure the "check" method returns an Integer, and you assign it to an Integer not an int. Because if an "int" gets involved along the way, the automatic boxing and unboxing can cause problems.
Check for null in your check() method and return an invalid value such as -1 or zero if null. Then the check would be for that value rather than passing the null along. This would be a normal thing to do in old time 'C'.
Any Primitive data type like int,boolean, or float etc can't store the null(lateral),since java has provided Wrapper class for storing the same like int to Integer,boolean to Boolean.
Eg: Integer i=null;
An int is not null, it may be 0 if not initialized. If you want an integer to be able to be null, you need to use Integer instead of int . primitives don't have null value. default have for an int is 0.
Data Type / Default Value (for fields)
int ------------------ 0
long ---------------- 0L
float ---------------- 0.0f
double ------------- 0.0d
char --------------- '\u0000'
String --------------- null
boolean ------------ false
Since you ask for another way to accomplish your goal, I suggest you use a wrapper class:
new Integer(null);
I'm no expert, but I do believe that the null equivalent for an int is 0.
For example, if you make an int[], each slot contains 0 as opposed to null, unless you set it to something else.
In some situations, this may be of use.

Categories

Resources