Java Reference
In-Depth Information
base value for natural logarithms (calculated with
static
Math
method
log
). These con-
stants are declared in class
Math
with the modifiers
public
,
final
and
static
. Making
them
public
allows you to use them in your own classes. Any field declared with keyword
final
is
constant
—its value cannot change after the field is initialized. Making these fields
static
allows them to be accessed via the class name
Math
and a dot (
.
) separator, just as
class
Math
's methods are.
Why Is Method
main
Declared
static
?
When you execute the Java Virtual Machine (JVM) with the
java
command, the JVM
attempts to invoke the
main
method of the class you specify—at this point no objects of
the class have been created. Declaring
main
as
static
allows the JVM to invoke
main
with-
out creating an instance of the class. When you execute your application, you specify its
class name as an argument to the
java
command, as in
java
ClassName
argument1
argument2
…
The JVM loads the class specified by
ClassName
and uses that class name to invoke method
main
. In the preceding command,
ClassName
is a
command-line argument
to the JVM
that tells it which class to execute. Following the
ClassName
, you can also specify a list of
String
s (separated by spaces) as command-line arguments that the JVM will pass to your
application. Such arguments might be used to specify options (e.g., a filename) to run the
application. As you'll learn in Chapter 7, Arrays and
ArrayList
s, your application can ac-
cess those command-line arguments and use them to customize the application.
Methods often require more than one piece of information to perform their tasks. We now
consider how to write your own methods with
multiple
parameters.
Figure 6.3 uses a method called
maximum
to determine and return the largest of three
double
values. In
main
, lines 14-18 prompt the user to enter three
double
values, then
read them from the user. Line 21 calls method
maximum
(declared in lines 28-41) to deter-
mine the largest of the three values it receives as arguments. When method
maximum
returns the result to line 21, the program assigns
maximum
's return value to local variable
result
. Then line 24 outputs the maximum value. At the end of this section, we'll discuss
the use of operator + in line 24.
1
// Fig. 6.3: MaximumFinder.java
2
// Programmer-declared method maximum with three double parameters.
3
import
java.util.Scanner;
4
5
public class
MaximumFinder
6
{
7
// obtain three floating-point values and locate the maximum value
8
public static void
main(String[] args)
9
{
10
// create Scanner for input from command window
11
Scanner input =
new
Scanner(System.in);
12
Fig. 6.3
|
Programmer-declared method
maximum
with three
double
parameters. (Part 1 of 2.)