Write a Program to show how Ternary and Compound Operators Works in java

The Conditional operator is the only ternary (operator takes three arguments) operator in Java. The operator evaluates the first argument and, if true, evaluates the second argument. If the first argument evaluates to false, then the third argument is evaluated. The conditional operator is the expression equivalent of the if-else statement. The conditional expression can be nested and the conditional operator associates from right to left

Program: Ternary Operator
public class TernaryOperatorsDemo {

public TernaryOperatorsDemo() {
int x = 10, y = 12, z = 0;
z = x > y ? x : y;
System.out.println("z : " + z);
}
public static void main(String args[]) {
new TernaryOperatorsDemo();
}
}

Compound Operators
The compound operators perform shortcuts in common programming operations. Java has eleven compound assignment operators.

Syntax:

argument1 operator = argument2.

Program: Compound Operator
public class CompoundOperatorsDemo {

public CompoundOperatorsDemo() {
int x = 0, y = 5;
x += 3;
System.out.println("x : " + x);
y *= x;
System.out.println("y : " + y);
}
public static void main(String args[]) {
new CompoundOperatorsDemo();
}
}
Similarly other operators can be applied as shortcuts. Other assignment operators include boolean logical, bitwiseand shift operators

No comments:

Google Search