Java Reference
In-Depth Information
c)
Method
instructions
, which does not take any arguments and does not return a value.
[
Note:
Such methods are commonly used to display instructions to a user.]
d)
Method
intToFloat
, which takes integer argument
number
and returns a
float
.
6.5
Find the error in each of the following program segments. Explain how to correct the error.
a)
void
g()
{
System.out.println(
"Inside method g"
)
;
void
h()
{
System.out.println(
"Inside method h"
);
}
}
b)
int
sum(
int
x,
int
y)
{
int
result;
result = x + y;
}
c)
void
f(
float
a);
{
float
a;
System.out.println(a);
}
d)
void
product()
{
int
a =
6
, b =
5
, c =
4
, result;
result = a * b * c;
System.out.printf(
"Result is %d%n"
, result);
return result;
}
6.6
Declare method
sphereVolume
to calculate and return the volume of the sphere. Use the
following statement to calculate the volume:
double
volume = (
4.0
/
3.0
) *
Math.PI
* Math.pow(radius,
3
)
Write a Java application that prompts the user for the
double
radius of a sphere, calls
sphereVolume
to calculate the volume and displays the result.
Answers to Self-Review Exercises
6.1
a) method call. b) local variable. c)
return
. d)
void
. e) top. f) last-in, first-out (LIFO).
g)
return;
or
return
expression
;
or encountering the closing right brace of a method. h)
SecureRan-
dom
. i) stack frame, activation record. j) stack overflow. k) scope. l) method overloading.
6.2
a) class body. b) block that defines method
rollDice
's body. c) class body. d) class body.
e) block that defines method
main
's body.
6.3
The following solution demonstrates the
Math
class methods in Fig. 6.2:
1
// Exercise 6.3: MathTest.java
2
// Testing the Math class methods.
3
public
class
MathTest
4
{
5
public static void
main(String[] args)
6
{