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

I have an interesting question. I understand that the following C # code allows users to enter null values ​​in parameters:

public DateTime? date (DateTime dt) {} 

What is the equivalent when coding in Java?

+6
source share
4 answers

If I remember correctly, every object in java can be null. Primitive types ( int, double, float, char , etc.) cannot be null. To use null with them you must use their object instance ( Integer, Double, Float... )

As for dates, java.util.Date is an object, so it can be null. The same goes for Calendar and GregorianCalendar.

the equivalent code would look something like this:

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

In C # can you use? to allow null val in primitive types (for example, to force the null reference of an object to be checked). I don’t understand why this thing bothers you. If you need, for example, a null integer parameter in java, you just need to use java.lang.Integer , not a primitive int type.

+5
source

Since Date in Java is a class, the reference to it may already be null. In other words:

 public Date date(Date dt) { } 

... is the same version of Java.

Please note that this option may also be empty in Java, which may not be in C # version.

+1
source

How to represent a null primitive int type in Java? says: "Java does not have a zero capability, like C #." This is the answer?

0
source

Java does not support custom value types (for example, types that cannot be null). In this regard, the Java DateTime object already supports the value NULL, because it allows you to assign the value null.

For other types, such as int and double , you can achieve the same effect using the plug-in versions of Integer and double , which are allowed to assign zero.

0
source

Source: https://habr.com/ru/post/906466/


All Articles