Java Reference
In-Depth Information
You can also declare more than one variable in one declaration, and initialize some or all.
// Declaration of variables num1, num2 and num3. Initialization of only num1 and num3
int num1 = 10, num2, num3 = 200;
// Declaration and initialization of variables num1, num2 and num3
int num1 = 10, num2 = 20, num3 = 30;
Java will not let you use a variable unless it has been assigned a value either through the process of initialization
or assignment. Java implicitly initializes variables declared in a particular context. Variables declared in other contexts
must be initialized, or assigned a value, before they are used, if Java does not initialize them implicitly. I will discuss
the implicit initialization of a variable by Java in the chapter on classes and objects. It is a good programming practice
to initialize a variable at the time of its declaration.
Arithmetic Operators
Table 4-1 lists all arithmetic operators in Java. All operators listed in Table 4-1 can only be used with numeric type
operands. That is, both operands to arithmetic operators must be one of types byte , short , char , int , long , float ,
and double . These operators cannot have operands of boolean primitive type and reference type. The following
sections describe arithmetic operators in detail.
Table 4-1. List of Arithmetic Operators in Java
Operators
Description
Type
Usage
Result
+
2 + 5
Addition
Binary
7
-
5 - 2
Subtraction
Binary
3
+
+5
Unary plus
Unary
Positive five. Same as 5
-
-5
Unary minus
Unary
Negative of five
*
5 * 3
Multiplication
Binary
15
/
5 / 2
Division
Binary
2
6 / 2
3
5.0 / 2.0
2.5
6.0 / 2.0
3.0
%
5 % 3
Modulus
Binary
2
++
num++
Increment
Unary
Evaluates to the value of num,
increments num by 1.
--
num--
Evaluates to the value of num ,
decrements num by 1.
Decrement
Unary
+=
num += 5
Adds 5 to the value of num and
assigns the result to num . If num is 10,
the new value of num will be 15.
Arithmetic
compound-assignment
Binary
( continued )
 
 
Search WWH ::




Custom Search