Switch to full style
Java2 codes,problems ,discussions and solutions are here
Post a reply

Arithmetic Operators in java

Thu Jan 29, 2009 10:29 pm

Arithmetic Operators in Java :
Arithmetic operators are most well known programming basics. It is simple consists of summation, subtract, multiplication, division and mod. In java these operators are applied on all primitives of types short, integer, long, float, and double.

Plus- Operator (+)


Plus operator is used to sum variables as follows:
Example:
java code
int x=5;
int y=43;
int z=x+y;

You sum variables from different datatypes but to be attention to the lose of precision and casting:
java code
float x=54.3f;
int y=4;
long z=53l;
double sum=x+y+z;

Or using casting :
java code
float x=54.3f;
int y=4;
long z=53l;
int sum=(int) (x+y+z);

You can use the plus operator in suffix or prefix manner but here you work on one variable only, as follows:

Suffix , add the double plus the operators before the variable name:
Code:
int y=++x;

This means that the variable X one is increased by one before assigning its value to variable y.
Prefix, add the double plus operators after the variable name:
java code
int y=x++;

This means that the variable X one is increased by one after assigning its value to variable y.
You can use the prefix and suffix at the same time as:


Mines - Operator (-)


Used to subtract two variables
Example :
java code
int x=5;
int y=4;
int z=x-y


It also has suffix and prefix same as Plus operator

Example :
Code:
--x or x--

but it decreases the value of x by 1 .

Star- Operator (*)


Binary operator to multiply two variables or values :
Example :
java code
int x=5;
int y=4;
int z=x*y;


multiply the value of x by y .

Divide- Operator (/)


Example :
Code:
x/y


divide the value x by y .

Mod- Operator (%)


Mod is used to get the reminder of division between two numbers.
Example :
Code:
x%y

For Example:
java code
int x=13;
int z=54;
int y;
y=z%x;
System.out.println(y);

The output is :
Code:
2

Get the remainder of dividing x ,y



Post a reply
  Related Posts  to : Arithmetic Operators in java
 Results of Java expressions for arithmetic operations     -  
 Arithmetic data comparison and decompression java code     -  
 Bitwise operators in java     -  
 Comparison Operators in java     -  
 Program for "Selection of arithmetic operations" in Java     -  
 Arithmetic Promotion     -  
 Arithmetic data comparison in C#     -  
 PHP operators     -  
 C++ Increment Operators     -  
 using bit-wise operators in c++     -  

Topic Tags

Java Basics