boolean riddle = !( 1 < 8 || (5 > 2 && 3 < 5));
boolean is a true or false.
! = not
|| = or
&& = and
but I still dont understand this syntax... can someone explain me what this syntax excactly does?
Just dissect it:
There are some comparisons such as
5 > 2 ... true
3 < 5 ... true
Those two are pulled together using &&; so true && true --> true
1 < 8 ... true
That one is or'ed to the rest; so we get true or true --> true
Finally, not (true) --> false
Long story short: if you don't understand the whole picture, break it down into the parts you understand; and then pull those together again.
Edit: and of course, the order I am using in my explanation isn't what happens in reality. There, 1 < 8 is evaluated first; and as that is true; and "true or X" is always true, the other comparisons are not even computed.
The not ! operator negates what it is in front of. In this case !() it will produce the opposite of the what is inside of the parenthesis.
the || or operator checks to see if one condition or the other is true. At least one must be true for the condition to return true.
Finally the && checks both sides of the conditional statement to see if they are both true, and both of them must be true to proceed.
boolean riddle = !( 1 < 8 || (5 > 2 && 3 < 5));
Let's parse it the way Java does :
boolean : Here comes a boolean, i.e. true or false.
riddle : The variable riddle is declared to be a boolean.
= : The boolean variable riddle is initialized with the expression on the right.
!(...) : It returns a boolean, the negation (=opposite) of the boolean inside of the parentheses.
Inside the parentheses is a bool1 || bool2 expression, where || is a "lazy OR" operator. If bool1 is true, there's no need to evaluate bool2.
bool1 is 1 < 8, which is true.
bool2 isn't evaluated
bool1 ||bool2 is true
!(...) is false
riddle is initialized with false
At no point in time are 5 > 2 or 3 < 5 evaluated. Eclipse warns that those 2 expressions are "dead code" and could be removed.
The whole expression could be :
boolean riddle = !( 1 < 8 || (5 > 2 && doSomethingVeryDangerous()));
the result would be the same and no method call would happen at all.
The problem that you have is that you initialize at the same time as you are checking if it's true or false. You cannot compare boolean with integer. If you want to do it then you need to solve it in another way by converting from one datatype to another, or involve another variable in your solution. The way you need to solve your syntax problem is by dividing it like this:
How you did it...
boolean riddle = !( 1 < 8 || (5 > 2 && 3 < 5));
How to potentially solve it...
boolean riddle;
"...some code to decide if riddle will be true or
false and assign it to the variable riddle..."
if (riddle == true){
"...do some code here...";
}
if (riddle == false){
"...do some code here...";
}
Or you can solve the problem by not using boolean as datatype and instead only use integers like this...
int riddle;
"...some code to decide what value riddle will
have and assign it to the variable riddle..."
if ( riddle < 8 && riddle > 1){
"...do some code here...";
}
Related
I'm trying to determine the conditions under which the following expression, where a and b are properly declared boolean variables, evaluates to false:
(a && (b || !a)) == a && b
To me, it seems that this expression will always evaluate to true. If either a or b is false, both sides of the equality operator will evaluate to false. If a and b are both true, then both sides will evaluate to true. That's all the options, and it's the correct answer for my online homework. However, when I run this in IntelliJ CE with the Java 11 JVM, it seems like it prints false whenever b is false:
when a and b are both false, IntelliJ outputs false
I get the same output when b is false and a is true. Can someone explain where the fault in my logic is? Thank you very much.
I think it is giving == operation priority over &&
Try this -
(a && (b || !a)) == (a && b)
You code should be:
boolean c = (a && (b || !a)) == (a && b);
otherwise it is evaluated as:
boolean c = ((a && (b || !a)) == a) && b;
Boolean operations have equivalent mathematical operations (this is what the CPU is ultimately doing). You can use this method to check any equation to make sure that it is coming out how you expect.
It can help you quickly see if your boolean logic is correct for all cases.
Using your equation here is an example:
Replace "true" with 1 and "false" with 0. Replace && with * (as in multiplies) and || with + (as in add). ! does what you expect still. Then check equality
so
a*(b+!a) == a*b
Then when a = false (0) and b = false(0) we have
0*(0+1) == 0*0
or 0=0
Which is true.
We can keep going with the other options to check.
a=1, b=1
1*(1+0) == 1*1
or 1=1
again, true
a=1, b=0
1*(0+1) == 1*0
1*1=0?
Not correct (false).
With that last test, we can see that this equation does not always evaluate to true. Just like in math, boolean operations have an order of operations (as mentioned by many others), but I like using this method to make sure my equations are working as intended.
I was running through some practice questions for an upcoming exam and came across a question that me nor my class mates can seem to understand. It is as follows:
where all variables are int or int array.
score += (rounds[i]) ? i + START : 0
How does the ternary operator work in java with += ?
This is my understanding:
so it is score += round[i] == i+start or == 0.
Is this a correct understanding?
Kind regards,
James
As with any combination of operators, it's a question of operator precedence and (where the operators have the same precedence) associativity. In Java, the simple assignment and all the operator/assignment operators share the lowest precedence tier. The ternary operator is the sole occupant of the next higher precedence tier. Therefore, your expression is equivalent to
score += ((rounds[i]) ? (i + START) : 0)
That is, the ternary expression is evaluiated, and its result is the right-hand operand of the +=.
As others have observed, that's not valid in Java if the type of rounds[i] is int, though that would be ok in C. But the expression could be sensible in Java if rounds[i] were an array of boolean, or it could be rewritten like this ...
score += ((rounds[i] != 0) ? (i + START) : 0)
... on the assumption that a C-style boolean interpretation of integer rounds[i] is what is wanted.
score += (some condition which is true or false) ? value to add if true : value to add if false;
We can try it.
int START = 3;
int score = 0;
boolean[] rounds = { true, false };
for (int i = 0; i < rounds.length; i++) {
score += (rounds[i]) ? i + START : 0;
System.out.format("i is %d, score is %d%n", i, score);
}
Output:
i is 0, score is 3
i is 1, score is 3
So the first time through the loop i is 0 and rounds[i] is true. In this case Java adds i and START to get 3 and adds this to score. Second time i is 1 and rounds[i] is false, so instead just 0 is added.
The statement you ask about adds a value to score. The value added is i + START if rounds[i] can be evaluated to true and 0 if it’s false. If i and START are both numeric, a number will be added. If score is numeric, adding 0 usually makes no difference, so you may think of the statement as adding a value only if rounds[i] is true.
so it is score += round[i] == i+start or == 0.
No, there is no implicit == comparison in the statement (as others have said, it requires that rounds[i] is a Boolean value, true or false).
The ternary operator ?: is used as follows:
a = bolean_expression ? this if true : else this if false.
int start = 5;
// In this case, start was added to itself to obtain 10.
start += true ? start : 0;
System.out.println(start); // prints 10
// with out the compound assignment operator (+=) the
// expression should be enclosed in ()
start = start + (true ? start : 0);
System.out.println(start); // prints 20
In the above cases, if the boolean was false, the start always have the value 5 since 0 would be added each time.
I have next task: Given an array of ints, return true if the array contains no 1's and no 3's.
First version and it's right:
for (int i = 0; i < nums.length; i++){
if(nums[i] == 1 || nums[i] == 3)
return false;
}
return true;
but here's I got many wrong tests:
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 1 || nums[i] != 3)
return true;
}
return false;
Can you explain me reason why does it work like this? I supposed reason is something happened in second if(...)
The code should return true if there are no 1s and no 3s.
Let us take a look at your second code:
// Iterate all values
for (int i = 0; i < nums.length; i++) {
// Return true if value is not 1 OR not 3
if (nums[i] != 1 || nums[i] != 3)
return true;
}
// Return false
return false;
The key here is the condition val != 1 || val != 3 which is a tautology, i.e. it is true in all cases. Suppose a value of 5, it is not 1, so true is returned. Now suppose a value of 1, it is 1 but it is not 3, also true is returned.
You would need to substitute || by && which means and, which also better reflects your textual condition:
return true if the array contains no 1's and no 3's
However you can not directly return true if you found the first element which is not 1 and not 3. You first need to check all elements. However you can directly return false if you found the first 1 or 3. And that is exactly the first version of your code, which is correct.
Note that when negating a conditions you need to negate all quantifiers and operators too.
The first code realizes an approach using this logic:
Not (there exists one element which is 1 or 3)
¬(∃ e : e = 1 ∨ e = 3)
When now solving the negation you receive this logic:
All elements are not 1 and not 3
∀ e : e ≠ 1 ∧ e ≠ 3
So ∃ (exists) turns to ∀ (for all), = to ≠ and ∨ (or) to ∧ (and).
Why the first one works
It returns false if any item is not 1 or 3, and true if no items match
Why the second one does not work
It returns true all the time (if any item is not equal to 1 or 3, and no integer is equal to both 1 and 3), the only way to get false is to pass it an empty array.
You're implementing a short-circuit evaluation. The first version is right. In the second version, you prematurely return true when you encounter a number that isn't 1 or 3 - which is every number, since 1 is not 3 and vise versa.
For the second answer, you are using OR instead of AND. Hence whatever value you provide, it will always enter into the if condition.
Hope this helps.
I am programming a Pit scoring system and I have a piece of code that looks like this:
while(highestConverted<scoreConverted||highestConverted!=scoreConverted)
It will always return true and repeat the code within it regardless of the value of scoreConverted or highestConverted. I don't think it really matters but both values or ints which are converted from scanner variables using Integer.parseInt . I don't have that much experience with Java but I do know some of the basics.
Consider your code:
while(highestConverted<scoreConverted||highestConverted!=scoreConverted)
Let's suppose highestConverted = 5 and scoreConverted = 2.
highestConverted < 2 = 5 < 2 -> false
highestConverted != 2 -> 5 != 2 -> true
false || true = true.
So the while loop will always repeat.
It should be
while(highestConverted<scoreConverted && highestConverted!=scoreConverted)
Or, better
while(highestConverted<scoreConverted)
highestConverted<scoreConverted implicitly includes highestConverted!=scoreConverted as it will stop at scoreConverted - 1.
Is following true in java:
In java if you use || then after getting first true condition it neglects the rest conditions. That is If you write if(a || b || c) in java and java finds a is true then it will not check for b and c, just go into the if case.
Yes this is called short circuiting, if you put less expensive checks to the left you might avoid the expensive ones to follow.
This works for || and &&
one of the best uses is checking a value from an object that might be null:
if(myList != null && myList.size() > 6)
the previous line is null safe, reversing the condition will cause a null pointer exception in case myList is null
This is correct. || is called short-circuit OR evaluation, or an OR-ELSE operator.
This is important in situations when evaluating the right-hand side may cause an undesirable consequence:
if (myString == null || myString.indexOf("hello") != -1)
...
would crash if it were not for short-circuiting.
Yes, This way the compiler avoids unnecessary checking and calculation overhead.
That's correct, and that's not just laziness on part of the language implementation, but rather it is a crucial feature - short-circuiting allows you to write something like this:
if (myarray.length > 10 && myarray[10] == 5) { /* ... */ }
Here the second condition may only even be evaluated if the first one is true. Thanks to short-circuiting, if the first condition is false the second is never touched.
YES
(AFAIK)
The same things applies to && but in reverse manner.(for first false).
The same rule as in circuits for AND and OR gates.
Yes, it's called short-circuiting. It also will short circuit &&, i.e.
if (a && b && c)
If a is false then the condition cannot be true, neither b nor c are checked.
This can be problematic if you call methods that return booleans. To get around this, you can use bitwise & and |.
Yes it is correct. If you use | this operator to check OR condition then it checks rest all conditions. It also applied on AND(&) operator.
Yes, and one important thing, if you do any operations in the second part, they will not be made. For example:
int a = 5;
int b = 5;
if ( a == b || a++ == b){
...
}
//a = 5
//b = 5
BUT in case:
int a = 3;
int b = 5;
if ( a == b || a++ == b){
...
}
//a = 4
//b = 5
I tried to make a simple example, but sometimes you call a method in the second part, (which will not be called if first part was true in case of ||), or the first part was false in case of &&