AWb
AWb

Reputation: 161

What is the Java equivalent for the following C# code?

I have an interesting question. I understand the following C# code enables users to input null values in parameters:

public DateTime? date (DateTime dt) {}

What is the equivalent when coding in Java?

Upvotes: 9

Views: 4242

Answers (4)

BigMike
BigMike

Reputation: 6873

If I recall correctly each object in java can be nullable. Primitive types (int, double, float, char etc...) cannot be null. For using null with them you have to use their Object counterpart (Integer, Double, Float...)

Regarding dates, java.util.Date is an Object, so it can be null. Same goes for Calendar & GregorianCalendar.

equivalent code will be something like:

public Date date(Date dt) throws NullPointerException { 
  if (dt == null) throw new NullPointerException();
  ...
}

In C# you can use ? to allow null val in primitive types (e.g. to enforce object null reference errors). I don't understand why this thing bothers you. If you need for example a nullable integer parameter in java, you simply have to use java.lang.Integer and not primitive int type.

Upvotes: 6

Joachim Isaksson
Joachim Isaksson

Reputation: 181027

Since a Date in Java is a class, a reference to it can already be null. In other words;

public Date date(Date dt) { }

...is Java's version of the same.

Note that the parameter also can be null in Java, which it can't in the C# version.

Upvotes: 1

Jeff Foster
Jeff Foster

Reputation: 44706

Java doesn't support user-defined value types (e.g. types that can not be null). In this regard, a Java DateTime object already supports nullable by virtue of allowing null to be assigned.

For other types, such as int and double, you can achieve the same effect by using the boxed versions Integer and Double which are allowed to be assigned null.

Upvotes: 0

Mr Lister
Mr Lister

Reputation: 46589

How to present the nullable primitive type int in Java? says "Java does not have a nullable feature as C# has." Is that an answer?

Upvotes: 0

Related Questions