Java Special Operators

There are some special operators supported in Java language.

  • Conditional Operator ( ? : )
  • instanceof Operator

1. Conditional Operator ( ? : )

Conditional operator is supported in Java language. It is also known as ternary operator. The conditional operator contains three operands and it is used to evaluate Boolean expressions. This operator definnes which value should be assigned to the variable.

Syntax

variable x = (expression) ? value if true : value if false 
							

Let's take an example to see the usage of conditional operator.

Conditional Operator Example

/**
 * 
 * @author JavaTportal Corporation
 *
 */
public class Test {

	public static void main(String args[]) {
		int a, b;
		a = 10;
		b = (a == 1) ? 20 : 30;
		System.out.println("Value of b is : " + b);
		b = (a == 10) ? 20 : 30;
		System.out.println("Value of b is : " + b);
	}
}
Value of b is : 30
Value of b is : 20

instanceof Operator

The instanceof operator is used to specify object reference variables. It checks if the object is of a particular type (class type or interface type) or not.

Syntax

( Object reference variable ) instanceof  (class/interface type) 

If the left side object referred by the variable passes the IS-A check for the class/interface type on the right side, then the result is displayed as true.

Let's take some example to demonstrate the usage of instanceof operator.

Instanceof Operator Examples

/**
 * 
 * @author JavaTportal Corporation
 *
 */
public class Team {

	public static void main(String args[]) {
	      String name = "Kohli";
	      boolean result = name instanceof String;
	      System.out.println( result );
	   }
	} 
	

Output

	
true

Example 2

/**
 * 
 * @author JavaTportal Corporation
 *
 */
class Library {
}

public class Book extends Library {
	public static void main(String args[]) {
		Library a = new Book();
		boolean result = a instanceof Bookk;
		System.out.println(result);
	}
}

Output

	
true