I've been doing a code where its mandatory to use the data type cannot be void and I don't need to return anything.
In Java, null
is only a valid value for reference types. It cannot represent a primitive type such as int
. Here are some alternatives to consider:
OptionalInt
type to represent an int
value that may or may not be present. In that case, you would return OptionalInt.empty()
in the case that there is no int
value to return, and OptionalInt.of(x)
to return an int x
. Note that the caller will need to unwrap the int
value (if it is present) using one of the other methods available on that class. This approach is often preferred for new code, as it makes the intention and usage very clear.Integer
. This is a wrapper class for int
values that does allow for null
to be returned. In addition, Java's auto-unboxing rules allow it to be used in contexts where an int
value is expected, when the value is not null
. However, if a null
value is unboxed to an int
value, it will result in a NullPointerException
, so it is important to check for null
before performing operations that would result in unboxing.int
return type, it is common to use a sentinal value to represent an abnormal return. For example, if the normal return values for the method are all non-negative integers, you could use a value such as -1
to represent an absent return value. This is commonly used in older JDK methods such as String.indexOf()
.Exception
when no valid value can be returned. It's only a good idea to use this approach for truly exceptional circumstances, as the runtime cost for throwing exceptions is much higher than normal method returns, and the flow of control can make the code harder to understand.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.