Short Circuit in Java

Source: Internet
Author: User

Today I looked at the third edition of Java programming ideas. When I talked about logical operators in Chapter 3, I mentioned a short-circuit ranking I have never heard of before. What is short-circuit? Let's take a look at the followingCode

Public   Class Shortcut
{
Public   Static   Boolean Test ( Int A)
{
System. Out. println ("Come in and a =" +A );
ReturnA> 1;
}

Public   Static   Void Main (string [] ARGs)
{
If (Test ( 0 ) && Test ( 1 ))
{
System. Out. println ("Result is true");
}
Else
{
System. Out. pringln ("Result is fasle");
}
}
}

What results will the above Code output? If I don't see the short circuit, I will give the following results.
Come in and a = 0
Come in and a = 1
Result is false
Because I think both of the test methods will be executed here. If you think my results are correct, you and I will not understand the short circuit. The actual output result of running the code is
Come in and a = 0
Result is false
Why? Let me give you a simple example.

System. Out. println ( True   &&   True   &&   False   &&   True   &&   True );

What will the above statement output? You can see at a glance that it is false, because there is a false in these operations, so you don't have to look down and know that the returned result is definitely false. In fact, there is a "Short Circuit" here, in fact, if operations are the same as our thinking.
First, execute test (0) to return false, while Java judges that the latter is an operation. Therefore, no matter whether the latter is true or false, the result is not affected, this will also improve the performance.

Related Article

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.