Java Reference
In-Depth Information
The basic elements in the original version of the program are shown below:
This specifies that
is accessible from outside
of the class
main()
public class Fruit
{
This specifies that
exists without any objects
being defined
main()
public static void main(String[] args)
{
This specifies that
does not return a value
main()
//Declare and initialize three variables
int oranges = 5;
int apples = 10;
int fruit = 0;
fruit = oranges + apples; //Calculate the total fruit
System.out.println("A totally fruity program");
System.out.println("Total fruit is " + fruit); // Display the result
Execution starts with
this statement
Executable code
for main()
This displays the
first output line
This displays the
second output line
}
}
Our program consists of just one class, Fruit , and just one method, main() . Execution of an
application always starts at the first executable statement in the method main() . There are no objects
of our class Fruit defined, but the method main() can still be executed because we have specified it
as static . The method main() is always specified as public and static and with the return type
void . We can summarize the effects of these on the method as:
public
Specifies that the method is accessible from outside the Fruit class.
static
Specifies that the method is a class method that is to be executable, even though
no class objects have been created. (Methods that are not static can only be
executed for a particular object of the class, as we will see in Chapter 5.)
void
Specifies that the method does not return a value.
Don't worry if these are not completely clear to you at this point - you will meet them all again later.
The first three statements in main() declare the variables numOranges , numApples , and numFruit
to be of type int and initialize them to the values 5, 10, and 0 respectively. The next statement adds the
values stored in numOranges and numApples , and stores the result, 15, in the variable numFruit .
We then generate some output from the program.
Producing Output
The next two statements use the method println() which displays text output. The statement looks a
bit complicated but it breaks down quite simply:
This is the name of the class
that contains the object out
This is a method in
the object out
System.out.println("A totally fruity program");
This is a
variable
Whatever you specify between the parentheses
is passed to the
static
System
in the class
method and displayed
println()
Search WWH ::




Custom Search