The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

Tutorial for those having problems with logical operators

This thread is not a question but rather a snippet of code for those starting Java and coming across logical operators to come to. This will specifically cover the & operator and its short-circuit equivalent &&. The reason I am posting this is for others, who like myself in the past, have difficulty understanding the differences. With practice you too will learn to use these properly. Here is a snippet of code to observe:

//This program will demonstrate using short circuit operatorspublicclass ShortCirtcuitOps
{publicstaticvoid main(String args[]){int n, d, q;
n =10;
d =2;//This shows in the consoleif(d !=0&&(n % d)==0)//since d does not equal 0 it then checks to see if the remainder of 10 / 2 is 0System.out.println(d +" is a factor of "+ n +".");
d =0;//d is now set to 0//Since d is 0 the second operand is not evaluated, this will not show in the consoleif(d !=0&&(n % d)==0)//This keeps there from being a division by 0 since d is 0System.out.println(d +" is a factor of "+ n +".");//This will cause a divide by 0 error since both expressions are allowed to be evaluated//if(d != 0 & (n % d) == 0)//System.out.println(d + " is a factor of " + n ".");}}

If you take the last if statement out of comments then you will generate a compile error and be unable to run the program. This is why I have left that segment in comments. The difference between '&' and '&&' is that '&' will automatically check both of these before continuing. This causes the divide by zero error at the end of the code. By using '&&' you can stop this error from occurring. As you can see with the second 'if' statement it will check to see if d != 0. Since it does equal 0 it will then skip over the next section of the if statement thus avoiding the divide by zero error. You may also notice that int q has not been defined. I put this here for anyone who wishes to play around with this code to define q when and where they wish in order to create other instances for this code. I hope this has helped anyone searching for more information involving the difference between these.