Ternary Operators in Java:

The ternary operator (?:) is a shortcut for if-else conditions. It evaluates a boolean expression and returns one of two values based on whether the condition is true or false. It’s called “ternary” because it takes three operands condition, true result, false result.

Syntax:

condition ? expression1 : expression2;

How it Works

  • If condition is true → returns expression1
  • If condition is false → returns expression2

Example 1: Simple Comparison

class ShikshaSanchar{
	public static void main(String[] args){
int a = 10, b = 20;
int max = (a > b) ? a : b;
System.out.println("Maximum: " + max);
	}
}

Output:

Maximum: 20

Explanation

  • (a > b) is false, so the value after the colon b is assigned to max.

Example 2: Even or Odd

class ShikshaSanchar{
	public static void main(String[] args){
int num = 7;
String result = (num % 2 == 0) ? "Even" : "Odd";
System.out.println(num + " is " + result);
	}
}

Output:

7 is Odd

Explanation

  • (num % 2 == 0) is false, so "Odd" is returned and stored in result.

Example 3: Nested Ternary

class ShikshaSanchar{
	public static void main(String[] args){
int marks = 75;
String grade = (marks >= 90) ? "A" :
               (marks >= 75) ? "B" :
               (marks >= 50) ? "C" : "Fail";
System.out.println("Grade: " + grade);
	}
}

Output:

Grade: B

Explanation:

  • First condition (marks >= 90) is false.
  • Second condition (marks >= 75) is true, so "B" is returned.

Notes:

  • Used for concise condition checks.
  • Can be nested, but avoid too much nesting to keep code readable.
  • Can be used in assignment or directly in print statements.

Summary:

  • Ternary operator = compact if-else.
  • Syntax: condition ? true : false
  • Returns value based on the condition.
  • Suitable for short, simple decision-making logic.

Welcome to ShikshaSanchar!

ShikshaSanchar is a simple and helpful learning platform made for students who feel stressed by exams, assignments, or confusing topics. Here, you can study with clarity and confidence.

Here, learning is made simple. Notes are written in easy English, filled with clear theory, code examples, outputs, and real-life explanations — designed especially for students like you who want to understand, not just memorize.

Whether you’re from school, college, or someone learning out of curiosity — this site is for you. We’re here to help you in your exams, daily studies, and even to build a strong base for your future.

Each note on this platform is carefully prepared to suit all levels — beginner to advanced. You’ll find topics explained step by step, just like a good teacher would do in class. And the best part? You can study at your pace, anytime, anywhere.

Happy Learning! – Team ShikshaSanchar