REVIEW QUESTIONS AND EXERCISES ANSWERS Java Essentials for C and C++ Programmers ------------------------------------------------------------ Part I: Concepts Chapter 1: The Philosophy of Java 1a. - Memory leak in line 6 - Memory overwrite in line 8 - Accesses data outside of its allocated memory in line 5. 1b. These mistakes cannot occur in Java because Java manages the memory for you. 2. - Memory management - Thread synchronization - Platform independence (Error handling is also formalized as part of the language.) 3. - stand-alone, text-based - stand-alone, graphical - Web-hosted, graphical (These three will be covered in this book.) Other types are: - extensions to HTML in the form of a JavaScript, a scripting language based on Java- protocol and content handlers to extend the functionality of browsers built with Java 4a. 0 + 1 + 2 + ... 9 = 45 4b. 5! = 120 4c. x = 22 ------------------------------------------------------------ Chapter 2: How Java Implements Object-Oriented Programming 1. Structures are not allowed in Java; globals cannot be defined outside of classes; methods cannot be defined outside of classes. 2a. Execute the name of the file containing the compiled and linked program. The program starts at the main() function. 2b. Launch the Java interpreter, passing it the name of the class you want to start at. The program starts at that class's main method. 3a. Cat can inherit from both Animal and Pet. 3b. Change Pet from a class to an interface; now Cat can inherit from Animal and implement the Pet interface. 4a. no (it's a primitive data type) 4b. no (it's a primitive data type) 4c. yes 4d. no (strings are first class objects, and you cannot use pointer or addresses or pointer arithmetic to directly access memory--you must use the class's interfaces) 4 e. no (no operator overloading) 4 f. yes (there is method overloading) ------------------------------------------------------------ Chapter 3: Language Foundations 1. Only a, d, and e are used in Java. 2. First, they are open to programmer error, which could cause inadvertent havoc to computers on the Web. Second, they cannot be verified before they are executed, so it is possible to program viruses applets in languages other than Java that could infect a computer that runs the applet. 3. The very first object allocated is a candidate for garbage collection, since there is no way to ever obtain a reference to this object again. ------------------------------------------------------------ Chapter 4: Development Cycles 1a. In C, you start by writing a function. You are immediately concerned with your algorithm: that is, how you will code a specific set of instructions. 1b. In Java, you start by writing a class. You are immediately concerned with your program's framework and design: that is, what your program will do, rather than how it will do it. 2a. Java compiles for a generic machine called the Java Virtual Machine (JVM). 2b. The Java interpreter stands between your compiled classes and your computer's hardware and operating environment. The Java interpreter translates between the bytecodes of your compiled classes and the machine instructions for your computer. The Java interpreter is essentially the JVM, implemented in software rather than hardware. 3. Java source files should use the extension .java. Compiled classes will be in files with the extension .class. 4. When all user- and application-created threads come to a halt and the main() method exits. 5a. HTML files generated by Sun's Java SDK tool that creates documentation (called javadoc) 5b. Java source code files 5c. bytecode or compiled class files 5d. packages (Java's class framework) ------------------------------------------------------------ Chapter 5: Java Environments 1. - platform independent - safe - secure - multithreaded - dynamic Two others are: - small - standard 2a. Java provides bounds checking for arrays; there is no pointer arithmetic for accessing arbitrary memory locations. 2b. Java programs are verified for correctness before they are executed; methods calls are referenced by name and resolved into an address only after they have been verified; applets run in a restricted region of memory. 3a. Protocol handlers allow the browser to access a resource on the Web using a protocol that it does not already know how to handle. For example, in the URL provided above, "baseball" would be the name of the new protocol. 3b. Content handlers allow the browser to display a document that it does not understand. In the URL above, the extension .era might not be known to the browser; a content handler would be able to extend the browser to work with a document with this type of extension. ------------------------------------------------------------ Part II: Quick Start Chapter 6: Text-Based Applications 1. C C++ Java functions x x methods x x preprocessor directives x x classes x x objects x x 2. class MyClass { } It will compile, but it won't run because there's no main method. To make it run, you can supply a main method, like this: class MyClass { static public void main(String args[]) { } } 3. class MyClass { static public void main(String args[]) { MyClass myClass = new MyClass(); } } 4. class MyClass static public void main(String args[]) { System.out.println("Madam, I'm Adam"); } } 5. { char c; StringBuffer strng; while ((c = (char)System.in.read()) != '\n') strng.appendChar(c); } 6. // input is in string Double myDouble; myDouble = Double.valueOf(strng); 7. double d = myDouble.doubleValue(); 8. This won't compile because we've assigned a double to an integer without casting. Instead, try: myInt = (int)myDouble; 9. try { statement to try } catch (the exception to catch) error handling code } 10. args.length > 0 The first argument will be in args[0] 11. class MyClass { static public void main(String args[]) { String s; int num = 1; int i; if (args.length > 0) { s = args[0]; try { int num = Integer.valueOf(string).intValue(); } catch (Exception e) { num = 1; } } for (i = 0; i < num; i++) System.out.println("Hello, Java"); } } ------------------------------------------------------------ Chapter 7: Graphical Applications 1. - Your application will run without change on a wide variety of platforms. - You only need to maintain a single code base. - You can take advantage of Java's powerful graphics and networking libraries, multithreading, and object-oriented environment to create powerful applications quickly. 2. class MyButton extends Button { } 3. Frame 4. paint() 5. resize() 6. init() 7. show() 8. The frame that is created has its own event loop and so a thread of execution is still running for the program. When the user closes the window, the program will end. 9. import java.awt.Graphics; import java.applet.Applet; public class HelloApplet extends Applet { public void init() { resize(200,60); } public void paint(Graphics g) { String s1 = "Single short "; String s2 = "non-fat "; String s3 = "mocha"; g.drawString(s1 + s2 + s3, 60, 25); } } 10. Panel 11. add(), passing the user interface object to add to it 12. TextField 13. String s = textField.getText(); 14. handleEvent(), an Event object 15. if (e.target instanceof TextField && e.id == Event.ACTION_EVENT) { // handle this event } 16. import java.awt.Graphics; import java.applet.Applet; public class HelloApplet extends Applet { public void init() { resize(200,60); } public boolean handleEvent(Event e) { if (e.id == Event.ACTION_EVENT) { System.out.println("Action event detected"); } // Return what our superclass thinks is appropriate. return super.handleEvent(e); } } ------------------------------------------------------------ Chapter 8: Applets on the Web 1. The Applet class, which inherits from the Frame class. 2. You do not need to create a main routine if your applet will only run within the context of a Web browser. If you want your applet to also be able to run as a stand-alone program, you must create a main() routine to invoke your applet class directly from the Java interpreter. 3. // Create an instance of this applet. // Create a frame in which to display this applet. // Add this applet to the frame and show the frame. 4. init(), start(), stop(), destroy() 5. 6. ------------------------------------------------------------ Part III: Details Chapter 9: Designing Your Classes 1a. Classes declared as public can be accessed across packages. Otherwise, the class can only be used in the package in which it is defined. 1b. An abstract class defines (or inherits) an abstract method and does not implement it. Therefore, the class cannot be instantiated; it is declared as abstract to indicate this to the system. 2a. MyClass mc = new MyClass(); 2b. mc.myInt = 10; 2c. mc.myPrint(); 3a. The words "I am the walrus" will appear on the standard output. 3b. The words "Flew in from Miami Beach BOAC" will appear on the standard output. 3c. The words "I'm back in the USSR" and "Don't know how lucky you are, boys" will appear on the standard output. 4a. Any object in the same package can execute the method or access the variable. 4b. Only the object that defines a private method or variable can access that method and variable. 4c. Only instances of subclasses of the object that defines a protected method or variable can access that method or variable. 4d. Any object can access a public method or variable, even if the class that defines it is in another package. 5. public, static, and final 6. static 7. You'd have to implement the abstract method called turnOn(), or you would also have to make Fluorescent an abstract method and you would not be able to instantiate it. 8. class Nod implements Winken, Blinken { } 9. class Giggle extends LaughIn { void guffaw() { super(); System.out.println("Hee hee!"); } } ------------------------------------------------------------ Chapter 10: Implementing Your Classes 1a. i is an instance variable, yet we're accessing it in a class method without reference to an instance. 1b. class contains an abstract method but it is not declared as abstract. 1c. All class variables must be initialized in an interface. 1d. If FirstClass is not going to implement FirstInterface, it must be declared as abstract. 1e. After a String is initialized, it cannot be changed. 1f. There is no signed data type in Java. All data types are signed. (Similarly, there's no unsigned.) 1g. Cannot access an instance method from a class method. 2. The output is: 0 false 10 0 3. class TownCrier { int oclock; TownCrier(int createdAt) { oclock = createdAt; System.out.println(createdAt + " o'clock and all's well!"); } } 4a. float and double 4b. short, byte, int, long 5. You cannot lose accuracy (unless you explicitly cast!). Therefore, you can't assign a long to a float, a double or a float to an int, or a double to a long. Also, boolean values are only able to take the values true or false; they cannot take numeric values. ------------------------------------------------------------ Chapter 11: More Power to You 1a. You will overwrite memory that is likely assigned to other variables or parts of the program. 1b. You will cause an exception to be thrown. If you do not handle the exception, the thread in which your code is executing will terminate. (If your program only has one thread, this means your program will terminate.) 2. boolean[][][] b; 3a. FirstSubclass 3b. FirstSubclass[] 3c. Object[] 4. String objects are read-only; StringBuffer objects are read/write. Given a StringBuffer object named sb, you can obtain a String by: String s = sb.toString(); 5a. class MyThread extends Thread { // thread code } 5b. MyThread t = new MyThread(); 5c. t.start(); 5d. The thread's run() method 6. You can indicate that an object that spawns the thread (such as an applet instance) handle the run() method for the thread. Here's the key lines of code: public class MyApplet extends Applet implements Runnable { // applet code public void start() { // or wherever the thread is created... Thread t = new Thread(self); t.start(); } public void run() { // behavior for the thread } } 7. class CircuitBreaker extends Exception { } throw new CircuitBreaker(); 8. Java requires all methods that throw an exception to indicate the exception they might throw as part of the method declaration. For example: void voltMeter() throws CircuitBreaker { } 9. The thread in which the exception was thrown would halt. (If this were the only thread in the application, the application would halt.) 10. catch (Exception e) { // handle all exceptions here } 11. void myMethod () throws Exception { } Here, Exception is any exception; you can substitute the particular exception you might not handle to be more specific (such as java.io.IOException). 12. The lines "After the return statement" and "Catching exception" both appear on the standard output. ------------------------------------------------------------ Chapter 12: Final Differences Between C/C++ and Java 1. unions references preprocessor variables macros templates Three other examples are: conditional compilation header files variable length param lists 2a. objects 2b. methods 2c. global static final variables 2d. interfaces 3a. By overriding the finalize() method for your class. 3b. By using the keyword "final." (See also the compiler options for forcing all final methods to be expanded inline.) 3c. By using the keyword "volatile." 4a. class, interface, extends, implements (also abstract and public) 4b. public, private, protected 4c. try, throw, catch ------------------------------------------------------------ Chapter 13: Working with Java's Packages 1a. lang, util, AWT, net, io, and applet 1b. lang 1c. Abstract Windows Toolkit 1d. Math, Date, Random, Vector 1e. System, String, Object, Thread 2a. FlowLayout 2b. BorderLayout 2c. GridLayout 2d. CardLayout 2e. GridBagLayout 2f. layoutContainer() 3a. Graphics 3b. g.drawLine(0,0,10,10, 3c. g.fillOval(15,15,10,10); (Remember that the first two coordinates indicate the top left of the oval, not its center.) 4a. mouseDrag(), mouseUp(), mouseDown() 4b. Event, x, and y 5. List getFileList() { File cwd = new File("."); return cwd.list(); } 6. boolean findText(String web, String search) { boolean result; try { URL url = new URL(web); DataInputStream stream = new DataInputStream(url.openStream()); StringBuffer buffer = new StringBuffer(); String str; while ((str = stream.readLine()) != null) { buffer.append(str); } String page = buffer.toString(); if (search.indexOf(page, 0) >= 0) result = true; } catch (Exception e) { result = false; } return result; } 7. Date d = Date(101, 0, 1); ------------------------------------------------------------ Chapter 14: Writing for the Web 1a. applet 1b. init(), start(), stop(), destroy() 1c. 2a. AppletContext ac = getAppletContext(); 2b. URL u = getCodeBase(); 2c. URL u = getDocumentBase(); 3. String bloom = getParameter("season"); 4. Create a thread in the init() method; start a thread in the start() method; stop a thread in the stop() method, and destroy a thread in the destroy() method. 5a. First draw to an off-screen buffer. 5b. Pause between images for a brief amount of time. 5c. Use a thread to sequence the display of images. 6. File I/O, accessing URLs, and running native methods.