Categories
java

Ternary Operator in java with example

Ternary Operator

In this example we will learn to use ternary operator in java with example

  • Ternary Operator will be used instead of if else 
  • We can use this ternary operator to do null check
  • we can use this to check numeric operations

Syntax

(conditon) ? true : false ;

Example with String

public class TernaryOperatorExample {

	public static void main(String[] args) {
		String s = null;
		System.out.println((s == null) ? "String s is null" : "String s is not null");
	}
}

Output

String s is not null

Example with numeric operations

public class TernaryOperatorWithNumeric {

	public static void main(String[] args) {
		int i = 10;
		System.out.println((i > 10) ? true : false);
	}
}

Output

false

Github link

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/TernaryOperatorExample.java

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/TernaryOperatorWithNumeric.java

Leave a Reply

Your email address will not be published. Required fields are marked *