REVIEW QUESTIONS AND EXERCISES QUESTIONS Java Essentials for C and C++ Programmers ------------------------------------------------------------ Part I: Concepts Chapter 1: The Philosophy of Java 1. In the pseudo code provided below, developed for a C/C++ program, a. determine: - Where is the memory leak? - Where is the memory overwrite? - Where does the program access memory outside of its allocated memory? b. Can any of these common programming oversights ever occur in Java? Why or why not? function: Allocate1K line 1: Allocate a 1K-byte buffer line 2: Return the buffer end of Allocate1K function: main line 3: Set a variable named b to the value returned by Allocate1K() line 4: Write "allocated" to the screen line 5: Loop through the first 2K bytes in b; write each byte to a file. line 6: Set b to the value returned by Allocate1K() line 7: Read in a 2K buffer into a variable named b2 line 8: Set b to b2 end of main 2. Java is innovative, shifting many of the traditional programmer burdens to become the responsibility of the language and runtime environment. What are three examples of this shift of responsibilities? 3. What are three different types of Java programs you might write and in what environment might these programs run? 4. The syntax of Java is often very similar to C/C++, especially when concerning flow of control. What do you think the variable x is equal to at the end of each of the following code snippets? a. { int i; int x; for (i = 0; i < 10; i++) x = x + i; } b. { int x = 5; while (x > 1) x = x * --x; } c. { int i = 2; switch (i) { case (1): x = 11; break; case (2): x = 22; break; default: x = 0; break; } ------------------------------------------------------------ Chapter 2: How Java Implements Object-Oriented Programming 1. What are three things wrong with this outline of a Java program? start a class definition named Alpaca define a class variable named NUM_ALPACAS define a structure named characteristics define a main routine end class definition named Alpaca define a global variable named NUM_LLAMAS start a method named hum play the sound of a llama humming end method named hum 2. C/C++ and Java programs are invoked in different ways. a. How do you run a C/C++ program? Where does the program start? b. How do you run a stand-alone Java program? Where does the program start? 3. In C++, imagine a class called Animal and a class called Pet. a. In a sentence, describe the design of a C++ class called Cat. b. Now redesign these classes to work in Java. 4. How object-oriented is Java? a. Is a variable declared as int an object? b. Is a variable declared as boolean an object? c. Are arrays objects? d. Can you directly access the memory inside of a character string? e. Can you overload the * operator to perform a factorial operation? f. Given a method in a class called myMethod(int i), can you write a second method called myMethod that takes a boolean instead of an int? ------------------------------------------------------------ Chapter 3: Language Foundations 1. Java uses which of these building blocks from C and C++? a. classes b. addresses c. functions d. objects e. methods f. pointers g. structures 2. The lure of "executable content" on the Web is tremendous. However, traditional languages, like C and C++, have some serious drawbacks for use as the programming language for the Web. What are two of them? 3. Will any objects be candidates for garbage collection at the end of the following block of pseudo code? Why or why not? Allocate an object and assign it to a variable named obj1. Allocate an object and assign it to a variable named obj2. Set obj1 to obj2. At this point, are any objects candidates for garbage collection? ------------------------------------------------------------ Chapter 4: Development Cycles 1. Approaching your application's development is different for C and Java. a. What is the first consideration in C? b. What is the first consideration in Java? 2. When you compile a program in C or C++, you compile for a particular machine. a. What does Java do instead? b. What is the Java interpreter and how does it work with your compiled classes? 3. What file extension should you give your Java source code? What file extension will the compiler use for your compiled classes? 4. If your stand-alone Java program does cause any unhandled exceptions to be thrown, when will the program come to a halt? 5. What are the Java equivalents for these elements in your C/C++ programs: a. APIs in header files b. C source code files c. object/executable files d. library routines ------------------------------------------------------------ Chapter 5: Java Environments 1. What are five "buzz words" that indicate why is Java perfect for the Web, while C and C++ are not? 2. Java has been described as "C++ without the guns and knives." a. What are some features that makes Java a "safer" language to program in than C/C++? b. What are some reasons that make Java more "secure" than C/C++? 3. Browsers built using Java (such as Sun's HotJava browser) can extend themselves with Java programs called protocol handles and content handlers. a. What are protocol handlers? b. What are content handlers? Use the URL "baseball://majorleague.org/pitcher.era" to illustrate each of these. ------------------------------------------------------------ Part II: Quick Start Chapter 6: Text-Based Applications 1. What are the elements in C, C++, and Java versions of the Hello, World program? (Check off the element associated with each language. Note: C++ sometimes spans the two worlds of Java and C.) C C++ Java functions methods preprocessor directives classes objects 2. Define an empty Java class called MyClass. What happens if you try to compile and run this class? How could you change this class so that it would run? 3. Create a main routine that creates an instance of itself--that is, the routine creates an object of MyClass. 4. Write the palindrome "Madam, I'm Adam" to the standard output inside a main method. 5. Write a block of code that reads from the standard input until the first newline character. 6. Write a block of code that converts a String instance to a Double instance. 7. How can you add onto the above block of code (in question 6) to then retrieve the primitive data type double from a Double instance? 8. Why won't the following code compile in Java? What do you have to do to make it compile? double myDouble = 5.0; int myInt; myInt = myDouble; 9. Write an outline for preparing to execute a statement that might cause an exception to be thrown, and what you must do to catch that exception. 10. How can you tell if your program is passed any arguments from the command line? How can you access the first element of the arguments? 11. Write a program that prints "Hello, World" according to the number of arguments passed to the program. If no arguments were passed or the argument is not a number, just print "Hello, World" once. ------------------------------------------------------------ Chapter 7: Graphical Applications 1. What are some advantages to writing a graphical Java application, even if you don't plan to run the application over the Web? 2. Create an empty subclass definition of Java's Button class called MyButton. 3. What class do you need to extend to create a top-level window for your graphical user interface? 4. What method do you have to override to draw in the frame? 5. What method can you use to resize your frame? 6. What method can you override for your Frame subclass to resize the frame when it first appears on the screen? 7. What method do you dispatch to a frame object to make it appear on the screen? 8. Why doesn't the program end as soon as main exits? When will the program end? 9. Given three variables defined in an applet's paint() method: String s1 = "Single short "; String s2 = "non-fat "; String s3 = "mocha"; write an applet that paints the text "Single short non-fat mocha" in its frame. 10. What class can you use to group together other objects? 11. What method do you dispatch to a container object (frame or panel) to add another user interface component to it? What parameter do you pass the container? 12. What is the user interface component you can use to have users enter text? 13. How do you retrieve a string object that contains the text within a TextField instance called textField? 14. What method do you need to override to handle input events from the user (mouse clicks, typing, etc.)? What parameter is passed to this method? 15. How can you use this event object to identify that the target of the event is a TextField object and that the user has hit the enter key? 16. Write a method that prints "action event detected" to the standard output every time the user generates an action event (such as by clicking in the window). ------------------------------------------------------------ Chapter 8: Applets on the Web 1. What class do you need to subclass to create an applet? This applet inherits from which other class that allows you to use the class as a user interface component in its own right? 2. Do you need to create a main routine for your applet? Why or why not? When might you want to? 3. Write pseudo code to invoke an applet from the main routine. (The chapter suggested three steps within the source code.) 4. What method should you override to perform initializations for your applet? What method is called each time your applet starts? Which method is called each time your applet stops? Which method can you override for your applet to perform clean up when your applet goes away? 5. Which tag can you use to put an applet into an HTML document? 6. Write an HTML document to display an applet subclass called MyApplet in a window that is 300 by 300 pixels big. ------------------------------------------------------------ Part III: Details Chapter 9: Designing Your Classes 1. There are two keywords that you can use with classes. a. What does public mean when used with a class? b. What does abstract mean when used with a class? 2. Given the following class definition: class MyClass { int myInt; void myPrint() { System.out.println("Hi there"); } } a. How can you instantiate this class? b. How can you assign a value of 10 to myInt for this instance? c. How can you make the words "Hi there" appear on the standard output? 3. Here's some Java code for a class called MysteryClass. class Beatles { void testMethod(int i) { System.out.println("Don't know how lucky you are, boys"); } } class MysteryClass extends Beatles { static { System.out.println("I am the walrus"); } void testMethod() { System.out.println("Flew in from Miami Beach BOAC"); } void testMethod(int i) { System.out.println("I'm back in the USSR"); super(); } } a. What will occur when the class MysteryClass is loaded? b. What will occur when this block of code is executed? { MysteryClass mc = MysteryClass(); mc.testMethod(); } c. What will occur when this block of code is executed? { MysteryClass mc = MysteryClass(); mc.testMethod(0); } 4. Keywords help determine the access privileges for methods and variables. a. What is the default? b. What does private mean? c. What does protected mean? d. What does public mean? 5. What three keywords can be used to define a global constant that resides in a public class? 6. What keyword is used to assign a method or variable to a class? 7. Given the following classes: abstract class LightBulb { abstract void turnOn(); } class Fluorescent extends LightBulb { } How would you have to change Fluorescent to be able to compile this code and instantiate this class? 8. How can you indicate your class will inherit the characteristics from two interfaces called Winken and Blinken? 9. Given the following class: class LaughIn { void guffaw() { System.out.println("Ha ha!"); } } Write a subclass called Giggle that prints "Hee hee!" after "Ha ha!" when its guffaw() method is invoked. ------------------------------------------------------------ Chapter 10: Implementing Your Classes 1. What is wrong with each of the following blocks of code? a. class MyClass { int i; static public void main(String args[]) { i = 3; } } b. class NewClass { abstract void myMethod(); } c. interface AnotherClass { static int i; } d. interface FirstInterface { void myMethod(); } class FirstClass implements FirstInterface { } e. { String s = "Hello"; s = "Good bye"; } f. { int i = 5; signed j = -3; } g. class NewClass { void testMessage() { System.out.println("hello"); } static void myMethod() { testMessage(); } } 2. Given this class definition: class FamilyValues { int numBrothers; boolean married; int[] sisterAges; public static void main(String args[]) { FamilyValues fv = new FamilyValues(); fv.sisterAges = new int[2]; fv.sisterAges[0] = 24; System.out.println(numBrothers); System.out.println(married); System.out.println(sisterAges[0]); System.out.println(sisterAges[1]); } } What is the output from this program? 3. How would you write a constructor for a class called TownCrier that called out the appropriate "all's well" message when it's created, given an int value that indicates the time? (Also, save this time in an instance variable.) 4. Java has a limited number of data types. a. What are the two floating point data types? b. What are the four integer data types? 5. Java is very picky about data types. Why would each of these assignments, after the variable declarations, be illegal? float myFloat; boolean myBoolean; int myInt; long myLong; myFloat = 3L; myInt = 1.0; myInt = 1F; myLong = 1.0; myBoolean = 0; ------------------------------------------------------------ Chapter 11: More Power to You 1. Given an array allocated to 10 elements in C/C++ and the similar array allocated to 10 elements in Java: a. What are the consequences of writing to the 11th element in C/C++? b. What are the consequences of writing to the 11th element in Java? 2. How do you declare a variable in Java to hold a three-dimensional array of boolean values? 3. Given these class definitions: class FirstSubclass { } class SecondSubclass extends FirstSubclass { } a. What is the ancestor for SecondSubclass? b. What is the ancestor for SecondSubclass[]? c. What is the ancestor for FirstSubclass[]? 4. What is the difference between a String and a StringBuffer object? How you can obtain a String object from a StringBuffer object named sb? 5. Java provides a Thread class to help make multitasking easy. a. How do you subclass Java's Thread class? b. How do you create a thread? c. How do you start a thread? d. What do you have to override for the new thread to make it do something? 6. Instead of creating your own Thread subclass, what's another approach to providing behavior for a multitasking application? Write the key lines of code that illustrate what's involved. 7. How do you define and throw your own exception called CircuitBreaker? 8. How does Java formalize exceptions as part of the language? Provide an example using a method called voltMeter that takes no parameters and returns no value; use the new exception class created in question 6 above. 9. If the caller of voltMeter(), above, did not handle the exception, and no other part of the application handled the exception, what would happen? 10. In C++, you can indicate you'd like to handle all exceptions by writing a block of code like this: catch(...) { // handle all exceptions here } What is the equivalent block of code in Java? 11. Often, if you use a system method that might throw an exception, you can handle any exceptions it throws with a try/catch block. If you don't want to handle the exception, how do you tell the system that your method might not catch an exception it might trigger? 12. The finally keyword is an amazing feature of Java. What will the output be when the FinallyExample class is executed by the Java interpreter? class FinallyExample { static public void main(String args[]) { try { myMethod1(); } catch (Exception e) { System.out.println("Catching exception"); } } static void myMethod1() { try { return; } finally { System.out.println("After the return statement"); } } } ------------------------------------------------------------ Chapter 12: Final Differences Between C/C++ and Java 1. Java is a simpler language than C++. Some things you can do in C++ you cannot do in Java. What are five examples? 2. Some elements that exist in C/C++ but not in Java have direct equivalents in Java. What can you use in the place of the following? a. structures b. functions c. constants and preprocessor variables d. multiple inheritance 3. Java's primary mission is to make the programmer's job easier. However, by using some advanced features of Java, programmers can still write efficient code and perform optimizations. How can you: a. Take part in freeing memory during garbage collection? b. Specify you would like a method to be expanded inline? c. Suppress optimization for variables? 4. By now you should know every Java keyword and every aspect of its syntax. (The only keyword not covered yet is native--for details, see the appendices.) a. What are the important keywords for defining classes? b. What are the important keywords for setting the access privileges for variables and methods? c. What three keywords are used for exception handling? ------------------------------------------------------------ Chapter 13: Working with Java's Packages 1. In addition to the language itself, all implementations of Java include a collection of packages that provide a class framework and useful methods and predefined objects that you can use in your own applications. a. What are Java's six major packages? b. In which package are the numeric "wrapper" types defined? c. What does AWT stand for? d. Name four useful classes defined in the util package. e. Name four common classes, not include wrapper types, defined in the lang package. 2. The Java packages define a number of LayoutManagers that you can use to position your user interface components. a. What LayoutManager is best for a toolbar, positioning items left to right until it runs out of room and goes to the next row? b. What LayoutManager is useful for positioning items along one of the four edges of a window or in the window's center? c. What LayoutManager would be best for creating a table? d. What LayoutManager simulates a deck of cards that you can flip through programmatically? e. What LayoutManager provides the most control? f. What is the primary method you must concern yourself with when creating your own LayoutManager? 3. The Java packages provide some low-level drawing capabilities. a. What Java package class defines methods for low-level drawing? b. How can you draw a line from (0,0) to (10,10), given a Graphics object referenced by a variable called g? c. How can you draw a circle centered at (20,20) with a diameter of 10 given the same graphics object? 4. Rather than override handleEvent(), your component can specifically look for certain mouse events. a. What are three events you can identify? b. What three parameters do these methods take? 5. Write a method called getFileList that returns a list of files in the current working directory. 6. Write a method called findText that takes two Strings. The first string is a URL for a Web page, the second contains text to search for. Open the Web page, search the text on that page, and return true of the text matches, false otherwise. 7. Create a Date instance for the turn of the Century--which actually takes place at the start of the year 2001. ------------------------------------------------------------ Chapter 14: Writing for the Web 1. There are three basic steps for writing your own Java applet: a. What Java class do you need to subclass? b. What four Applet methods are you likely to override? (These are the applet's life cycle methods.) c. Write a very simple HTML file to embed an applet into a Web page. 2. Your Java applet has the ability to find out some information about itself. How would your applet: a. Locate a handle to the Web browser? b. Determine the URL from where the applet came? c. Determine the URLwhere the Web page came from in which your applet was embedded? 3. How would you pass a parameter named "season" with the value "summer" an applet named Rose when the applet is invoked? How would you retrieve this value from inside the program? 4. When should you create, start, stop, and destroy threads in an applet's life cycle? 5. There are a number of considerations to take into account when creating animation. What might you do to: a. reduce flicker? b. ensure your animation plays at a certain speed? c. ensure your animation does not tie up the system? 6. When Java programs run over the Web, they are restricted in the types of operations they can perform. Name three areas where Web programs might be restricted.