Returning null in a method whose signature says return int?

public int pollDecrementHigherKey(int x) { int savedKey, savedValue; if (this.higherKey(x) == null) { return null; // COMPILE-TIME ERROR } else if (this.get(this.higherKey(x)) > 1) { savedKey = this.higherKey(x); savedValue = this.get(this.higherKey(x)) - 1; this.remove(savedKey); this.put(savedKey, savedValue); return savedKey; } else { savedKey = this.higherKey(x); this.remove(savedKey); return savedKey; } }

The method lies within a class that is an extension of TreeMap, if that makes any difference... Any ideas why I can't return null here?

4

5 Answers

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.

2

int is a primitive data type . It is not a reference variable which can take null values . You need to change the method return type to Integer wrapper class .

Change your return type to java.lang.Integer . This way you can safely return null

The type int is a primitive and it cannot be null, if you want to return null, mark the signature as

public Integer pollDecrementHigherKey(int x) { x = 10; if (condition) { return x; // This is auto-boxing, x will be automatically converted to Integer } else if (condition2) { return null; // Integer inherits from Object, so it's valid to return null } else { return new Integer(x); // Create an Integer from the int and then return } return 5; // Also will be autoboxed and converted into Integer
}
1

Do you realy want to return null ? Something you can do, is maybe initialise savedkey with 0 value and return 0 as a null value. It can be more simple.

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like