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:
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.//This program will demonstrate using short circuit operators public class ShortCirtcuitOps { public static void main(String args[]) { int n, d, q; n = 10; d = 2; //This shows in the console if(d != 0 && (n % d) == 0) //since d does not equal 0 it then checks to see if the remainder of 10 / 2 is 0 System.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 console if(d != 0 && (n % d) == 0) //This keeps there from being a division by 0 since d is 0 System.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 "."); } }