Archive for October, 2007

Chapter 10 Strings and Characters 539 7 public (Kids web site)

Wednesday, October 31st, 2007

Chapter 10 Strings and Characters 539 7 public class StringConstructors { 8 9 // test String constructors 10 public static void main( String args[] ) 11 { 12 char charArray[] = { ‘b’, ‘i’, ‘r’, ‘t’, ‘h’, ‘ ‘, 13 ‘d’, ‘a’, ‘y’ }; 14 byte byteArray[] = { ( byte ) ‘n’, ( byte ) ‘e’, 15 ( byte )’w', ( byte) ‘ ‘, ( byte ) ‘y’, 16 ( byte ) ‘e’, ( byte ) ‘a’, ( byte ) ‘r’ }; 17 18 StringBuffer buffer; 19 String s, s1, s2, s3, s4, s5, s6, s7, output; 20 21 s = new String( “hello” ); 22 buffer = new StringBuffer( “Welcome to Java Programming!” ); 23 24 // use String constructors 25 s1 = new String(); 26 s2 = new String( s ); 27 s3 = new String( charArray ); 28 s4 = new String( charArray, 6, 3 ); 29 s5 = new String( byteArray, 4, 4 ); 30 s6 = new String( byteArray ); 31 s7 = new String( buffer ); 32 33 // append Strings to output 34 output = “s1 = ” + s1 + “ns2 = ” + s2 + “ns3 = ” + s3 + 35 “ns4 = ” + s4 + “ns5 = ” + s5 + “ns6 = ” + s6 + 36 “ns7 = ” + s7; 37 38 JOptionPane.showMessageDialog( null, output, 39 “Demonstrating String Class Constructors”, 40 JOptionPane.INFORMATION_MESSAGE ); 41 42 System.exit( 0 ); 43 } 44 45 } // end class StringConstructors Fig. 10.1 Demonstrating the Stringclass constructors (part 2 of 2). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

538 Strings and (Free web design) Characters Chapter 10 10.2 Fundamentals

Tuesday, October 30th, 2007

538 Strings and Characters Chapter 10 10.2 Fundamentals of Characters and Strings Characters are the fundamental building blocks of Java source programs. Every program is composed of a sequence of characters that when grouped together meaningfully is interpreted by the computer as a series of instructions used to accomplish a task. A program might contain character constants. A character constant is an integer value represented as a character in single quotes. As we stated previously, the value of a character constant is the integer value of the character in the Unicode character set. For example, ‘z’ represents the integer value of z, and ‘n’represents the integer value of newline. See Appendix D for the integer equivalents of these characters. A string is a series of characters treated as a single unit. A string may include letters, digits and various special characters, such as +, -, *, /, $and others. A string is an object of class String. String literals or string constants (often called anonymous String objects) are written as a sequence of characters in double quotation marks as follows: “John Q. Doe” (a name) “9999 Main Street” (a street address) “Waltham, Massachusetts” (a city and state) “(201) 555-1212″ (a telephone number) A Stringmay be assigned in a declaration to a Stringreference. The declaration String color = “blue”; initializes Stringreference colorto refer to the anonymous Stringobject “blue”. Performance Tip 10.1 Java treats all anonymous Strings with the same contents as one anonymous String object that has many references. This conserves memory. 10.3 StringConstructors Class String provides nine constructors for initializing String objects in a variety of ways. Seven of the constructors are demonstrated in Fig. 10.1. All the constructors are used in the StringConstructors application s mainmethod. Line 25 instantiates a new String object and assigns it to reference s1, using class String s default constructor. The new Stringobject contains no characters (the empty string) and has a length of 0. Line 26 instantiates a new String object and assigns it to reference s2, using class String s copy constructor. The new Stringobject contains a copy of the characters in the String object sthat is passed as an argument to the constructor. 1 // Fig. 10.1: StringConstructors.java 2 // This program demonstrates the String class constructors. 3 4 // Java extension packages 5 import javax.swing.*; 6 Fig. 10.1 Demonstrating the Stringclass constructors (part 1 of 2). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Chapter 10 Strings and Characters 537 (Free web hosting music) Outline 10.1

Tuesday, October 30th, 2007

Chapter 10 Strings and Characters 537 Outline 10.1 Introduction 10.2 Fundamentals of Characters and Strings 10.3 String Constructors 10.4 String Methods length, charAt and getChars 10.5 Comparing Strings 10.6 String Method hashCode 10.7 Locating Characters and Substrings in Strings 10.8 Extracting Substrings from Strings 10.9 Concatenating Strings 10.10 Miscellaneous String Methods 10.11 Using String Method valueOf 10.12 String Method intern 10.13 StringBuffer Class 10.14 StringBuffer Constructors 10.15 StringBuffer Methods length, capacity, setLengthand ensureCapacity 10.16 StringBuffer Methods charAt, setCharAt, getCharsand reverse 10.17 StringBuffer append Methods 10.18 StringBuffer Insertion and Deletion Methods 10.19 Character Class Examples 10.20 Class StringTokenizer 10.21 Card Shuffling and Dealing Simulation 10.22 (Optional Case Study) Thinking About Objects: Event Handling Summary Terminology Self-Review Exercises Answers to Self-Review Exercises Exercises Special Section: Advanced String Manipulation Exercises Special Section: Challenging String Manipulation Projects 10.1 Introduction In this chapter, we introduce Java s string and character-processing capabilities. The techniques discussed here are appropriate for validating program input, displaying information to users and other text-based manipulations. The techniques also are appropriate for developing text editors, word processors, page-layout software, computerized typesetting systems and other kinds of text-processing software. We have already presented several string- processing capabilities in the text. This chapter discusses in detail the capabilities of class String, class StringBuffer and class Character from the java.lang package and class StringTokenizer from the java.utilpackage. These classes provide the foundation for string and character manipulation in Java. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Web hosting services - 10 Strings and Characters Objectives To be

Monday, October 29th, 2007

10 Strings and Characters Objectives To be able to create and manipulate nonmodifiable character string objects of class String. To be able to create and manipulate modifiable character string objects of class StringBuffer. To be able to create and manipulate objects of class Character. To be able to use a StringTokenizer object to break a Stringobject into individual components called tokens. The chief defect of Henry King Was chewing little bits of string. Hilaire Belloc Vigorous writing is concise. A sentence should contain no unnecessary words, a paragraph no unnecessary sentences. William Strunk, Jr. I have made this letter longer than usual, because I lack the time to make it short. Blaise Pascal The difference between the almost-right word & the right word is really a large matter it s the difference between the lightning bug and the lightning. Mark Twain Mum s the word. Miguel de Cervantes, Don Quixote de la Mancha Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Chapter 9 (Tomcat web server) Object-Oriented Programming 535 in the application s

Sunday, October 28th, 2007

Chapter 9 Object-Oriented Programming 535 in the application s constructor). The paint method (for your subclass of JFrame) should draw the shape with a statement like currentShape.draw( g ); where currentShape is the MyShape reference and g is the Graphics object that the shape will use to draw itself on the background of the window. 9.29 Next, change the single MyShapereference into an array of MyShapereferences and hard code several MyLineobjects into the program for drawing. The application s paintmethod should walk through the array of shapes and draw every shape. After the preceding part is working, you should define the MyOval and MyRect classes and add objects of these classes into the existing array. For now, all the shape objects should be created in the constructor for your subclass of JFrame. In Chapter 12, we will create the objects when the user chooses a shape and begins drawing it with the mouse. In Exercise 9.28, you defined a MyShape hierarchy in which classes MyLine, MyOval and MyRectsubclass MyShape directly. If the hierarchy was properly designed, you should be able to see the tremendous similarities between the MyOval and MyRect classes. Redesign and reimplement the code for the MyOval and MyRect classes to factor out the common features into the abstractclass MyBoundedShapeto produce the hierarchy in Fig. 9.46. Class MyBoundedShape should define two constructors that mimic the constructors of class MyShapeand methods that calculate the upper-left x-coordinate, upper-left y-coordinate, width and height. No new data pertaining to the dimensions of the shapes should be defined in this class. Remember, the values needed to draw an oval or rectangle can be calculated from two (x,y) coordinates. If designed properly, the new MyOval and MyRect classes should each have two constructors and a drawmethod. java.lang.Object MyShapeMyLine MyBoundedShapeMyRectMyOval Fig. 9.46 The MyShapehierarchy. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Apache web server tutorial - 534 Object-Oriented Programming Chapter 9 Class MyShape in

Saturday, October 27th, 2007

534 Object-Oriented Programming Chapter 9 Class MyShape in Fig. 9.45 must be abstract. The only data representing the coordinates of the shapes in the hierarchy should be defined in class MyShape. Lines, rectangles and ovals can all be drawn if you know two points in space. Lines require x1, y1, x2 and y2 coordinates. The drawLine method of the Graphics class will connect the two points supplied with a line. If you have the same four coordinate values (x1, y1, x2 and y2) for ovals and rectangles, you can calculate the four arguments needed to draw them. Each requires an upper-left x-coordinate value (minimum of the two x-coordinate values), an upper-left y-coordinate value (minimum of the two y coordinate values), a width (difference between the two x-coordinate values; must be nonnegative) and a height (difference between the two y-coordinate values; must be nonnegative). [Note: In Chapter 12, each x,y pair will be captured by using mouse events from mouse interactions between the user and the program s background. These coordinates will be stored in an appropriate shape object as selected by the user. As you begin the exercise, you will use random coordinate values as arguments to the constructor.] In addition to the data for the hierarchy, class MyShape should define at least the following methods: a) A constructor with no arguments that sets the coordinates to 0. b) A constructor with arguments that sets the coordinates to the supplied values. c) Set methods for each individual piece of data that allow the programmer to independently set any piece of data for a shape in the hierarchy (e.g., if you have an instance variable x1, you should have a method setX1). d) Get methods for each individual piece of data that allow the programmer to independent ly retrieve any piece of data for a shape in the hierarchy (e.g., if you have an instance vari able x1, you should have a method getX1). e) The abstractmethod public abstract void draw( Graphics g ); This method will be called from the program s paintmethod to draw a shape onto the screen. The preceding methods are required. If you would like to provide more methods for flexibility, please do so. However, be sure that any method you define in this class is a method that would be used by all shapes in the hierarchy. All data must be private to class MyShape in this exercise (this forces you to use proper encapsulation of the data and provide proper set/get methods to manipulate the data). You are not allowed to define new data that can be derived from existing information. As explained previously, the upper-left x, upper-left y, width and height needed to draw an oval or rectangle can be calculated if you already know two points in space. All subclasses of MyShape should provide two constructors that mimic those provided by class MyShape. Objects of the MyOval and MyRectclasses should not calculate their upper-left x-coordinate, upper-left y-coordinate, width and height until they are about to draw. Never modify the x1, y1, x2 and y2 coordinates of a MyOvalor MyRect object to prepare to draw them. Instead, use the temporary results of the calculations described above. This will help us enhance the program in Chapter 12 by allowing the user to select each shape s coordinates with the mouse. There should be no MyLine, MyOvalor MyRect references in the program only MyShape references that refer to MyLine, MyOval and MyRect objects are allowed. The program should keep an array of MyShape references containing all shapes. The program s paint method should walk through the array of MyShape references and draw every shape (i.e., call every shape s draw method). Begin by defining class MyShape, class MyLine and an application to test your classes. The application should have a MyShape instance variable that can refer to one MyLine object (created Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Best web hosting - Chapter 9 Object-Oriented Programming 533 9.22 How does

Saturday, October 27th, 2007

Chapter 9 Object-Oriented Programming 533 9.22 How does polymorphism promote extensibility? 9.23 You have been asked to develop a flight simulator that will have elaborate graphical outputs. Explain why polymorphic programming would be especially effective for a problem of this nature. 9.24 Develop a basic graphics package. Use the Shape class inheritance hierarchy from Figure 9.3. Limit yourself to two-dimensional shapes such as squares, rectangles, triangles and circles. Interact with the user. Let the user specify the position, size, shape and fill colors to be used in drawing each shape. The user can specify many items of the same shape. As you create each shape, place a Shapereference to each new Shapeobject into an array. Each class has its own drawmethod. Write a polymorphic screen manager that walks through the array sending drawmessages to each object in the array to form a screen image. Redraw the screen image each time the user specifies an additional shape. Investigate the methods of class Graphicsto help draw each shape. 9.25 Modify the payroll system of Fig. 9.16 Fig. 9.21 to add private instance variables birthDate (use class Date from Figure 8.13) and departmentCode (an int) to class Employee. Assume this payroll is processed once per month. Then, as your program calculates the payroll for each Employee (polymorphically), add a $100.00 bonus to the person s payroll amount if this is the month in which the Employee s birthday occurs. 9.26 In Exercise 9.15, you developed a Shape class hierarchy and defined the classes in the hierarchy. Modify the hierarchy so that class Shapeis an abstractsuperclass containing the interface to the hierarchy. Derive TwoDimensionalShape and ThreeDimensionalShape from class Shape these classes should also be abstract. Use an abstractprintmethod to output the type and dimensions of each class. Also include areaand volumemethods so these calculations can be performed for objects of each concrete class in the hierarchy. Write a driver program that tests the Shapeclass hierarchy. 9.27 Rewrite your solution to Exercise 9.26 to use a Shape interface instead of an abstract Shapeclass. 9.28 (Drawing Application) Modify the drawing program of Exercise 8.19 to create a drawing application that draws random lines, rectangles and ovals. [Note: Like an applet, a JFrame has a paintmethod that you can override to draw on the background of the JFrame.] For this exercise, modify the MyLine, MyOval and MyRect classes of Exercise 8.19 to create the class hierarchy in Fig. 9.45. The classes of the MyShapehierarchy should be smart shape classes where objects of these classes know how to draw themselves (if provided with a Graphics object that tells them where to draw). The only switch or if/else logic in this program should be to determine the type of shape object to create (use random numbers to pick the shape type and the coordinates of each shape). Once an object from this hierarchy is created, it will be manipulated for the rest of its lifetime as a superclass MyShapereference. java.lang.Object MyShape MyLine MyOval MyRect Fig. 9.45 The MyShapehierarchy. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

532 Object-Oriented (Web hosting plans) Programming Chapter 9 9.4 Define each

Friday, October 26th, 2007

532 Object-Oriented Programming Chapter 9 9.4 Define each of the following terms: single inheritance, multiple inheritance, interface, superclass and subclass. 9.5 Discuss why casting a superclass reference to a subclass reference is potentially dangerous. 9.6 Distinguish between single inheritance and multiple inheritance. What feature of Java helps realize the benefits of multiple inheritance? 9.7 (True/False) A subclass is generally smaller than its superclass. 9.8 (True/False) A subclass object is also an object of that subclass s superclass. 9.9 Some programmers prefer not to use protected access because it breaks information hiding in the superclass. Discuss the relative merits of using protected access vs. private access in superclasses. 9.10 Many programs written with inheritance could be solved with composition instead, and vice versa. Discuss the relative merits of these approaches in the context of the Point, Circle, Cylinderclass hierarchy in this chapter. Rewrite the program of Fig. 9.22 Fig. 9.26 (and the supporting classes) to use composition rather than inheritance. After you do this, reassess the relative merits of the two approaches both for the Point, Circle, Cylinder problem and for object-oriented programs in general. 9.11 Rewrite the Point, Circle, Cylinder program of Fig. 9.22 Fig. 9.26 as a Point, Square, Cube program. Do this two ways once with inheritance and once with composition. 9.12 In the chapter, we stated, When a superclass method is inappropriate for a subclass, that method can be overridden in the subclass with an appropriate implementation. If this is done, does the subclass-is-a-superclass-object relationship still hold? Explain your answer. 9.13 Study the inheritance hierarchy of Fig. 9.2. For each class, indicate some common attributes and behaviors consistent with the hierarchy. Add some other classes (e.g., UndergraduateStudent, GraduateStudent, Freshman, Sophomore, Junior, Senior), to enrich the hierarchy. 9.14 Write an inheritance hierarchy for classes Quadrilateral, Trapezoid, Parallelogram, Rectangle and Square. Use Quadrilateral as the superclass of the hierarchy. Make the hierarchy as deep (i.e., as many levels) as possible. The private data of Quadrilateral should include the (x, y) coordinate pairs for the four endpoints of the Quadrilateral. Write a driver program that instantiates and displays objects of each of these classes. [In Chapter 11, Graphics and Java2D, you will learn how to use Java s drawing capabilities.] 9.15 Write down all the shapes you can think of both two-dimensional and three-dimensional and form those shapes into a shape hierarchy. Your hierarchy should have superclass Shape, from which class TwoDimensionalShape and class ThreeDimensionalShape are derived. Once you have developed the hierarchy, define each of the classes in the hierarchy. We will use this hierarchy in the exercises to process all shapes as objects of superclass Shape. 9.16 How is it that polymorphism enables you to program in the general rather than in the specific ? Discuss the key advantages of programming in the general. 9.17 Discuss the problems of programming with switch logic. Explain why polymorphism is an effective alternative to using switchlogic. 9.18 Distinguish between inheriting interface and inheriting implementation. How do inheritance hierarchies designed for inheriting interface differ from those designed for inheriting implementation? 9.19 Distinguish between nonabstract methods and abstract methods. 9.20 (True/False) All methods in an abstract superclass must be declared abstract. 9.21 Suggest one or more levels of abstract superclasses for the Shape hierarchy discussed in the beginning of this chapter (the first level is Shape and the second level consists of the classes TwoDimensionalShape and ThreeDimensionalShape). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Web space - Chapter 9 Object-Oriented Programming 531 object-oriented programming (OOP)

Thursday, October 25th, 2007

Chapter 9 Object-Oriented Programming 531 object-oriented programming (OOP) subclass reference override a method super override an abstractmethod superclass overriding vs. overloading superclass constructor polymorphism superclass reference protected member of a class switchlogic reference to an abstract class this setSize method type-wrapper class setVisiblemethod uses a relationship single inheritance WindowAdapter class software reusability windowClosingmethod standardized software components WindowEvent class subclass WindowListener interface subclass constructor SELF-REVIEW EXERCISES 9.1 Fill in the blanks in each of the following statements: a) If the class Alphainherits from the class Beta, class Alpha is called the class and class Beta is called the class. b) Inheritance enables , which saves time in development and encourages using previously proven and high-quality software components. c) An object of a class can be treated as an object of its corresponding class. d) The four member access specifiers are , , and . e) A has a relationship between classes represents and an is a relationship between classes represents . f) Using polymorphism helps eliminate logic. g) If a class contains one or more abstract methods, it is an class. h) A method call resolved at run-time is referred to as binding. i) A subclass may call any nonprivate superclass method by prepending to the method call. 9.2 State whether each of the following statements is true or false. If false, explain why. a) A superclass typically represents a larger number of objects than its subclass represents (true/false). b) A subclass typically encapsulates less functionality than does its superclass. (true/false). ANSWERS TO SELF-REVIEW EXERCISES 9.1 a) sub, super. b) software reusability. c) sub, super. d) public, protected, privateand package access. e) composition, inheritance. f) switch. g) abstract. h) dynamic. i) super. 9.2 a) True. b) False. A subclass includes all the functionality of its superclass. EXERCISES 9.3 Consider the class Bicycle. Given your knowledge of some common components of bicycles, show a class hierarchy in which the class Bicycle inherits from other classes, which, in turn, inherit from yet other classes. Discuss the instantiation of various objects of class Bicycle. Discuss inheritance from class Bicyclefor other closely related subclasses. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

530 Object-Oriented Programming Chapter 9 An inner

Thursday, October 25th, 2007

530 Object-Oriented Programming Chapter 9 An inner class can also be defined inside a method of a class. Such an inner class has access to its outer class s members and to the final local variables for the method in which it is defined. Inner class definitions are used mainly in event handling. Class JFrame provides the basic attributes and behaviors of a window a title bar and buttons to minimize, maximize and close the window. An inner class object has access to all the variables and methods of the outer class object. Because an anonymous inner class has no name, one object of the anonymous inner class must be created at the point where the class is defined in the program. An anonymous inner class can implement an interface or extend a class. The event generated when the user clicks the window s close box is a window closing event. Method addWindowListener registers a window event listener. The argument to addWindowListener must be a reference to an object that is a WindowListener (package java.awt.event). For event handling interfaces with more than one method, Java provides a corresponding class (called an adapter class) that already implements all the methods in the interface for you. Class WindowAdapter implements interface WindowListener, so every WindowAdapter object is a WindowListener. Compiling a class that contains inner classes results in a separate .classfile for every class. Inner classes with class names can be defined as public, protected, package access or private and are subject to the same usage restrictions as other members of a class. To access the outer class s this reference, use OuterClassName.this. The outer class is responsible for creating objects of its nonstatic inner classes. An inner class can be declared static. TERMINOLOGY abstract class hierarchical relationship abstract method implementation inheritance abstract superclass implicit reference conversion abstraction indirect superclass anonymous inner class infinite recursion error base class inheritance Boolean class inheritance hierarchy Character class inner class class hierarchy Integer class client of a class interface composition interface inheritance direct superclass is a relationship Double class JFrame class dynamic method binding late binding extends Long class extensibility member access control final class member object final instance variable method overriding final method multiple inheritance garbage collection Number class has a relationship Object class Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01