First, some background: I am an IT teacher-in-training and I'm trying to introduce the boolean operators of java to my 10th grade class. My teacher-mentor looked over a worksheet I prepared and commented that I could let them use just a single & or | to denote the operators, because they "do the same thing".
I am aware of the difference between & and &&.
& is a bitwise operator intended for use between integers, to perform "bit-twiddling".
&& is a conditional operator intended for use between boolean values.
To prove the point that these operators do not always "do the same thing" I set out to find an example where using the bitwise between boolean values would lead to an error. I found this example
boolean bitwise;
boolean conditional;
int i=10, j=12;
bitwise = (i<j) | ((i=3) > 5); // value of i after oper: 3
System.out.println(bitwise+ " "+ i);
i=10;
conditional = (i<j) || (i=3) > 5 ; // value of i after oper: 10
System.out.println(conditional+ " "+ i);
i=10;
bitwise = (i>j) & (i=3) > 5; // value of i after oper: 3
System.out.println(bitwise+ " "+ i);
i=10;
conditional = (i>j) && (i=3) > 5; // value of i after oper: 10
System.out.println(conditional+ " "+ i);
This example shows that if a value has to be changed by the second half of the expression, this would lead to a difference between the results, since bitwise is an eager operator, while the conditional behaves as a short circuit (does not evaluate the second half, if the first half is false in the case of && and true in the case of ||).
I have an issue with this example. Why would you want to change a value at the same time as you do a comparision on it? It doesn't seem like a robust way to code. I've always been averse to doing multiple operations in a single line in my production code. It seems like something a "coding cowboy" with no conscience as to the maintainability of his code would do. I know that in some domains code needs to be as compact as possible, but surely this is a poor practice in general?
I can explain my choice of encouraging the use of && and || over & and | because this is an accepted coding convention in software engineering.
But could someone please give me a better, even real-world, example of using a bitwise operator in a conditional expression?