Java Ternary Operators - androidpro.in

Unary operators are used with only one operand. For example, ++ is a unary operator that increases the value of a variable by 1. That is, ++15 will return 16.

Different types of unary operators are:

Operator

Meaning

+

Unary plus: not necessary to use since numbers are positive without using it

-

Unary minus: inverts the sign of an expression

++

Increment operator: increments value by 1

--

Decrement operator: decrements value by 1

!

Logical complement operator: inverts the value of a boolean

 

Increment and Decrement Operators

Java also provides increment and decrement operators: ++ and -- respectively. ++ increases the value of the operand by 1, while -- decrease it by 1. For example,

 

int num = 15;

 

// increase num by 1

++num;

Here, the value of num gets increased to 16 from its initial value of 15.

Example 5: Increment and Decrement Operators

 

class Main {

  public static void main(String[] args) {

   

    // declare variables

    int a = 12, b = 12;

    int result1, result2;

 

    // original value

    System.out.println("Value of a: " + a);

 

    // increment operator

    result1 = ++a;

    System.out.println("After increment: " + result1);

 

    System.out.println("Value of b: " + b);

 

    // decrement operator

    result2 = --b;

    System.out.println("After decrement: " + result2);

  }

}