Hello, I was brushing up on Java basics when I came across the shifting operators. Usually I don't give much importance to this because I've never found a good reason to use them. In the Tutorial Sun states that they are widely use to keep state of things, for instance, if a window is resizable, or hidden, whatever.
I've always used boolean variables to keep this kind of info, I guess that one good reason to use it is that in one inetger var you could keep 32 different states by using flags whereas you should create a boolean (8 bits?) for each one of those hence having only 4 possible state variables.
My point of view is that it difficults the readibility of the code for the programmer has to check what are the values of each flag every time he wants to do something, creating ugly sintax.
Is there a good reason to use bit flags, can you give examples of real applications that use this type of syntax.
> Is there a good reason to use bit flags, can you give > examples of real applications that use this type of > syntax.
You should abstract this stuff inside a method. Inside the method, you use bit-shifting operations, but anyone who uses your api doesn't have to know about this.
The use of it is that you don't need to declare a new method for each boolean flag. I hope I'm understanding you correctly!
Using bitfields in Java is not nearly as popular as it was with C or even C++. These days, with the amount of memory available, guarding your bits so jealously is rarely necessary.
Probably in Java the best reason to use bit-shifting is if you are deciphering some binary format.
There's another reason for using bitfields especially in JAVA. You can group huge amounts of booleans together making your code simpler and even a lot faster. Example:
long status; // Holds 64 booleans and platform independent! long previousStatus; // The same of yesterday.
if(status == previousStatus) // Check them 64 at once! { update(..... } The rest of the code might be complex, the testing was swift and simple. ;JOOP!