I'm trying to get prepared for the OCA Java certification and got stuck in some questions dealing assignment in if conditions. Can anyone explain me the reason of the different behaviours in the code below? By my point of view I'm just putting the same two boolean values in an "inclusive or" condition 6 times...
package pck;
class SuperMain{
boolean b;
public static void main(String args[]){
new SuperMain();
}
SuperMain(){
if(_true()|_false())
System.out.println(b); //1 - prints false
if(b=true|_false())
System.out.println(b); //2 - prints true
if(_true()|(b=false))
System.out.println(b); //3 - prints false
if((b=true)|_false())
System.out.println(b); //4 - prints false
if(b=true|(b=false))
System.out.println(b); //5 - prints true
if((b=true)|(b=false))
System.out.println(b); //6 - prints false
}
boolean _true(){return b=true;}
boolean _false(){return b=false;}
}
The difference is in precedence. | has higher precedence ("binds tighter") than =.
So this:
if(b=true|_false())
is effectively:
if (b = (true | _false()))
...
Likewise this:
if(b=true|(b=false))
is effectively:
if (b = (true | (b = false))
In these cases, the assignment of false to b occurs before the assignment of true to b... so b ends up being true. In every other case, the assignments occur in the opposite order.
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.
final int a=5;
System.out.println(a+1)
prints 6 whereas System.out.println(a++) or a=a+1 and then s.o.p(a) would give error.
Why would it print 6 when final values cant be changed?
Both a++ and a=a+1 assign a new value to a.
a+1 does not: it just evaluates to 1 more than the value in a.
Evaluating the statements:
System.out.println(a);
System.out.println(a+1);
System.out.println(a);
will show that the value of a is the same before and after. Doing the same with a++ or a=a+1 in the middle statement (obviously making a non-final first) will show that a is changed.
This should be no more surprising than System.out.println(5+1) printing 6, whilst leaving the values of 5 and 1 unchanged.
Because you never modify a in your example. You print the result of a+1. If you print a afterwards you'll see that it is still 5.
It is basically
int a = 5;
int b = a+1;
System.out.println(b); // prints 6
System.out.println(a); // still prints 5
What would the if condition be using this example.
A - if true, B or C must also be true; Pass
if false, B and C do not matter; Fail
B - if true, A must also be true and C can be false or true
if false, A must be true and C must be true; Pass, else Fail
C - if true, A must also be true and B can be false or true
if false, A must be true and B must be true; Pass, else Fail
I am not sure how to set this up. Here is what I think the if may look like:
//Not sure if the "or" needs to be double or single bar.
if(A && B | C){
//pass
}else{//fail}
The broken apart code for this logic would be this:
if(A){
if(B|C){
//PASS
}else{//fail}
}else{//fail}
Depending on the language you're working with it's mostly || double bars.
I think this will work:
if(A && (B || C)) {
pass;
} else {
fail;
}
This means if A is true and B or C is true pass, otherwise fail.
In Java, the difference btw single and double operators is that double operators (&& and ||) are short-circuit (i.e. if the result of the expression is pre-determined, the right side won't be executed).
e.g. in these cases, foo() would never be called:
false && foo(); // evaluates to false
true || foo(); // evaluates to true
but in these cases it would:
false & foo(); // still evaluates to false
true | foo(); // still evaluates to true
This question already has answers here:
How does an array's equal method work?
(5 answers)
Closed 8 years ago.
So I was doing review, and came across this question that I'm not very sure about.
Consider the following code segment:
int[] A = {1,2,3};
int[] B = {1,2,3};
int[] C = A;
After this code executes, which of the following expressions would evaluate to true?
I. A.equals (B)
II. A == B
III. A ==C
I only
II only
III only
I and III only
I, II, and III
I thought it was I only, but one of my classmates said that it was III only.
Could some please explain this?
Thanks for the help.
The answer is in the above linked question by #J L:
Arrays.equals(array1, array2) works as you would expect (i.e. compares
content), array1.equals(array2) falls back to Object.equals
implementation, which in turn compares identity, and thus better
replaced by == (for purists: yes I know about null).
Simply put, you are setting C equal to A, so that's why A == C is true. You performing an Object.equals essentially. While it appears on the surface that A.equals(B) would be true, they are not because of the internals behind Object.equals.
So your friend is right.
The third has a and c pointing the same object. The others not.
Your friend is correct.
In the code you are saying C = A.
This means that C is the same exact object as A.
In other cases, they are not the same object, although they have the same content.
You might want to have a look at Arrays.deepEquals which returns true (your code is slightly modified):
package arrays;
import java.util.Arrays;
public class ArraysTest {
public static void main(String[] args) {
Integer[] A = { 1, 2, 3 };
Integer[] B = { 1, 2, 3 };
Integer[] C = A;
System.out.println("A.equals(B) is " + (A.equals(B)));
System.out.println("Arrays.deepEquals(A, B) is "
+ (Arrays.deepEquals(A, B)));
System.out.println("A == B is " + (A == B));
System.out.println("A == C is " + (A == C));
}
}
The output will be:
A.equals(B) is false
Arrays.deepEquals(a, b) is true
A == B is false
A == C is true
only the third one would be true.
take the first
int[] A = {1,2,3};
witch means A has position 0:1, position 1:2, position 2:3.
then take the second
int[] B = {1,2,3};
witch means B has position 0:1, position 1:2, position 2:3.
so they have the same values in each position but they are two different int arrays
but then take the third
int[] C = A;
their you are saying `int[] C is equal to int[] A,
just like saying
String a = "LOL";
String b = a;
Also just a few notes, Only strings are compared by using .equalsanything else is compared using ==, and always use lower case letters for variables, it makes it easier to code.
you can always test methods with this
if(A.equals(B)
{
System.out.println("A.equals(B) is true");
}
else
{
System.out.println("A.equals(B) is false";
}
same for
if(A == B)
{
System.out.println("A == B is true");
}
else
{
System.out.println("A == B is false");
}
Hope this helps, Luke.
I'm doing the oracle certified associate Java SE7 Programmer practice exams (the book) and came across a question, and I don't understand the answer even with the explanation.
Here's the explanation and the code:
It will print 3. The loop body is executed twice and the program will print 3.
I don't understand how the loop body is executed twice, maybe I don't understand what the b=!b means. Can someone explain please?
class TestClass {
public static void main(String args[]){
boolean b = false;
int i = 1;
do{
i + + ;
} while (b = !b);
System.out.println(i);
}
}
b = !b is an assignment which assigns the inverse of b to itself (effectively flipping between true and false)
in java, an assignment returns what was assigned (so that a=b=1 is possible)
therefore while (b=!b) will flip the value of b, and then check the value of b.
b=!b
Will always be true, why?
Because, what you are doing is that you insert to "b" the opposite value (T->F, F->T),and if there was no problem while (b = !b); will return TRUE....
So at your case while (b = !b); will always return true
Iteration 1
boolean b = false;
int i = 1;
do{
i++ ; // i = 2
} while (b = !b); // b = !false = true so one more execution
Iteration 2
do{
i++ ; // i = 3
} while (b = !b); // b = !true = false so loop breaks
So it will print 3. simple :)
Actually the confusion is with = sign. = is assigning operator where as == is the conditional operator. The first will assign the value whereas later will check for the condition. You can play with it and have some other result like
int a = 6;
int b = 10;
System.out.println(a = b);
System.out.println(a == b);
and you will get the idea.
At the end of the first iteration the variable i will be 2 because of the increment operator. The expression b=!b will result to true (b = !false) and set the variable b to true as well. So the loop gets executed again.
At the end of the second iteration the variable i is now 3. The expression b=!b will result to false (b = !true), which will be also the value of the variable b. So the whole do-while-loop terminates and the println() statement shows 3.
Keep in mind: = (assign operator) is not the same as == (equality check).
The condition
b = !b;
uses the assignment operator, which returns the value that has been assigned.
Initially, b is false, and therefore true is assigned to b, and used for the condition. The while loop therefore executes a second time. In this execution, b is true, and therefore false is assigned to b and used for the loop condition. The loop therefore exits.