Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple values separated by a pipe in Java

Tags:

java

int

pipe

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!

like image 418
public static void Avatar asked Dec 24 '22 17:12

public static void


1 Answers

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.

like image 67
Richard Neish Avatar answered Jan 05 '23 05:01

Richard Neish