79

I want to convert a web form to a model in Java.

In C# I can write this:

<input name="id" value="" type="text"/>


public class Test
{
    public int? Id{get;set;}
}

The id can be null.

But in Java when using struts2 it throws an exception:

Method "setId" failed

So how to write this case in Java?

2

4 Answers 4

161

Instead of using int you can use Integer (Integer javadoc) because it is a nullable Java class.

2
  • 7
    thanks~ 'int' is same as 'Integer' in C#,so I didn't know this solution.
    – Dozer
    Jan 14, 2013 at 15:21
  • @Dozer don't forget to mark this post as an answer once the 15 mins have past. Jan 14, 2013 at 15:24
51

You can use an Integer, which is a reference type (class)in Java and therefore nullable.

Int32 (or int) is a struct (value type) in C#. In contrast, Integer in Java is a class which wraps an int. Instances of reference types can be null, which makes Integer an legit option.

Nullable<T> in .NET gives you similar options because it enables you to treat a value type like a nullable type. However, it's still different from Java's Integer since it's implemented as a struct (value type) which can be compared to null, but cannot actually hold a genuine null reference.

1
  • 4
    this is a more thorough answer than the accepted one Nov 23, 2015 at 14:58
8

In Java, just use Integer instead of int. This is essentially a nullable int. I'm not too familiar with Struts, but using Integer should allow you to omit the value.

1

Optional<Integer> - The purpose of the class is to provide a type-level solution for representing optional values instead of null references.

OptionalInt - 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.