Java Reference
In-Depth Information
The arithmetic operators we have described so far are binary operators, so called because they require
two operands. There are also unary versions of the + and - operators that apply to a single operand to
the right of the operator. Note that the unary - operator is not just a sign, as in a literal such as -345, it
is an operator that has an effect. When applied to a variable it results in a value that has the opposite
sign to that of the value stored in the variable. For example, if the variable count has the value -10, the
expression -count has the value +10. Of course, applying the unary + operator to the value of a
variable results in the same value.
Let's try out some simple arithmetic in a working console application.
Try It Out - Apples and Oranges (or Console Yourself)
Key in this example and save it in a file Fruit.java . You will remember from the last chapter that
each file will contain a class, and that the name of the file will be the same as that of the class with the
extension .java . Store the file in a directory that is separate from the hierarchy containing the SDK.
You can give the directory any name that you want, even the name Fruit if that helps to identify the
program that it contains.
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);
}
}
Just to remind you, to compile this program using the SDK, first make sure that the current directory is
the one containing your source file, and execute the command:
javac Fruit.java
As we noted in the previous chapter, you may need to use the -classpath option if the CLASSPATH
environment variable has been defined. If there are no errors, this will generate a file, Fruit.class ,
in the same directory, and this file contains the byte codes for the program. To execute the program you
then invoke the Java interpreter with the class name for your application program:
java Fruit
In some Java development environments, the output may not be displayed long enough for you to see
it. If this is the case, you can add a few lines of code to get the program to wait until you press Enter
before it ends. The additional lines to do this are shown shaded in the following listing:
Search WWH ::




Custom Search