Java Ternary operators

Source: Internet
Author: User

/*

Ternary (trinocular) operator

Format

Boolean-type expression? Expression 1: Expression 2;


Execution process:

Determine the value of a Boolean type expression first

True to execute an expression 1

False to execute an expression 2


Expression 1 or expression 2 eventually there is a result that is generally a data


Case: Get the maximum value of two numbers?


Analysis:

1: Determine the size of two to use >

A, b

A>b If the result is true a large

The result is false B large


A>b? A:B;

*/

Class Operatordemo{public static void Main (string[] args) {//has two variables int a = 15;int b = 10;int max = a>b? a:b;// Must be a result in general is a data//Two expression result data type to be consistent//so you can use variables of the same data type to receive System.out.println ("Max:" +max);}}


/*

A: Case Demo

Compare whether two integers are the same

B: Case Demo

Gets the maximum value in three integers

Analysis:

A b C


Let A, B compare to get a larger value---here to use a ternary


Let the larger value compare with C------use ternary


Compare whether two integers are the same


Analysis:

A, b

A==b if the equality result is true

If the result is not equal to false



Format:

Boolean-type expression? Expression 1: Expression 2;

*/

Class Operatortest{public static void Main (string[] args) {/*//Determines whether two numbers are equal to an int a = 20;int b = 30;boolean flag = (a==b? True : false);       SYSTEM.OUT.PRINTLN (flag);   System.out.println (A==B);   *///three integers to find the maximum int a = 40;   int B = 20;   int c = 30; First get the larger value of a and b int max1 = a>b?   A:B; Max1 and c compare int max = max1>c?       MAX1:C; System.out.println ("Max:" +max);}}


This article from the "Clear Sky" blog, declined reprint!

Java Ternary operators

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.