Arithmetic Operators in Java
For example, in below statement the expression 47 + 3, the numbers 47 and 3 are operands. The arithmetic operators are examples of binary operators because they require two operands. The operands of the arithmetic operators must be of a numeric type. You cannot use them on boolean types, but you can use them on char types, since the char type in Java is, essentially, a subset of int.
int a = 47+3;
Operator
|
Use
|
Description
|
Example
|
+
|
x + y
|
Adds x and y
|
float num = 23.4 + 1.6; // num=25
|
-
|
x - y
|
Subtracts y from x
|
long n = 12.456 – 2.456; //n=10
|
-x
|
Arithmetically negates x
|
int i = 10; -i; // i = -10
| |
*
|
x * y
|
Multiplies x by y
|
int m = 10*2; // m=20
|
/
|
x / y
|
Divides x by y
|
float div = 20/100 ; // div = 0.2
|
%
|
x % y
|
Computes the remainder of dividing x by y
|
int rm = 20/3; // rm = 2
|
In Java, you need to be aware of the type of the result of a binary (two-argument) arithmetic operator.
- If either operand is of type double, the other is converted to double.
- Otherwise, if either operand is of type float, the other is converted to float.
- Otherwise, if either operand is of type long, the other is converted to long.
- Otherwise, both operands are converted to type int.
- If the operand is of type byte, short, or char then the result is a value of type int.
- Otherwise, a unary numeric operand remains as is and is not converted.
The following simple program demonstrates the arithmetic operators. It also illustrates the difference between floating-point division and integer division.
Example :
The Modulus Operator
Example:
public class RemainderDemo
{
public static void main (String [] args)
{
int x = 15;
int int_remainder = x % 10;
System.out.println("The result of 15 % 10 is the "
+ "remainder of 15 divided by 10. The remainder is " + int_remainder);
double d = 15.25;
double double_remainder= d % 10;
System.out.println("The result of 15.25 % 10 is the "
+ "remainder of 15.25 divided by 10. The remainder is " + double_remainder);
}
}
Shortcut Arithmetic Operators (Increment and decrement operator)
{
public static void main(String[] args)
{
int a,b,c,d;
a=b=c=d=100;
int p = a++;
int r = c--;
int q = ++b;
int s = --d;
System.out.println("prefix increment operator result= "+ p + " & Value of a= "+ a);
System.out.println("prefix decrement operator result= "+ r + " & Value of c= "+c);
System.out.println("postfix increment operator result= "+ q + " & Value of b= "+ b);
System.out.println("postfix decrement operator result= "+ s + " & Value of d= "+d);
}
}
Summary
- Arithmetic operators are used in mathematical expressions.
- Arithmetic operators are +(addition) , -(subtraction), * (multiplication), / (division) and % (reminder).
- Java provides built in short-circuit addition and subtraction operators.
No comments:
Post a Comment