Java Reference
In-Depth Information
import java.io.IOException; // For code that delays ending the program
public class Fruit {
public static void main(String[] args) {
// Declare and initialize three variables
int numOranges = 5; // Count of oranges
int numApples = 10; // Count of apples
int numFruit = 0; // Count of fruit
numFruit = numOranges + numApples; // Calculate the total fruit count
// Display the result
System.out.println("A totally fruity program");
System.out.println("Total fruit is " + numFruit);
// Code to delay ending the program
System.out.println("(press Enter to exit)");
try {
System.in.read(); // Read some input from the keyboard
} catch (IOException e) { // Catch the input exception
return; // and just return
}
}
}
We won't go into this extra code here. If you need to, just put it in for the moment. You will understand
exactly how it works later in the topic.
The stuff between parentheses following main - that is String[] args - provides a means of
accessing data that passed to the program from the command line when you run it. We will be going
into this in detail later on so you can just ignore it for now, though you must always include it in the first
line of main() .
All that additional code in the body of the main() method just waits until you press Enter before
ending the program. If necessary, you can include this in all of your console programs to make sure
they don't disappear before you can read the output. It won't make any difference to how the rest of the
program works. We will defer discussing in detail what is happening in the bit of code that we have
added until we get to exceptions in Chapter 7.
If you run this program with the additional code, the output will be similar to the following window:
Search WWH ::




Custom Search