Java Reference
In-Depth Information
Self-Test Exercises
3. Write a method called
getNextYear
that could be added to the class
DateSecondTry
in Display 4.2 . The method
getNextYear
returns an
int
value
equal to the value of the
year
instance variable plus one.
Display 4.3
Using the Class in Display 4.2
1
public class
DemoOfDateSecondTry
2{
3
An invocation of a
void
method is a
statement.
public static void
main(String[] args)
4
{
5
DateSecondTry date =
new
DateSecondTry();
6
date.readInput();
7
int dayNumber = date.getDay();
8
System.out.println("That is the " + dayNumber
9
+ "th day of the month.");
10
}
An invocation of a method that returns a value is an expression that can be
used anyplace that a value of the type returned by the method can be used.
11 }
Sample Dialogue
Enter month, day, and year.
Do not use a comma.
July 4 1776
That is the 4th day of the month.
Local Variables
Look at the definition of the method
readInput()
given in Display 4.2 . That method
definition includes the declaration of a variable called
keyboard
. A variable declared
within a method is called a
local variable
. It is called
local
because its meaning is
local to—that is, confined to—the method definition. If you have two methods and
each of them declares a variable of the same name—for example, if both were named
keyboard
—they would be two different variables that just happen to have the same
name. Any change that is made to the variable named
keyboard
within one method
would have no effect upon the variable named
keyboard
in the other method.
As we noted in Chapter 1 , the
main
part of a program is itself a method. All variables
declared in
main
are variables local to the method
main
. If a variable declared in
main
local variable