|
The type conversion also takes place when you return a value from method. The type of value you are returning is converted to the declared return type of method. The rules of conversion are exactly same as the rules for method arguments. For example:
1. In a method that has a primitive return type, you can return any value that can be converted to the declared type. In the following example, method getAge() method has int return type, but it can return a char value.
public int getAge() {
char c = ‘a’;
return c; // valid as char can be converted to int
}
Thus, you can return any value that has a type that can be converted into the declared return type of method. In simple words, Java automatically converts the type when you return a value that is of narrower type than the return type. Since boolean and non-boolean primitives are incompatible, you cannot return a non-boolean value from a method with boolean as return type.
2. In a method that has an object reference as a return type, you can return any object reference that can be converted to the declared type. In the following example, method getAccount() method has Account return type, but it can return an object reference of CheckingAccount type.
public Account getAccount() {
CheckingAccount myAcc = new CheckingAccount()
return myAcc; // CheckingAccount can be converted to Account
}
Thus, you can return any object reference whose type can be converted into the declared return type of method. In simple words, Java automatically converts the type when you return a object reference of narrower type than the return type. For example, Object is wider data type than int[] array therefore following method is valid.
public Object getList() {
int[] numbers = new int[] {123, 343, 765, 213};
return numbers; // valid as int[] can be converted to Object
}
Tip: null value is convertible to any object reference type. Hence, you can return null from any method that declares an object reference type as return type. In fact you can also send null value to a method expecting any object reference type of argument.
3. Method with void as return type should not return anything.
In simple words, you should not have a return statement in a method with void return type. For example, all of the following method declarations are invalid.
public void doSomething1() {
// some implementation
return null; // invalid
}
public void doSomething2() {
// some implementation
return 0; // invalid
}