7.6 Java OperatorsHomepage  « Java6 Certification « 7.6 Java Operators

In our final lesson within this section we look at the various assignment, arithmetic, relational, logical operators that are available in Java and how to use them. We then take a look at the ? : tenary (takes three operands) operator and finish our certification studies with a look at the instanceof operator.

Lets take a look at the points outlined at the Oracle Website for this part of the certification.

  • Section 7: Fundamentals

    • Write code that correctly applies the appropriate operators including assignment operators (limited to: =, +=, -=), arithmetic operators (limited to: +, -, *, /, %, ++, --), relational operators (limited to: <, <=, >, >=, ==, !=), the instanceof operator, logical operators (limited to: &, |, ^, !, &&, ||), and the conditional operator ( ? : ), to produce a desired result. Write code that determines the equality of two objects or two primitives.

Assignment Operatorsgo to top of page Top

The single equal sign = is used for assignment in Java and we have been using this throughout the lessons so far. This operator is fairly self explanatory and takes the form variable = expression;. A point to note here is that the type of variable must be compatible with the type of expression.

Shorthand Assignment Operators

The shorthand assignment operators allow us to write compact code that is is implemented more efficiently.

Operator Meaning Example Result Notes
+=Additionint b = 5; b += 5;10
-=Subtractionint b = 5; b -= 5;0
/=Divisionint b = 7, b /= 22;3When used with an integer type, any remainder will be truncated.
*=Multiplicationint b = 5; b *= 5;25
%=Modulusint b = 5; b %= 2;1Holds the remainder value of a division.
&=ANDboolean a = false; boolean b = false;
if (a &= b) {..}

boolean a = false; boolean b = true;
if (a &= b) {..}

boolean a = true; boolean b = false;
if (a &= b) {..}

boolean a = true; boolean b = true;
if (a &= b) {..}

false

false

false

true
Will check both operands for true values and assign true or false to the first operand dependant upon the outcome of the expression.
|=ORboolean a = false; boolean b = false;
if (a |= b) {..}

boolean a = false; boolean b = true;
if (a |= b) {..}

boolean a = true; boolean b = false;
if (a |= b) {..}

boolean a = true; boolean b = true;
if (a |= b) {..}

false

true

true

true
Will check both operands for true values and assign true or false to the first operand dependant upon the outcome of the expression.
^=XORboolean a = false; boolean b = false;
if (a ^= b) {..}

boolean a = false; boolean b = true;
if (a ^= b) {..}

boolean a = true; boolean b = false;
if (a ^= b) {..}

boolean a = true; boolean b = true;
if (a ^= b) {..}

false

true

true

false
Will check both operands for different boolean values and assign true or false to the first operand dependant upon the outcome of the expression.

Automatic Type Conversion, Assignment Rulesgo to top of page Top

The following table shows which types can be assigned to which other types, of course we can assign to the same type so these boxes are greyed out.

When using the table use a row for the left assignment and a column for the right assignment. So in the highlighted permutations byte = int won't convert and int = byte will convert.

Type boolean char byte short int long float double
boolean = NONONONONONONO
char = NONONONONONONO
byte = NONONONONONONO
short = NONOYESNONONONO
int = NOYESYESYESNONONO
long = NOYESYESYESYESNONO
float = NOYESYESYESYESYESNO
double = NOYESYESYESYESYESYES

Casting Incompatible Typesgo to top of page Top

The above table isn't the end of the story though as Java allows us to cast incompatible types. A cast instructs the compiler to convert one type to another enforcing an explicit type conversion.

A cast takes the form    target = (target-type) expression.

There are a couple of things to consider when casting incompatible types:

  • With narrowing conversions such as an int to a short there may be a loss of precision if the range of the int exceeds the range of a short as the high order bits will be removed.
  • When casting a floating-point type to an integer type the fractional component is lost through truncation.
  • The target-type can be the same type as the target or a narrowing conversion type.
  • The boolean type is not only incompatible but also inconvertible with other types.

Lets look at some code to see how casting works and the affect it has on values:


/*
  Casting Incompatible Types
*/ 
public class Casting {

    public static void main (String[] args) {
        char a = 'D';
        short b = 129;
        int c = 4127;
        long d = 33445566L;
        float e = 12.34F;
        double f = 456.789;
        byte g = (byte) a;
        System.out.println(a + " When cast from char to byte has the value: " + g); 
        g = (byte) b;
        System.out.println(b + " When cast from short to byte has the value: " + g); 
        g = (byte) c;
        System.out.println(c + " When cast from int to byte has the value: " + g); 
        g = (byte) d;
        System.out.println(d + " When cast from long to byte has the value: " + g); 
        g = (byte) e;
        System.out.println(e + " When cast from float to byte has the value: " + g); 
        g = (byte) f;
        System.out.println(e + " When cast from dobule to byte has the value: " + g); 
    }
    
}

run casting

The first thing to note is we got a clean compile because of the casts, all the type conversions would fail otherwise. You might be suprised by some of the results shown in the screenshot above, for instance some of the values have become negative. Because we are truncating everything to a byte we are losing not only any fractional components and bits outside the range of a byte, but in some cases the signed bit as well. Casting can be very useful but just be aware of the implications to values when you enforce explicit type conversion.

Arithmetic Operatorsgo to top of page Top

We are familiar with most of the arithmetic operators in the table below from everyday life and they generally work in the same way in Java. The arithmetic operators work with all the Java numeric primitive types and can also be applied to the char primitive type.

Operator Meaning Example Result Notes
+Additionint b = 5; b = b + 5;10
-Subtractionint b = 5; b = b - 5;0
/Divisionint b = 7, b = b / 22;3When used with an integer type, any remainder will be truncated.
*Multiplicationint b = 5; b = b * 5;25
%Modulusint b = 5; b = b % 2;1Holds the remainder value of a division.
++Incrementint b = 5; b++;6See below.
--Decrementint b = 5; b--;4See below.

Increment And Decrement Operators

Both these operators can be prepended (prefix) or appended (postfix) to the operand they are used with. When applied to an operand as part of a singular expression it makes no difference whether the increment and decrement operators are applied as a prefix or postfix. With larger expressions however, when an increment or decrement operator precedes its operand, Java will perform the increment or decrement operation prior to obtaining the operand's value for use by the rest of the expression. When an increment or decrement operator follows its operand, Java will perform the increment or decrement operation after obtaining the operand's value for use by the rest of the expression. Lets look at some code to illustrate how this works:


/*
  Increment And Decrement Operators
*/ 
public class IncDec {

    public static void main (String[] args) {
        byte a = 5;
        byte b = 5;
        // Singular Expressions
        a++;
        ++b;
        System.out.println("a = " + a);
        System.out.println("b = " + b);
        // Larger Expressions
        a = 1;
        b = a++;
        System.out.println("b using a postfix = " + b);
        a = 1;
        b = ++a;
        System.out.println("b using a prefix = " + b);
    }

}

run incdec

As you can see with the last two lines of output, the postfix increment is applied after the expression is evaluated, whereas the prefix increment is applied before.

Relational Operatorsgo to top of page Top

Relational Operators refer to the relationships that values can have to each other. Relational Operators produce a true or false result and are used with control statements such as if and while. Any type can be compared for equality or inequality but only types that support an ordering relationship can be applied for comparison. The table below clarifies this.

Operator Meaning Example Result Notes
==Equal toint a = 5; int b = 5;
if (a == b) {..}
trueAll types can be compared for equality
!=Not Equal toint a = 5; int b = 5;
if (a != b) {..}
falseAll types can be compared for inequality
<Less thanint a = 5; int b = 5;
if (a < b) {..}
falseCan be used with all numeric types and the char type.
<=Less than or equal toint a = 5; int b = 5;
if (a <= b) {..}
trueCan be used with all numeric types and the char type.
>Greater thanint a = 5; int b = 5;
if (a > b) {..}
falseCan be used with all numeric types and the char type.
>=Greater than or equal toint a = 5; int b = 5;
if (a >= b) {..}
trueCan be used with all numeric types and the char type.

Logical Operatorsgo to top of page Top

Logical Operands must be the boolean type and the result of a logical operation is the boolean type and are used with control statements such as if and while. The following table shows all possible combinations and their result.

Operator Meaning Example Result Notes
&ANDboolean a = false; boolean b = false;
if (a & b) {..}

boolean a = false; boolean b = true;
if (a & b) {..}

boolean a = true; boolean b = false;
if (a & b) {..}

boolean a = true; boolean b = true;
if (a & b) {..}

false

false

false

true
Will check both operands for true values, even if the first operand is false.
&&Short-circuit ANDif (a && b) {..}Same results as AND but if the first operand returns false, the second operand will not be checked (short-circuited) and false is returned.
|ORboolean a = false; boolean b = false;
if (a | b) {..}

boolean a = false; boolean b = true;
if (a | b) {..}

boolean a = true; boolean b = false;
if (a | b) {..}

boolean a = true; boolean b = true;
if (a | b) {..}

false

true

true

true
Will check both operands for true values, even if the first operand is true.
||Short-circuit ORif (a || b) {..}Same results as OR but if the first operand returns true, the second operand will not be checked (short-circuited) and true is returned.
^XOR (exclusive OR)boolean a = false; boolean b = false;
if (a ^ b) {..}

boolean a = false; boolean b = true;
if (a ^ b) {..}

boolean a = true; boolean b = false;
if (a ^ b) {..}

boolean a = true; boolean b = true;
if (a ^ b) {..}

false

true

true

false
Will check both operands and return true if they have different boolean values.
!NOTboolean a = false;
if (!a) {..}

boolean a = true;
if (!a) {..}

true

false
Will check if operand is not true.

The short-circuit operators && and || can be more efficient to use; if you want both operands to be evaluated use the & and | operators.

The ? : Operatorgo to top of page Top

The ? : tenary (takes three operands) operator can be used to replace an if....else construct of the following form:

Construct Description
if....else
if (condition) {
    var = expression1;
} else {
    var = expression2;
}

Assign result of expression1 to var  if condition evaluates to true,

otherwise assign result of expression2 to var.
? : Operator
expression1 ? expression2 : expression3
  • expression1 can be any expression that returns a boolean value.
  • expression2 and expression3 can be any returned type apart from void.
  • expression2 and expression3 must be of the same type type.

If expression1 returns true evaluate expression2,

otherwise evaluate expression3,

Lets examine some code to see how the ? : operator works:


/*
  The ? : Operator
*/ 
public class QuestionMarkOperator {

    public static void main (String[] args) {
	int int1 = 1234, int2 = 5678, maxInt;
	if (int1 > int2) {
	    maxInt = int1;
	}
	else {
  	    maxInt = int2;
	}
        System.out.println("Using an if...else construct maxInt holds a value of: " + maxInt);
        
	maxInt = (int1 > int2) ? int1 : int2;
        System.out.println("Using the ? : operator maxInt holds a value of: " + maxInt);
    } 
}

run ? operator

You should see 2 lines of output with the same values showing how we can replace this form of the if....else construct with the ? : operator.

The instanceof Operatorgo to top of page Top

We use the instanceof operator to find out whether an object is of a particular type. Because Java is a strongly typed language, it cares about the type of the variables we declare and try to use. So just be aware when using the instanceof operator to check for a String object, when you have an instance of Monkey that knows nothing about String, you will get a compiler error.


/*
  Test Class for instanceof Operator
*/ 
public class Testinstanceof {

    public static void main (String[] args) {
        Cat moggy = new Cat();
        if (moggy instanceof Cat) {;   // Check for Cat instance
            System.out.println("moggy is a Cat.");
        } 
    } 
}

run runinstanceof

The screenshot shows the output from the Testinstanceof test class, showing that moggy is indeed a Cat.

We can also use the instanceof operator with polymorphic types and this is discussed next.

Using instanceof With Interfacesgo to top of page Top

The following program uses the Vehicle hierarchy and the PublicTransport interface as shown in the OO Concepts - Interfaces lesson to show some instanceof usages:


/*
  A Minibus Class
*/ 
public class Minibus extends Bus {
    public static void main(String[] args) {
        Vehicle bus = new Bus();
        checkType(bus);
        Vehicle car = new Car();
        checkType(car);
        Vehicle minibus = new Minibus();
        checkType(minibus);
        PassengerPlane  pp = new PassengerPlane();
        checkType(pp);
        Vehicle taxi = new Taxi();
        checkType(taxi);
    }
    public static void checkType(Object o) {
        if (o instanceof Minibus) {
            ((Minibus)o).MinibusClassOnlyMethod(); // Downcast to minibus
        }
        if (o instanceof PublicTransport ) {
            /*
              Downcast argument to PublicTransport interface type
            */                
            PublicTransportOnlyMethod(((PublicTransport)o));  
        }
    } 
    private static void MinibusClassOnlyMethod() {
        System.out.println("We are in the MinibusClassOnlyMethod()."); 
        System.out.println("We have safely downcast to the Minibus class to get here."); 
    } 
    private static void PublicTransportOnlyMethod(PublicTransport pt) {
        pt.queue(10); 
        pt.payFare(2); 
    } 
}

In the code above we are instantiating objects from two different hierachies. We call the checkType(Object o) which uses The Object Superclass as a parameter. This enables us to pass any argument to the method. Within the method we firstly use the instanceof operator to test for a Minubus type and if so we print some messages for that type. We then check to see if this type is an instance of the PublicTransport interface. If it is we cast the object argument to the PublicTransport interface type and pass this to the PublicTransportOnlyMethod(PublicTransport pt) method. Within this method the overridden methods for the appropriate class are called.

run Minibus Class

The above screenshot shows the output of running our Minibus test class. If you look closely at the output you will see that the queue() and payFare() methods are output twice for the Bus class and yet we only made one occurrence of Bus. The second lot of output is actually for the Minibus class. The reason for this is inheritance; if a superclass implements an interface, then a subclass will have an implicit implementation through the superclass.

Related Java6 Tutorials

Beginning Java6 - Operators
Beginning Java6 - Conditional statements
Objects & Classes - Reference Variables
OO Concepts - Interfaces - Using instanceof With Interfaces

go to home page Java6 Tutor Homepage go to home page Top