Java provides a rich set of operators to manipulate
variables. We can divide all the Java operators into the
following groups:
·
Arithmetic
Operators
·
Relational
Operators
·
Bitwise
Operators
·
Logical
Operators
·
Assignment
Operators
·
Misc
Operators
The Arithmetic
Operators:
Arithmetic operators are used in mathematical
expressions in the same way that they are used in algebra. T he
following table lists the arithmetic operators:
Assume integer variable A holds 10 and variable B
holds 20, then:
Operator
|
Description
|
Example
|
+
|
Addition - Adds values on
either side of the operator
|
A + B will give 30
|
-
|
Subtraction - Subtracts right
hand operand from left hand operand
|
A - B will give -10
|
*
|
Multiplication - Multiplies
values on either side of the operator
|
A * B will give 200
|
/
|
Division - Divides left hand
operand by right hand operand
|
B / A will give 2
|
%
|
Modulus - Divides left hand
operand by right hand operand and returns
remainder
|
B % A will give 0
|
++
|
Increment - Increases the value
of operand by 1
|
B++ gives 21
|
--
|
Decrement - Decreases the value
of operand by 1
|
B-- gives 19
|
// Demonstrate the
basic arithmetic operators.
class BasicMath {
public static void
main(String args[]) {
// arithmetic using
integers
System.out.println("Integer
Arithmetic");
int a = 1 + 1;
int b = a * 3;
int c = b / 4;
int d = c - a;
int e = -d;
System.out.println("a
= " + a);
System.out.println("b
= " + b);
System.out.println("c
= " + c);
System.out.println("d
= " + d);
System.out.println("e
= " + e);
// arithmetic using
doubles
System.out.println("\nFloating
Point Arithmetic");
double da = 1 + 1;
double db = da * 3;
double dc = db / 4;
double dd = dc - a;
double de = -dd;
System.out.println("da
= " + da);
System.out.println("db
= " + db);
System.out.println("dc
= " + dc);
System.out.println("dd
= " + dd);
System.out.println("de
= " + de);
}
}
When you run this
program, you will see the following output:
Integer Arithmetic
a = 2
b = 6
c = 1
d = -1
e = 1
Floating Point
Arithmetic
da = 2.0
db = 6.0
dc = 1.5
dd = -0.5
de = 0.5
No comments:
Post a Comment