Skip to content

Latest commit

 

History

History
109 lines (77 loc) · 1.8 KB

File metadata and controls

109 lines (77 loc) · 1.8 KB

Operators And Expressions

Arithmetic Operators

  • + addition
  • - subtraction
  • * multiplication
  • / division
  • % remainder

Example:

int a = 5;
int b = 2;

System.out.println(a + b); // 7
System.out.println(a - b); // 3
System.out.println(a * b); // 10
System.out.println(a / b); // 2
System.out.println(a % b); // 1

String Concatenation

  • When + is used with strings, Java joins values as text.

Example:

System.out.println("Hello" + "World"); // HelloWorld
System.out.println("2" + "3");         // 23
System.out.println(2 + 3 + "2" + 2);   // 522

Comparison Operators

  • == equal to
  • != not equal to
  • > greater than
  • < less than
  • >= greater than or equal to
  • <= less than or equal to

Example:

System.out.println(10 > 5);  // true
System.out.println(10 == 5); // false

Logical Operators

  • && logical AND
  • || logical OR
  • ! logical NOT

Example:

System.out.println(10 + 5 > 4 && 5 + 7 > 10); // true
System.out.println(10 + 5 < 4 && 5 + 7 > 10); // false

Short-Circuit Evaluation

  • In &&, if the left side is false, Java does not evaluate the right side.
  • In ||, if the left side is true, Java does not evaluate the right side.

Example:

System.out.println(10 + 5 < 4 && 5 / 0 > 10);

This does not throw an error because the first condition is already false.

Unary Operators

  • x++ is post-increment
  • ++x is pre-increment
  • x-- is post-decrement
  • --x is pre-decrement

Example:

int x = 5;
System.out.println(x++); // 5
System.out.println(x);   // 6
System.out.println(++x); // 7

Ternary Operator

  • A short form of if-else

Syntax:

condition ? valueIfTrue : valueIfFalse;

Example:

int marks = 64;
String status = (marks >= 33) ? "Pass" : "Fail";