• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

SoftwareTestingo - Interview Questions, Tutorial & Test Cases Template Examples

SoftwareTestingo - Interview Questions, Tutorial & Test Cases Template Examples

  • Home
  • Test Case Examples
  • Interview Questions
  • Interview Questions Asked
  • Java
  • Java Program
  • Selenium
  • Selenium Programs
  • Manual Testing
  • Difference
  • Tools
  • SQL
  • Contact Us
  • Search
SoftwareTestingo » Java » Java Tutorial » Ternary Operator In Java

Ternary Operator In Java

Last Updated on: August 15, 2020 By Softwaretestingo Editorial Board

This post, we are going to another different type of Java operator called the ternary operator. The Java ternary operator functions are much similar to Java If Statement. This ternary operator validates a condition; after evaluating the condition, it returns true or false. Based on the evaluating result, if it evaluates true, then the Java operand returns the second operand else it returns the third operand.

Ternary Operator In Java With Explanation
Ternary Operator In Java With Explanation

Syntax of java ternary operator is:

result = testStatement ? value1 : value2;

The above syntax, if the test statement is true, then the value1 is assigned to result otherwise value2 is assigned to result.

import java.util.Scanner;
public class JavaExample
{
   public static void main(String[] args)
   {
      int num1, num2, num3, result, temp;
      /* Scanner is used for getting user input.
       * The nextInt() method of scanner reads the
       * integer entered by user.
       */
      Scanner scanner = new Scanner(System.in);
      System.out.println("Enter First Number:");
      num1 = scanner.nextInt();
      System.out.println("Enter Second Number:");
      num2 = scanner.nextInt();
      System.out.println("Enter Third Number:");
      num3 = scanner.nextInt();
      scanner.close();

      /* In first step we are comparing only num1 and
       * num2 and storing the largest number into the
       * temp variable and then comparing the temp and
       * num3 to get final result.
       */
      temp = num1>num2 ? num1:num2;
      result = num3>temp ? num3:temp;
      System.out.println("Largest Number is:"+result);
   }
}

Ref: article

    Filed Under: Java Tutorial

    Reader Interactions

    Leave a Reply Cancel reply

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

    Primary Sidebar

    Join SoftwareTestingo Telegram Group

    Categories

    Copyright © 2023 SoftwareTestingo.com ~ Contact Us ~ Sitemap ~ Privacy Policy ~ Testing Careers