×

Conditional operator in Java

In Java, there are around eight operators, and among them, three operators are used to evaluate the condition and decide the Result based on the Result of the evaluated condition.

Below are the three conditional operators described.

  • Conditional AND
  • Conditional OR
  • Ternary operator

Conditional AND— symbol (&&)

By using AND, the evaluation is done by comparing the two Boolean expressions specified before and after “&&”. The Result will be true only if the return value of both expressions is true. Else false will be returned.

Let's see the truth table of how && will be compared.

True && false = false

False && false = false

False && true= false

True && true = true.

And example syntax:

The explanation for each of the above four conditions:

int a=5, b=5, c=2;
if (a==b && b>c) 
{
//logic to be executed
}

In the above example, a==b is true because a=5 and b=5, and b>c is true because 5>2 is true.

So, a combination of true && true will return true, and then the code inside the block will be executed.

int a=5, b=4, c=2;
if (a==b && b>c)
{
//logic to be executed
}

In the above example, a==b is false because a=5 and b=4, and b>c is true because 4>2 is true.

So, a combination of false && true will return false and exits from the block without going into the block of code.

Conditional OR — symbol (||).

The OR is quite the opposite of the AND. Unlike AND, if the result of one among the two expressions is true, then the Result will be true. Only if both the results are false then OR will return false.

Let's see the truth table of how || will be compared.

True && false = true

False && false = false

False && true= true

True && true = true.

OR example syntax:

The explanation for each of the above four conditions:

int a=5, b=5, c=2;
if (a==b && b<c)
{
//logic to be executed
}

In the above example, a==b is true because a=5 and b=5, and b<c is false because 5<2 is false.

So, a combination of true || false will return true, and then the code inside the block will be executed.

False condition example

int a=5, b=4, c=2;
if (a==b && b<c)
{
//logic to be executed
}

In the above example, a==b is false because a=5 and b=4, and b<c is false because 4<2 is false.

So, a combination of false || false will return false and exits from the block without going into the block of code.

Ternary Operator:

The ternary operator is a type of conditional operator. This operator is known as a ternary operator because it employs three operands: a Boolean expression that can be either true or false; the Result when the Boolean expression is true; and the Result when it is false.

The syntax for the ternary operator:

Result_Value = Conditional _ Statement? value1: value2;

Result_value = this variable gets the Value assigned after computational work.

Conditional_ Statement = this part of the ternary operator performs the execution condition and returns Boolean values.

Value1 = this can be an output statement or Value assigned to Result _Value that gets executed when the conditional_ Statement returns actual Boolean Value.

Value2 = this can be another output statement or Value to be assigned to Result _Value that gets executed when the conditional_ Statement returns a false Boolean value.

For Example:

String resvalue = (20 > 12) ? “ True ” : “ False ”;  

Benefits of Ternary Operator:         

An if-then-else statement can be expressed using the ternary operator as a shortcut. The code is easier to read as a result.

Let's have a look at the use of the subsequent sample programmes.

Example1: ternary operator with a single condition

TernaryDemo.java

import java.io.*;
import java.util.*;






public class TernaryDemo
{
  public static void main (String [] args)
 {
  Scanner scan = new Scanner (System.in);
  System.out.println (" enter the value of x ");
                               int x = scan.nextInt ();
  System.out.println(" enter the value of y ");
                               int y = scan.nextInt ();
        String resultValue = (x >= y)?" x is greater than or equal to y ":" x is less than y ";
       System.out.println (resultValue); 
// it finds outs the greatest of two numbers
  }
}

Output:

The conditional operator in Java

Example2: ternary operator with multiple conditions

TernaryDemo1.java

import java.io.*;
import java.util.*;
public class TernaryDemo
{
  public static void main (String [] args)
 {
  Scanner scan = new Scanner (System.in);
  System.out.println (" enter the marks in x ");
                               int x = scan.nextInt ();
  System.out.println (" enter the marks in y ");
                               int y = scan.nextInt ();
        String resultValue = (x >= 80 && y>= 80)?" A grade ":(x >= 60 && y >= 60)?" B Grade ":" Not Eligible ");
       System.out.println (resultValue); 
// it finds outs the greatest of two numbers
  }
}

Output:

The conditional operator in Java

Related Topics

Zigzag Traversal of Binary Tree in Java

In this article, you will be acknowledged about the zigzag traversal of binary tree in java and the approaches or ways in which the zigzag traversal can be done. Zigzag Traversal A...

10 minutes read.

Economical number in Java

Economical number is said to be economically efficient if the number of digits after prime factorization of the original number with their powers is less than the number of digits...

3 minutes read.

Access Modifier in Java

The access modifiers in java are used to change the accessibility and scope of a method, constructor, class, and fields. If you are aware of C++ language, when we declare any member...

2 minutes read.

Java Serialization

JAVA SERIALIZATION Serialization is a process by which objects can be represented as a sequence of bytes. These bytes have information about object's data, object's type and datatypes of members in...

3 minutes read.

Sleeping Barber Problem in Java

The barbershop in this issue has one barber, one barber chair, and N chairs for customers in the waiting area. We may demonstrate the issue by keeping with the original...

6 minutes read.

Palindrome Partitioning problem in Java

In this article, you will be acknowledged about partitioning of the palindrome. It can be done in many ways. This article makes sure every method is discussed. Palindrome If a string remains...

6 minutes read.

Difference between next() and nextline() in Java

One of the simplest methods for receiving input of the basic data types, also including int, double, and strings, in Java, is to use the Scanner class, which is part...

3 minutes read.

Java Anon Proxy

The Java Anon Proxy (JAP), also known as JonDonym, is a proxy system designed to enable Web browsing with revocable (the use of or publication under a pseudonym, a false...

4 minutes read.

Java Font

The font is a Java class that is a part of java.awt package. The Serializable interface is implemented by it. The direct recognized child of a Java Font class is...

8 minutes read.

Console Errors in Java

An unlawful motion taken through the person that reasons this system to act abnormally is amistake until this system is compiled or run; maximum programming mistakes pass unnoticed.The software is...

3 minutes read.

Difference Between replace() and replaceall() in Java

In this article, you will be acknowledged about the replace() and replaceall() methods in java. Also, most importantly you will be acknowledged the differences between them along with the example...

4 minutes read.

Producer Consumer Problem in Java Using Synchronized Block

The producer-consumer dilemma is a well-known instance of a multi-process synchronization issue in computing. Two processes—the producer and the consumer—are described in the issue, and they share a single, fixed-size...

4 minutes read.

MessageDigest in Java

The compression of mathematical numbers is accomplished using hash functions. In almost every data security application, hash functions are employed. The hashing, often called has values, returns a value called...

3 minutes read.

Set Matrix Zeros in Java

In coding round interviews, it is frequently asked as the most significant challenge. an m*n matrix is provided. Set the entire column and row of the matrix to 0 if any...

6 minutes read.

Program to find the duplicate characters in a string

Problem statement You have given with a string and your task is to find out the repeated characters from the string and print them. If no character is repeated, then you...

2 minutes read.

Snake and Ladder Problem in Java

Find the smallest number of dice throws necessary to reach the destination or last cell from the source or first cell on a snake and ladder board. Essentially, the player...

6 minutes read.

Java Characters

Normally, when we work with characters, we use primitive data types char. When we have to work with the objects of char, we use Character class. Character class has many important...

2 minutes read.

How to check Date Null in Java?

In this section, we will be acknowledged about Date Null in Java. The date null in Java is an entity that is used when there is no specified value for...

3 minutes read.

Java Math pow() Method

The pow() method of Math class returns the value of first argument raised to the power of second argument i.e. ab. Syntax: public static double pow(double a, double b) Parameters: The parameters ‘a’ and...

3 minutes read.

Sierpinski Number in Java

The Sierpinski triangle—is it a fractal? The Sierpinski Triangle fractals. A self-similar fractal is the Sierpinski triangle. It is made of an equilateral triangle with its residual area successively reduced by...

3 minutes read.