Java Reference
In-Depth Information
In the expression (iii), 3 and 4 are the operands for the operator + . Because the operator +
has two operands, in this expression, + is a binary operator. Now consider the following
expression:
+27
2
In this expression, the operator + is used to indicate that the number 27 is positive. Here,
because + has only one operand, it acts as a unary operator.
From the preceding discussion, it follows that - and + can be unary or binary arithmetic
operators. However, the arithmetic operators * , / , and % are binary and must have two
operands.
The following examples show how arithmetic operators—especially / and % —work with
integral data types. As you can see from these examples, the operator / represents the
quotient in ordinary division when used with integral data types.
EXAMPLE 2-2
Arithmetic
Expression
Result
Description
2 + 5
7
13 + 89
102
34 - 20
14
45 - 90
-45
2 * 7
14
5 / 2
2
In the division 5 / 2, the quotient is 2 and the remainder is 1.
Therefore, 5 / 2 with the integral operands evaluates to the
quotient, which is 2.
14 / 7
2
34 % 5
4
In the division 34 / 5, the quotient is 6 and the remainder is 4.
Therefore, 34 % 5 evaluates to the remainder, which is 4.
4 % 6
4
In the division 4 / 6, the quotient is 0 and the remainder is 4.
Therefore, 4 % 6 evaluates to the remainder, which is 4.
The following Java program evaluates the preceding expressions:
// This program illustrates how integral expressions evaluate.
public class Example2_2
{
public static void main(String[] args)
{
System.out.println("2 + 5 = " + (2 + 5));
System.out.println("13 + 89 = " + (13 + 89));
System.out.println("34 - 20 = " + (34 - 20));
System.out.println("45 - 90 = " + (45 - 90));
Search WWH ::




Custom Search