Java Reference
In-Depth Information
figure 1.5
Layout of a
switch
statement
1
switch(
someCharacter
)
2
{
3
case
'('
:
4
case
'['
:
5
case
'{'
:
6
// Code to process opening symbols
7
break;
8
9
case
')'
:
10
case
']'
:
11
case
'}'
:
12
// Code to process closing symbols
13
break;
14
15
case
'\n'
:
16
// Code to handle newline character
17
break;
18
19
default:
20
// Code to handle other cases
21
break;
22
}
methods
1.6
A
method
is similar
to a function in
other languages.
The
method header
consists of the
name, return type,
and parameter list.
The
method decla-
ration
includes the
body.
What is known as a function or procedure in other languages is called a
method
in Java. A more complete treatment of methods is provided in Chapter 3. This
section presents some of the basics for writing functions, such as
main
, in a non-
object-oriented manner (as would be encountered in a language such as C)
so that we can write some simple programs.
A
method header
consists of a name, a (possibly empty) list of parame-
ters, and a return type. The actual code to implement the method, sometimes
called the
method body
, is formally a
block
. A
method declaration
consists of
a header plus the body. An example of a method declaration and a
main
routine
that uses it is shown in Figure 1.6.
By prefacing each method with the words
public static
, we can mimic the
C-style global function. Although declaring a method as
static
is a useful
technique in some instances, it should not be overused, since in general we do
not want to use Java to write “C-style” code. We will discuss the more typical
use of
static
in Section 3.6.
The method name is an identifier. The parameter list consists of zero or
more
formal parameters
, each with a specified type. When a method is
called, the
actual arguments
are sent into the formal parameters using normal
A
public static
method is the
equivalent of a
“C-style”
global function.
In
call-by-value
, the
actual arguments
are copied into the
formal parameters.
Variables are
passed using call-
by-value.
Search WWH ::
Custom Search