Explain if (++value % 2 == 0 && ++count < limit) in java - java

public class AndOperator {
public static void main(String[] arg) {
int value = 8;
int count = 10;
int limit = 11;
if (++value % 2 == 0 && ++count < limit) {
System.out.println("here");
System.out.println(value);
System.out.println(count);
} else{
System.out.println("there");
System.out.println(value);
System.out.println(count);
}
}
}
i am getting output as
there
9
10
explain how count is 10....?

&& is short-circuit operator. It will only evaluate the 2nd expression if the 1st expression evaluates to true.
Since ++value % 2 == 0 is false, hence it doesn't evaluate the 2nd expression, and thus doesn't increment count.

++value = 9 so ++value % 2 == 0 is false so ++count < limit is not evaluated.
This is called Short circuit evaluation. See the wikipedia page : http://en.wikipedia.org/wiki/Short-circuit_evaluation

Since you are using &&(logical and) operator.
logical and evaluate second condition only if first condition is evaluated to true
Here in your code first condition ++value % 2 == 0 is evaluated to false,so second condition ++count < limit won't be evaluated.
If you want to execute ++count < limit also use &.
more information read Difference between & and &&

Because ++value % 2 == 0 is false, thus it won't return the first statement. The reason ++value % 2 is false is because value is incremented by one before the mod operator is evaluated. So ++value % 2 is 9 % 2 which != 0.

Related

Java For Loop Confusion (iteration) "Don't know why it still went through!" [duplicate]

This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 5 years ago.
So I was trying to figure out if the the first iteration in a for loop does not go through the termination condition.
Since when I called it in the main method with an input of 4 IsPrime(4) the for loop still went through. I was expecting it to not go through since i = 2 and n/2 = 4/2 = 2 which will be 2 == 2 which will meet the condition to terminate but it went through and I got the right output but I don't get why it did not fail.
Please help.
public static boolean isPrime(int n){
if(n <= 1){
return false;
}
for(int i = 2; i <= n/2; i++){
if(n % i == 0){
return false;
}
}
return true;
}
Your for loop condition says continue while i <= n/2.
If you start with n == 4 then n/2 == 2. On the first iteration i == 2 so the for loop condition 2 <= 2 is true and it will iterate once.
Then i++ is executed so now i == 3 and fails the condition so there is no second iteration.
You seem to have a confusion around how for loop works. Let's see the operation on a per-iteration basis :
Iteration 1 :
i = 2
i <= 2 ? --> True
n % i == 0 ? --> 2 % 2 == 0? True
return false
End of function
Now let's assume your for loop looked something like this :
for(int i = 2; i <= n/2; i++){
if(n % i == 0){
System.out.println("Remainder is 0");
}
}
Then the following will the iteration sequence :
Iteration 1
i = 2
i <= 2 ? --> True
n % i == 0 ? --> 2 % 2 == 0? True
print --> Remainder is 0
i++ --> i = 3 now
Iteration 2
i = 3
i <= 3 ? --> False
Cannot proceed further. For loop condition failed.
End of function

Java post increment and pre increment

The following code in Java:
int a = 0, b = 0, c = 0;
boolean d = (a++ > 0 && b-- < 0) || --c < 0;
results in the values:
a = 1, b = 0, c = -1 and d = true
I don't understand why a is = 1, because it is a post-increment and should also react the same way that value b does. Also, if I change the b-- to --b it still has no effect on the value of b.
What is the best way of understanding this logic?
a++ > 0 returns false, since a++ return the previous value of a (0).
Therefore b-- < 0 is not evaluated at all, since && is a short circuiting operator. The right operand is only evaluated if the left operand is true.
--c < 0 is evaluated, since the first operand of the || operator is false, so the second operand must be evaluated.
After d is evaluated, the value of a is 1, since a was incremented. b remains 0, since b-- wasn't executed. c is -1 since --c was executed.
And d is true since --c < 0 is true.
After the expression runs then a will indeed be 1 as the post increment operator has then executed.
During the evaluation of the expression a is 0 as far as the expression is concerned (but a is now 1 for other code), so the first part of the logical OR, your logical AND, is evaluated as false and the b post decrement does not get evaluated.
The second part of the logical or then runs, and the pre-decrement executes to reduce c to -1, which then causes the comparison to evaluate to true, hence d being true.
Expand the different clauses to separate variables and run through a debugger for a more interactive explanation of what's happening.
a++ at moment of comparing is NOT >0, so b part is not evaluated, and not incremented.
Second part of && and || expressions is not evaluated if cannot change result. For && first false determines result false.
Analogically, first true determines result of || (but not here)
a++ effectively means a= a+1
So, the existing value of a (=0) is used for evaluating the expression, and later on the value of a is incremented. So, a becomes 1.
Regarding why b =0 and why --b has the same effect as b--, the value of b is unchanged because of &&. Since a++ > 0 is not satisfied, the next expression b-- < 0 is not evaluated and value of b remains 0. && stops evaluation once the expression evaluates to false, while || stops evaluation once the statement evaluates to false.
When you write a++ OR b--, it passes the value 'a' and 'b' currently holds, and then modifies the variables.
So your expression is simply,
boolean d = (0 > 0 && 0 < 0) || -1 < 0;
Now while evaluating, (0 > 0 && 0 < 0) -> first expression returns false and you have used short-circuit AND operator. Meaning don't evaluate the right hand side if it isn't necessary. As LHS of && returns false, b-- won't be evaluated.
And we have 'd' is true.
Remember,
Post-increment within expressions --> assign current value first, modify later.
Pre-increment within expressions --> modify first, assign updated value later.
Refer this link for better understanding short circuit operators:
Short-Circuit Explanation
Please Execute This code..
int a = 0, b = 0, c = 0;
System.out.println("b = " + --b);
b=0;
System.out.println("b = " + b--);
System.out.println("a = " + a++);
a=0;
System.out.println("a = " + ++a);
System.out.println("c = " + c--);
c=0;
System.out.println("c = " + --c);
a=b=c=0;
boolean d = (a++ > 0 && --b < 0) || --c < 0;
System.out.println("d = " + d);
I think you understand full logic.

Simple logic not working or am I missing something?

I don't understand why the following class prints out:
true
false
I thought the output should be:
false
false
because this line prints false:
System.out.println((11 >= 1 || 11 <= 10) & (true == false));
so this line should also print false:
System.out.println(in1To10(11, false));
What am I missing here? Here's the class.
public class TestClass {
public static void main(String[] args) {
System.out.println(in1To10(11, false));
System.out.println((11 >= 1 || 11 <= 10) & (true == false));
}
public static boolean in1To10(int n, boolean outsideMode) {
if ((n >= 1 || n <= 10) & (outsideMode == false)) {
return true;
}
return false;
}
}
You want to test if value is in the range 1 to 10 ?
If thats the case, change (n >= 1 || n <= 10) to (n >= 1 && n <= 10)
( true )
( true ) & ( true )
(true || false ) & ( true ) <--- false == false is true!
if ((n >= 1 || n <= 10) & (outsideMode == false)) {
return true;
}
Look, is n >= 1? Yes, so it's true. true v p <-> true, so Java doesn't even check further. true /\ true <-> true so we enter if. return true;
Your code is in plain English:
if ((n is greater or equal to 1 OR smaller or equal 10) AND is the mode set to false)
return true
If you want it to return true if the number is between 1 and 10 incl, it would be:
if ((n is greater or equal to 1 AND smaller or equal 10) AND is the mode set to false)
return true
which in Java is:
if ((n >= 1 && n <= 10) && (outsideMode == false)) {
return true;
}
Also remember to use && and || as they are logical operators instead of | and & bitwise logical operators when dealing with boolean values.
so this line should also print false: System.out.println(in1To10(11, false));
No, this line should not print false. Although the first parameter, 11, indeed turns the expression n >= 1 || n <= 10 from your method into 11 >= 1 || 11 <= 10, which matches your other expression, the second parameter, false, turns outsideMode == false into false == false, while your other expression has true == false.
That is why the two outputs are different: the output from in1To10 is true because the comparison false == false produces true, while the output from main is false, because true == false produces false.
Note: your expression does not match its stated goal of checking if n is between 1 and 10, inclusive. You need to replace || with && to accomplish that.
I think you missed that in function in1to10, you are comparing (false == false) and in main you are comparing (true == false). And so is the result. Hope this helps.
Let's decompose the test in in1to10 :
Parameters : outsideMode = false; n = 11;
(n >= 1 || n <= 10) :=> (11 >= 1 || 11 <= 10) :=> (true || false) :=> so TRUE
outsideMode == false :=> false == false :=> so TRUE
In the end :
public static boolean in1To10(int n, boolean outsideMode) {
if ((TRUE) & (TRUE)) {
return true;
}
return false;
}
:=> return TRUE !
This will return true. How?
if ((n >= 1 || n <= 10) & (outsideMode == false)) {
return true;
}
You are passing 11 and false to the function.
When it goes to inside the first condition it will check that n >= 1 mean 11 >= 1 that is true, so it will not check n<=10. Again it will check the second condition and your outsideMode is false,
That will be like this, (true) & (true)
hence the whole condition will be true and the funciton will return true.
Again the second condition,
(11 >= 1 || 11 <= 10) & (true == false)
It will return false. How?
As 11 >= 1 is true and again it will not check 11 <= 10, and right side is false.
So the condition will be become like this,
true & false that will be false.

The operator < is undefined for the argument type(s) boolean, int

I am new to processing and I am having trouble with this. I keep getting an error message for the bolded part of the code below. Is my syntax wrong?
void block(int x, int y, int s, color tinto) {
fill(tinto);
for (int i = 0; i < 3; i++) {
triple(x, y+i*s, s, tinto);
}
if (0 < i < 3 && 6 < i < 9) { // HERE
tinto = 255;
}
else {
tinto = tinto - 200;
}
}
In Java, to check if a variable is in a range you have to divide the statement into two parts, like this:
if (0 < i && i < 3 && 6 < i && i < 9){
}
This specific code will never be true, however, because you're asking for it to be in two different ranges. Perhaps you meant to check for either range?
if (0 < i && i < 3 || 6 < i && i < 9){
}
Note the || or operator instead of the && and operator.
The syntax is not valid, and I think you're expression is wrong anyway. You say i has to be within a range AND within another. I think you mean to write that it could be between one OR the other.
Example of valid syntax: instead of 0 < i < 3, write i > 0 && i < 3.
Try this:
if ( (i > 0 && i < 3) || (i > 6 && i < 9) )
Note that the following (which is what you were trying to do apparently) will never be evaluated to true because it cannot be within both ranges.
if ( (i > 0 && i < 3) && (i > 6 && i < 9) ) // incorrect
This isn't valid java expression. Try:
if (0<i && i<3 && 6<i && i<9){
There are two different problems with this code snippet. First, you have defined the 'i' variable as in "int" inside of the for loop. This instance of 'i' is no longer defined once you exit that for loop -- so the if statement below does not refer to that instance. To overcome this, define 'i' before the for loop...
int i;
for ( i=0; i<3; I++ ) {
...
}
if ( i ...
which brings me to the second error. The syntax "0 < i < 3" is not correct. In c/c++ the operators are executed one at a time ... so in this case the first "<" operator will be evaluated as "0 < i" and the result will be a Boolean (which will always be 'true' in your particular code snippet). But the important point is that the result is a Boolean. Next the code will attempt to evaluate that result with the next part of the statement -- "true < 3", which just doesn't make any sense, and so that receives a compiler error.
In your code snippet, there is no exit to the for loop until the value of i reaches 3, so this second "if" statement is unneeded. But if you did want to test to see whether i was between 1 and 2 (inclusive), then you would have to break those up into individual tests...
if ( 0 < i && i < 3 ...
Lastly ... if the value of i is between 1 and 2 (inclusive), then it cannot also be between 7 and 8 (inclusive) .. therefore the if statement as you coded it will always be false even after we correct the syntax.

Postincrement in java expressions

In this example:
int i = 1;
while(i < 10)
if(i++%2 == 0)
System.out.println(i);
Why is the output 3,5,7,9 and not 2,4,6,8?
The condition is performed on the previous value of i, before it is incremented (which is even), but the output is done on the incremented value of i (which is odd).
The ++ operator applied after a variable returns the value of the variable and increments the variable after the expression is evaluated. The semantic is the same than this:
int i = 1;
while(i < 10) {
boolean cond = i % 2 == 0;
i = i + 1;
if(cond) {
System.out.println(i);
}
}
The post-increment operator, uses the current value of its operand in the expression and then increments it.
We can break this down using a literal value of '2' for example.
Basically this is what your present code is doing:
int i = 2;
if (i % 2 == 0) //true, 2 % 2 = 0
i = i + 1; //i now becomes 3
System.out.println (i);
OR to make it simpler, if we remove the loop and put back your code
int i = 1;
if (i++ % 2 == 0) //1 % 2 != 0
System.out.println (i); //Nothing will print for the if statement
System.out.print i; //Will print 2, because this print statement is outside
//the body of the if-statement
to get the output that you are looking for, you will have to use the prefix-increment operator (++i)
int i = 1;
if ( ++i % 2 == 0)
System.out.println (i);
this is equivalent to
int i = 1
if ( (i + i) % 2 == 0) //++i increments i and then uses it in the expression
System.out.println (i);

Categories

Resources