A better way to convert Integer (may be null) to int in Java?

java int cast null
int to integer java
converting null to int
convert empty string to int java
error: incompatible types null cannot be converted to int
null integer to 0
failed to convert from type null to type int for value 'null
integer to int value in java

An Integer can be null. I convert an Integer to an int by:

Integer integer = null;
int i;

try {
    i = integer.intValue();
}
catch (NullPointerException e) {
    i = -1;
} 

Is there a better way?

Avoiding an exception is always better.

int i = integer != null ? integer.intValue() : -1;

Why null pointer instead of class cast?, When executing your code, the Java runtime does the following: Cast Try to unbox the Integer object to an int by calling the method intValue(); Calling a In other words, null can be cast to Integer without a problem, but a null integer object almost two years ago provides almost the same explanation, but is more clear. 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.

With Java8 the following works, too:

Optional.ofNullable(integer).orElse(-1)

Convert String to Integer with default value, here is a solution : int tryParseInt(String value) { try { return Integer. parseInt with an additional null check. It would be really great if there were a way to accomplish this without having to catch Parsing Methods in Java Convert String to Int. That's all about how to convert an Integer to String in Java. As you have seen, the most straightforward way is to use Integer.toString() method, it doesn't need autoboxing and it's a direct way to get String from Integer. Alternatively, you can concatenate Integer object with empty String. This will internally call the toString() only.

If you already have guava in your classpath, then I like the answer provided by michaelgulak.

Integer integer = null;
int i = MoreObjects.firstNonNull(integer, -1);

Converting Between Numbers and Strings (The Java™ Tutorials , The Number subclasses that wrap primitive numeric types ( Byte , Integer , Double , Float example, parseFloat() ) that can be used to convert strings to primitive numbers. instead of an object, the parseFloat() method is more direct than the valueOf() method. There are several easy ways to convert a number to a string:. @khelwood, I don't agree. If you see the source of Integer#intValue() you can see that the method returns the nested private final int value;. So, by assigning integer.intValue() to an int doesn't trigger any boxing/unboxing features of the compiler. However, having int i = integer; will actually force the compiler to do unboxing from Integer to int.

Apache Commons Lang 3

ObjectUtils.firstNonNull(T...)

Java 8 Stream

Stream.of(T...).filter(Objects::nonNull).findFirst().orElse(null)

Taken From: https://stackoverflow.com/a/18741740/6620565

Integer (Java Platform SE 8 ), In addition, this class provides several methods for converting an int to a String and a String to an A constant holding the maximum value an int can have, 231-​1. The first argument is null or is a string of length zero. constructor Integer(int​) , as this method is likely to yield significantly better space and time performance​  \$\begingroup\$ The method take Integer instead of int because the input could potentially be null (nullable database field). However, I screwed up by not checking for a null input, which I've fixed. \$\endgroup\$ – Jason Feb 22 '15 at 12:55

Interesting facts about null in Java, Below are some important points about null in java which every Java value, which can be assigned to any reference type and you can type cast null to any type. Examples: // null can be assigned to String String str = null; // you can assign null to Integer also //Unboxing null to integer throws NullpointerException. int a = i;. I normally use the following idiom to check if a String can be converted to an integer. public boolean seem a bit hackish? What's a better way?

String to Integer in Java - parseInt(), Convert String to Integer in Java using parseInt() with examples. public static int parseInt(String s, int radix) throws NumberFormatException The first method can be considered as an equivalent of the second method with radix = 10 (​Decimal). String is null or of zero length; The value represented by the string is not a  A container object which may or may not contain a int value. If a value is present, isPresent() will return true and getAsInt() will return the value. Additional methods that depend on the presence or absence of a contained value are provided, such as orElse() (return a default value if value not present) and ifPresent() (execute a block of code if the value is present).

How to convert Integer to String in Java, Let's see a couple of more ways to convert an Integer to String in Java. we are dealing with the object here and not primitive int, which can never null. You can  Which means that if you use the radix 10, you better call the Integer.toString(int foo) directly. For the other cases use the Integer.toString(int foo, int radix). The concat solution first transforms the int value into a String and later concatenates with the empty String. This obviously is the most expensive case.

Comments
  • Use assert to make sure it's not null.
  • you shouldn't use assert in this case cause null is a valid execution path and could indeed happen in production
  • Darn you and your fast fingers. I was going for the autoboxing way of int i = integer == null ? 0 : integer;.
  • avoiding C legacy notation could also be considered to be a better way by some ppl
  • @kocko My original answer (before your edit) without .intValue() works fine (Java handles the auto-unboxing). Do you think calling intValue explicitly is more efficient?
  • @kocko .intValue() isn't avoiding unboxing; it is explicitly unboxing
  • @khelwood, I don't agree. If you see the source of Integer#intValue() you can see that the method returns the nested private final int value;. So, by assigning integer.intValue() to an int doesn't trigger any boxing/unboxing features of the compiler. However, having int i = integer; will actually force the compiler to do unboxing from Integer to int. That's why I find the explicit call to .intValue() a bit more efficient (even there's not much performance difference) and readable.