Use commons-lang NumberUtils.createInteger() method:
CopyNumberUtils.createInteger(null); // null
NumberUtils.createInteger("5"); // 5
Answer from Maciej Walkowiak on Stack OverflowUse commons-lang NumberUtils.createInteger() method:
CopyNumberUtils.createInteger(null); // null
NumberUtils.createInteger("5"); // 5
Touches Java 8:
CopyOptional<String> maxAgeStr = Optional.ofNullable(settings.get("maxAge"));
maxAgeStr.ifPresent((str) -> { constraints.setMaxAge(Integer.valueOf(str)); });
Optional<String> enableActionStr = Optional.ofNullable(settings.get("enableAction"));
constraints.setEnableAction(Boolean.valueOf(enableActionStr.orElse(false)));
Optional<String> enableActionStr = Optional.ofNullable(settings.get("enableAction"));
constraints.setEnableAction(Boolean.valueOf(enableActionStr.orElseGet(() -> i%2 == 0)));
null is not a valid representation of integer number. Integer.parseInt() requires that the string be parsed is a vaild representation of integer number.
Integer.parseInt()
public static int parseInt(String s, int radix)
440 throws NumberFormatException
441 {
442 if (s == null) {
443 throw new NumberFormatException("null");
444 }
Integer.valueOf(str)] // which inviokes Integer.parseInt(Str) to return an Integer instance.
public static Integer valueOf(String s) throws NumberFormatException
569 {
570 return new Integer(parseInt(s, 10));
571 }
The folks at Sun who implemented Integer (a long time ago :) ) probably were not thinking of databases when they wrote that method. Except when dealing with database data, or rare cases where you are trying to explicitly represent "unknown" with null, null is usually a sign of something gone terribly wrong. In general, it's a good idea to raise an exception as soon as there is a problem. (a Fail fast design)
If you have ever spent time hunting down a segmentation fault in C that is due to a string value longer than the memory you supplied for it (which then overwrote some program code or other data) you will have a very good appreciation of how bad it is to not fail when something has gone wrong.
Since the time of Java 1.0, interaction with databases in java has become extremely common so you might be right to suggest that there should be a method to handle this. Integer is a final class so if you build your own Integer like class you will loose autoboxing, so this probably does require a change to the language by oracle.
Basically, what you observed is the way it is for now, and someone will have to pay you to code around it :)
I am sure you are over-complicating the problem, it is a real simple thing to do. Check the code below:
Integer i = null;
System.out.println(i == null ?"":i);
Use Integer wrapper class instead of primitive
Integer myInt= null;
For object references you can set null.But you cannot to primitives.
here is a solution :
int tryParseInt(String value) {
try {
return Integer.parseInt(value);
} catch(NumberFormatException nfe) {
// Log exception.
return 0;
}
}
you should catch NumberFormatException instead of exception.
I'd consider using NumberUtils.toInt from Apache Commons Lang which does exactly this:
public static int NumberUtils.toInt(java.lang.String str, int defaultValue)
The implementation uses the already mentioned Integer.parseInt with an additional null check.
See also: Effective Java, 2nd edition, Item 47: Know and use the libraries (The author mentions only the JDK's built-in libraries but I think the reasoning could be true for other libraries too.)
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> or java.util.OptionalInt
No. Only object references can be null, not primitives.
parseInt() is just going to throw an exception if the parsing can't complete successfully. You can instead use Integers, the corresponding object type, which makes things a little bit cleaner. So you probably want something closer to:
Integer s = null;
try {
s = Integer.valueOf(startField.getText());
}
catch (NumberFormatException e) {
// ...
}
if (s != null) { ... }
Beware if you do decide to use parseInt()! parseInt() doesn't support good internationalization, so you have to jump through even more hoops:
try {
NumberFormat nf = NumberFormat.getIntegerInstance(locale);
nf.setParseIntegerOnly(true);
nf.setMaximumIntegerDigits(9); // Or whatever you'd like to max out at.
// Start parsing from the beginning.
ParsePosition p = new ParsePosition(0);
int val = format.parse(str, p).intValue();
if (p.getIndex() != str.length()) {
// There's some stuff after all the digits are done being processed.
}
// Work with the processed value here.
} catch (java.text.ParseFormatException exc) {
// Something blew up in the parsing.
}
Try this:
Integer startIn = null;
try {
startIn = Integer.valueOf(startField.getText());
} catch (NumberFormatException e) {
.
.
.
}
if (startIn == null) {
// Prompt for value...
}
That code will give a NullPointerException when you run it. It's basically equivalent to:
Integer a = null;
int b = a.intValue();
... which makes it clearer that it will indeed fail.
You're not really assigning a null value to an int - you're trying and failing.
It's fine to use null as a value for an Integer; indeed often Integer is used instead of int precisely as a "nullable equivalent`.
It is not possible. You will get NullPointerException