Java Reference
In-Depth Information
As I said earlier, these arithmetic operators are binary operators, so called because they require two oper-
ands. 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 application.
TRY IT OUT: Apples and Oranges
Key in the code for this example and save it in a file with the name Fruit.java . Remember from the
previous chapter that each source file contains a class definition, and that the name of the file is the same
as that of the class with the extension .java . Store the file in a directory that is separate from the hier-
archy containing the JDK. 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);
}
}
code snippet Fruit.java
In some Java development environments, the output may not be displayed long enough for you to see it
when you run the program. 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 bolded in the following
listing:
import java.io.IOException; // For code that delays ending the
program
public class FruitWait {
public static void main(String[] args) {
Search WWH ::




Custom Search