returning a value

returning a value

Have to remember only six rules for returning a value:

We can return null in a method that has an object reference return type.

public Button doStuff() {
return null;
}
</code>
An array is a perfectly legal return type.
<code>
public String [] go() {
return new String[] {\"Fred\", \"Barney\", \"Wilma\"};
}


In a method with a primitive return type, we can return any value or variable that can be implicitly converted to the declared return type.

public int foo() {
char c = \'c\';
return c; // char is compatible with int
}


In a method with a primitive return type, We can return any value or variable that can be explicitly cast to the declared return type.

public int foo () {
float f = 32.5f;
return (int) f;
}


We must not return anything from a method with a void return type.

public void bar() {
return \"this is it\"; // Not legal!!
}


In a method with an object reference return type, We can return any object type that can be implicitly cast to the declared return type.

public Animal getAnimal() {
return new Horse(); // Assume Horse extends Animal
}
public Object getObject() {
int[] nums = {1,2,3};
return nums; // Return an int array, which is still an object
}
public interface Chewable { }
public class Gum implements Chewable { }
public class TestChewable {
// Method with an interface return type
public Chewable getChewable {
return new Gum(); // Return interface implementer
}
}

By:UMANG
Date:2004-03-09 00:00:00

Post Your Answers


User Email:

User Name:
Answers:

Related scjp1.5 chap6 Links

scjp1.5 chap6 interview questions and answers for experienced and fresher