Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using or "|" operator for statements in java

Suppose I have an array a[] , if I want to change the value of a[i] and change it to zero , I can do it by using temp variable like.

int temp = a[i];
a[i] = 0;

But I came across a code similar to this

int temp = a[i] | (a[i] = 0);

I had hard time understanding this. Please explain does it work? Is it a good practice to use similar type of code ?

like image 435
mc20 Avatar asked Mar 22 '26 07:03

mc20


1 Answers

The purpose of the straightforward code is to grab a value from an array and set its location in the array to 0.

Let's see how the tricky code does it.

The | operator is the bitwise-or operator. First, a[i] is evaluated, and whatever value is there is the left operand. Next, the parentheses force a[i] = 0 to be evaluated. This sets the array element to 0 and the right operand of | is now 0. Performing a bitwise-or with the value 0 doesn't change the other value. The value of the entire expression on the right of temp = is the original value of a[i]. This has the effect of doing everything the straightforward code does, in one statement.

This code is tricky and it's not good practice, because it's confusing. I would never use such a technique.

like image 83
rgettman Avatar answered Mar 23 '26 20:03

rgettman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!