Java Reference
In-Depth Information
Common Programming Error
Statement after Return
It's illegal to place other statements immediately after a
return
statement,
because those statements can never be reached or executed. New programmers
often accidentally do this when trying to print the value of a variable after return-
ing. Say you've written the
hypotenuse
method but have accidentally written
the parameters to
Math.pow
in the wrong order, so the method is not producing
the right answer. You would try to debug this by printing the value of
c
that is
being returned. Here's the faulty code:
// trying to find the bug in this buggy version of hypotenuse
public static double hypotenuse(double a, double b) {
double c = Math.sqrt(Math.pow(2, a) + Math.pow(2, b));
return c;
System.out.println(c); // this doesn't work
}
The compiler complains about the
println
statement being unreachable, since
it follows a
return
statement. The compiler error output looks something like this:
Triangles.java:10: unreachable statement
System.out.println(c);
^
Triangles.java:11: missing return statement
}
^
2 errors
The fix is to move the
println
statement earlier in the method, before the
return
statement:
public static double hypotenuse(double a, double b) {
double c = Math.sqrt(Math.pow(2, a) + Math.pow(2, b));
System.out.println(c); // better
return c;
}
We've spent a considerable amount of time discussing the primitive types in Java and how
they work, so it's about time that we started talking about objects and how they work.
The idea for objects came from the observation that as we start working with new
kinds of data (integers, reals, characters, text, etc.), we find ourselves writing a lot of
Search WWH ::
Custom Search