I've been working with Java for Android development for sometime. However, only today did I notice that it is possible to do this:
int myInt = 1|3|4;
As far as I'm aware the variable myInt should only have one integer value. Could someone explain what's going on here?
Thanks!
The |
character in Java is a bitwise OR (as mentioned in the comments). This is often used to combine flags, as in the example you gave.
In this case, the individual values are powers of two, which means that only one bit of the value will be 1
.
For example, given code like this:
static final int FEATURE_1 = 1; // Binary 00000001
static final int FEATURE_2 = 2; // Binary 00000010
static final int FEATURE_3 = 4; // Binary 00000100
static final int FEATURE_4 = 8; // Binary 00001000
int selectedOptions = FEATURE_1 | FEATURE_3; // Binary 00000101
then FEATURE_1
and FEATURE_2
are set in the selectedOptions
variable.
Then to use the selectedOptions
variable later, the application would use the bitwise AND operation &
and there would be code like:
if ((selectedOptions & FEATURE_1) == FEATURE_1) {
// Implement feature 1
}
if ((selectedOptions & FEATURE_2) == FEATURE_2) {
// Implement feature 2
}
if ((selectedOptions & FEATURE_3) == FEATURE_3) {
// Implement feature 3
}
if ((selectedOptions & FEATURE_4) == FEATURE_4) {
// Implement feature 4
}
This is a common coding pattern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With