Operators and Methods
Introducing the Operators
The basic operators in Java are:
| Operator |
Explanation |
Example |
| + |
adds two numbers |
1 + 2 |
| - |
subtracts two numbers |
7 - 4 |
| * |
multiplies two numbers |
4 * 5 |
| / |
divides two numbers |
21 / 3 |
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 |
New on the Java Boutique:
New Review:
Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling
API boasts simplicity, ease-of-integration, a well-rounded feature
set, and it's free!
New Applet:
Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA
sequences into three useful formats.
Elsewhere on internet.com:
WebDeveloper Java
Lots of Java information on webdeveloper.com
WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.
ScriptSearch Java
Hundreds of free Java code files to download.
jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.
|