Assignment and Ternary Operator

Author: Ravi Poswal

Assignment Operator 

The most prevalent operator in all of programming is the assignment operator. It is used to assign the value of the right-side variable. These are such types : (=, +=, -=, *=, /=, %=, &=, >>=, <<=, etc.) Example: 

Operator Example Same as
= a=5 a=5
+= a+=5 a=a+5
-= a-=5 a=a-5
*= a-=5 a=a*5
/= a-=5 a=a/5
%= a-=5 a=a%5
&= a-=5 a=a&5
|= a-=5 a=a|5
^= a-=2 a=a^2
>>= a-=2 a=a>>2
<<= a-=2 a=a<<2

 

Code Example

public class Main {
  public static void main(String[] args) {
    int a = 8;
    System.out.println(a);
 System.out.println(a += 5);
 System.out.println(a -= 5);
 System.out.println(a *= 5);
 System.out.println(a /= 5);
 System.out.println(a %= 5);
 System.out.println(a &= 5);
 System.out.println(a |= 5);
 System.out.println(a ^= 2);
 System.out.println(a >>= 2); // 1000 binary number of 8 and add 2 digit (0) on the right side then count the value i.e answer will be 2.  
 System.out.println(a <<= 2); //1000 of 8 and add 2 digit (0) on right side then count the value i.e answer will be 32
  }
}

Ternary Operator

It is the conditional operator used to evaulate a condition and return the value whether the condition true and false. This operator is the replacement of the short “if then else” statement symbol (?:)

Syntax: 

variable= condition ? expression 1 : expression 2; 

Code Example

class Main {
    public static void main(String[] args) {

        int n1 = 15, n2 = 10;
        int n = (n1 > n2) ? n1 : n2;
        System.out.println("Expression is = " + n);
    }
}