Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Java Utilities Package and Bit
Manipulation
Outline
21.1
21.2
21.3
21.4
21.5
21.6
21.7
Introduction
Vector Class and Enumeration Interface
Stack Class of Package java.util
Hashtable Class
Properties Class
Bit Manipulation and the Bitwise Operators
BitSet Class
2003 Prentice Hall, Inc. All rights reserved.
Introductions
• Java Utility package is one of the most commonly used
packages in the java program. The Components are
1. collections framework
2. legacy collection classes
3. event model
4. date and time facilities
5. internationalization
6. miscellaneous utility classes (string tokenizer, randomnumber generator and bit array)
2003 Prentice Hall, Inc. All rights reserved.
Random Number Generation
• The Random class of java.util package can be used
to generate a random number in the range which
can be specified
• Example1
2003 Prentice Hall, Inc. All rights reserved.
Breaking the String into Words
• StringTokenizer(String str):
This constructor creates token of the given string. It
takes a string type value as a parameter which has to
be tokenized.
• hasMoreTokens():
Above method checks the token created by the
StringTokenizer() methods. It returns Boolean type
value either true or false. If the above method returns
true then the nextToken() method is called.
• nextToken():
This method returns the tokenized string which is the
separate word of the given string. Example2
2003 Prentice Hall, Inc. All rights reserved.
Comparing Arrays : Java Util
• Arrays.equals():
Above method compares two arrays.
• Arrays is the class of the java.util.*; package.
This class and it's methods are used for
manipulating arrays.
• Example3
2003 Prentice Hall, Inc. All rights reserved.
Shuffling the Element of a List or Array
• Shuffling the element means moving the element from one
place to another place randomly.
• List:
This is the class of java.util.*; package which extends
Collection. This is used to list elements available in the
Collections.
• ArrayList():
This is the construction of ArrayList class of the
java.util.*; package that extends the AbstractList class. It
constructs an empty list. You can specify the capacity of
the list by passing a value to the constructor.
• sort(list):
This is the method of the Collections class which is used
to sort the list elements in the default order.
• Example4
2003 Prentice Hall, Inc. All rights reserved.
21.1 Introduction
• Utility classes and interfaces
– Contained in package java.util
•
•
•
•
•
•
Class Vector
Interface Enumeration
Class Stack
Class Hashtable
Class Properties
Class BitSet
2003 Prentice Hall, Inc. All rights reserved.
Java Iterators
• Iterator in Java is traversing object.
• Index based traversing methods like for-loop ,while
loop,do-while
• Iterator is a way to traverse as well as access the data from
the collection.
• Even with traversing with object we have Enumeration,
Iterator and ListIterator
• Java iterator is an interface belongs to collection
framework allow us to traverse the collection and access
the data element of collection without bothering the user
about specific implementation of that collection
2003 Prentice Hall, Inc. All rights reserved.
Methods Declared by Iterator
1) boolean hasNext( )
Returns true if there are more elements. Otherwise,
returns false.
2) Object next( )
Returns the next element. Throws
NoSuchElementException if there is not a next element.
3) void remove( )
Removes the current element. Throws
IllegalStateException if an attempt is made to call
remove( ) that is not preceded by a call to next( ).
2003 Prentice Hall, Inc. All rights reserved.
Methods Declared by ListIterator
• void add(Object obj) - Inserts obj into the list
• boolean hasNext( ) - Returns true if there is a next element.
• boolean hasPrevious( ) -Returns true if there is a previous
element.
• Object next( ) - Returns the next element.
• int nextIndex( ) - Returns the index of the next element.
• Object previous( ) - Returns the previous element.
• int previousIndex( ) - Returns the index of the previous
element.
• void remove( ) - Removes the current element from the list.
• void set(Object obj) - Assigns obj to the current element.
• Example
Demo
2003 Prentice Hall, Inc. All rights reserved.
Vector Class
• Vector implements a dynamic array. It is similar to ArrayList, but
with two differences:
– Vector is synchronized.
– Vector contains many legacy methods that are not part of the
collections framework.
• Constructors
Vector( ) - creates a default vector, which has an initial size of 10
Vector(int size) - creates a vector whose initial capacity is specified
by size
Vector(int size, int incr)- creates a vector whose initial capacity is
specified by size and whose increment is specified by incr
Vector(Collection c) - fourth form creates a vector that contains the
elements of collection c Example
2003 Prentice Hall, Inc. All rights reserved.
Set Interfaces
• A Set is a Collection that cannot contain duplicate elements.
It models the mathematical set abstraction.
• Methods
• add( ) - Adds an object to the collection
• clear( ) - Removes all objects from the collection
• contains( ) - Returns true if a specified object is an element
within the collection
• isEmpty( )-Returns true if the collection has no elements
• iterator( ) -Returns an Iterator object for the collection
which may be used to retrieve an object
• remove( )-Removes a specified object from the collection
• size( ) - Returns the number of elements in the collection
2003 Prentice Hall, Inc. All rights reserved.
Example
import java.util.*;
public class SetDemo {
public static void main(String args[]) {
int count[] = {34, 22,10,60,30,22};
Set<Integer> set = new HashSet<Integer>();
try{ for(int i = 0; i<5; i++){
set.add(count[i]); }
System.out.println(set);
TreeSet sortedSet = new TreeSet<Integer>(set);
System.out.println("The sorted list is:");
System.out.println(sortedSet);
System.out.println("The First element of the set is: "+
(Integer)sortedSet.first()); System.out.println("The last element of the set
is: "+ (Integer)sortedSet.last());
}
catch(Exception
e){} } }
2003 Prentice Hall, Inc. All rights reserved.
Output
[amrood]$ java SetDemo [34, 30, 60, 10, 22]
The sorted list is: [10, 22, 30, 34, 60]
The First element of the set is: 10
The last element of the set is: 60
2003 Prentice Hall, Inc. All rights reserved.
21.3 Stack Class of Package java.util
• Stack
– Implements stack data structure
– Extends class Vector
– Stores references to Objects (as does Vector)
2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Outline
// Fig. 21.2: StackTest.java
// Program to test java.util.Stack.
import java.util.*;
StackTest.java
public class StackTest {
Line 9
public StackTest()
{
Stack stack = new Stack();
Create empty
Stack
Lines
18, 20, 22 and
// create objects to store in the stack
Boolean bool = Boolean.TRUE;
Character character = new Character( '$' );
Integer integer = new Integer( 34567 );
String string = "hello";
// use push
stack.push(
printStack(
stack.push(
printStack(
stack.push(
printStack(
stack.push(
printStack(
method
bool );
stack );
character );
stack );
integer );
stack );
string );
stack );
24
Stack method push adds
Object to top of Stack
2003 Prentice Hall, Inc.
All rights reserved.
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// remove items from stack
try {
Object removedObject = null;
Outline
Stack method pop removes
Object from top of Stack
while ( true ) {
removedObject = stack.pop(); // use pop method
System.out.println( removedObject.toString() + " popped" );
printStack( stack );
}
StackTest.java
Line 32
Line 46
}
// catch exception if stack is empty when item popped
catch ( EmptyStackException emptyStackException ) {
emptyStackException.printStackTrace();
}
}
Line 51
Stack method isEmpty returns
true if Stack is empty
private void printStack( Stack stack )
{
if ( stack.isEmpty() )
System.out.print( "stack is empty" ); // the stack is empty
else {
System.out.print( "stack contains: " );
Enumeration items = stack.elements();
Stack extends Vector, so
class Stack may use method
elements to obtain
Enumeration for Stack
2003 Prentice Hall, Inc.
All rights reserved.
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// iterate through the elements
while ( items.hasMoreElements() )
System.out.print( items.nextElement() + " " );
}
Outline
StackTest.java
System.out.println( "\n" ); // go to the next line
}
public static void main( String args[] )
{
new StackTest();
}
} // end class StackTest
2003 Prentice Hall, Inc.
All rights reserved.
stack contains: true
stack contains: true $
Outline
StackTest.java
stack contains: true $ 34567
stack contains: true $ 34567 hello
hello popped
stack contains: true $ 34567
34567 popped
stack contains: true $
$ popped
stack contains: true
true popped
stack is empty
java.util.EmptyStackException
at java.util.Stack.peek(Stack.java:79)
at java.util.Stack.pop(Stack.java:61)
at StackTest.<init>(StackTest.java:32)
at StackTest.main(StackTest.java:63)
2003 Prentice Hall, Inc.
All rights reserved.
21.4 Hashtable Class
• Hashtable
– Data structure that uses hashing
• Algorithm for determining a key in table
– Keys in tables have associated values (data)
– Each table cell is a hash “bucket”
• Linked list of all key-value pairs that hash to that cell
• Minimizes collisions
2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Fig. 21.3: WordTypeCount.java
// Count the number of occurrences of each word in a string.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class WordTypeCount extends JFrame {
private JTextArea inputField;
private JLabel prompt;
private JTextArea display;
private JButton goButton;
Outline
WordTypeCount.j
ava
Line 21
private Hashtable table;
public WordTypeCount()
{
super( "Word Type Count" );
inputField = new JTextArea( 3, 20 );
table = new Hashtable();
Create empty Hashtable
goButton = new JButton( "Go" );
goButton.addActionListener(
2003 Prentice Hall, Inc.
All rights reserved.
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
new ActionListener() { // anonymous inner class
public void actionPerformed( ActionEvent event )
{
createTable();
display.setText( createOutput() );
}
}
Outline
WordTypeCount.j
ava
// end anonymous inner class
); // end call to addActionListener
prompt = new JLabel( "Enter a string:" );
display = new JTextArea( 15, 20 );
display.setEditable( false );
JScrollPane displayScrollPane = new JScrollPane( display );
// add components to GUI
Container container = getContentPane();
container.setLayout( new FlowLayout() );
container.add( prompt );
container.add( inputField );
container.add( goButton );
container.add( displayScrollPane );
2003 Prentice Hall, Inc.
All rights reserved.
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
setSize( 400, 400 );
setVisible( true );
} // end constructor
method
// create table from userHashtable
input
private void createTable()
{
containsKey
determines
String input = inputField.getText();
method get obtains
whether the keyHashtable
specified as an
StringTokenizer words = new StringTokenizer(
input,
" \n\t\r"
);
Object associated with
key from
Outline
WordTypeCount.j
ava
Line 66
argument is in the hash table
Line 68
Hashtable (returns null if
while ( words.hasMoreTokens() ) {
Hashtable method put adds
neither key nor Object
exist)
String word = words.nextToken().toLowerCase();
// get word
key and valueLines
to Hashtable
71 and 74
(returns
null
if
key
has been
// if the table contains the word
inserted previously)
if ( table.containsKey( word ) ) {
Integer count = (Integer) table.get( word ); // get value
// and increment it
table.put( word, new Integer( count.intValue() + 1 ) );
}
else // otherwise add the word with a value of 1
table.put( word, new Integer( 1 ) );
} // end while
2003 Prentice Hall, Inc.
All rights reserved.
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
} // end method createTable
// create string containing table values
private String createOutput() {
String output = "";
Enumeration keys = table.keys();
Outline
WordTypeCount.j
ava
Line 83
Hashtable method keys returns an
returns
Enumeration of keys inLine
the hash
93 table
Hashtable
method
isEmpty returns
the number
of key-value
pairs
that indicates whether
the key-value pairs
in boolean
the hash table
Line 94
currentKey + "\t" Hashtable
+ table.get( currentKey
) +
"\n";
contains any
Objects
// iterate through the keys
while ( keys.hasMoreElements() ) {
Hashtable method size
Object currentKey = keys.nextElement();
// output
output +=
}
output += "size: " + table.size() + "\n";
output += "isEmpty: " + table.isEmpty() + "\n";
return output;
} // end method createOutput
2003 Prentice Hall, Inc.
All rights reserved.
100
101
102
103
104
105
106
public static void main( String args[] )
{
WordTypeCount application = new WordTypeCount();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
Outline
WordTypeCount.j
ava
} // end class WordTypeCount
2003 Prentice Hall, Inc.
All rights reserved.
21.5 Properties Class
• Properties
– Persistent Hashtable
• Can be written to output stream
• Can be read from input stream
– Provides methods setProperty and getProperty
• Store/obtain key-value pairs of Strings
• Preferences API
– Replace Properties
– More robust mechanism
2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Fig. 21.4: PropertiesTest.java
// Demonstrates class Properties of the java.util package.
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
public class PropertiesTest extends JFrame {
private JLabel statusLabel;
private Properties table;
private JTextArea displayArea;
private JTextField valueField, nameField;
Outline
PropertiesTest.
java
Line 20
// set up GUI to test Properties table
public PropertiesTest()
{
super( "Properties Test" );
table = new Properties(); // create Properties table
Create empty Properties
Container container = getContentPane();
// set up NORTH of window's BorderLayout
JPanel northSubPanel = new JPanel();
northSubPanel.add( new JLabel( "Property value" ) );
valueField = new JTextField( 10 );
northSubPanel.add( valueField );
2003 Prentice Hall, Inc.
All rights reserved.
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
northSubPanel.add( new JLabel( "Property name (key)" ) );
nameField = new JTextField( 10 );
northSubPanel.add( nameField );
JPanel northPanel = new JPanel();
northPanel.setLayout( new BorderLayout() );
northPanel.add( northSubPanel, BorderLayout.NORTH );
Outline
PropertiesTest.
java
statusLabel = new JLabel();
northPanel.add( statusLabel, BorderLayout.SOUTH );
container.add( northPanel, BorderLayout.NORTH );
// set up CENTER of window's BorderLayout
displayArea = new JTextArea( 4, 35 );
container.add( new JScrollPane( displayArea ),
BorderLayout.CENTER );
// set up SOUTH of window's BorderLayout
JPanel southPanel = new JPanel();
southPanel.setLayout( new GridLayout( 1, 5 ) );
// button to put a name-value pair in Properties table
JButton putButton = new JButton( "Put" );
southPanel.add( putButton );
putButton.addActionListener(
2003 Prentice Hall, Inc.
All rights reserved.
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
new ActionListener() { // anonymous inner class
Outline
// put name-value pair in Properties table
Properties method
public void actionPerformed( ActionEvent event )
PropertiesTest.
setProperty stores
{
Object value = table.setProperty(
value for the specifiedjava
key
nameField.getText(), valueField.getText() );
Lines 64-65
if ( value == null )
showstatus( "Put: " + nameField.getText() +
" " + valueField.getText() );
else
showstatus( "Put: " + nameField.getText() + " " +
valueField.getText() + "; Replaced: " + value );
listProperties();
}
} // end anonymous inner class
); // end call to addActionListener
// button to empty contents of Properties table
JButton clearButton = new JButton( "Clear" );
southPanel.add( clearButton );
clearButton.addActionListener(
2003 Prentice Hall, Inc.
All rights reserved.
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
Outline
new ActionListener() { // anonymous inner class
// use method clear to empty table
public void actionPerformed( ActionEvent event )
{
table.clear();
showstatus( "Table in memory cleared" );
listProperties();
}
PropertiesTest.
java
Lines 113-114
} // end anonymous inner class
); // end call to addActionListener
// button to get value of a property
JButton getPropertyButton = new JButton( "Get property" );
southPanel.add( getPropertyButton );
getPropertyButton.addActionListener(
new ActionListener() { // anonymous inner class
// use method getProperty to obtain a property value
public void actionPerformed( ActionEvent event )
{
Object value = table.getProperty(
nameField.getText() );
Properties method
getProperty locates value
associated with the specified key
if ( value != null )
showstatus( "Get property: " + nameField.getText() +
" " + value.toString() );
2003 Prentice Hall, Inc.
All rights reserved.
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
else
showstatus( "Get: " + nameField.getText() +
" not in table" );
listProperties();
Outline
PropertiesTest.
java
}
} // end anonymous inner class
); // end call to addActionListener
// button to save contents of Properties table to file
JButton saveButton = new JButton( "Save" );
southPanel.add( saveButton );
saveButton.addActionListener(
new ActionListener() { // anonymous inner class
// use method save to place contents in file
public void actionPerformed( ActionEvent event )
{
// save contents of table
try {
FileOutputStream output =
new FileOutputStream( "props.dat" );
2003 Prentice Hall, Inc.
All rights reserved.
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
table.store( output, "Sample Properties" );
output.close();
listProperties();
}
Outline
Properties method store
saves Properties contents
PropertiesTest.
to FileOutputStream
java
// process problems with file output
catch( IOException ioException ) {
ioException.printStackTrace();
}
Line 147
}
} // end anonymous inner class
); // end call to addActionListener
// button to load contents of Properties table from file
JButton loadButton = new JButton( "Load" );
southPanel.add( loadButton );
loadButton.addActionListener(
new ActionListener() { // anonymous inner class
// use method load to read contents from file
public void actionPerformed( ActionEvent event )
{
2003 Prentice Hall, Inc.
All rights reserved.
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
// load contents of table
try {
FileInputStream input =
new FileInputStream( "props.dat" );
table.load( input );
input.close();
listProperties();
}
Outline
PropertiesTest.
java
Properties method
load
Line 179
restores Properties contents
from FileInputStream
// process problems with file input
catch( IOException ioException ) {
ioException.printStackTrace();
}
}
} // end anonymous inner class
); // end call to addActionListener
container.add( southPanel, BorderLayout.SOUTH );
setSize( 550, 225 );
setVisible( true );
} // end constructor
2003 Prentice Hall, Inc.
All rights reserved.
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
// output property values
public void listProperties()
{
StringBuffer buffer = new StringBuffer();
String name, value;
Outline
Enumeration enumeration = table.propertyNames();
while ( enumeration.hasMoreElements() ) {
name = enumeration.nextElement().toString();
value = table.getProperty( name );
buffer.append( name ).append( '\t' );
buffer.append( value ).append( '\n' );
}
PropertiesTest.
java
Line 207
Properties method
propertyNames obtains
Enumeration of property names
displayArea.setText( buffer.toString() );
}
// display String in statusLabel label
public void showstatus( String s )
{
statusLabel.setText( s );
}
public static void main( String args[] )
{
PropertiesTest application = new PropertiesTest();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
} // end class PropertiesTest
2003 Prentice Hall, Inc.
All rights reserved.
Outline
PropertiesTest.
java
Program Output
2003 Prentice Hall, Inc.
All rights reserved.
21.6 Bit Manipulation and the Bitwise
Operators
• Bitwise operators
– Used for bit manipulation
– Used for getting down to “bit-and-bytes” level
2003 Prentice Hall, Inc. All rights reserved.
21.6 Bit Manipulation and the Bitwise
Operators (cont.)
Description
The bits in the result are set to 1 if the corresponding bits
in the two operands are both 1.
|
bitwise inclusive OR The bits in the result are set to 1 if at least one of the corresponding bits in the two operands is 1.
^
The bits in the result are set to 1 if exactly one of the
bitwise exclusive
corresponding bits in the two operands is 1.
OR
<<
Shifts the bits of the first operand left by the number of
left shift
bits specified by the second operand; fill from the right
with 0.
>>
Shifts the bits of the first operand right by the number of
signed right shift
bits specified by the second operand. If the first operand
is negative, 1s are filled in from the left; otherwise, 0s
are filled in from the left.
>>>
unsigned right shift Shifts the bits of the first operand right by the number of
bits specified by the second operand; 0s are filled in
from the left.
~
bitwise complement All 0 bits are set to 1, and all 1 bits are set to 0.
Fig. 21.5 Bitwise operators.
Operator
&
Name
bitwise AND
2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Fig. 21.6: PrintBits.java
// Printing an unsigned integer in bits.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
Outline
PrintBits.java
public class PrintBits extends JFrame {
private JTextField outputField;
// set up GUI
public PrintBits()
{
super( "Printing bit representations for numbers" );
Container container = getContentPane();
container.setLayout( new FlowLayout() );
container.add( new JLabel( "Enter an integer " ) );
// textfield to read value from user
JTextField inputField = new JTextField( 10 );
container.add( inputField );
inputField.addActionListener(
new ActionListener() { // anonymous inner class
2003 Prentice Hall, Inc.
All rights reserved.
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// read integer and get bitwise representation
public void actionPerformed( ActionEvent event )
{
int value = Integer.parseInt( event.getActionCommand() );
outputField.setText( getBits( value ) );
}
} // end anonymous inner class
); // end call to addActionListener
Outline
PrintBits.java
Lines 31-32
Convert String to int, then pass
Line
55 getBits
int to private
method
to get the int’s bit representation
container.add( new JLabel( "The integer in bits is" ) );
// textfield to display integer in bitwise form
outputField = new JTextField( 33 );
outputField.setEditable( false );
container.add( outputField );
setSize( 720, 70 );
setVisible( true );
1 << 31 equals 10000000 00000000 00000000 00000000
} // end constructor
// display bit representation of specified int value
private String getBits( int value )
{
// create int value with 1 in leftmost bit and 0s elsewhere
int displayMask = 1 << 31;
2003 Prentice Hall, Inc.
All rights reserved.
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
StringBuffer buffer = new StringBuffer( 35 ); // buffer for output
// for each bit append 0 or 1 to buffer
for ( int bit = 1; bit <= 32; bit++ ) {
// use displayMask to isolate bit
buffer.append( ( value & displayMask ) == 0 ? '0' : '1' );
Outline
PrintBits.java
Line 63
Line 65
value <<= 1; // shift value one position to left
if ( bit % 8 == 0 )
buffer.append( ' ' );Use
// append
every 8 bits
bitwisespace
ANDto
(&)buffer
to combine
}
each bit in value and 1 << 31
Shift value one position to left
return buffer.toString();
} // end method getBits
public static void main( String args[] )
{
PrintBits application = new PrintBits();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
} // end class PrintBits
2003 Prentice Hall, Inc.
All rights reserved.
Outline
PrintBits.java
Program Output
2003 Prentice Hall, Inc.
All rights reserved.
21.6 Bit manipulation and the Bitwise
Operators (cont.)
Bit 1
0
1
0
1
Fig. 21.7
Bit 2
Bit 1 & Bit 2
0
0
0
0
1
0
1
1
Bitwise AND operator (&) combining two bits.
2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Fig. 21.8: MiscBitOps.java
// Using the bitwise operators.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
Outline
MiscBitOps.java
public class MiscBitOps extends JFrame {
private JTextField input1Field, input2Field,
bits1Field, bits2Field, bits3Field, resultField;
private int value1, value2;
// set up GUI
public MiscBitOps()
{
super( "Bitwise operators" );
JPanel inputPanel = new JPanel();
inputPanel.setLayout( new GridLayout( 4, 2 ) );
inputPanel.add( new JLabel( "Enter 2 ints" ) );
inputPanel.add( new JLabel( "" ) );
inputPanel.add( new JLabel( "Value 1" ) );
input1Field = new JTextField( 8 );
inputPanel.add( input1Field );
inputPanel.add( new JLabel( "Value 2" ) );
input2Field = new JTextField( 8 );
inputPanel.add( input2Field );
2003 Prentice Hall, Inc.
All rights reserved.
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
inputPanel.add( new JLabel( "Result" ) );
resultField = new JTextField( 8 );
resultField.setEditable( false );
inputPanel.add( resultField );
Outline
MiscBitOps.java
JPanel bitsPanel = new JPanel();
bitsPanel.setLayout( new GridLayout( 4, 1 ) );
bitsPanel.add( new JLabel( "Bit representations" ) );
bits1Field = new JTextField( 33 );
bits1Field.setEditable( false );
bitsPanel.add( bits1Field );
bits2Field = new JTextField( 33 );
bits2Field.setEditable( false );
bitsPanel.add( bits2Field );
bits3Field = new JTextField( 33 );
bits3Field.setEditable( false );
bitsPanel.add( bits3Field );
JPanel buttonPanel = new JPanel();
// button to perform bitwise AND
JButton andButton = new JButton( "AND" );
buttonPanel.add( andButton );
andButton.addActionListener(
new ActionListener() { // anonymous inner class
2003 Prentice Hall, Inc.
All rights reserved.
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// perform bitwise AND and display results
public void actionPerformed( ActionEvent event )
Use bitwise AND (&) to combine
{
value1 and value2
setFields();
resultField.setText( Integer.toString( value1 & value2 ) );
MiscBitOps.java
bits3Field.setText( getBits( value1 & value2 ) );
}
Outline
Lines 66 and 67
} // end anonymous inner class
Lines 86 and 87
); // end call to addActionListener
// button to perform bitwise inclusive OR
JButton inclusiveOrButton = new JButton( "Inclusive OR" );
buttonPanel.add( inclusiveOrButton );
inclusiveOrButton.addActionListener(
new ActionListener() { // anonymous inner class
// perform bitwise inclusive OR and display results Use bitwise inclusive OR (|) to
public void actionPerformed( ActionEvent event )
combine value1 and value2
{
setFields();
resultField.setText( Integer.toString( value1 | value2 ) );
bits3Field.setText( getBits( value1 | value2 ) );
}
} // end anonymous inner class
); // end call to addActionListener
2003 Prentice Hall, Inc.
All rights reserved.
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
// button to perform bitwise exclusive OR
JButton exclusiveOrButton = new JButton( "Exclusive OR" );
buttonPanel.add( exclusiveOrButton );
MiscBitOps.java
exclusiveOrButton.addActionListener(
new ActionListener() { // anonymous inner class
Outline
Lines 106 and 107
Use bitwise exclusive OR (^) to
combine value1 and value2
// perform bitwise exclusive OR and display results
public void actionPerformed( ActionEvent event )
{
setFields();
resultField.setText( Integer.toString( value1 ^ value2 ) );
bits3Field.setText( getBits( value1 ^ value2 ) );
}
} // end anonymous inner class
); // end call to addActionListener
// button to perform bitwise complement
JButton complementButton = new JButton( "Complement" );
buttonPanel.add( complementButton );
complementButton.addActionListener(
new ActionListener() { // anonymous inner class
// perform bitwise complement and display results
public void actionPerformed( ActionEvent event )
{
2003 Prentice Hall, Inc.
All rights reserved.
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
input2Field.setText( "" );
bits2Field.setText( "" );
Outline
int value = Integer.parseInt( input1Field.getText() );
MiscBitOps.java
resultField.setText( Integer.toString( ~value ) );
bits1Field.setText( getBits( value ) );
bits3Field.setText( getBits( ~value ) );
Lines 130 and 132
}
} // end anonymous inner class
Use bitwise complement (~) on value
); // end call to addActionListener
Container container = getContentPane();
container.add( inputPanel, BorderLayout.WEST );
container.add( bitsPanel, BorderLayout.EAST );
container.add( buttonPanel, BorderLayout.SOUTH );
setSize( 600, 150 );
setVisible( true );
} // end constructor
// display numbers and their bit form
private void setFields()
{
value1 = Integer.parseInt( input1Field.getText() );
value2 = Integer.parseInt( input2Field.getText() );
bits1Field.setText( getBits( value1 ) );
bits2Field.setText( getBits( value2 ) );
}
2003 Prentice Hall, Inc.
All rights reserved.
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
// display bit representation of specified int value
private String getBits( int value )
{
// create int value with 1 in leftmost bit and 0s elsewhere
int displayMask = 1 << 31;
Outline
MiscBitOps.java
StringBuffer buffer = new StringBuffer( 35 ); // buffer for output
// for each bit append 0 or 1 to buffer
for ( int bit = 1; bit <= 32; bit++ ) {
// use displayMask to isolate bit
buffer.append( ( value & displayMask ) == 0 ? '0' : '1' );
value <<= 1; // shift value one position to left
if ( bit % 8 == 0 )
buffer.append( ' ' ); // append space to buffer every 8 bits
}
return buffer.toString();
} // end method getBits
public static void main( String args[] )
{
MiscBitOps application = new MiscBitOps();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
} // end class MiscBitOps
2003 Prentice Hall, Inc.
All rights reserved.
Outline
MiscBitOps.java
Program Output
2003 Prentice Hall, Inc.
All rights reserved.
21.6 Bit Manipulation and the Bitwise
Operators (cont.)
Bit 1
0
1
0
1
Fig. 21.9
Bit 2
Bit 1 | Bit 2
0
0
0
1
1
1
1
1
Bitwise inclusive OR operator (|) combining two bits.
2003 Prentice Hall, Inc. All rights reserved.
21.6 Bit Manipulation and the Bitwise
Operators (cont.)
Bit 1
Bit 2
Bit 1 ^ Bit 2
0
0
0
1
0
1
0
1
1
1
1
0
Fig. 21.10 Bitwise exclusive OR operator (^) combining two bits.
2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Fig. 21.11: BitShift.java
// Using the bitwise shift operators.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
Outline
BitShift.java
public class BitShift extends JFrame {
private JTextField bitsField, valueField;
// set up GUI
public BitShift()
{
super( "Shifting bits" );
Container container = getContentPane();
container.setLayout( new FlowLayout() );
container.add( new JLabel( "Integer to shift " ) );
// textfield for user to input integer
valueField = new JTextField( 12 );
container.add( valueField );
valueField.addActionListener(
new ActionListener() { // anonymous inner class
// read value and display its bitwise representation
public void actionPerformed( ActionEvent event )
{
2003 Prentice Hall, Inc.
All rights reserved.
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
int value = Integer.parseInt( valueField.getText() );
bitsField.setText( getBits( value ) );
Outline
}
BitShift.java
} // end anonymous inner class
Line 56
); // end call to addActionListener
// textfield to display bitwise representation of an integer
bitsField = new JTextField( 33 );
bitsField.setEditable( false );
container.add( bitsField );
// button to shift bits left by one position
JButton leftButton = new JButton( "<<" );
container.add( leftButton );
leftButton.addActionListener(
new ActionListener() { // anonymous inner class
Use bitwise left-shift operator
(<<) to shift value’s bits to
the left by one position
// left shift one position and display new value
public void actionPerformed( ActionEvent event )
{
int value = Integer.parseInt( valueField.getText() );
value <<= 1;
valueField.setText( Integer.toString( value ) );
bitsField.setText( getBits( value ) );
}
2003 Prentice Hall, Inc.
All rights reserved.
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
} // end anonymous inner class
Outline
); // end call to addActionListener
// button to signed right shift value one position
JButton rightSignButton = new JButton( ">>" );
container.add( rightSignButton );
rightSignButton.addActionListener(
new ActionListener() { // anonymous inner class
BitShift.java
Line 77
Use bitwise signed right-shift
(>>) to shift value’s bits to
the right by one position
// right shift one position and display new value
public void actionPerformed( ActionEvent event )
{
int value = Integer.parseInt( valueField.getText() );
value >>= 1;
valueField.setText( Integer.toString( value ) );
bitsField.setText( getBits( value ) );
}
} // end anonymous inner class
); // end call to addActionListener
// button to unsigned right shift value one position
JButton rightZeroButton = new JButton( ">>>" );
container.add( rightZeroButton );
rightZeroButton.addActionListener(
new ActionListener() { // anonymous inner class
2003 Prentice Hall, Inc.
All rights reserved.
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
// right shift one position and display new value
public void actionPerformed( ActionEvent event )
{
int value = Integer.parseInt( valueField.getText() );
value >>>= 1;
valueField.setText( Integer.toString( value ) );
bitsField.setText( getBits( value ) );
}
} // end anonymous inner class
Outline
BitShift.java
Line 98
Use bitwise unsigned rightshift (>>>) to shift value’s
bits to the right by one position
); // end call to addActionListener
setSize( 400, 120 );
setVisible( true );
} // end constructor
// display bit representation of specified int value
private String getBits( int value )
{
// create int value with 1 in leftmost bit and 0s elsewhere
int displayMask = 1 << 31;
StringBuffer buffer = new StringBuffer( 35 ); // buffer for output
2003 Prentice Hall, Inc.
All rights reserved.
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
// for each bit append 0 or 1 to buffer
for ( int bit = 1; bit <= 32; bit++ ) {
Outline
// use displayMask to isolate bit
buffer.append( ( value & displayMask ) == 0 ? '0' : '1' );
BitShift.java
value <<= 1; // shift value one position to left
Program Output
if ( bit % 8 == 0 )
buffer.append( ' ' ); // append space to buffer every 8 bits
}
return buffer.toString();
} // end method getBits
public static void main( String args[] )
{
BitShift application = new BitShift();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
} // end class BitShift
2003 Prentice Hall, Inc.
All rights reserved.
Outline
BitShift.java
Program Output
2003 Prentice Hall, Inc.
All rights reserved.
21.6 Bit Manipulation and the Bitwise
Operator (cont.)
Bitwise
assignment
operators
&=
Bitwise AND assignment operator.
|=
Bitwise inclusive OR assignment operator.
^=
Bitwise exclusive OR assignment operator.
<<=
Left-shift assignment operator.
>>=
Signed right-shift assignment operator.
>>>=
Unsigned right-shift assignment operator.
Fig. 21.12 Bitwise assignment operators.
2003 Prentice Hall, Inc. All rights reserved.
21.7 BitSet class
• BitSet
– Facilitates the creation and manipulation of bit sets
– Represent set of boolean flags
– Dynamically resizable
2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Fig. 21.13: BitSetTest.java
// Using a BitSet to demonstrate the Sieve of Eratosthenes.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
Outline
BitSetTest.java
Line 18
public class BitSetTest extends JFrame {
private BitSet sieve;
private JLabel statusLabel;
private JTextField inputField;
// set up GUI
public BitSetTest()
{
super( "BitSets" );
sieve = new BitSet( 1024 );
Create bitset of 1024 bits
Container container = getContentPane();
statusLabel = new JLabel( "" );
container.add( statusLabel, BorderLayout.SOUTH );
JPanel inputPanel = new JPanel();
inputPanel.add( new JLabel( "Enter a value from 2 to 1023" ) );
2003 Prentice Hall, Inc.
All rights reserved.
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// textfield for user to input a value from 2 to 1023
inputField = new JTextField( 10 );
inputPanel.add( inputField );
container.add( inputPanel, BorderLayout.NORTH );
Outline
BitSetTest.java
inputField.addActionListener(
new ActionListener() { // inner class
// determine whether value is prime number
public void actionPerformed( ActionEvent event )
{
int value = Integer.parseInt( inputField.getText() );
if ( sieve.get( value ) )
statusLabel.setText( value + " is a prime number" );
else
statusLabel.setText( value + " is not a prime number" );
}
} // end inner class
); // end call to addActionListener
JTextArea primesArea = new JTextArea();
container.add( new JScrollPane( primesArea ), BorderLayout.CENTER );
2003 Prentice Hall, Inc.
All rights reserved.
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
Outline
int size = sieve.size(); // set all bits from 2 to 1023
for ( int i = 2; i < size; i++ )
sieve.set( i );
Use method set to turn
on all bits in BitSet
// perform Sieve of Eratosthenes
int finalBit = ( int ) Math.sqrt( size );
for ( int i = 2; i < finalBit; i++ )
if ( sieve.get( i ) )
BitSetTest.java
Lines 59-60
Lines 63-70
Determine prime numbers
for ( int j = 2 * i; j < size; j += i )
sieve.clear( j );
int counter = 0; // display prime numbers from 2 to 1023
for ( int i = 2; i < size; i++ )
if ( sieve.get( i ) ) {
primesArea.append( String.valueOf( i ) );
primesArea.append( ++counter % 7 == 0 ? "\n" : "\t" );
}
setSize( 600, 450 );
setVisible( true );
} // end constructor
2003 Prentice Hall, Inc.
All rights reserved.
86
87
88
89
90
91
92
public static void main( String args[] )
{
BitSetTest application = new BitSetTest();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
Outline
BitSetTest.java
} // end class BitSetTest
2003 Prentice Hall, Inc.
All rights reserved.