Learning Java
Custom Search

Previous Next

Operators

Java contains many operators to perform various operations upon data. These operators are used to assign values to variables, to perform arithmetic, to compare data, and more.

Assignment Operator

Variables are assigned values by using the equal sign, =. Some examples are:

	num1 = 5;
	f2 = 2.45;
	apple = "red fruit";
	x = y + 2;

Arithmetic Operators

The following are the 5 basic operators for arithmetic.

    Operator Operation Example
    + addition 16 + 3
    - subtraction 16 - 3
    * multiplication 16 * 3
    / division 16 / 3
    % modulus 16 % 3

The modulus operator tells us to divide the first operand by the second one. The remainder is our answer. A modulus example:

    int k;
    k = 28 % 8;
    This will give k the value of 4, since dividing 8 into 28 is 3 and leaves a remainder of 4.
    k = 24 % 8;
    This will give k the value of 0.

Unary Operators

The above table showed binary operators which has an operand on each side of the sign. A unary operator has only one operand.

    Syntax Meaning
    ++x increment x by 1 before using the value of x
    x++ increment x by 1 after using the value of x
    - -x decrement x by 1 before using the value of x
    x- - decrement x by 1 after using the value of x

An example:

    int b;
    int a = 10;
    b = 5 * (a- -);
    Here a is 9 and b is 50. We did not subtract 1 from a until after we calculated b.
    int b;
    int a = 10;
    b = 5 * (- -a);
    Now a is 9 and b is 45. We subtracted 1 from a before we calculated b.

Logical and Relational Operators

At times, we need to make a decision whether or not to execute a set of commands based on whether an expression is true or false. Java provides logical and relational operators to assist in determining the Boolean value of true or false for a particular expression.

    Operator Operation Example
    == equal a == 7
    != not equal a != 7
    < less than a < 7
    > greater than a > 7
    <= less than or equal to a <= 7
    >= greater than or equal to a >= 7
    && AND (a < 7) && (b > 0)
    || OR (a < 7) || (b > 0)
    ! NOT !(a < 7)

In the following 2 statements, the first would cause a compiler error.

    if (a = b) System.out.println("Single equal sign used");
    if (a == b) System.out.println("Double equal sign used");

Comparing Objects

When you are comparing 2 objects, you should use the equals() method of the object, as shown below.

	String s1 = "Life is good";
	String s2 = "Life is good";

	if (s1.equals(s2))
	    System.out.println("These objects are equal.");

Previous Next

Steps In Learning

Contact us

Copyright © 2008      N. Nelson      All Rights Reserved