? Operator

Source: Internet
Author: User
? Operator-Linux general technology-Linux programming and kernel information. For more information, see the following. Java provides a special ternary operator that is often used to replace an if-then-else statement of a certain type. This operator is ?, And its usage in Java is almost the same as in C/C ++. This symbol seems a bit confusing at first, but once you master it, use it? Operators are convenient and efficient .? The general format of operators is as follows:

Expression1? Expression2: expression3

Expression1 is a Boolean expression. If expression1 is true, expression2 is evaluated; otherwise, expression3 is evaluated. Whole? The expression value is the value of the evaluated expression (expression2 or expression3. Expression2 and expression3 are expressions of any type except void, and they must be of the same type. Which of the following is a exploitation? Operator example:

Ratio = denom = 0? 0: num/denom;

When Java calculates this expression, it first looks at the expression on the left of the question mark. If denom is equal to 0, the expression between the question mark and colon is evaluated, and the value is used as the whole? The value of the expression. If denom is not equal to zero, the expression after the colon is evaluated and the value is used as the whole? The value of the expression. Then the entire? The expression value is assigned to the variable ratio.

What is the description of the following program? Returns the absolute value of a variable.

// Demonstrate ?.
Class Ternary {

Public static void main (String args []) {int I, k; I = 10; k = I <0? -I: I; // get absolute value of iSystem. out. print ("Absolute value of"); System. out. println (I + "is" + k); I =-10; k = I <0? -I: I; // get absolute value of iSystem. out. print ("Absolute value of"); System. out. println (I + "is" + k );

}
}

The program output is as follows:

Absolute value of 10 is 10 Absolute value of-10 is 10

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.