do | and & make any sense in java?

你说的曾经没有我的故事 提交于 2019-12-05 16:42:55
bsiamionau

You forgot about bitwise operations

The bitwise & operator performs a bitwise AND operation.

The bitwise | operator performs a bitwise inclusive OR operation.

But here you can find example when unconditional AND operator is better:

What are the cases in which it is better to use unconditional AND (& instead of &&)

The single & and | are not logical operators, they're bitwise and logical operators.

From Bitwise and Bit Shift Operators

The bitwise & operator performs a bitwise AND operation.
The bitwise ^ operator performs a bitwise exclusive OR operation.
The bitwise | operator performs a bitwise inclusive OR operation.

From JLS 15.22. Bitwise and Logical Operators

The bitwise operators and logical operators include the AND operator &, exclusive OR operator ^, and inclusive OR operator |. Blockquote

You can use the | and & operators as you said above. Some static code analyzers will warn you because it might mask a possible problem. In those cases where you really want both conditions evaluated, you can do something like:

boolean cond1=cond1();
boolean cond2=cond2();
boolean myCond=cond1 && cond2;

if you just use

boolean myCond=cond1()&cond2();

someone is bound to "correct" it for you. So yes, there are places where you would use & and |, but most likely it's not a good idea and you can get around it for the sake of clarity.

Imagine if B was a function that you wanted to execute all the time then it would be useful.

I think that might be quite good example:

if (initializeConnectionA() & initializeConnectionB() & initializeConnectionC()) {
    performOperation();
} else {
    logger.warn("Not all modules are working properly");
}

Where methods initializeConnection connects to i.e. some external servers that might not all be working. You might not require to initialize them all but you want to be warned if some of them are not working.

Of course it might not be the clearest solution for this problem, but this is example where & operator might be useful.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!