Misc Operators in Java

In addition to the above mentioned, there are several other operators, which are supported by Java.

Conditional Operator ( ? : ):

he conditional operator is a ternary operator that contains three operands. Essentially, this operator is used for the evaluation of boolean expressions. The operator tests the first operand or condition and if the condition is true, then the second value is assigned to the variable. However, if the condition is false, the third operand is assigned to the variable. The syntax of this operator is as follows:

variable a = (<condition>) ? valueiftrue : valueiffalse

Sample implementation:

public class myTest {

public static void main(String args[]){

int x, y;

x = 5;

y = (x == 5) ? 15: 40;

System.out.println( “y = ” + y );

y = (x == 34) ? 60: 95;

System.out.println( “x = ” + y );

}

}

The compilation and execution of this code shall give the following result:
y = 15
y = 95

instanceof Operator:

Only object reference variables can be used with this operator. The objective of this operator is to check is an object is an instance of an exiting class. The syntax of this operator is as follows:

(<object reference variable>) instanceof(<interface/class>)

Sample implementation of this operator and its purpose of use is given below:

public class myTest {

public static void main(String args[]){

int x = 4;

boolean resultant = x instanceof int;

System.out.println( resultant );

}

}

The output of this code shall be true. This operator can also be used in comparison. A sample implementation of this is given below:

class Animal {}public class Monkey extends Animal {

public static void main(String args[]){

Animal newa = new Monkey();

boolean resultant = newa instanceof Monkey;

System.out.println( resultant );

}

}

The output for this code will also be true.