Clarification on why this code is resulting in false and not true - java

The following code results in false. Could anyone explain to me why? I am having some trouble understanding using truth tables. I am a beginner with java, thank you in advance for the help.
boolean x = false;
boolean y = true;
boolean z = true;
System.out.println((!x || y && !z));
I expected the printed line to be false but the correct answer is true.

The factors that come into play here are operator precedence, left-to-right evaluation, and the special "short circuit" nature of '&&' and '||'.
'and' binds tighter than 'or'.
Firstly, operator precedence means the expression is effectively
( (!x) || (y && !z) );
Given the short-circuit execution of '||', once we know that !x is true, the right-hand side does not get evaluated.
I wrote this hack to print out each term as it was evaluated:
static boolean P(String s, boolean x) { System.out.println(" "+s); return x; }
and then replaced every boolean term 'b' to a call to P("b", b):
{
... same as before...
System.out.println( P("!x",!x) || (P("y",y) && P("!z",!z)));
}
results in output
!x
true
note: nothing related to y or z printed.

Related

Reading and interpreting a logical expression in a program

How do you usually read logical expressions in a program? For example:
(1 == x) && ( 2 > x++)? (x=1)
What is the purpose of ? and what is the way of thinking for generating the right answer for the expression?
The following statement:
var value = (boolean expression) ? some value if `true` : some value if `false`
Is a special conditional statement which makes use of a Ternary Operator (?:) to assign values, based on the boolean expression, to the variable.
It's a much more concise way of expressing this conditional statement:
var value;
//this is the boolean expression you evaluate before the question mark
if (boolean expression is true) {
//this is what you assign after the question mark
value = some value if true;
}
else {
//this is what you assign after the colon
value = some other value if false;
}
So based on your example (syntactically faulty btw), that would be something like:
if ((1 == x) && (2 > x++)){
x = 1;
}
else {
/*This is the value that would be put after the colon
*(which is missing in your example, and would cause a compiler error)
*/
x = some other value;
}
Which would translate to:
x = (1 == x) && (2 > x++) ? 1 : some other value
This statement does not even compile, ? is used with : as a ternary operator.
After (x=1) you should have the else branch, just an example:
(1 == x) && ( 2 > x++) ? (x=1) : (x = 2)
The way this boolean expression is evaluated is the following, suppose x is 1 :
(1 == x) = true
(2 > x++) = false
true && false = false
You expression will always be false regardless of the value of your x
In addition to the relevant comments about ?: where the colon is required, the following is also needed to "understand" the operation of the code in example :
Evaluation order of && implies that ´ ( 2 > x++) ´ will not be evaluated al all unless ´(1 == x)´ is true. Meaning in particular that the side-effect from x++ will not occur.
´x=1´ is an assignment so at first glance that doesn't look like an expression that evaluates to a value, but in java assignments are themselves expressions that take on the value being assigned.
(1 == x) && ( 2 > x++)? (x=1);
? stands for ternary operation. , if left of ? is true then it follows immediate right side.
In your case if ( 2 > x++) is true then value of x will be 1. but to travel towards ( 2 > x++) your left expression have to be true which means x==1, so if
(1 == x) is true and so( 2 > x++) is true then your overall condition to true.

Does && operator really have greater precedence over || operator ? Look at the code

In Oracle Java Docs it is mentioned that && operator has higher precedence over || operator.
Please look at the following code:
class TestLogicalOperators
{
public static void main(String... args)
{
if(doFalse() || doTrue1() && doTrue2() )
{
System.out.println(true+" inside if");
}
}
static boolean doTrue1()
{
System.out.println("doTrue1");
return true;
}
static boolean doTrue2()
{
System.out.println("doTrue2");
return true;
}
static boolean doFalse()
{
System.out.println("doFalse");
return false;
}
}
The output is:
doFalse
doTrue1
doTrue2
true inside if
Now if && operator has higher precedence over || operator shouldn't the methods doTrue1() and doTrue2() be evaluated first before doFalse()?
No.
The && operator has precedence, insofar as the expression:
doFalse() || doTrue1() && doTrue2()
... can also be read as:
doFalse() || ( doTrue1() && doTrue2() ) (note the parenthesis).
It doesn't mean the && expression will be evaluated before, your expression is still evaluated left to right.
The || operator can be a shortcut (i.e. no evaluation of second operand), if the first operand is true.
See example below:
// no shortcut, evaluates (true && false) and returns false anyway
System.out.println(false || true && false);
// no shortcut, evaluates (true && true) and returns true
System.out.println(false || true && true);
// shortcut (see warning), evaluates true and disregards "&&" expression
System.out.println(true || false && false);
You are missunderstanding the documentation. It doesn´t mean that the && operator will get executed first, it just says that the conditions surrunding a && are precedence over an other condition with a lower precedence.
In your example you can notice that the compiler is checking the condition of the if statement from left to right.
If we would go straigt from left to right the condition would be: (note parenthesis)
if((doFalse() || doTrue1()) && doTrue2() )
{
//This means either doFalse or doTrue1 would be true and doTrue2 would be true
}
But since the precedence of the && operator is higher then the on of the || operator it is read correctly as
if(doFalse() || (doTrue1() && doTrue2()))
{
//This correctly means either doFalse is true or doTrue1 and doTrue2 are true
}
NO, Normally first condition of OR operation is executed first. Which if evaluated to false, further checks second condition.
Otherwise it doesn't.
Operator && has preference over || but evaluation from left to right is still present and has precedende over operators as described in JLS §15.7
The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.

Differences in boolean operators: & vs && and | vs ||

I know the rules for && and || but what are & and |? Please explain these to me with an example.
Those are the bitwise AND and bitwise OR operators.
int a = 6; // 110
int b = 4; // 100
// Bitwise AND
int c = a & b;
// 110
// & 100
// -----
// 100
// Bitwise OR
int d = a | b;
// 110
// | 100
// -----
// 110
System.out.println(c); // 4
System.out.println(d); // 6
Thanks to Carlos for pointing out the appropriate section in the Java Language Spec (15.22.1, 15.22.2) regarding the different behaviors of the operator based on its inputs.
Indeed when both inputs are boolean, the operators are considered the Boolean Logical Operators and behave similar to the Conditional-And (&&) and Conditional-Or (||) operators except for the fact that they don't short-circuit so while the following is safe:
if((a != null) && (a.something == 3)){
}
This is not:
if((a != null) & (a.something == 3)){
}
"Short-circuiting" means the operator does not necessarily examine all conditions. In the above examples, && will examine the second condition only when a is not null (otherwise the whole statement will return false, and it would be moot to examine following conditions anyway), so the statement of a.something will not raise an exception, or is considered "safe."
The & operator always examines every condition in the clause, so in the examples above, a.something may be evaluated when a is in fact a null value, raising an exception.
I think you're talking about the logical meaning of both operators, here you have a table-resume:
boolean a, b;
Operation Meaning Note
--------- ------- ----
a && b logical AND short-circuiting
a || b logical OR short-circuiting
a & b boolean logical AND not short-circuiting
a | b boolean logical OR not short-circuiting
a ^ b boolean logical exclusive OR
!a logical NOT
short-circuiting (x != 0) && (1/x > 1) SAFE
not short-circuiting (x != 0) & (1/x > 1) NOT SAFE
Short-circuit evaluation, minimal evaluation, or McCarthy evaluation (after John McCarthy) is the semantics of some Boolean operators in some programming languages in which the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression: when the first argument of the AND function evaluates to false, the overall value must be false; and when the first argument of the OR function evaluates to true, the overall value must be true.
Not Safe means the operator always examines every condition in the clause, so in the examples above, 1/x may be evaluated when the x is, in fact, a 0 value, raising an exception.
I know there's a lot of answers here, but they all seem a bit confusing. So after doing some research from the Java oracle study guide, I've come up with three different scenarios of when to use && or &.
The three scenarios are logical AND, bitwise AND, and boolean AND.
Logical AND:
Logical AND (aka Conditional AND) uses the && operator. It's short-circuited meaning: if the left operand is false, then the right operand will not be evaluated. Example:
int x = 0;
if (false && (1 == ++x) {
System.out.println("Inside of if");
}
System.out.println(x); // "0"
In the above example the value printed to the console of x will be 0, because the first operand in the if statement is false, hence java has no need to compute (1 == ++x) therefore x will not be computed.
Bitwise AND:
Bitwise AND uses the & operator. It's used to preform a bitwise operation on the value. It's much easier to see what's going on by looking at operation on binary numbers ex:
int a = 5; // 5 in binary is 0101
int b = 12; // 12 in binary is 1100
int c = a & b; // bitwise & preformed on a and b is 0100 which is 4
As you can see in the example, when the binary representations of the numbers 5 and 12 are lined up, then a bitwise AND preformed will only produce a binary number where the same digit in both numbers have a 1. Hence 0101 & 1100 == 0100. Which in decimal is 5 & 12 == 4.
Boolean AND:
Now the boolean AND operator behaves similarly and differently to both the bitwise AND and logical AND. I like to think of it as preforming a bitwise AND between two boolean values (or bits), therefore it uses & operator. The boolean values can be the result of a logical expression too.
It returns either a true or false value, much like the logical AND, but unlike the logical AND it is not short-circuited. The reason being, is that for it to preform that bitwise AND, it must know the value of both left and right operands. Here's an ex:
int x = 0;
if (false & (1 == ++x) {
System.out.println("Inside of if");
}
System.out.println(x); //"1"
Now when that if statement is ran, the expression (1 == ++x) will be executed, even though the left operand is false. Hence the value printed out for x will be 1 because it got incremented.
This also applies to Logical OR (||), bitwise OR (|), and boolean OR (|)
Hope this clears up some confusion.
The operators && and || are short-circuiting, meaning they will not evaluate their right-hand expression if the value of the left-hand expression is enough to determine the result.
& and | provide the same outcome as the && and || operators. The difference is that they always evaluate both sides of the expression where as && and || stop evaluating if the first condition is enough to determine the outcome.
In Java, the single operators &, |, ^, ! depend on the operands. If both operands are ints, then a bitwise operation is performed. If both are booleans, a "logical" operation is performed.
If both operands mismatch, a compile time error is thrown.
The double operators &&, || behave similarly to their single counterparts, but both operands must be conditional expressions, for example:
if (( a < 0 ) && ( b < 0 )) { ... } or similarly,
if (( a < 0 ) || ( b < 0 )) { ... }
source: java programming lang 4th ed
& and | are bitwise operators on integral types (e.g. int): http://download.oracle.com/javase/tutorial/java/nutsandbolts/op3.html
&& and || operate on booleans only (and short-circuit, as other answers have already said).
Maybe it can be useful to know that the bitwise AND and bitwise OR operators are always evaluated before conditional AND and conditional OR used in the same expression.
if ( (1>2) && (2>1) | true) // false!
&& ; || are logical operators.... short circuit
& ; | are boolean logical operators.... Non-short circuit
Moving to differences in execution on expressions. Bitwise operators evaluate both sides irrespective of the result of left hand side. But in the case of evaluating expressions with logical operators, the evaluation of the right hand expression is dependent on the left hand condition.
For Example:
int i = 25;
int j = 25;
if(i++ < 0 && j++ > 0)
System.out.println("OK");
System.out.printf("i = %d ; j = %d",i,j);
This will print i=26 ; j=25, As the first condition is false the right hand condition is bypassed as the result is false anyways irrespective of the right hand side condition.(short circuit)
int i = 25;
int j = 25;
if(i++ < 0 & j++ > 0)
System.out.println("OK");
System.out.printf("i = %d ; j = %d",i,j);
But, this will print i=26; j=26,
If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand.
When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand evaluates to false, the evaluation of the second operand is skipped.
If the first operand returns a value of true then the second operand is evaluated. If the second operand returns a value of true then && operator is then applied to the first and second operands.
Similar for | and ||.
While the basic difference is that & is used for bitwise operations mostly on long, int or byte where it can be used for kind of a mask, the results can differ even if you use it instead of logical &&.
The difference is more noticeable in some scenarios:
Evaluating some of the expressions is time consuming
Evaluating one of the expression can be done only if the previous one was true
The expressions have some side-effect (intended or not)
First point is quite straightforward, it causes no bugs, but it takes more time. If you have several different checks in one conditional statements, put those that are either cheaper or more likely to fail to the left.
For second point, see this example:
if ((a != null) & (a.isEmpty()))
This fails for null, as evaluating the second expression produces a NullPointerException. Logical operator && is lazy, if left operand is false, the result is false no matter what right operand is.
Example for the third point -- let's say we have an app that uses DB without any triggers or cascades. Before we remove a Building object, we must change a Department object's building to another one. Let's also say the operation status is returned as a boolean (true = success). Then:
if (departmentDao.update(department, newBuilding) & buildingDao.remove(building))
This evaluates both expressions and thus performs building removal even if the department update failed for some reason. With &&, it works as intended and it stops after first failure.
As for a || b, it is equivalent of !(!a && !b), it stops if a is true, no more explanation needed.

How to PROVE the precedence of '&&' and '||' by coding in Java?

I know from somewhere that logical AND: && has a higher precedence than logical OR: || in Java, but until now I haven't found any clue about how this precedence really acts. What would happen if I didn't know about the precedence of the two and what mistake would I make?
I tried to write some code to PROVE the precedence of && and || but failed, for example:
boolExp1 || boolExp2 && boolExp3 || boolExp4
The code above produces the same results no matter the precedence of && and ||, that is,
false || false && true || false
results in false no matter what the precedence is.
I want a method or function that can PROVE the precedence of && and ||. It should produce different results depending on the precedence of && and ||. Is it possible?
Let's take your example expression:
boolExp1 || boolExp2 && boolExp3 || boolExp4
Now we believe that acts as:
boolExp1 || (boolExp2 && boolExp3) || boolExp4
right?
So let's suppose the opposite is true, and it's actually
(boolExp1 || boolExp2) && (boolExp3 || boolExp4)
What values of boolExp1 etc would give us different results?
Well, let's take:
boolExp1 = true
boolExp2 = false
boolExp3 = false
boolExp4 = false
Under the "&& has higher precedence" rules, the result would be true. Under the "|| has higher precedence rules", the result would be false. A quick test shows that the expression evaluates to true, however.
Of course, this doesn't actually prove that && has higher precedence than || - merely that || doesn't have higher precedence than &&. We could consider whether they have equal precedence - and test that with other expressions in a similar way... find a sample expression and values which would give different results under different precedence rules, and test them.
Ultimately though, I prefer:
To trust the spec unless I have specific doubts
To use parentheses to make my intentions clear
I wouldn't use the first expression "as is" in the first place... because unless you actually know the precedence rules (and I suspect many Java devs don't - I couldn't swear that I'd have got && and || right) you're in the dark. Better to make it explicit and clear where there's any doubt.
If && didn't have higher precedence than ||, then this expression:
a || b && c
would be evaluated like this:
(a || b) && c
To verify if this is the case or not,
you can generate all combinations of a, b, and c,
and compare the result of these two expressions,
to see if they are always equal or not, that is:
For all combinations of a, b, and c
Verify that: (a || b && c) == ((a || b) && c)
Sample code:
for (int i = 0; i < 8; ++i) {
boolean a = ((i >> 2) & 1) == 1;
boolean b = ((i >> 1) & 1) == 1;
boolean c = (i & 1) == 1;
boolean x1 = (a || b && c);
boolean x2 = ((a || b) && c);
if (x1 != x2) {
System.out.println(String.format("%s %s %s", a, b, c));
System.out.println(String.format(" %s || %s && %s => %s", a, b, c, x1));
System.out.println(String.format(" (%s || %s) && %s => %s", a, b, c, x2));
}
}
The output:
true false false
true || false && false => true
(true || false) && false => false
true true false
true || true && false => true
(true || true) && false => false
As such, && has higher precedence than ||.
I too had this same question but the answer was practically giving to me.
Here is my example:
true || true && false
is equivalent to
true || (true && false)
So with this example it is easy to see that under the hood in Java the logical && has a higher precedence than ||.
You cannot prove anything useful about a programming language by just writing / running examples. For all you know, the compiler might be implemented so as to compile code in an illogical, inconsistent or non-deterministic fashion.
Even if you assume deterministic compilation and deterministic execution, the only thing that compiling / running an example proves is that that particular example exhibits a particular behavior. You cannot logically generalize from one example to another one, because without reference to a specification the compiler is just a black box. (Your very next example could be the one that is handled in a totally counter-intuitive fashion.)
The correct way to develop an understanding of a programming language is to read the language specification, a good textbook or a good tutorial. Combine this with writing code to confirm your understanding.
If you rely solely on reading example code and writing test programs, you are liable to pick up misconceptions, and bad habits that can be painful to unlearn.
I was looking at the java specification to see if they defined operator precedence for && and ||
Both are defined as left-associative and no operator precedence is defined.
See s. 15.7.3 a bit down from s. 17.7,
&& s. 15.23,
|| s. 15.24
i.e. Java defines:
boolExp1 || boolExp2 && boolExp3 || boolExp4
As:
((((boolExp1) || boolExp2) && boolExp3) || boolExp4)
A simple test is:
boolean a = true || false && false;
boolean b = false && false || true;
if (a == b) { // different precedence
if (a == true) {
System.out.println("&& has higher precedence than ||");
} else { // a == false
System.out.println("|| has higher precedence than &&");
}
} else { // a != b, same precedence
if (a == true) { // and b == false
System.out.println("&& and || have equal precedence, and are executed right to left.");
} else { // a == false, b == true
System.out.println("&& and || have equal precedence, and are executed left to right.");
}
}
Note that this accounts for the possibility that && and || could have equal precedence, and then, in that case, determines if they're executed left to right, or right to left.
Unfortunately, this does not account for precedence that changes or precedence based on inside to outside or outside to inside, or many other possible orders of operation, not to mention it can be defeated by malicious or broken compilers, malicious or broken computers, and cosmic rays.
Anyway, it's really hard to prove your compiler/computer/universe isn't messing with you. So check the language specification in addition to testing.
This is relyed upon all the time in lines like the following.
Clearly these examples would blow up if the first expression were not always evaluated and the second expression not evaluated conditionally.
// second expression on evaluated if text != null in both cases.
String text = ??
if (text != null && text.length() > 0)
if (text == null || text.length() == 0
public static void main(String[] args) {
boolean res = b(false,1) || b(true,2) && b(false,3) || b(false,4);
System.out.println(res);
}
static boolean b(boolean b, int i){
System.out.println(i);
return b;
}
// 1 2 3 4 false
Both && and || have the same precedence, Evaluation happens from left to right. Let me explain with an example.
public static void main(String[] args) {
System.out.println("Result = " + (arg1() || arg2() && arg3() || arg4()));
}
private static boolean arg1() {
System.out.println("arg1");
return false;
}
private static boolean arg2() {
System.out.println("arg2");
return true;
}
private static boolean arg3() {
System.out.println("arg3");
return true;
}
private static boolean arg4() {
System.out.println("arg4");
return false;
}
this evaluates to :-
arg1
arg2
arg3
Result = true
But now let me change arg3() to return false
private static boolean arg3() {
System.out.println("arg3");
return false;
}
this results in :-
arg1
arg2
arg3
arg4
Result = false
So to conclude.. the evaluation takes place form left to right i.e
arg1 || arg2 && arg3 || arg4
output && arg3 || arg4
output || arg4
output
Hope this helps.

Creating a "logical exclusive or" operator in Java

Observations:
Java has a logical AND operator.
Java has a logical OR operator.
Java has a logical NOT operator.
Problem:
Java has no logical XOR operator, according to sun. I would like to define one.
Method Definition:
As a method it is simply defined as follows:
public static boolean logicalXOR(boolean x, boolean y) {
return ( ( x || y ) && ! ( x && y ) );
}
Method Call:
This method is called in the following way:
boolean myVal = logicalXOR(x, y);
Operator Usage:
I would much rather have an operator, used as follows:
boolean myVal = x ^^ y;
Question:
I can't find anything on how to go about defining a new operator in Java. Where should I start?
Java does have a logical XOR operator, it is ^ (as in a ^ b).
Apart from that, you can't define new operators in Java.
Edit: Here's an example:
public static void main(String[] args) {
boolean[] all = { false, true };
for (boolean a : all) {
for (boolean b: all) {
boolean c = a ^ b;
System.out.println(a + " ^ " + b + " = " + c);
}
}
}
Output:
false ^ false = false
false ^ true = true
true ^ false = true
true ^ true = false
Isn't it x != y ?
Java has a logical AND operator.
Java has a logical OR operator.
Wrong.
Java has
two logical AND operators: normal AND is & and short-circuit AND is &&, and
two logical OR operators: normal OR is | and short-circuit OR is ||.
XOR exists only as ^, because short-circuit evaluation is not possible.
Perhaps you misunderstood the difference between & and &&, | and ||
The purpose of the shortcut operators && and || is that the value of the first operand can determine the result and so the second operand doesn't need to be evaluated.
This is especially useful if the second operand would results in an error.
e.g.
if (set == null || set.isEmpty())
// or
if (list != null && list.size() > 0)
However with XOR, you always have to evaluate the second operand to get the result so the only meaningful operation is ^.
You can just write (a!=b)
This would work the same as way as a ^ b.
Logical exclusive-or in Java is called !=. You can also use ^ if you want to confuse your friends.
That's because operator overloading is something they specifically left out of the language deliberately. They "cheated" a bit with string concatenation, but beyond that, such functionality doesn't exist.
(disclaimer: I haven't worked with the last 2 major releases of java, so if it's in now, I'll be very surprised)
The following your code:
public static boolean logicalXOR(boolean x, boolean y) {
return ( ( x || y ) && ! ( x && y ) );
}
is superfluous.
Why not to write:
public static boolean logicalXOR(boolean x, boolean y) {
return x != y;
}
?
Also, as javashlook said, there already is ^ operator.
!= and ^ work identically* for boolean operands (your case), but differently for integer operands.
* Notes:
1. They work identically for boolean (primitive type), but not Boolean (object type) operands. As Boolean (object type) values can have value null. And != will return false or true when one or both of its operands are null, while ^ will throw NullPointerException in this case.
2. Although they work identically, they have different precedence, e.g. when used with &: a & b != c & d will be treated as a & (b != c) & d, while a & b ^ c & d will be treated as (a & b) ^ (c & d) (offtopic: ouch, C-style precedence table sucks).
The only operator overloading in Java is + on Strings (JLS 15.18.1 String Concatenation Operator +).
The community has been divided in 3 for years, 1/3 doesn't want it, 1/3 want it, and 1/3 doesn't care.
You can use unicode to create method names that are symbols... so if you have a symbol you want to use you could do myVal = x.$(y); where $ is the symbol and x is not a primitive... but that is going to be dodgy in some editors and is limiting since you cannot do it on a primitive.
Here is a var arg XOR method for java...
public static boolean XOR(boolean... args) {
boolean r = false;
for (boolean b : args) {
r = r ^ b;
}
return r;
}
Enjoy
You can use Xtend (Infix Operators and Operator Overloading) to overload operators and 'stay' on Java
What you're asking for wouldn't make much sense. Unless I'm incorrect you're suggesting that you want to use XOR to perform Logical operations the same way AND and OR do. Your provided code actually shows what I'm reffering to:
public static boolean logicalXOR(boolean x, boolean y) {
return ( ( x || y ) && ! ( x && y ) );
}
Your function has boolean inputs, and when bitwise XOR is used on booleans the result is the same as the code you've provided. In other words, bitwise XOR is already efficient when comparing individual bits(booleans) or comparing the individual bits in larger values. To put this into context, in terms of binary values any non-zero value is TRUE and only ZERO is false.
So for XOR to be applied the same way Logical AND is applied, you would either only use binary values with just one bit(giving the same result and efficiency) or the binary value would have to be evaluated as a whole instead of per bit. In other words the expression ( 010 ^^ 110 ) = FALSE instead of ( 010 ^^ 110 ) = 100. This would remove most of the semantic meaning from the operation, and represents a logical test you shouldn't be using anyway.
I am using the very popular class "org.apache.commons.lang.BooleanUtils"
This method is tested by many users and safe. Have fun.
Usage:
boolean result =BooleanUtils.xor(new boolean[]{true,false});
A and B would have to be boolean values to make != the same as xor so that the truth table would look the same. You could also use !(A==B) lol.
This is an example of using XOR(^), from this answer
byte[] array_1 = new byte[] { 1, 0, 1, 0, 1, 1 };
byte[] array_2 = new byte[] { 1, 0, 0, 1, 0, 1 };
byte[] array_3 = new byte[6];
int i = 0;
for (byte b : array_1)
array_3[i] = b ^ array_2[i++];
Output
0 0 1 1 1 0
Because boolean data type is stored like an integer, bit operator ^ functions like a XOR operation if used with boolean values.
//©Mfpl - XOR_Test.java
public class XOR_Test {
public static void main (String args[]) {
boolean a,b;
a=false; b=false;
System.out.println("a=false; b=false; -> " + (a^b));
a=false; b=true;
System.out.println("a=false; b=true; -> " + (a^b));
a=true; b=false;
System.out.println("a=true; b=false; -> " + (a^b));
a=true; b=true;
System.out.println("a=true; b=true; -> " + (a^b));
/* output of this program:
a=false; b=false; -> false
a=false; b=true; -> true
a=true; b=false; -> true
a=true; b=true; -> false
*/
}
}
Here's an example:
Given 2 int values, return true if one is negative and one is positive. Except if the parameter "negative" is true, then return true only if both are negative.
public boolean posNeg(int a, int b, boolean negative) {
if(!negative){
return (a>0 && b<0)^(b>0 && a<0);
}
else return (a<0 && b<0);
}
you'll need to switch to Scala to implement your own operators
pipe example
Can be achieved using stream API in java 8 and above
public static boolean logicalXOR(boolean x, boolean y) { // can modify to take [] or list of bools
return Stream.of(x, y) // modify as per method params
.filter(bool -> bool)
.count() == 1;
}

Categories