int is a primitive, null is not a value that it can take on. You could change the method return type to return java.lang.Integer and then you can return null, and existing code that returns int will get autoboxed.
Nulls are assigned only to reference types, it means the reference doesn't point to anything. Primitives are not reference types, they are values, so they are never set to null.
Using the object wrapper java.lang.Integer as the return value means you are passing back an Object and the object reference can be null.
Answer from Nathan Hughes on Stack Overflowint is a primitive, null is not a value that it can take on. You could change the method return type to return java.lang.Integer and then you can return null, and existing code that returns int will get autoboxed.
Nulls are assigned only to reference types, it means the reference doesn't point to anything. Primitives are not reference types, they are values, so they are never set to null.
Using the object wrapper java.lang.Integer as the return value means you are passing back an Object and the object reference can be null.
Change your return type to java.lang.Integer . This way you can safely return null
Videos
StackOverflow has a good discussion about this exact topic in this Q&A. In the top rated question, kronoz notes:
Returning null is usually the best idea if you intend to indicate that no data is available.
An empty object implies data has been returned, whereas returning null clearly indicates that nothing has been returned.
Additionally, returning a null will result in a null exception if you attempt to access members in the object, which can be useful for highlighting buggy code - attempting to access a member of nothing makes no sense. Accessing members of an empty object will not fail meaning bugs can go undiscovered.
Personally, I like to return empty strings for functions that return strings to minimize the amount of error handling that needs to be put in place. However, you'll need to make sure that the group that your working with will follow the same convention - otherwise the benefits of this decision won't be achieved.
However, as the poster in the SO answer noted, nulls should probably be returned if an object is expected so that there is no doubt about whether data is being returned.
In the end, there's no single best way of doing things. Building a team consensus will ultimately drive your team's best practices.
In all the code I write, I avoid returning null from a function. I read that in Clean Code.
The problem with using null is that the person using the interface doesn't know if null is a possible outcome, and whether they have to check for it, because there's no not null reference type.
In F# you can return an option type, which can be some(Person) or none, so it's obvious to the caller that they have to check.
The analogous C# (anti-)pattern is the Try... method:
public bool TryFindPerson(int personId, out Person result);
Now I know people have said they hate the Try... pattern because having an output parameter breaks the ideas of a pure function, but it's really no different than:
class FindResult<T>
{
public FindResult(bool found, T result)
{
this.Found = found;
this.Result = result;
}
public bool Found { get; private set; }
// Only valid if Found is true
public T Result { get; private set;
}
public FindResult<Person> FindPerson(int personId);
...and to be honest you can assume that every .NET programmer knows about the Try... pattern because it's used internally by the .NET framework. That means they don't have to read the documentation to understand what it does, which is more important to me than sticking to some purist's view of functions (understanding that result is an out parameter, not a ref parameter).
So I'd go with TryFindPerson because you seem to indicate it's perfectly normal to be unable to find it.
If, on the other hand, there's no logical reason that the caller would ever provide a personId that didn't exist, I would probably do this:
public Person GetPerson(int personId);
...and then I'd throw an exception if it was invalid. The Get... prefix implies that the caller knows it should succeed.
I am a learning java, btw why is used the return null;?
I was trying to test it with this code:
import java.util.Objects;
public class Main {
public static void main (String args[]) {
String a = myMethod();
System.out.println(Objects.isNull(a));
}
public static String myMethod() {
}
}But a compilation error is raised before I can see the outcome.
Just out of curiosity
If you don't want to throw an Exception and want to clearly handle cases where the value is missing, you can return an Optional
private static final Optional<String> getHostName() {
try {
return Optional.of(
InetAddress.getLocalHost().getCanonicalHostName().toLowerCase());
} catch (UnknownHostException ex) {
logger.logError("error = ", ex);
return Optional.absent();
}
}
The client code would look like this:
private static String findData() {
Optional<String> optionalHost = getHostName();
if (optionalHost.isPresent()) {
String host = optionalHost.get();
// do something
} else {
// otherwise do something else
}
}
More info about avoiding and handling null here.
If you are expecting callers to handle this case, then you can either use Optional (either from Guava or from JDK 8), or else simply let the exception bubble up (with or without logging it first).
If you are not expecting this case to ever arise, and you don't expect callers to handle it, but you're simply trying to satisfy the "catch or specify" requirement, then you can wrap it in an unchecked exception and raise that.
Your code as it stands try's to index into the Object array without checking for null with the code things.length, which will throw a NullPointerException because there is no array object in existence, so the length field also does not exist.
To fix this use an if statement!
static String concatAll(Object[] things) {
if(things == null) {
return null;
}
...continue code....
This will first check things for a null value BEFORE executing code that could throw an exception.
Calling a method on a null object causes a NullPointerException.
In your case if obj = null, then when you call concatAll, things will be null as well. You then try and call things.length which is not valid on a null object.
You can make this method safer by checking the input of strings first. What you want to do exactly will depend on your situation, but here is one example.
static String concatAll(Object[] things) {
if (things == null)
{
return "";
}
StringBuffer result = new StringBuffer();
for (int i = 0; i < things.length; i++) {
result.append( things[i] );
}
String x = result.toString();
return x;
}
If you're using Java 8, consider the Optional class, but do note that it's not applicable everywhere.
Many think (me included) that Optional should be used only for return values, not parameters and especially not for object attributes. However as always there's no hard rule, just be careful that you don't replace null handling with Optional blindly, without understanding if you get any advantage from it.
In the example code for example, Optional won't do you any good. Since you perform some action regardless of null or not, you'll just be changing if(s == null) to if(s.isPresent()). However if the logic did something only if s is non-null, without an else you may be able to use Optional.ifPresent() to make things a bit cleaner. Of course there are other useful methods present in Optional that will give you cleaner code, such as the orElse() which can be used effectively for using default values.
Looks like you mean the special case pattern (particular implementations are the Option or the Null Object pattern).
There are Java implementations of the Option type, named Optional, in Java 8 and in the Guava libraries.
In your case, you'll be using Optional<SomeObject> and having this implementation (I'm using the Guava implementation):
Optional<SomeObject> getSomeObject(List<SomeObject>, int x) {
/* Search for object in list that has a properties
with value x */
if (found) {
return Optional.of(objectFound);
} else {
return Optional.absent(); // or Optional.empty(); in Java 8
}
// if objectFound variable is null when not found, you can simply use
// return Optional.fromNullable(objectFound);
// or return Optional.ofNullable(objectFound); in Java 8
}
So the code is self-explainable about returning an optional object. You would then have:
void doSomething(Optional<SomeObject> o) {
if (o.isPresent()) {
SomeObject someObject = o.get();
/* Do action 1 */
} else {
/* Do action 2 */
}
// or opt.map(/* action 1 */).orElse(/* action 2 */); in Java 8
}