Reputation: 321
Here the code.
public class Test {
public static void main(String[] args) {
int x=2; int y = 3;
if((y == x++) | (x < ++y)){
System.out.println("x = " + x + "Y = " + y);
}
}
}
This outputs x=3 y=4
Another Criteria
public class Test {
public static void main(String[] args) {
System.out.println(4|3);
}
}
This outputs 7
Here the second criteria |
works as bit wise operator. But in first criteria |
is not. It manipulates and giving the output. I need explanation how the first criteria works.
The thing i know is, |
will compare both sides and ||
will compare only left side and it true it proceeds to next.
Hope my question is clear. Thankyou in advance..
Upvotes: 2
Views: 120
Reputation: 62864
For the first example you will have:
if ((3 == 2) | (3 < 4))
which is equal to:
if ( false | true )
and evaluates to true
(since the both sides of the expression are compared).
For the second example, since you already know that |
will compare both sides, here's what it really happens. The numbers are converted into binary ones and then the operation is applied:
4 | 3
will be converted to:
100 | 011 = 111
which is equal to 7
.
Upvotes: 2
Reputation: 49372
Follow the JLS 15.22.2:
When both operands of a
&
,^
, or|
operator are of typeboolean
orBoolean
, then the type of the bitwise operator expression isboolean
. In all cases, the operands are subject to unboxing conversion (§5.1.8) as necessary.For
&
, the result value istrue
if both operand values aretrue
; otherwise, the result isfalse
.For
^
, the result value istrue
if the operand values are different; otherwise, the result isfalse
.For
|
, the result value isfalse
if both operand values arefalse
; otherwise, the result istrue
.
Take the first case:
int x=2; int y = 3;
if((y == x++) | (x < ++y)){
System.out.println("x = " + x + "Y = " + y);
}
(y == x++)
is false because x++
is post-increment , (x < ++y)
is true , hence false|true
is true
and you get the console o/p with the values of x=3
and y=4
.
Second case , is natural bitwise OR :
System.out.println(4|3);
That in 3-bits is (011|100)
= (111)
= 7
(base 10).
Upvotes: 1
Reputation: 9775
In the first example, first the left side of the expression is evaluated:
y == x++ // y == x; x=x + 1
y
is 3, x is 2, the equality check is false
, and the x
is incremented to 3.
and then the right side of the expression is evaluated:
x < ++y; // y = y + 1; x < y
y
is incremented and is 4, and then is checked if x
is smaller than y
. And yes, 3 is smaller than 4, and the result of the right part is true
.
Since there is bitwise |
operator between false
on the left side and true
on the right side, the result is
false | true = true
And that's why the expression is true
and syso
is executed.
In the second example, a bitwise OR is executed, hence
100 | 011 = 111 //is equal to 7
Upvotes: 1