×

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

Java Thread Priority in Multithreading

As we realise, java, being object-situated, works inside a multithreading climate in which the string scheduler relegates the processor to a string in light of the need for a string....

6 minutes read.

Mutable and Immutable in Java

Java is a programming language in which everything is treated as an object. Its procedures and functions are centred around objects because it is an object-oriented programming language. Mutable and...

6 minutes read.

How to Convert Object to String in Java

How to Convert Object to String in Java You can convert any Object to String in Java whether it is a user-defined class, StringBuilder or StringBuffer, etc. There are two methods...

2 minutes read.

Java LDAP Authentication

WHAT IS LDAP? Clients can communicate with directory services by sending requests and receiving responses using the Lightweight Directory Access Protocol (LDAP). The term "LDAP server" refers to a directory service...

7 minutes read.

ArrayList vs Vector in Java

ArrayList Vs. Vector in Java In Java, the two classes ArrayList and Vector both are associated with Java Collections Framework. Both classes implement java.util.List interface. Even so, these classes have noticeable...

4 minutes read.

Java.lang.Exception.NoRunnableMethods

In Programming language, the java lang unexpected no precompiled methods error generally refers to a Junit exception that happens whenever Junit is incapable of locate the precompiled test methods. When...

4 minutes read.

How to Create an Immutable Class in Java

How to Create an Immutable Class in Java In Java, immutable means something that cannot be change. A class is called an immutable class if its content cannot be changed, once...

3 minutes read.

JDBC Program in Java

JDBC Program in Java JDBC is an API that defines how a client may access a database. It is a part of Java Standard Edition (Java SE). JDBC stands for Java...

4 minutes read.

Java BufferedWriter

BufferWriter Class: It is used to write the data more efficiently. This class is present in the java.io package, it inherits the data from the Writer class. Writer class is...

4 minutes read.

Features of Java

The objective of the Java programming language is to provide portability, security, and simplicity. In spite of this, Java has a number of features that makes it a popular language...

5 minutes read.

Java Comparator Interface

Java comparator interface is used in a situation when we have to sort an object which does not implement Comparable or do sorting in a different way than the Comparable....

1 minute read.

Java import packages

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

How to Convert Binary to Decimal in Java

How to Convert Binary to Decimal in Java There are two methods to convert binary to decimal. Using Integer.parseInt() method Using user-defined logic Using Integer.parseInt() method The parseInt() is a static method of...

2 minutes read.

Java Try-Catch Block

Java Try Block The handling of the exceptions in a block of code is done with the help of java try block. It throws the code that is enclosed in a...

3 minutes read.

Java Binary Operators

In this article, we are going to discuss about the binary operators in Java and their operations. Also, an example program will be discussed along with the operations. These are...

6 minutes read.

Java Base64 Encoding and Decoding

Introduction to Encoding and Decoding Encoding is the process of putting the sequence of characters like letters, numbers, punctuations, and other symbols into a specialised format for the efficient transmission or...

11 minutes read.

DatabaseMetaData in Java

The Data about another data is called Meta data. The DatabaseMetaData interface has the meta data of the database present in the system. It consists of database product name, total...

2 minutes read.

Java Math rint() Method

The rint() method of Java Math class returns the double value which is close to the specified argument and is equal to mathematical integer. Syntax: public static double rint(double a) Parameters: The parameter ‘a’...

1 minute read.

Java Architecture

Java architecture is a combination of three parts they are JVM, JRE and JDK. These components will help in the functioning of the java programs. The process of code interpretation...

6 minutes read.

Java Console

If there is a character-based console device connected to the active Java virtual machine, it can be accessed using methods provided by the Java.io.Console class. JDK 6 adds the Console...

3 minutes read.