Java Reference
In-Depth Information
result = reverse(result);
System.out.println("Previous result reversed:\n" +
toBinaryString(result));
System.out.println("Bit count in number:" + bitCount(number));
}
}
This program produces the following output:
number:
1111000000000000000000000000000000000000000000000000000000001111
number rotated left 2 bits:
1100000000000000000000000000000000000000000000000000000000111111
number rotated right 3 bits:
1111111000000000000000000000000000000000000000000000000000000001
Previous result reversed:
1000000000000000000000000000000000000000000000000000000001111111
Bit count in number: 8
I inserted \n characters in the output to put the binary value on the line following its description because
it would not fit within the page width in the topic. You might find it more convenient to remove the
newlines but insert spaces to make the binary values align vertically. They are easier to compare that
way.
How It Works
The program applies a variety of the methods for bit operation in the Long class to the value in number .
The toBinaryString() method in the Long class creates a string representation of the binary value that
is passed to the method, and you output that using the println() method. By comparing the bit patterns
produced by each method with the original, you can clearly see what the methods do. You might like to
try the same thing with the methods in the Integer class. Because there is an import statement for all
the static members of the Long class, none of the methods from the Long class that the program uses need
to be qualified with the class name.
VARIABLES WITH A FIXED SET OF INTEGER
VALUES
You often need variables that can have values only from a predefined fixed set. For example, suppose you
want to define an integer variable with the name weekday , which stores an integer value representing a day
of the week. The variable ideally needs to be limited to seven possible values, one for each of Monday
through Sunday. This is a situation where a facility called an enumerated type , or simply an enumeration ,
is a natural choice. You could define an enumeration for this situation with the following declaration state-
ment:
enum Day {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }
Search WWH ::




Custom Search