Why is implicit conversion from int to Long not possible? - java

I can implicitly conver int to long and long to Long. Why is it not possible to implicitly convert int to Long? Why can't Java do the implicit conversion on the last line of the example?
int i = 10; //OK
long primitiveLong = i; //OK
Long boxedLong = primitiveLong; //OK
boxedLong = i; //Type mismatch: cannot convert from int to Long

Long and Integer are objects. Boxing/unboxing only works with primitives.
Doing Long boxedLong = i is like Long boxedLong = new Integer(10), that's a no no !
Plus, remember that there is no inheritance between Long and Integer so even Integer i = new Long() is not valid

Boxing only works with primitives. That's why.
Try this: Long.valueOf(int);
Documentation

the biggest difference I see between long and Long in this context is that Long may be null. If there's a possibility you might have missing values the Long object will be helpful as the null can indicate missing values. If you're using primitives you'll have to use some special value to indicate missing, which is probably going to be a mess. Speed or size is not likely to be an issue unless you're planning on making an array of a million of these things and then serializing. (When to use Long vs long in java?)
In truth, there is no practical reason. Except that int is a primitive, long is a primitive, but Long is not.
I suggest you use Long.valueOf()
So like this:
Long longValue = Long.valueOf(InsertIntHere);

Related

What is the use of intValue() when you can directly assign Integer value to primitive int? [duplicate]

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;

When converting primitive data types to Objects, should you cast or create a new object?

This may break the discussion vs. answer rules, but I figure there's a preferred way of doing things.
--
Let's say you need to convert a primitive data type to an Object. Let's use int --> Integer as an example. You can do this by casting or straight up making a new Object. For example:
int a = 5; int b = 10;
Integer c = new Integer(a);
Integer d = (Integer) b;
Which is the better way to do it, a --> c or b --> d? I suspect they perform the same operation, so which one is usually used?
Thanks in advance.
Let's say you need to convert a primitive data type to an Object.
Let's use int --> Integer as an example. You can do this by casting or
straight up making a new Object. For example:
int a = 5; int b = 10;
Integer c = new Integer(a);
Integer d = (Integer) b;
Which is the better way to do it, a --> c or b --> d? I suspect they
perform the same operation, so which one is usually used?
Java compilers in versions 5 and later perform autoboxing to convert between a primitive value and it's corresponding boxed object. Autoboxing blurs, but does not erase, the distinction between primitive values and objects.
The following line is discouraged:
Integer c = new Integer(a);
This is because a new object is always created and prevents cached Integer objects from being reused.
This line is transformed by the Java compiler:
Integer d = (Integer) b;
Instead, this line becomes
Integer d = Integer.valueOf(b);
This is the code you would get if you omitted the cast from the assignment altogether. The primitive value is boxed into its corresponding object using the valueOf() function. This is the preferred way to assign primitive values to their objects because this allows the JVM to reuse frequently cached objects.
None of the above.
Use Integer.valueOf as it yields to significantly better space and time performance by caching frequently requested values.
From the docs of Integer.valueOf
Returns an {#code Integer} instance representing the specified
{#code int} value. If a new {#code Integer} instance is not
required, this method should generally be used in preference to
the constructor {#link #Integer(int)}, as this method is likely
to yield significantly better space and time performance by
caching frequently requested values.
But with autoboxing, the compiler will do it automatically for you.
Integer i = 1;
Which is a syntactic sugar for
Integer i = Integer.valueOf(1);
None of the above. You can lean on autoboxing in this scenario to take care of the casts.
That would make your code this:
int a = 5;
int b = 10;
Integer c = a;
Integer d = b;

Format String to Integer in java

I am facing the below problem:
I will be getting values similar or of greater length compared to temp value :
public class NumberFormat {
public static void main(String arg[]){
Integer numValue = null;
String temp="5474151538110135";
numValue=Integer
.parseInt(temp.trim());
System.out.println("--> "+numValue);
}
}
Please provide a solution.
Exception in thread "main" java.lang.NumberFormatException: For input string: "5474151538110135"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:60)
at java.lang.Integer.parseInt(Integer.java:473)
at java.lang.Integer.parseInt(Integer.java:511)
at com.filetransfer.August.NumberFormat.main(NumberFormat.java:10)
5474151538110135 is greater than Integer.MAX_VALUE. Use Long.parseLong instead or BigInteger if the input number is likely to grow significantly
Long numValue = Long.parseLong(temp.trim());
Probably beacuse the value is larger than max int value which is 2147483647.
System.out.println(Integer.MAX_VALUE);
You should parse it to Long which max value is 9223372036854775807.
System.out.println(Long.MAX_VALUE);
like this
Long numValue = null;
String temp="5474151538110135";
numValue=Long
.parseLong(temp.trim());
I would recommend use BigInteger for avoiding errors
Advantage of BigInteger Class
Integer is a wrapper of the primitive type int.The wrapper classes are basically used in cases where you want to treat the primitive as an object for ex-trying to pass an int value in a method that would take only a type of Object in such a case you would want to wrap primitive int value in the wrapper Integer which is of type Object. To know specific advantages of Integer I would suggest you to take a look at the Integer api provided by Sun.
Now coming to the BigInteger, you would use it in calculations which deal with very large numbers.The use of BigIntegers is in Security where typically it is used for keys specifications.For more info on BigIntegers take a look at the following link http://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html
I hope the info helped you.

Is it possible to add wrapped numbers without boxing/unboxing?

I'm getting a Long value as a result of some method. Now, when I want to add 1 to that number, the compiler warns me about the value being boxed / unboxed to perform the sum.
public Long getLongValue() {return new Long(5L);}
// ...
Long val = getLongValue();
val++; // Warning: The expression of type Long is unboxed into long
val = val + 1L; // Warning: The expression of type Long is unboxed into long
Since Long class doesn't seem to have an "add" method, is there any way to avoid this autoboxing behaviour?
(Note: I know I can just #suppressWarnings or manually box / unbox the values instead of using the Autoboxing feature. What I'm trying to achieve is to totally avoid boxing / unboxing)
Since, as you noted, Long does not have have any add() method (or any other arithmetic methods) you have no choice but to unbox (manually or automatically) it to do calculations with it and then box (manually or automatically) the result.
It will likely be more performant if you unbox before any calculations, do all the calculations, and rebox at the end rather than boxing and unboxing during each calculation (and sub-calculation).
Do it this way
long val = getLongValue();
val++;
val = val + 1L;
it's more efficient and there will be no warnings

Where do you put the parentheses to concisely convert a casted object to a primitive type without auto-unboxing?

With autounboxing, this statement will automatically work:
int myPrimitive = (Integer) doIt();
But if I want to explicitly convert from an Integer to an int here in a single line, where do I have to put the parentheses?
You could do this :
int myPrimitive = (int) (Integer) doIt();
But as you said, auto-unboxing will get that for you.
A bad example to show that chain casts work (don't ever use this code) :
Map notReallyAMap = (Map) (Object) new String();
The thing with chain casts, is that wherever you use it, either the cast is legit, and you can remove intermediaries; or the cast will simply cause a ClassCastException. So you should never use it.
Either the compiler unboxes the Integer for you, or you do it yourself - this cannot be avoided.
So you need to either do
int myPrimitive = ((Integer) doIt()).intValue();
or more simply, change doIt() to return an int since you seem to want to deal with ints rather than (null-able) Integers.

Categories