Tuesday, March 20, 2018

java - What does "|=" mean? (pipe equal operator)



I tried searching using Google Search and Stack Overflow, but it didn't show up any results. I have seen this in opensource library code:



Notification notification = new Notification(icon, tickerText, when);
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;



What does "|=" ( pipe equal operator ) mean?


Answer



|= reads the same way as +=.



notification.defaults |= Notification.DEFAULT_SOUND;


is the same as




notification.defaults = notification.defaults | Notification.DEFAULT_SOUND;


where | is the bit-wise OR operator.



All operators are referenced here.



A bit-wise operator is used because, as is frequent, those constants enable an int to carry flags.




If you look at those constants, you'll see that they're in powers of two :



public static final int DEFAULT_SOUND = 1;
public static final int DEFAULT_VIBRATE = 2; // is the same than 1<<1 or 10 in binary
public static final int DEFAULT_LIGHTS = 4; // is the same than 1<<2 or 100 in binary


So you can use bit-wise OR to add flags



int myFlags = DEFAULT_SOUND | DEFAULT_VIBRATE; // same as 001 | 010, producing 011



so



myFlags |= DEFAULT_LIGHTS;


simply means we add a flag.



And symmetrically, we test a flag is set using & :




boolean hasVibrate = (DEFAULT_VIBRATE & myFlags) != 0;

No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...