Java Basic Operators: Unary, Binary, Ternary Operators

Types of Java Operators

Java uses unary operators, binary operators, ternary operators.

  • Unary operators: operator op or op operator
  • Byadic operators: op1 operator op2
  • Ternary operators: expr ? op1 : op2

Unary and Binary Operators and Usage

Operator How to use Explanation Remarks
+ op1 + op2 Add op1 and op2 Unary and Binary
op1 – op2 Subtract op2 from op1 Unary and Binary
* op1 * op2 Multiply op1 and op2 Binary
/ op1 / op2 Divide op1 by op2 Binary
% op1 % op2 The rest of op1 divided by op2 Binary
++ op++ Pre-evaluate the value of op and increment 1 Unary
++ ++op Increase the value of op by 1 and evaluate Unary
op– Pre-evaluate the value of op and decrement 1 Unary
–op Decrease the value of op by 1 and evaluate Unary

Ternary operator

The ternary operator is an abbreviation of the if-then-else statement of the selection statement.

Equation 1? Equation 2: Equation 3

The ternary operator evaluates Equation 1 to determine true or false; if true, executes Equation 2; if false, executes Equation 3 and returns the result to Equation 1.

flag = count > 0 ? 0 : 1;

The above code evaluates count and 0 as an example of a ternary operator. If it is true, it returns 0, and if it is flase, it returns 1 as flag.

Share This Post

댓글 남기기

이메일은 공개되지 않습니다. 필수 입력창은 * 로 표시되어 있습니다

Latest Post