Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

c#

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?

like image 653
AWb Avatar asked Jan 20 '12 10:01

AWb


2 Answers

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.

like image 116
BigMike Avatar answered Nov 15 '22 06:11

BigMike


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.

like image 30
Joachim Isaksson Avatar answered Nov 15 '22 06:11

Joachim Isaksson