Download presentation
Presentation is loading. Please wait.
Published bySusanti Atmadja Modified over 6 years ago
1
Chapter 20 – Java Utilities Package and Bit Manipulation
Outline Introduction Vector Class and Enumeration Interface Stack Class Dictionary Class Hashtable Class Properties Class Random Class Bit Manipulation and the Bitwise Operators BitSet Class
2
Utility classes and interfaces
Introduction Utility classes and interfaces Contained in package java.util Class Vector Interface Enumeration Class Stack Class Dictionary Class Hashtable Class Properties Class Random Class BitSet
3
20.2 Vector Class and Enumeration Interface
Class java.util.Vector Array-like data structure that can resize itself dynamically Contains a capacity Grows by capacity increment if it requires additional space
4
Fig. 20.1 Demonstrating class Vector of package java.util. Line 26
1 // Fig. 20.1: VectorTest.java 2 // Testing the Vector class of the java.util package 3 4 // Java core packages 5 import java.util.*; 6 import java.awt.*; 7 import java.awt.event.*; 8 9 // Java extension packages 10 import javax.swing.*; 11 12 public class VectorTest extends JFrame { private JLabel statusLabel; private Vector vector; private JTextField inputField; 16 // set up GUI to test Vector methods public VectorTest() { super( "Vector Example" ); 21 Container container = getContentPane(); container.setLayout( new FlowLayout() ); 24 statusLabel = new JLabel(); vector = new Vector( 1 ); 27 container.add( new JLabel( "Enter a string" ) ); 29 inputField = new JTextField( 10 ); container.add( inputField ); 32 // button to add element to vector JButton addButton = new JButton( "Add" ); 35 Fig Demonstrating class Vector of package java.util. Line 26 Create Vector with initial capacity of one element
5
Vector method addElement appends Object to Vector
addButton.addActionListener( 37 new ActionListener() { 39 public void actionPerformed( ActionEvent event ) { // add an element to vector vector.addElement( inputField.getText() ); statusLabel.setText( "Added to end: " + inputField.getText() ); inputField.setText( "" ); } } ); // end call to addActionListener 50 container.add( addButton ); 52 // button to remove element from vector JButton removeButton = new JButton( "Remove" ); 55 removeButton.addActionListener( 57 new ActionListener() { 59 public void actionPerformed( ActionEvent event ) { // remove element from vector if ( vector.removeElement( inputField.getText() ) ) statusLabel.setText( "Removed: " + inputField.getText() ); else statusLabel.setText( inputField.getText() + " not in vector" ); } } Fig Demonstrating class Vector of package java.util (Part 2). Line 43 Lines 63-65 Vector method addElement appends Object to Vector Vector method removeElement removes Object from Vector
6
Vector method firstElement obtains first Object in Vector
); // end call to addActionListener 72 container.add( removeButton ); 74 // button to get first element of vector JButton firstButton = new JButton( "First" ); 77 firstButton.addActionListener( 79 new ActionListener() { 81 public void actionPerformed( ActionEvent event ) { // return first element of vector try { statusLabel.setText( "First element: " + vector.firstElement() ); } 89 // catch exception if Vector empty catch ( NoSuchElementException exception ) { statusLabel.setText( exception.toString() ); } } } ); // end call to addActionListener 97 container.add( firstButton ); 99 // button to get last element of vector JButton lastButton = new JButton( "Last" ); 102 lastButton.addActionListener( 104 Fig Demonstrating class Vector of package java.util (Part 3). Line 87 Vector method firstElement obtains first Object in Vector
7
Vector method lastElement obtains last Object in Vector
new ActionListener() { 106 public void actionPerformed( ActionEvent event ) { // return last element of vector try { statusLabel.setText( "Last element: " + vector.lastElement() ); } 114 // catch exception if Vector empty catch ( NoSuchElementException exception ) { statusLabel.setText( exception.toString() ); } } } ); // end call to addActionListener 122 container.add( lastButton ); 124 // button to determine whether vector is empty JButton emptyButton = new JButton( "Is Empty?" ); 127 emptyButton.addActionListener( 129 new ActionListener() { 131 public void actionPerformed( ActionEvent event ) { // determine if Vector is empty statusLabel.setText( vector.isEmpty() ? "Vector is empty" : "Vector is not empty" ); } } ); // end call to addActionListener Vector method lastElement obtains last Object in Vector Fig Demonstrating class Vector of package java.util (Part 4). Line 112 Line 135 Vector method isEmpty returns boolean that indicates whether Vector contains any Objects
8
140 container.add( emptyButton ); 142 // button to determine whether vector contains search key JButton containsButton = new JButton( "Contains" ); 145 containsButton.addActionListener( 147 new ActionListener() { 149 public void actionPerformed( ActionEvent event ) { String searchKey = inputField.getText(); 153 // determine if Vector contains searchKey if ( vector.contains( searchKey ) ) statusLabel.setText( "Vector contains " + searchKey ); else statusLabel.setText( "Vector does not contain " + searchKey ); } } ); // end call to addActionListener 164 container.add( containsButton ); 166 // button to determine location of value in vector JButton locationButton = new JButton( "Location" ); 169 locationButton.addActionListener( 171 new ActionListener() { 173 Fig Demonstrating class Vector of package java.util (Part 5). Line 155 Vector method contains returns boolean that indicates whether Vector contains a specific Object
9
174 public void actionPerformed( ActionEvent event )
{ // get location of an object in Vector statusLabel.setText( "Element is at location " + vector.indexOf( inputField.getText() ) ); } } ); // end call to addActionListener 182 container.add( locationButton ); 184 // button to trim vector size JButton trimButton = new JButton( "Trim" ); 187 trimButton.addActionListener( 189 new ActionListener() { 191 public void actionPerformed( ActionEvent event ) { // remove unoccupied elements to save memory vector.trimToSize(); statusLabel.setText( "Vector trimmed to size" ); } } ); 200 container.add( trimButton ); 202 // button to display vector size and capacity JButton statsButton = new JButton( "Statistics" ); 205 statsButton.addActionListener( 207 Fig Demonstrating class Vector of package java.util (Part 6). Line 178 Line 195 Vector method indexOf returns index of first location in Vector containing the argument Vector method trimToSize reduces the Vector capacity to the current number of elements in Vector
10
208 new ActionListener() {
209 public void actionPerformed( ActionEvent event ) { // get size and capacity of Vector statusLabel.setText( "Size = " + vector.size() + "; capacity = " + vector.capacity() ); } } ); // end call to addActionListener 218 container.add( statsButton ); 220 // button to display vector contents JButton displayButton = new JButton( "Display" ); 223 displayButton.addActionListener( 225 new ActionListener() { 227 public void actionPerformed( ActionEvent event ) { // use Enumeration to output Vector contents Enumeration enum = vector.elements(); StringBuffer buf = new StringBuffer(); 233 while ( enum.hasMoreElements() ) buf.append( enum.nextElement() ).append( " " ); 236 JOptionPane.showMessageDialog( null, buf.toString(), "Display", JOptionPane.PLAIN_MESSAGE ); } } ); // end call to addActionListener Fig Demonstrating class Vector of package java.util (Part 7). Lines Line 231 Vector methods size and capacity return number of Objects in Vector and Vector capacity, respectively Vector method elements returns Enumeration for iterating Vector elements
11
243 container.add( displayButton ); container.add( statusLabel ); 246 setSize( 300, 200 ); setVisible( true ); 249 } // end VectorTest constructor 251 // execute application public static void main( String args[] ) { VectorTest application = new VectorTest(); 256 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } 260 261 } // end class VectorTest Fig Demonstrating class Vector of package java.util (Part 8) Program Output
12
20.3 Stack Class Stack Implements stack data structure
Extends class Vector Stores references to Objects (as does Vector)
13
Fig. 20.2 Demonstrating class Stack of package java.util. Line 25
1 // Fig. 20.2: StackTest.java 2 // Testing the Stack class of the java.util package 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 import java.util.*; 8 9 // Java extension packages 10 import javax.swing.*; 11 12 public class StackTest extends JFrame { private JLabel statusLabel; private JTextField inputField; private Stack stack; 16 // create GUI to manipulate a Stack public StackTest() { super( "Stacks" ); 21 Container container = getContentPane(); 23 statusLabel = new JLabel(); stack = new Stack(); 26 container.setLayout( new FlowLayout() ); container.add( new JLabel( "Enter a string" ) ); inputField = new JTextField( 10 ); container.add( inputField ); 31 // button to place object on stack JButton pushButton = new JButton( "Push" ); 34 Fig Demonstrating class Stack of package java.util. Line 25 Create empty Stack
14
Stack method push adds Object argument to top of Stack
pushButton.addActionListener( 36 new ActionListener() { 38 public void actionPerformed( ActionEvent event ) { // put object on Stack statusLabel.setText( "Pushed: " + stack.push( inputField.getText() ) ); } } ); 47 container.add( pushButton ); 49 // button to remove top object on stack JButton popButton = new JButton( "Pop" ); 52 popButton.addActionListener( 54 new ActionListener() { 56 public void actionPerformed( ActionEvent event ) { // remove element from Stack try { statusLabel.setText( "Popped: " + stack.pop() ); } 63 // process exception if Stack empty catch ( EmptyStackException exception ) { statusLabel.setText( exception.toString() ); } } } Fig Demonstrating class Stack of package java.util (Part 2). Line 43 Line 61 Stack method push adds Object argument to top of Stack Stack method pop removes Object from top of Stack
15
); 71 container.add( popButton ); 73 // button to look at top element of stack JButton peekButton = new JButton( "Peek" ); 76 peekButton.addActionListener( 78 new ActionListener() { 80 public void actionPerformed( ActionEvent event ) { // look at top object on Stack try { statusLabel.setText( "Top: " + stack.peek() ); } 87 // process exception if Stack empty catch ( EmptyStackException exception ) { statusLabel.setText( exception.toString() ); } } } ); 95 container.add( peekButton ); 97 // button to determine whether stack is empty JButton emptyButton = new JButton( "Is Empty?" ); 100 emptyButton.addActionListener( 102 new ActionListener() { 104 Fig Demonstrating class Stack of package java.util (Part 3). Line 85 Stack method peek returns Object from top of Stack, without removing that Object
16
105 public void actionPerformed( ActionEvent event )
{ // determine if Stack is empty statusLabel.setText( stack.empty() ? "Stack is empty" : "Stack is not empty" ); } } ); 113 container.add( emptyButton ); 115 // button to determine whether search key is in stack JButton searchButton = new JButton( "Search" ); 118 searchButton.addActionListener( 120 new ActionListener() { 122 public void actionPerformed( ActionEvent event ) { // search Stack for specified object String searchKey = inputField.getText(); int result = stack.search( searchKey ); 128 if ( result == -1 ) statusLabel.setText( searchKey + " not found" ); else statusLabel.setText( searchKey + " found at element " + result ); } } ); 137 container.add( searchButton ); 139 Fig Demonstrating class Stack of package java.util (Part 4). Line 108 Line 127 Stack method empty returns boolean that indicates whether Stack contains any Objects Stack method search returns boolean that indicates whether Stack contains specific Object argument
17
140 // button to display stack contents
JButton displayButton = new JButton( "Display" ); 142 displayButton.addActionListener( 144 new ActionListener() { 146 public void actionPerformed( ActionEvent event ) { // output Stack contents Enumeration enumeration = stack.elements(); StringBuffer buffer = new StringBuffer(); 152 while ( enumeration.hasMoreElements() ) buffer.append( enumeration.nextElement() ).append( " " ); 156 JOptionPane.showMessageDialog( null, buffer.toString(), "Display", JOptionPane.PLAIN_MESSAGE ); } } ); 163 container.add( displayButton ); container.add( statusLabel ); 166 setSize( 675, 100 ); setVisible( true ); } 170 Fig Demonstrating class Stack of package java.util (Part 5). Line 150 Stack extends Vector, so class Stack may use method elements to obtain Enumeration for Stack
18
171 // execute application
public static void main( String args[] ) { StackTest application = new StackTest(); 175 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } 179 180 } // end class StackTest Fig Demonstrating class Stack of package java.util (Part 6). Program Output
19
20.4 Dictionary Class Dictionary Maps keys to values
Provides public interface Methods required to maintain table of key-value pairs abstract class Superclass of class Hashtable
20
20.5 Hashtable Class Hashtable Data structure that use 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
21
Fig. 20.3 Demonstrating class Hashtable. Line 25
1 // Fig. 20.3: HashtableTest.java 2 // Demonstrates class Hashtable of the java.util package. 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 import java.util.*; 8 9 // Java extensions packages 10 import javax.swing.*; 11 12 public class HashtableTest extends JFrame { private JLabel statusLabel; private Hashtable table; private JTextArea displayArea; private JTextField lastNameField; private JTextField firstNameField; 18 // set up GUI to demonstrate Hashtable features public HashtableTest() { super( "Hashtable Example" ); 23 statusLabel = new JLabel(); table = new Hashtable(); displayArea = new JTextArea( 4, 20 ); displayArea.setEditable( false ); 28 JPanel northSubPanel = new JPanel(); 30 northSubPanel.add( new JLabel( "First name" ) ); firstNameField = new JTextField( 8 ); northSubPanel.add( firstNameField ); 34 Fig Demonstrating class Hashtable. Line 25 Create empty Hashtable
22
Fig. 20.3 Demonstrating class Hashtable (Part 2). Lines 59-60
northSubPanel.add( new JLabel( "Last name (key)" ) ); lastNameField = new JTextField( 8 ); northSubPanel.add( lastNameField ); 38 JPanel northPanel = new JPanel(); northPanel.setLayout( new BorderLayout() ); northPanel.add( northSubPanel, BorderLayout.NORTH ); northPanel.add( statusLabel, BorderLayout.SOUTH ); 43 JPanel southPanel = new JPanel(); southPanel.setLayout( new GridLayout( 2, 5 ) ); JButton putButton = new JButton( "Put" ); 47 putButton.addActionListener( 49 new ActionListener() { 51 // add new key/value pair to hash table public void actionPerformed( ActionEvent event ) { Employee employee = new Employee( firstNameField.getText(), lastNameField.getText() ); 58 Object value = table.put( lastNameField.getText(), employee ); 61 // first time this key was added if ( value == null ) statusLabel.setText( "Put: " + employee.toString() ); 66 Fig Demonstrating class Hashtable (Part 2). Lines 59-60 Hashtable method put adds key and value to Hashtable (returns null if key has been inserted previously)
23
Fig. 20.3 Demonstrating class Hashtable (Part 3). Line 88
// replaced previous value for this key else statusLabel.setText( "Put: " + employee.toString() + "; Replaced: " + value.toString() ); } } ); 75 southPanel.add( putButton ); 77 // button to get value for specific key JButton getButton = new JButton( "Get" ); 80 getButton.addActionListener( 82 new ActionListener() { 84 // get value for specific key public void actionPerformed( ActionEvent event ) { Object value = table.get( lastNameField.getText() ); 89 // value found for key if ( value != null ) statusLabel.setText( "Get: " + value.toString() ); 94 // value not found for key else statusLabel.setText( "Get: " + lastNameField.getText() + " not in table" ); } } Fig Demonstrating class Hashtable (Part 3). Line 88 Hashtable method get obtains Object associated with key from Hashtable (returns null if neither key nor Object exist)
24
Fig. 20.3 Demonstrating class Hashtable (Part 4). Lines 116-117
); 103 southPanel.add( getButton ); 105 // button to remove key/value pair from table JButton removeButton = new JButton( "Remove" ); 108 removeButton.addActionListener( 110 new ActionListener() { 112 // remove key/value pair public void actionPerformed( ActionEvent event ) { Object value = table.remove( lastNameField.getText() ); 118 // key found if ( value != null ) statusLabel.setText( "Remove: " + value.toString() ); 123 // key not found else statusLabel.setText( "Remove: " + lastNameField.getText() + " not in table" ); } } ); 131 southPanel.add( removeButton ); 133 // button to detetmine whether hash table is empty JButton emptyButton = new JButton( "Empty" ); 136 Fig Demonstrating class Hashtable (Part 4). Lines Hashtable method remove removes Object associated with key argument from Hashtable
25
Hashtable method isEmpty returns boolean that indicates whether Hashtable contains any Objects
emptyButton.addActionListener( 138 new ActionListener() { 140 // determine whether hash table is empty public void actionPerformed( ActionEvent event ) { statusLabel.setText( "Empty: " + table.isEmpty() ); } } ); 148 southPanel.add( emptyButton ); 150 // button to determine whether hash table contains key JButton containsKeyButton = new JButton( "Contains key" ); 153 containsKeyButton.addActionListener( 155 new ActionListener() { 157 // determine whether hash table contains key public void actionPerformed( ActionEvent event ) { statusLabel.setText( "Contains key: " + table.containsKey( lastNameField.getText() ) ); } } ); 166 southPanel.add( containsKeyButton ); 168 // button to clear all hash table contents JButton clearButton = new JButton( "Clear table" ); 171 Fig Demonstrating class Hashtable (Part 5). Line 144 Lines Hashtable method containsKey returns boolean that indicates whether Hashtable contains key argument
26
Hashtable method clear removes all elements from Hashtable
clearButton.addActionListener( 173 new ActionListener() { 175 // clear hash table contents public void actionPerformed( ActionEvent event ) { table.clear(); statusLabel.setText( "Clear: Table is now empty" ); } } ); 184 southPanel.add( clearButton ); 186 // button to display hash table elements JButton listElementsButton = new JButton( "List objects" ); 189 listElementsButton.addActionListener( 191 new ActionListener() { 193 // display hash table elements public void actionPerformed( ActionEvent event ) { StringBuffer buffer = new StringBuffer(); 198 for ( Enumeration enumeration = table.elements(); enumeration.hasMoreElements(); ) buffer.append( enumeration.nextElement() ).append( '\n' ); 203 displayArea.setText( buffer.toString() ); } } Fig Demonstrating class Hashtable (Part 6). Line 179 Lines Hashtable method clear removes all elements from Hashtable Hashtable method elements obtains Enumeration of Hashtable values
27
Fig. 20.3 Demonstrating class Hashtable (Part 7). Lines 223-224
); 208 southPanel.add( listElementsButton ); 210 // button to display hash table keys JButton listKeysButton = new JButton( "List keys" ); 213 listKeysButton.addActionListener( 215 new ActionListener() { 217 // display hash table KEYS public void actionPerformed( ActionEvent event ) { StringBuffer buffer = new StringBuffer(); 222 for ( Enumeration enumeration = table.keys(); enumeration.hasMoreElements(); ) buffer.append( enumeration.nextElement() ).append( '\n' ); 227 JOptionPane.showMessageDialog( null, buffer.toString(), "Display", JOptionPane.PLAIN_MESSAGE ); } } ); 234 southPanel.add( listKeysButton ); 236 Container container = getContentPane(); container.add( northPanel, BorderLayout.NORTH ); container.add( new JScrollPane( displayArea ), BorderLayout.CENTER ); container.add( southPanel, BorderLayout.SOUTH ); Fig Demonstrating class Hashtable (Part 7). Lines Hashtable method keys obtains Enumeration of Hashtable keys
28
Fig. 20.3 Demonstrating class Hashtable (Part 8).
242 setSize( 540, 300 ); setVisible( true ); } 246 // execute application public static void main( String args[] ) { HashtableTest application = new HashtableTest(); 251 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } 255 256 } // end class HashtableTest 257 258 // Employee class to represent first and last name 259 class Employee { private String first, last; 261 // initialize an Employee public Employee( String firstName, String lastName ) { first = firstName; last = lastName; } 268 // convert Employee to String representation public String toString() { return first + " " + last; } 274 275 } // end class Employee Fig Demonstrating class Hashtable (Part 8).
29
Fig. 20.3 Demonstrating class Hashtable (Part 9). Program Output
30
20.6 Properties Class Properties Persistent Hashtable
Can be written to output stream and directed to file Can be read from file into input stream Provides methods setProperty and getProperty Store/obtain key-value pairs of Strings
31
Fig. 20.4 Demonstrating class Properties. Line 25
1 // Fig. 20.4: PropertiesTest.java 2 // Demonstrates class Properties of the java.util package. 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 import java.io.*; 8 import java.util.*; 9 10 // Java extension packages 11 import javax.swing.*; 12 13 public class PropertiesTest extends JFrame { private JLabel statusLabel; private Properties table; private JTextArea displayArea; private JTextField valueField, nameField; 18 // set up GUI to test Properties table public PropertiesTest() { super( "Properties Test" ); 23 // create Properties table table = new Properties(); 26 Container container = getContentPane(); 28 // set up NORTH of window's BorderLayout JPanel northSubPanel = new JPanel(); 31 northSubPanel.add( new JLabel( "Property value" ) ); valueField = new JTextField( 10 ); northSubPanel.add( valueField ); 35 Fig Demonstrating class Properties. Line 25 Create empty Properties
32
Fig. 20.4 Demonstrating class Properties (Part 2). Lines 68-69
northSubPanel.add( new JLabel( "Property name (key)" ) ); nameField = new JTextField( 10 ); northSubPanel.add( nameField ); 39 JPanel northPanel = new JPanel(); northPanel.setLayout( new BorderLayout() ); northPanel.add( northSubPanel, BorderLayout.NORTH ); 43 statusLabel = new JLabel(); northPanel.add( statusLabel, BorderLayout.SOUTH ); 46 container.add( northPanel, BorderLayout.NORTH ); 48 // set up CENTER of window's BorderLayout displayArea = new JTextArea( 4, 35 ); container.add( new JScrollPane( displayArea ), BorderLayout.CENTER ); 53 // set up SOUTH of window's BorderLayout JPanel southPanel = new JPanel(); southPanel.setLayout( new GridLayout( 1, 5 ) ); 57 // button to put a name/value pair in Properties table JButton putButton = new JButton( "Put" ); 60 putButton.addActionListener( 62 new ActionListener() { 64 // put name/value pair in Properties table public void actionPerformed( ActionEvent event ) { Object value = table.setProperty( nameField.getText(), valueField.getText() ); 70 Fig Demonstrating class Properties (Part 2). Lines 68-69 Properties method setProperty stores value for the specified key
33
Fig. 20.4 Demonstrating class Properties (Part 3).
if ( value == null ) showstatus( "Put: " + nameField.getText() + " " + valueField.getText() ); 74 else showstatus( "Put: " + nameField.getText() + " " + valueField.getText() + "; Replaced: " + value.toString() ); 79 listProperties(); } } ); // end call to addActionListener 84 southPanel.add( putButton ); 86 // button to empty contents of Properties table JButton clearButton = new JButton( "Clear" ); 89 clearButton.addActionListener( 91 new ActionListener() { 93 // use method clear to empty table public void actionPerformed( ActionEvent event ) { table.clear(); showstatus( "Table in memory cleared" ); listProperties(); } } ); // end call to addActionListener 103 southPanel.add( clearButton ); 105 Fig Demonstrating class Properties (Part 3).
34
Fig. 20.4 Demonstrating class Properties (Part 4). Lines 116-117
// button to get value of a property JButton getPropertyButton = new JButton( "Get property" ); 108 getPropertyButton.addActionListener( 110 new ActionListener() { 112 // use method getProperty to obtain a property value public void actionPerformed( ActionEvent event ) { Object value = table.getProperty( nameField.getText() ); 118 if ( value != null ) showstatus( "Get property: " + nameField.getText() + " " + value.toString() ); 123 else showstatus( "Get: " + nameField.getText() + " not in table" ); 127 listProperties(); } } ); // end call to addActionListener 132 southPanel.add( getPropertyButton ); 134 // button to contents of Properties table to file JButton saveButton = new JButton( "Save" ); 137 saveButton.addActionListener( 139 Fig Demonstrating class Properties (Part 4). Lines Properties method getProperty locates value associated with the specified key
35
Fig. 20.4 Demonstrating class Properties (Part 5). Line 150
new ActionListener() { 141 // use method save to place contents in file public void actionPerformed( ActionEvent event ) { // save contents of table try { FileOutputStream output = new FileOutputStream( "props.dat" ); 149 table.store( output, "Sample Properties" ); output.close(); 152 listProperties(); } 155 // process problems with file output catch( IOException ioException ) { ioException.printStackTrace(); } } } ); // end call to addActionListener 163 southPanel.add( saveButton ); 165 // button to load contents of Properties table from file JButton loadButton = new JButton( "Load" ); 168 loadButton.addActionListener( 170 new ActionListener() { 172 Fig Demonstrating class Properties (Part 5). Line 150 Properties method store saves Properties contents to FileOutputStream
36
Fig. 20.4 Demonstrating class Properties (Part 6). Line 181
// use method load to read contents from file public void actionPerformed( ActionEvent event ) { // load contents of table try { FileInputStream input = new FileInputStream( "props.dat" ); 180 table.load( input ); input.close(); listProperties(); } 185 // process problems with file input catch( IOException ioException ) { ioException.printStackTrace(); } } } ); // end call to addActionListener 193 southPanel.add( loadButton ); 195 container.add( southPanel, BorderLayout.SOUTH ); 197 setSize( 550, 225 ); setVisible( true ); } 201 // output property values public void listProperties() { StringBuffer buffer = new StringBuffer(); String name, value; 207 Fig Demonstrating class Properties (Part 6). Line 181 Properties method load restores Properties contents from FileInputStream
37
Fig. 20.4 Demonstrating class Properties (Part 7). Line 208
Enumeration enumeration = table.propertyNames(); 209 while ( enumeration.hasMoreElements() ) { name = enumeration.nextElement().toString(); value = table.getProperty( name ); 213 buffer.append( name ).append( '\t' ); buffer.append( value ).append( '\n' ); } 217 displayArea.setText( buffer.toString() ); } // end method ListProperties 220 // display String in statusLabel label public void showstatus( String s ) { statusLabel.setText( s ); } 226 // execute application public static void main( String args[] ) { PropertiesTest application = new PropertiesTest(); 231 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } 235 236 } // end class PropertiesTest Properties method propertyNames obtains Enumeration of property names Fig Demonstrating class Properties (Part 7). Line 208
38
Fig. 20.4 Demonstrating class Properties (Part 8). Program Output
39
20.7 Random Class Class Random
Provides (pseudo-) random-number generation Random r = new Random(); Use seed to generate same random-number sequences Random r = new Random( seedValue ); (useful when debugging) Can generate distributed numbers uniformly r.nextInt(); r.nextFloat(); Use % operator to scale generated number e.g., rolling a six-sided die Math.abs( r.nextInt() ) % 6 + 1;
40
20.8 Bit Manipulation and the Bitwise Operators
Used for bit manipulation Used for getting down to “bit-and-bytes” level
41
20.8 Bit Manipulation and the Bitwise Operators (cont.)
42
Fig. 20.6 Printing the bits in an integer.
1 // Fig. 20.6: PrintBits.java 2 // Printing an unsigned integer in bits 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 8 // Java extension packages 9 import javax.swing.*; 10 11 public class PrintBits extends JFrame { private JTextField outputField; 13 // set up GUI public PrintBits() { super( "Printing bit representations for numbers" ); 18 Container container = getContentPane(); container.setLayout( new FlowLayout() ); 21 container.add( new JLabel( "Enter an integer " ) ); 23 // textfield to read value from user JTextField inputField = new JTextField( 10 ); 26 inputField.addActionListener( 28 new ActionListener() { 30 Fig Printing the bits in an integer.
43
31 // read integer and get bitwise representation
public void actionPerformed( ActionEvent event ) { int value = Integer.parseInt( event.getActionCommand() ); outputField.setText( getBits( value ) ); } } ); 40 container.add( inputField ); 42 container.add( new JLabel( "The integer in bits is" ) ); 44 // textfield to display integer in bitwise form outputField = new JTextField( 33 ); outputField.setEditable( false ); container.add( outputField ); 49 setSize( 720, 70 ); setVisible( true ); } 53 // 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; 59 // buffer to build output StringBuffer buffer = new StringBuffer( 35 ); 62 // for each bit append 0 or 1 to buffer for ( int bit = 1; bit <= 32; bit++ ) { 65 Fig Printing the bits in an integer (Part 2). Lines Line 58 Convert String to int, then pass int to private method getBits to get the int’s bit representation 1 << 31 equals
44
Fig. 20.6 Printing the bits in an integer (Part 3). Line 69
// use displayMask to isolate bit and determine whether // bit has value of 0 or 1 buffer.append( ( value & displayMask ) == 0 ? '0' : '1' ); 70 // shift value one position to left value <<= 1; 73 // append space to buffer every 8 bits if ( bit % 8 == 0 ) buffer.append( ' ' ); } 78 return buffer.toString(); } 81 // execute application public static void main( String args[] ) { PrintBits application = new PrintBits(); 86 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } 90 91 } // end class PrintBits Fig Printing the bits in an integer (Part 3). Line 69 Use bitwise AND (&) to combine each bit in value and 1 << 31
45
Fig. 20.6 Printing the bits in an integer (Part 4). Program Output
46
20.8 Bit manipulation and the Bitwise Operators (cont.)
47
1 // Fig. 20.8: MiscBitOps.java
2 // Using the bitwise AND, bitwise inclusive OR, bitwise 3 // exclusive OR, and bitwise complement operators. 4 5 // Java core packages 6 import java.awt.*; 7 import java.awt.event.*; 8 9 // Java extension packages 10 import javax.swing.*; 11 12 public class MiscBitOps extends JFrame { private JTextField input1Field, input2Field, bits1Field, bits2Field, bits3Field, resultField; private int value1, value2; 16 // set up GUI public MiscBitOps() { super( "Bitwise operators" ); 21 JPanel inputPanel = new JPanel(); inputPanel.setLayout( new GridLayout( 4, 2 ) ); 24 inputPanel.add( new JLabel( "Enter 2 ints" ) ); inputPanel.add( new JLabel( "" ) ); 27 inputPanel.add( new JLabel( "Value 1" ) ); input1Field = new JTextField( 8 ); inputPanel.add( input1Field ); 31 inputPanel.add( new JLabel( "Value 2" ) ); input2Field = new JTextField( 8 ); inputPanel.add( input2Field ); 35 Fig Demonstrating the bitwise AND, bitwise inclusive OR, bitwise exclusive OR and bitwise complement operators.
48
36 inputPanel.add( new JLabel( "Result" ) );
resultField = new JTextField( 8 ); resultField.setEditable( false ); inputPanel.add( resultField ); 40 JPanel bitsPanel = new JPanel(); bitsPanel.setLayout( new GridLayout( 4, 1 ) ); bitsPanel.add( new JLabel( "Bit representations" ) ); 44 bits1Field = new JTextField( 33 ); bits1Field.setEditable( false ); bitsPanel.add( bits1Field ); 48 bits2Field = new JTextField( 33 ); bits2Field.setEditable( false ); bitsPanel.add( bits2Field ); 52 bits3Field = new JTextField( 33 ); bits3Field.setEditable( false ); bitsPanel.add( bits3Field ); 56 JPanel buttonPanel = new JPanel(); 58 // button to perform bitwise AND JButton andButton = new JButton( "AND" ); 61 andButton.addActionListener( 63 new ActionListener() { 65 Fig Demonstrating the bitwise AND, bitwise inclusive OR, bitwise exclusive OR and bitwise complement operators (Part 2).
49
Use bitwise AND (&) to combine value1 and value2
// perform bitwise AND and display results public void actionPerformed( ActionEvent event ) { setFields(); resultField.setText( Integer.toString( value1 & value2 ) ); bits3Field.setText( getBits( value1 & value2 ) ); } } ); 76 buttonPanel.add( andButton ); 78 // button to perform bitwise inclusive OR JButton inclusiveOrButton = new JButton( "Inclusive OR" ); 81 inclusiveOrButton.addActionListener( 83 new ActionListener() { 85 // perform bitwise inclusive OR and display results public void actionPerformed( ActionEvent event ) { setFields(); resultField.setText( Integer.toString( value1 | value2 ) ); bits3Field.setText( getBits( value1 | value2 ) ); } } ); 96 buttonPanel.add( inclusiveOrButton ); 98 Use bitwise AND (&) to combine value1 and value2 Fig Demonstrating the bitwise AND, bitwise inclusive OR, bitwise exclusive OR and bitwise complement operators (Part 3). Line 71 Line 91 Use bitwise inclusive OR (|) to combine value1 and value2
50
Use bitwise exclusive OR (^) to combine value1 and value2
// button to perform bitwise exclusive OR JButton exclusiveOrButton = new JButton( "Exclusive OR" ); 101 exclusiveOrButton.addActionListener( 103 new ActionListener() { 105 // perform bitwise exclusive OR and display results public void actionPerformed( ActionEvent event ) { setFields(); resultField.setText( Integer.toString( value1 ^ value2 ) ); bits3Field.setText( getBits( value1 ^ value2 ) ); } } ); 116 buttonPanel.add( exclusiveOrButton ); 118 // button to perform bitwise complement JButton complementButton = new JButton( "Complement" ); 121 complementButton.addActionListener( 123 new ActionListener() { 125 // perform bitwise complement and display results public void actionPerformed( ActionEvent event ) { input2Field.setText( "" ); bits2Field.setText( "" ); 131 int value = Integer.parseInt( input1Field.getText() ); 133 Fig Demonstrating the bitwise AND, bitwise inclusive OR, bitwise exclusive OR and bitwise complement operators (Part 4). Line 111 Use bitwise exclusive OR (^) to combine value1 and value2
51
Use bitwise complement (~) on value
resultField.setText( Integer.toString( ~value ) ); bits1Field.setText( getBits( value ) ); bits3Field.setText( getBits( ~value ) ); } } ); 140 buttonPanel.add( complementButton ); 142 Container container = getContentPane(); container.add( inputPanel, BorderLayout.WEST ); container.add( bitsPanel, BorderLayout.EAST ); container.add( buttonPanel, BorderLayout.SOUTH ); 147 setSize( 600, 150 ); setVisible( true ); } 151 // display numbers and their bit form private void setFields() { value1 = Integer.parseInt( input1Field.getText() ); value2 = Integer.parseInt( input2Field.getText() ); 157 bits1Field.setText( getBits( value1 ) ); bits2Field.setText( getBits( value2 ) ); } 161 // 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; 167 Use bitwise complement (~) on value Fig Demonstrating the bitwise AND, bitwise inclusive OR, bitwise exclusive OR and bitwise complement operators (Part 5). Line 134
52
168 // buffer to build output
StringBuffer buffer = new StringBuffer( 35 ); 170 // for each bit append 0 or 1 to buffer for ( int bit = 1; bit <= 32; bit++ ) { 173 // use displayMask to isolate bit and determine whether // bit has value of 0 or 1 buffer.append( ( value & displayMask ) == 0 ? '0' : '1' ); 178 // shift value one position to left value <<= 1; 181 // append space to buffer every 8 bits if ( bit % 8 == 0 ) buffer.append( ' ' ); } 186 return buffer.toString(); } 189 // execute application public static void main( String args[] ) { MiscBitOps application = new MiscBitOps(); 194 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } 198 199 } // end class MiscBitOps Fig Demonstrating the bitwise AND, bitwise inclusive OR, bitwise exclusive OR and bitwise complement operators (Part 6).
53
Fig Demonstrating the bitwise AND, bitwise inclusive OR, bitwise exclusive OR and bitwise complement operators (Part 7). Program Output
54
20.8 Bit Manipulation and the Bitwise Operators (cont.)
55
20.8 Bit Manipulation and the Bitwise Operators (cont.)
56
Fig. 20.11 Demonstrating the bitwise shift operators.
1 // Fig : BitShift.java 2 // Using the bitwise shift operators. 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 8 // Java extension packages 9 import javax.swing.*; 10 11 public class BitShift extends JFrame { private JTextField bitsField; private JTextField valueField; 14 // set up GUI public BitShift() { super( "Shifting bits" ); 19 Container container = getContentPane(); container.setLayout( new FlowLayout() ); 22 container.add( new JLabel( "Integer to shift " ) ); 24 // textfield for user to input integer valueField = new JTextField( 12 ); container.add( valueField ); 28 valueField.addActionListener( 30 new ActionListener() { 32 Fig Demonstrating the bitwise shift operators.
57
Fig. 20.11 Demonstrating the bitwise shift operators (Part 2). Line 58
// read value and display its bitwise representation public void actionPerformed( ActionEvent event ) { int value = Integer.parseInt( valueField.getText() ); bitsField.setText( getBits( value ) ); } } ); 41 // textfield to display bitwise representation of an integer bitsField = new JTextField( 33 ); bitsField.setEditable( false ); container.add( bitsField ); 46 // button to shift bits left by one position JButton leftButton = new JButton( "<<" ); 49 leftButton.addActionListener( 51 new ActionListener() { 53 // 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 ) ); } } ); 64 container.add( leftButton ); 66 Fig Demonstrating the bitwise shift operators (Part 2). Line 58 Use bitwise left-shift operator (<<) to shift value’s bits to the left by one position
58
67 // button to right shift value one position with sign extension
JButton rightSignButton = new JButton( ">>" ); 69 rightSignButton.addActionListener( 71 new ActionListener() { 73 // 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 ) ); } } ); 84 container.add( rightSignButton ); 86 // button to right shift value one position with zero extension JButton rightZeroButton = new JButton( ">>>" ); 89 rightZeroButton.addActionListener( 91 new ActionListener() { 93 // 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 ) ); 100 bitsField.setText( getBits( value ) ); Use bitwise right-shift with signed extension operator (>>) to shift value’s bits to the right by one position Fig Demonstrating the bitwise shift operators (Part 3). Line 78 Line 98 Use bitwise right-shift with unsigned extension operator (>>>) to shift value’s bits to the right by one position
59
Fig. 20.11 Demonstrating the bitwise shift operators (Part 4).
} } ); 105 container.add( rightZeroButton ); 107 setSize( 400, 120 ); setVisible( true ); } 111 // 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; 117 // buffer to build output StringBuffer buffer = new StringBuffer( 35 ); 120 // for each bit append 0 or 1 to buffer for ( int bit = 1; bit <= 32; bit++ ) { 123 // use displayMask to isolate bit and determine whether // bit has value of 0 or 1 buffer.append( ( value & displayMask ) == 0 ? '0' : '1' ); 128 // shift value one position to left value <<= 1; 131 // append space to buffer every 8 bits if ( bit % 8 == 0 ) buffer.append( ' ' ); } 136 Fig Demonstrating the bitwise shift operators (Part 4).
60
137 return buffer.toString();
} 139 // execute application public static void main( String args[] ) { BitShift application = new BitShift(); 144 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } 148 149 } // end class BitShift Fig Demonstrating the bitwise shift operators (Part 5). Program Output
61
Fig. 20. 11 Demonstrating the bitwise shift operators (Part 6)
Fig Demonstrating the bitwise shift operators (Part 6). Program Output
62
20.8 Bit Manipulation and the Bitwise Operator (cont.)
63
BitSet class BitSet Facilitates the creation and manipulation of bit sets Represent set of boolean flags Dynamically resizable
64
1 // Fig. 20.13: BitSetTest.java
2 // Using a BitSet to demonstrate the Sieve of Eratosthenes. 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 import java.util.*; 8 9 // Java extension packages 10 import javax.swing.*; 11 12 public class BitSetTest extends JFrame { private BitSet sieve; private JLabel statusLabel; private JTextField inputField; 16 // set up GUI public BitSetTest() { super( "BitSets" ); 21 sieve = new BitSet( 1024 ); 23 Container container = getContentPane(); 25 statusLabel = new JLabel( "" ); container.add( statusLabel, BorderLayout.SOUTH ); 28 JPanel inputPanel = new JPanel(); 30 inputPanel.add( new JLabel( "Enter a value from 2 to 1023" ) ); 33 // textfield for user to input a value from 2 to 1023 inputField = new JTextField( 10 ); Fig Demonstrating the Sieve of Eratosthenes using a BitSet. Line 22 Create bitset of 1024 bits
65
Use method set to turn on all bits in BitSet
36 inputField.addActionListener( 38 new ActionListener() { 40 // determine whether value is prime number public void actionPerformed( ActionEvent event ) { int value = Integer.parseInt( inputField.getText() ); 45 if ( sieve.get( value ) ) statusLabel.setText( value + " is a prime number" ); 49 else statusLabel.setText( value + " is not a prime number" ); } } ); 56 inputPanel.add( inputField ); container.add( inputPanel, BorderLayout.NORTH ); 59 JTextArea primesArea = new JTextArea(); 61 container.add( new JScrollPane( primesArea ), BorderLayout.CENTER ); 64 // set all bits from 1 to 1023 int size = sieve.size(); 67 for ( int i = 2; i < size; i++ ) sieve.set( i ); 70 Fig Demonstrating the Sieve of Eratosthenes using a BitSet (Part 2). Lines 68-69 Use method set to turn on all bits in BitSet
66
Determine prime numbers
// perform Sieve of Eratosthenes int finalBit = ( int ) Math.sqrt( sieve.size() ); 73 for ( int i = 2; i < finalBit; i++ ) 75 if ( sieve.get( i ) ) 77 for ( int j = 2 * i; j < size; j += i ) sieve.clear( j ); 80 // display prime numbers from 1 to 1023 int counter = 0; 83 for ( int i = 2; i < size; i++ ) 85 if ( sieve.get( i ) ) { primesArea.append( String.valueOf( i ) ); primesArea.append( ++counter % 7 == 0 ? "\n" : "\t" ); } 90 setSize( 600, 450 ); setVisible( true ); } 94 // execute application public static void main( String args[] ) { BitSetTest application = new BitSetTest(); 99 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } 103 104 } // end class BitSetTest Determine prime numbers Fig Demonstrating the Sieve of Eratosthenes using a BitSet (Part 3). Lines 72-79
67
Fig. 20.13 Demonstrating the Sieve of Eratosthenes using a BitSet (Part 4). Program Output
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.