Table of Contents

[ Intro | Begin | if/else | Loops | Arrays | Graphics | Animation | Mouse | Game | Real | Methods | Class | Class 2 | Applet | MouseClick | Thread | Button ]


Java For Kids tutorial 3

Java Operators

Operators are special symbols used to combine variables and/or values.

The first set of Operators that we will look are maths operations such as plus, minus , multiply, divide.

Operator Name Example In plain English
+ Plus 1 + 2 one plus two
- Minus 7 - 3 seven minus three
* Multiply 5 * 2 five multiplied by two
/ Divide 9 / 3 nine divided by three

Here is a simple program that uses these operators:

    void main() {
            int a = 1;
            int b = 2;
            int c = a + b;
            printLine(c);
    }

What should you get printed out?

Java Relational Operators

Relational Operators compare two values to see if they are equal or one is greater or less than the other one.

Oper Meaning Example Example in english
= Is equal to a = b a equals b
!= Is not equal to c != d c is not equal to d
< Less Than x < 10 x is less than 10 (does not include ten)
> Greater Than y > 0 y is greater than zero(doesn't include 0)
Less than or equal to age ⇐ 25 age is less than or equal to 25 (includes 25)
>= Greater than or equal to wage >= 350 wage is greater than or equal to 350(includes 350)

Using the Java relational Operators

The main use for the above relational operators are in CONDITIONAL phrases. Or to put it simply in “What if” situations. Lets say you were writing a program for bus fares. And you wanted to know the correct fare based on age. How would you describe this problem? Here is a way:

    IF the passenger's age is greater than 18,
    THEN the price is normal Fare.
    OTHERWISE The price is half fare.

Lets write that same algorithm (what is written above in plain english) in Java. It is a CONDITIONAL phrase.

    if (age > 18)
    {
            price = 80;
    }
    else
    {
            price = 40;
    }

OK lets write our Java program to calculate bus fares.

    void main() {
	// 1. declare variables
	int fare = 80;
	int age;
 
	// 2. get the age
	printLine("What is your age please?");
 
	// 3. the user enters their age
	age = readInt();
 
	// 4. check if over 18
	if (age>18)
	{
	    printLine("The fare will be " +
	        fare + ", thank you.");
	}
	// 5. the IF statement is false
	else
	{
	    printLine("The fare will be " +
	        fare/2 + ", thanks kid");
	}
    }

Notes on the bus fare java program

Both set of statements, (if or else) cannot both be processed. Either one of them will be carried out. It is a case of EITHER OR.

    if (this statement is true)
    {
        // perform the actions inside these curly brackets
    }
    else
    {
        // if the statement after the IF is false or untrue then
        // perform the actions inside these brackets here
    }