How to write nullable int in java?

C#JavaNullable

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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.

Solution 3 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDozerView Question on Stackoverflow
Solution 1 - C#Ivaylo StrandjevView Answer on Stackoverflow
Solution 2 - C#Matthias MeidView Answer on Stackoverflow
Solution 3 - C#Polaris878View Answer on Stackoverflow