Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell if a Java integer is null?

Tags:

java

integer

Greetings,

I'm trying to validate whether my integer is null. If it is, I need to prompt the user to enter a value. My background is Perl, so my first attempt looks like this:

int startIn = Integer.parseInt (startField.getText());  if (startIn) {      JOptionPane.showMessageDialog(null,          "You must enter a number between 0-16.","Input Error",          JOptionPane.ERROR_MESSAGE);                 } 

This does not work, since Java is expecting boolean logic.

In Perl, I can use "exists" to check whether hash/array elements contain data with:

@items = ("one", "two", "three"); #@items = ();  if (exists($items[0])) {     print "Something in \@items.\n"; } else {     print "Nothing in \@items!\n"; } 

Is there a way to this in Java? Thank you for your help!

Jeremiah

P.S. Perl exists info.

like image 548
Jeremiah Burley Avatar asked Mar 14 '09 14:03

Jeremiah Burley


People also ask

Can you check if an int is null in Java?

Primitive data type int can not be checked for a null value.

How do you check if it is null in Java?

To check if a string is null or empty in Java, use the == operator.

Is 0 == null in Java?

null is Case sensitive: null is literal in Java and because keywords are case-sensitive in java, we can't write NULL or 0 as in C language.


2 Answers

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. } 
like image 141
John Feminella Avatar answered Sep 18 '22 11:09

John Feminella


Try this:

Integer startIn = null;  try {   startIn = Integer.valueOf(startField.getText()); } catch (NumberFormatException e) {   .   .   . }  if (startIn == null) {   // Prompt for value... } 
like image 31
John Topley Avatar answered Sep 21 '22 11:09

John Topley