[java] How can I tell if a Java integer is null?

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.

This question is related to java integer

The answer is


For me just using the Integer.toString() method works for me just fine. You can convert it over if you just want to very if it is null. Example below:

private void setCarColor(int redIn, int blueIn, int greenIn)
{
//Integer s = null;
if (Integer.toString(redIn) == null || Integer.toString(blueIn) == null ||     Integer.toString(greenIn) == null )

Try this:

Integer startIn = null;

try {
  startIn = Integer.valueOf(startField.getText());
} catch (NumberFormatException e) {
  .
  .
  .
}

if (startIn == null) {
  // Prompt for value...
}

There is no exists for a SCALAR in Perl, anyway. The Perl way is

defined( $x ) 

and the equivalent Java is

anInteger != null

Those are the equivalents.

exists $hash{key}

Is like the Java

map.containsKey( "key" )

From your example, I think you're looking for

if ( startIn != null ) { ...


This should help.

Integer startIn = null;

// (optional below but a good practice, to prevent errors.)
boolean dontContinue = false;
try {
  Integer.parseInt (startField.getText());
} catch (NumberFormatException e){
  e.printStackTrace();
}

// in java = assigns a boolean in if statements oddly.
// Thus double equal must be used. So if startIn is null, display the message
if (startIn == null) {
  JOptionPane.showMessageDialog(null,
       "You must enter a number between 0-16.","Input Error",
       JOptionPane.ERROR_MESSAGE);                            
}

// (again optional)
if (dontContinue == true) {
  //Do-some-error-fix
}

I don't think you can use "exists" on an integer in Perl, only on collections. Can you give an example of what you mean in Perl which matches your example in Java.

Given an expression that specifies a hash element or array element, returns true if the specified element in the hash or array has ever been initialized, even if the corresponding value is undefined.

This indicates it only applies to hash or array elements!


ints are value types; they can never be null. Instead, if the parsing failed, parseInt will throw a NumberFormatException that you need to catch.