Java Reference
In-Depth Information
The
if
-
else
statement in lines 32-35 sets
count
to
29
when the year is evenly divisible
by 4 and sets it to
28
otherwise.
The
if
statement in lines 36-37 uses the
&
operator to combine two conditional expres-
sions:
year % 100 == 0
and
year % 400 != 0
. If both these conditions are true,
count
is set to
28
.
The
countDays
method ends by returning the value of
count
in line 39.
When you run the
DayCounter
application, the
main()
method in lines 2-11 is executed.
In all Java applications, command-line arguments are stored in an array of
String
objects. This array is called
arguments
in
DayCounter
. The first command-line argument
is stored in
argument[0]
, the second in
argument[1]
, and upward until all arguments
have been stored. If the application is run with no arguments, the array is created with no
elements.
Lines 3-4 create
yearIn
and
monthIn
, two integer variables to store the year and month
that should be checked.
The
if
statement in line 5 uses
arguments.length
to make sure that the
arguments
array has at least one element. If it does, line 6 is executed.
4
Line 6 calls
parseInt()
, a class method of the
Integer
class, with
argument[0]
as an
argument. This method takes a
String
object as an argument, and if the string could be a
valid integer, it returns that value as an
int
. This converted value is stored in
monthIn
. A
similar thing happens in line 7;
parseInt()
is called with
argument[1]
, and this is used
to set
yearIn
.
The output of the program is displayed in lines 9-11. As part of the output, the
countDays()
method is called with
monthIn
and
yearIn
, and the value returned by this
method is displayed.
NOTE
At this point, you might want to know how to collect input from a
user in a program rather than using command-line arguments to
receive it. There isn't a method comparable to
System.out.
println()
that receives input. Instead, you must learn a bit more
about Java's input and output classes before you can receive input
in a program without a graphical user interface. This topic is cov-
ered during Day 15, “Working with Input and Output.”