Java by Example - introducing the operators
The basic operators in Java are:
Operator |
Explanation |
Example |
+ |
adds two numbers |
x = 1 + 2 |
- |
subtracts two numbers |
x = 7 - 4 |
* |
multiplies two numbers |
x = 4 * 5 |
/ |
divides two numbers |
x = 21 / 3 |
% |
modulo operator (rest of integer division) |
x = 17 % 3 //x = 2 |
For illustration, see the following example:
//Sourcecode
import java.awt.*;
import java.applet.*;
public class Project5D extends Applet
{
public void paint(Graphics g)
{
//two operators to do calculations with:
int op1=12, op2=4;
//we compute four numbers out of our two operators
int sum=op1+op2;
int diff=op1-op2;
int prod=op1*op2;
int quot=op1/op2;
g.setFont(new Font("Helvetica",Font.PLAIN,18));
g.drawString(op1+" + "+op2+" = "+sum, 100,40);
g.drawString(op1+" - "+op2+" = "+diff, 100,70);
g.drawString(op1+" * "+op2+" = "+prod, 100,100);
g.drawString(op1+" / "+op2+" = "+quot, 100,130);
}
}
|
A shorter and often used way to change variables, especially for incrementing and decrementing (adding or subtracting 1), can be seen in the following table:
Normal way (example) |
Short way |
x = x + 1 |
x++ |
x = x - 1 |
x-- |
x = x * 2 |
x*=2 |
x = x / 3 |
x/=3 |
x = x + 5 |
x+=5 |
x = x - 4 |
x-=4 |
The comparison operators and the logical operators are as follows:
Operator |
Meaning |
Example |
== |
equal |
if(a==b)c=d |
!= |
not equal |
if(a!=b)c=0 |
< |
less than |
if(a<b)c=d |
<= |
less or equal than |
if(a<=b)c=d |
> |
greater than |
if(a>b)c=d |
>= |
greater or equal than |
if(a>=b)c=d |
! |
not (logical) |
if(!a)c=d |
&& |
and (logical) |
if(a==1&&b==2)c=d |
|| |
or (logical) |
if(a<10||b==0)c=d |
Provided that "a" is a boolean variable, you can write: if(a)b=c instead of if(a==true)b=c, and if(!a)b=c instead of if(a==false)b=c, this is shorter and quite common. Remember that the operators * and / go before + and -, so you will often have to put combined expression inside brackets.
The following example demonstrates some of the basic operators, both comparison and boolean (see the sourcecode to understand what is going on here):
//Sourcecode
import java.awt.*;
import java.applet.*;
public class Project5E extends Applet
{
public void paint(Graphics g)
{
int a=3;
int b=3;
int c=2;
int d=5;
boolean x=false;
g.setFont(new Font("Helvetica",Font.PLAIN,18));
if(a==b)x=true;
g.drawString("x = "+x, 110,30);
if(a==c)x=true;
else x=false;
g.drawString("x = "+x, 110,50);
if(a>c)x=true;
else x=false;
g.drawString("x = "+x, 110,70);
if(b>=c)x=true;
else x=false;
g.drawString("x = "+x, 110,90);
if(a==b&&c>d)x=true;
else x=false;
g.drawString("x = "+x, 110,110);
if(a==b||c>d)x=true;
else x=false;
g.drawString("x = "+x, 110,130);
}
}
|
|