JAVA | and |, & amp; and & amp;

Source: Internet
Author: User

JAVA | and |, and the difference
The differences between these four operators can be easily distinguished by names: | (short circuit or), | (OR), & (short circuit and), & (by bit and) here is a simple example:

public class Test1 {        public static void main(String[] args) {           int i=0;           if (3>2 || (i++)>0){              System. out .println(i);           }       }}



The reason why the I value output by this program is 0 is | when judging, if the previous judgment is true, it will no longer judge whether the subsequent statements are true, then the subsequent statements will not be executed.
If you change | to |, what will happen?
public class Test1 {        public static void main(String[] args) {           int i=0;           if (3>2 | (i++)>0){              System. out .println(i);           }       }}




The result output I value is 1, because | when the operator is determining whether or not the previous expression is true, it will execute the following statement, the value of I is increased by 1 to 1.
public class Test2 {        public static void main(String[] args) {               // TODO Auto-generated method stub               int i=0;           if ((i++>2) && (i++)>2){                        System. out .println("i=" +i);           } else {              System. out .println(i);           }       }}


The value of result output I is 1 because the & operator determines that the entire expression is false when the first expression is false, the following statement will not be executed.
Replace & &
public class Test2 {        public static void main(String[] args) {               // TODO Auto-generated method stub               int i=0;           if ((i++>2) & (i++)>2){                        System. out .println("i=" +i);           } else {              System. out .println(i);           }       }}



The reason for the result output I value is 2 is that & the judgment results of the front and back expressions are compared, SO 2 is output.

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.