1300 JAVA Questions

Share Embed Donate


Short Description

Download 1300 JAVA Questions...

Description

MORE THAN 1300 JAVA QUESTIONS

1.what is a transient variable? A transient variable is a variable that may not be serialized. 2.which containers use a border Layout as their default layout? The window, Frame and Dialog classes use a border layout as their default layout . 3.Why do threads block on I/O? Threads block on i/o (that is enters the waiting state) so that other threads ma y execute while the i/o Operation is performed. 4. How are Observer and Observable used? Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the ob servers that it has changed state. The Observer interface is implemented by objects that observe Observable objects. 5. What is synchronization and why is it important? With respect to multithreading, synchronization is the capability to control the access of multiple threads toshared resources. Without synchronization, it is p ossible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often leads to significant errors. 6. Can a lock be acquired on a class? Yes, a lock can be acquired on a class. This lock is acquired on the class's Cla ss object. 7. What's new with the stop(), suspend() and resume() methods in JDK 1.2? The stop(), suspend() and resume() methods have been deprecated in JDK 1.2. 8. Is null a keyword? The null value is not a keyword. 9. What is the preferred size of a component? The preferred size of a component is the minimum component size that will allow the component to display normally. 10. What method is used to specify a container's layout? The setLayout() method is used to specify a container's layout. 11. Which containers use a FlowLayout as their default layout? The Panel and Applet classes use the FlowLayout as their default layout. 12. What state does a thread enter when it terminates its processing? When a thread terminates its processing, it enters the dead state. 13. What is the Collections API? The Collections API is a set of classes and interfaces that support operations o n collections of objects. 14. Which characters may be used as the second character of an identifier, but n ot as the first character of an identifier? The digits 0 through 9 may not be used as the first character of an identifier b ut they may be used after the first character of an identifier. 15. What is the List interface? The List interface provides support for ordered collections of objects. 16. How does Java handle integer overflows and underflows? It uses those low order bytes of the result that can fit into the size of the ty pe allowed by the operation. 17. What is the Vector class? The Vector class provides the capability to implement a growable array of object

s 18. What modifiers may be used with an inner class that is a member of an outer class? A (non-local) inner class may be declared as public, protected, private, static, final, or abstract. 19. What is an Iterator interface? The Iterator interface is used to step through the elements of a Collection. 20. What is the difference between the >> and >>> operators? The >> operator carries the sign bit when shifting right. The >>> zero-fills bit s that have been shifted out. 21. Which method of the Component class is used to set the position and size of a component? setBounds() 22. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 charac ters? Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 b it patterns. UTF-16 uses 16bit and larger bit patterns. 23What is the difference between yielding and sleeping? When a task invokes its yield() method, it returns to the ready state. When a ta sk invokes its sleep() method, it returns to the waiting state. 24. Which java.util classes and interfaces support event handling? The EventObject class and the EventListener interface support event processing. 25. Is sizeof a keyword? The sizeof operator is not a keyword. 26. What are wrapped classes? Wrapped classes are classes that allow primitive types to be accessed as objects . 27. Does garbage collection guarantee that a program will not run out of memory? Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It i s also possible for programs to create objects that are not subject to garbage collection 28. What restrictions are placed on the location of a package statement within a source code file? A package statement must appear as the first line in a source code file (excludi ng blank lines and comments). 29. Can an object's finalize() method be invoked while it is reachable? An object's finalize() method cannot be invoked by the garbage collector while t he object is still reachable. However, an object's finalize() method may be invoked by other objects. 30. What is the immediate superclass of the Applet class? Panel 31. What is the difference between preemptive scheduling and time slicing? Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines wh ich task should execute next, based on priority and other factors. 32. Name three Component subclasses that support painting. The Canvas, Frame, Panel, and Applet classes support painting. 33. What value does readLine() return when it has reached the end of a file? The readLine() method returns null when it has reached the end of a file.

34. What is the immediate superclass of the Dialog class? Window 35. What is clipping? Clipping is the process of confining paint operations to a limited area or shape . 36. What is a native method? A native method is a method that is implemented in a language other than Java. 37. Can a for statement loop indefinitely? Yes, a for statement can loop indefinitely. For example, consider the following: for(;;) ; 38. What are order of precedence and associativity, and how are they used? Order of precedence determines the order in which operators are evaluated in exp ressions. Associatity determines whether an expression is evaluated left-to-right or right-to-left 39. When a thread blocks on I/O, what state does it enter? A thread enters the waiting state when it blocks on I/O. 40. To what value is a variable of the String type automatically initialized? The default value of an String type is null. 41. What is the catch or declare rule for method declarations? If a checked exception may be thrown within the body of a method, the method mus t either catch the exception or declare it in its throws clause. 42. What is the difference between a MenuItem and a CheckboxMenuItem? The CheckboxMenuItem class extends the MenuItem class to support a menu item tha t may be checked or unchecked. 43. What is a task's priority and how is it used in scheduling? A task's priority is an integer value that identifies the relative order in whic h it should be executed with respect to other tasks. The scheduler attempts to schedule higher priority tasks before lower priority tasks. 44. What class is the top of the AWT event hierarchy? The java.awt.AWTEvent class is the highest-level class in the AWT event-class hi erarchy. 45. When a thread is created and started, what is its initial state? A thread is in the ready state after it has been created and started. 46. Can an anonymous class be declared as implementing an interface and extendin g a class? An anonymous class may implement an interface or extend a superclass, but may no t be declared to do both. 47. What is the range of the short type? The range of the short type is -(2^15) to 2^15 - 1. 48. What is the range of the char type? The range of the char type is 0 to 2^16 - 1. 49. In which package are most of the AWT events that support the event-delegatio n model defined? Most of the AWT-related events of the event-delegation model are defined in the java.awt.event package. The AWTEvent class is defined in the java.awt package. 50. What is the immediate superclass of Menu? MenuItem 51. What is the purpose of finalization? The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected. 52. Which class is the immediate superclass of the MenuComponent class. Object 53. What invokes a thread's run() method? After a thread is started, via its start() method or that of the Thread class, t

he JVM invokes the thread's run() method when the thread is initially executed. 54. What is the difference between the Boolean & operator and the && operator? If an expression involving the Boolean & operator is evaluated, both operands ar e evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the seco nd operand is evaluated. The && operator is then applied to the first and second operands. If the first opera nd evaluates to false, the evaluation of the second operand is skipped. 55. Name three subclasses of the Component class. Box.Filler, Button, Canvas, Checkbox, Choice, Container, Label, List, Scrollbar, or TextComponent 56. What is the GregorianCalendar class? The GregorianCalendar provides support for traditional Western calendars. 57. Which Container method is used to cause a container to be laid out and redis played? validate() 58. What is the purpose of the Runtime class? The purpose of the Runtime class is to provide access to the Java runtime system . 59. How many times may an object's finalize() method be invoked by the garbage c ollector? An object's finalize() method may only be invoked once by the garbage collector. 60. What is the purpose of the finally clause of a try-catch-finally statement? The finally clause is used to provide the capability to execute code no matter w hether or not an exception is thrown or caught. 61. What is the argument type of a program's main() method? A program's main() method takes an argument of the String[] type. 62. Which Java operator is right associative? The = operator is right associative. 63. What is the Locale class? The Locale class is used to tailor program output to the conventions of a partic ular geographic, political, or cultural region. 64. Can a double value be cast to a byte? Yes, a double value can be cast to a byte. 65. What is the difference between a break statement and a continue statement? A break statement results in the termination of the statement to which it applie s (switch, for, do, or while). A continue statement is used to end the current loop iteration and return contro l to the loop statement. 66. What must a class do to implement an interface? It must provide all of the methods in the interface and identify the interface i n its implements clause. 67. What method is invoked to cause an object to begin executing as a separate t hread? The start() method of the Thread class is invoked to cause an object to begin ex ecuting as a separate thread. 68. Name two subclasses of the TextComponent class. TextField and TextArea 69. What is the advantage of the event-delegation model over the earlier event-i nheritance model? The event-delegation model has two advantages over the event-inheritance model. First, it enables event handling to be handled by objects other than the ones that generate the events ( or their containers). This

allows a clean separation between a component's design and its use. The other ad vantage of the eventdelegation model is that it performs much better in applications where many events are gene rated. This performance improvement is due to the fact that the event-delegation model does not have to repeatedly process unhandled events, as is the case of the event-inheritance model. 70. Which containers may have a MenuBar? Frame 71. How are commas used in the initialization and iteration parts of a for state ment? Commas are used to separate multiple statements within the initialization and it eration parts of a for statement. 72. What is the purpose of the wait(), notify(), and notifyAll() methods? The wait(),notify(), and notifyAll() methods are used to provide an efficient wa y for threads to wait for a shared resource. When a thread executes an object's wait() method, it enters the waiting state. It only enters the ready state after another thread invokes the object's notify() or notifyAll( ) methods. 73. What is an abstract method? An abstract method is a method whose implementation is deferred to a subclass. 74. How are Java source code files named? A Java source code file takes the name of a public class or interface that is de fined within the file. A source code file may contain at most one public class or interface. If a public class o r interface is defined within a source code file, then the source code file must take the name of the public cla ss or interface. If no public class or interface is defined within a source code file, then the file must take on a name that is different than its classes and interfaces. Source code files use the .java extension. 75. What is the relationship between the Canvas class and the Graphics class? A Canvas object provides access to a Graphics object via its paint() method. 76. What are the high-level thread states? The high-level thread states are ready, running, waiting, and dead. 77. What value does read() return when it has reached the end of a file? The read() method returns -1 when it has reached the end of a file. 78. Can a Byte object be cast to a double value? No, an object cannot be cast to a primitive value. 79. What is the difference between a static and a non-static inner class? A non-static inner class may have object instances that are associated with inst ances of the class's outer class. A static inner class does not have any object instances. 80. What is the difference between the String and StringBuffer classes? String objects are constants. StringBuffer objects are not. 81. If a variable is declared as private, where may the variable be accessed? A private variable may only be accessed within the class in which it is declared . 82. What is an object's lock and which object's have locks? An object's lock is a mechanism that is used by multiple threads to obtain synch ronized access to the object. A thread may execute a synchronized method of an object only after it has acquir ed the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object. 83. What is the Dictionary class? The Dictionary class provides the capability to store key-value pairs. 84. How are the elements of a BorderLayout organized?

The elements of a BorderLayout are organized at the borders (North, South, East, and West) and the center of a container. 85. What is the % operator? It is referred to as the modulo or remainder operator. It returns the remainder of dividing the first operand by the second operand. 86. When can an object reference be cast to an interface reference? An object reference be cast to an interface reference when the object implements the referenced interface. 87. What is the difference between a Window and a Frame? The Frame class extends Window to define a main application window that can have a menu bar. 88. Which class is extended by all other classes? The Object class is extended by all other classes. 89. Can an object be garbage collected while it is still reachable? A reachable object cannot be garbage collected. Only unreachable objects may be garbage collected.. 90. Is the ternary operator written x : y ? z or x ? y : z ? It is written x ? y : z. 91. What is the difference between the Font and FontMetrics classes? The FontMetrics class is used to define implementation-specific properties, such as ascent and descent, of a Font object. 92. How is rounding performed under integer division? The fractional part of the result is truncated. This is known as rounding toward zero. 93. What happens when a thread cannot acquire a lock on an object? If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available. 94. What is the difference between the Reader/Writer class hierarchy and the Inp utStream/ OutputStream class hierarchy? The Reader/Writer class hierarchy is character-oriented, and the InputStream/Out putStream class hierarchy is byte-oriented. 95. What classes of exceptions may be caught by a catch clause? A catch clause can catch any exception that may be assigned to the Throwable typ e. This includes the Error and Exception types. 96. If a class is declared without any access modifiers, where may the class be accessed? A class that is declared without any access modifiers is said to have package ac cess. This means that the class can only be accessed by other classes and interfaces that are defined with in the same package. 97. What is the SimpleTimeZone class? The SimpleTimeZone class provides support for a Gregorian calendar. 98. What is the Map interface? The Map interface replaces the JDK 1.1 Dictionary class and is used associate ke ys with values. 99. Does a class inherit the constructors of its superclass? A class does not inherit constructors from any of its superclasses. 100. For which statements does it make sense to use a label? The only statements for which it makes sense to use a label are those statements that can enclose a break or continue statement. 101. What is the purpose of the System class? The purpose of the System class is to provide access to system resources.

102. Which TextComponent method is used to set a TextComponent to the read-only state? setEditable() 103. How are the elements of a CardLayout organized? The elements of a CardLayout are stacked, one on top of the other, like a deck o f cards. 104. Is &&= a valid Java operator? No, it is not. 105. Name the eight primitive Java types. The eight primitive types are byte, char, short, int, long, float, double, and b oolean. 106. Which class should you use to obtain design information about an object? The Class class is used to obtain information about an object's design. 107. What is the relationship between clipping and repainting? When a window is repainted by the AWT painting thread, it sets the clipping regi ons to the area of the window that requires repainting. 108. Is "abc" a primitive value? The String literal "abc" is not a primitive value. It is a String object. 109. What is the relationship between an event-listener interface and an event-a dapter class? An event-listener interface defines the methods that must be implemented by an e vent handler for a particular kind of event. An event adapter provides a default implementation of an event-listener interface. 110. What restrictions are placed on the values of each case of a switch stateme nt? During compilation, the values of each case of a switch statement must evaluate to a value that can be promoted to an int value. 111. What modifiers may be used with an interface declaration? An interface may be declared as public or abstract. 112. Is a class a subclass of itself? A class is a subclass of itself. 113. What is the highest-level event class of the event-delegation model? The java.util.EventObject class is the highest-level class in the event-delegati on class hierarchy. 114. What event results from the clicking of a button? The ActionEvent event is generated as the result of the clicking of a button. 115. How can a GUI component handle its own events? A component can handle its own events by implementing the required event-listene r interface and adding itself as its own event listener. 116. What is the difference between a while statement and a do statement? A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once. 117. How are the elements of a GridBagLayout organized? The elements of a GridBagLayout are organized according to a grid. However, the elements are of different sizes and may occupy more than one row or column of the grid. In addition, the r ows and columns may have different sizes. 118. What advantage do Java's layout managers provide over traditional windowing systems? Java uses layout managers to lay out components in a consistent manner across al l windowing platforms. Since Java's layout managers aren't tied to absolute sizing and positioning, the

y are able to accomodate platform-specific differences among windowing systems. 119. What is the Collection interface? The Collection interface provides support for the implementation of a mathematic al bag - an unordered collection of objects that may contain duplicates. 120. What modifiers can be used with a local inner class? A local inner class may be final or abstract. 121. What is the difference between static and non-static variables? A static variable is associated with the class as a whole rather than with speci fic instances of a class. Nonstatic variables take on unique values with each object instance. 122. What is the difference between the paint() and repaint() methods? The paint() method supports painting via a Graphics object. The repaint() method is used to cause paint() to be invoked by the AWT painting thread. 123. What is the purpose of the File class? The File class is used to create objects that provide access to the files and di rectories of a local file system. 124. Can an exception be rethrown? Yes, an exception can be rethrown. 125. Which Math method is used to calculate the absolute value of a number? The abs() method is used to calculate absolute values. 126. How does multithreading take place on a computer with a single CPU? The operating system's task scheduler allocates execution time to multiple tasks . By quickly switching between executing tasks, it creates the impression that tasks execute sequential ly. 127. When does the compiler supply a default constructor for a class? The compiler supplies a default constructor for a class if no other constructors are provided. 128. When is the finally clause of a try-catch-finally statement executed? The finally clause of the try-catch-finally statement is always executed unless the thread of execution terminates or an exception occurs within the execution of the finally clause. 129. Which class is the immediate superclass of the Container class? Component 130. If a method is declared as protected, where may the method be accessed? A protected method may only be accessed by classes or interfaces of the same pac kage or by subclasses of the class in which it is declared. 131. How can the Checkbox class be used to create a radio button? By associating Checkbox objects with a CheckboxGroup. 132. Which non-Unicode letter characters may be used as the first character of a n identifier? The non-Unicode letter characters $ and _ may appear as the first character of a n identifier 133. What restrictions are placed on method overloading? Two methods may not have the same name and argument list but different return ty pes. 134. What happens when you invoke a thread's interrupt method while it is sleepi ng or waiting? When a task's interrupt() method is executed, the task enters the ready state. T he next time the task enters the running state, an InterruptedException is thrown. 135. What is casting? There are two types of casting, casting between primitive numeric types and cast ing between object references. Casting between numeric types is used to convert larger values, such as double values, to

smaller values, such as byte values. Casting between object references is used t o refer to an object by a compatible class, interface, or array type reference. 136. What is the return type of a program's main() method? A program's main() method has a void return type. 137. Name four Container classes. Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane 138. What is the difference between a Choice and a List? A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices. Only one item may be selected from a Choice. A List may be displayed in such a way that several List items are visible. A List supports the selection of one or more List items. 139. What class of exceptions are generated by the Java run-time system? The Java runtime system generates RuntimeException and Error exceptions. 140. What class allows you to read objects directly from a stream? The ObjectInputStream class supports the reading of objects from input streams. 141. What is the difference between a field variable and a local variable? A field variable is a variable that is declared as a member of a class. A local variable is a variable that is declared local to a method. 142. Under what conditions is an object's finalize() method invoked by the garba ge collector? The garbage collector invokes an object's finalize() method when it detects that the object has become unreachable. 143. How are this() and super() used with constructors? this() is used to invoke a constructor of the same class. super() is used to inv oke a superclass constructor. 144. What is the relationship between a method's throws clause and the exception s that can be thrown during the method's execution? A method's throws clause must declare any checked exceptions that are not caught within the body of the method. 145. What is the difference between the JDK 1.02 event model and the event-deleg ation model introduced with JDK 1.1? The JDK 1.02 event model uses an event inheritance or bubbling approach. In this model, components are required to handle their own events. If they do not handle a particular event, t he event is inherited by (or bubbled up to) the component's container. The container then either handles the event or it is bubbled up to its container and so on, until the highest-level container has been tried. In the event-delegation model, specific objects are designated as event handlers for GUI components. These objects implement event-listener interfaces. The event-delegation model is more efficient than the event-inheritance model because it eliminates the processing required to support the bubbling of unhandled events. 146. How is it possible for two String objects with identical values not to be e qual under the == operator? The == operator compares two objects to determine if they are the same object in memory. It is possible for two String objects to have the same value, but located indifferent areas of memo ry. 147. Why are the methods of the Math class static?

So they can be invoked as if they are a mathematical code library. 148. What Checkbox method allows you to tell if a Checkbox is checked? getState() 149. What state is a thread in when it is executing? An executing thread is in the running state. 150. What are the legal operands of the instanceof operator? The left operand is an object reference or null value and the right operand is a class, interface, or array type. 151. How are the elements of a GridLayout organized? The elements of a GridBad layout are of equal size and are laid out using the sq uares of a grid. 152. What an I/O filter? An I/O filter is an object that reads from one stream and writes to another, usu ally altering the data in some way as it is passed from one stream to another. 153. If an object is garbage collected, can it become reachable again? Once an object is garbage collected, it ceases to exist. It can no longer become reachable again. 154. What is the Set interface? The Set interface provides methods for accessing the elements of a finite mathem atical set. Sets do not allow duplicate elements. 155. What classes of exceptions may be thrown by a throw statement? A throw statement may throw any expression that may be assigned to the Throwable type. 156. What are E and PI? E is the base of the natural logarithm and PI is mathematical value pi. 157. Are true and false keywords? The values true and false are not keywords. 158. What is a void return type? A void return type indicates that a method does not return a value. 159. What is the purpose of the enableEvents() method? The enableEvents() method is used to enable an event for a particular object. No rmally, an event is enabled when a listener is added to an object for a particular event. The enableEvents() method is used by objects that handle events by overriding their event-dispatch methods. 160. What is the difference between the File and RandomAccessFile classes? The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a f ile. 161. What happens when you add a double value to a String? The result is a String object. 162. What is your platform's default character encoding? If you are running Java on English Windows platforms, it is probably Cp1252. If you are running Java on English Solaris platforms, it is most likely 8859_1.. 163. Which package is always imported by default? The java.lang package is always imported by default. 164. What interface must an object implement before it can be written to a strea m as an object? An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object. 165. How are this and super used? this is used to refer to the current object instance. super is used to refer to the variables and methods of the superclass of the current object instance. 166. What is the purpose of garbage collection?

The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources may be reclaimed and reused. 167. What is a compilation unit? A compilation unit is a Java source code file. 168. What interface is extended by AWT event listeners? All AWT event listeners extend the java.util.EventListener interface. 169. What restrictions are placed on method overriding? Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides. The overriding method may not t hrow any exceptions that may not be thrown by the overridden method. 170. How can a dead thread be restarted? A dead thread cannot be restarted. 171. What happens if an exception is not caught? An uncaught exception results in the uncaughtException() method of the thread's ThreadGroup being invoked, which eventually results in the termination of the program in which it is thrown. 172. What is a layout manager? A layout manager is an object that is used to organize components in a container . 173. Which arithmetic operations can result in the throwing of an ArithmeticExce ption? Integer / and % can result in the throwing of an ArithmeticException. 174. What are three ways in which a thread can enter the waiting state? A thread can enter the waiting state by invoking its sleep() method, by blocking on I/O, by unsuccessfully attempting to acquire an object's lock, or by invoking an object's wait() method . It can also enter the waiting state by invoking its (deprecated) suspend() method. 175. Can an abstract class be final? An abstract class may not be declared as final. 176. What is the ResourceBundle class? The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program's appearance to the particular locale in which it is being ru n. 177. What happens if a try-catch-finally statement does not have a catch clause to handle an exception that is thrown within the body of the try statement? The exception propagates up to the next higher level try-catch statement (if any ) or results in the program's termination. 178. What is numeric promotion? Numeric promotion is the conversion of a smaller numeric type to a larger numeri c type, so that integer and floating-point operations may take place. In numerical promotion, byte, char, an d short values are converted to int values. The int values are also converted to long values, if ne cessary. The long and float values are converted to double values, as required. 179. What is the difference between a Scrollbar and a ScrollPane? A Scrollbar is a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling. 180. What is the difference between a public and a non-public class? A public class may be accessed outside of its package. A non-public class may no t be accessed outside of

its package. 181. To what value is a variable of the boolean type automatically initialized? The default value of the boolean type is false. 182. Can try statements be nested? Try statements may be tested. 183. What is the difference between the prefix and postfix forms of the ++ opera tor? The prefix form performs the increment operation and returns the value of the in crement operation. The postfix form returns the current value all of the expression and then performs t he increment operation on that value. 184. What is the purpose of a statement block? A statement block is used to organize a sequence of statements as a single state ment group. 185. What is a Java package and how is it used? A Java package is a naming context for classes and interfaces. A package is used to create a separate name space for groups of classes and interfaces. Packages are also used to organize r elated classes and interfaces into a single API unit and to control accessibility to these classes and interfa ces. 186. What modifiers may be used with a top-level class? A top-level class may be public, abstract, or final. 187. What are the Object and Class classes used for? The Object class is the highest-level class in the Java class hierarchy. The Cla ss class is used to represent the classes and interfaces that are loaded by a Java program. 188. How does a try statement determine which catch clause should be used to han dle an exception? When an exception is thrown within the body of a try statement, the catch clause s of the try statement are examined in the order in which they appear. The first catch clause that is capab le of handling the exception is executed. The remaining catch clauses are ignored. 189. Can an unreachable object become reachable again? An unreachable object may become reachable again. This can happen when the objec t's finalize() method is invoked and the object performs an operation which causes it to become accessibl e to reachable objects. 190. When is an object subject to garbage collection? An object is subject to garbage collection when it becomes unreachable to the pr ogram in which it is used. 191. What method must be implemented by all threads? All tasks must implement the run() method, whether they are a subclass of Thread or implement the Runnable interface. 192. What methods are used to get and set the text label displayed by a Button o bject? getLabel() and setLabel() 193. Which Component subclass is used for drawing and painting? Canvas 194. What are synchronized methods and synchronized statements? Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or cl ass. Synchronized statements are similar to synchronized methods. A synchronized statement can onl y be executed after a thread has acquired the lock for the object or class referenced in the synchroni

zed statement. 195. What are the two basic ways in which classes that can be run as threads may be defined? A thread class may be declared as a subclass of Thread, or it may implement the Runnable interface. 196. What are the problems faced by Java programmers who don't use layout manage rs? Without layout managers, Java programmers are faced with determining how their G UI will be displayed across multiple windowing systems and finding a common sizing and positioning th at will work within the constraints imposed by each windowing system. 197. What is the difference between an if statement and a switch statement? The if statement is used to select among two alternatives. It uses a boolean exp ression to decide which alternative should be executed. The switch statement is used to select among mul tiple alternatives. It uses an int expression to determine which alternative should be executed. 198. What is the List interface? The List interface provides support for ordered collections of objects. Most frequent questions 0) Q: Java and C++ A: Some of the similarities and differences are in the table: Features Java C/C++ Pointer No Yes Operator Overload No Yes Typedef, Define, Preprocessors No Yes Structures, Unions No Yes Enums No Yes Functions No (only methods within classes) Yes Goto statement No Yes Automatic CoercionsNo(types should be converted explicitly) Yes Global Variables No. Variable is part of a class Yes Templates No Yes Private, Protected, Public Inheritance No Yes Default parameters No Yes Garbage Collection Yes No Multi-thread support Yes No Multiple Inheritance Yes. Supports only interface inheritance and not implementation inheritance! Yes Exception Handling Yes. try/catch must be defined if the function declares that it may throw an exc eption. Yes. You may not include the try/catch even if the function throws an exception. Function Overload Yes Yes Internationalization Yes Yes Include of other Objects #import #include Comments "//","/* */,/** */ "//","/* */" 1) Q: What is the purpose of the toolkit in the Abstract Window Toolkit (AWT)? H ow does AWT work ? A: The AWT toolkit is an interface between the abstract window layer and a speci fic windowing implementation. 2) Q: What is layout manager ? How does it work ? A: A layout manager is an object that positions and resizes the components in a

Container according to some algorithm; for example, the FlowLayout layout manager lays out components f rom left to right until it runs out of room and then continues laying out components below that row. 3) Q: Advantages and disadvantages of layout manager ? 4) Q: Compare SWING components to standard AWT. A: Swing is an extension of, and not a replacement for the AWT. There is some ov erlap between AWT and Swing (for example a Swing JButton component might be viewed as an improved func tional replacement for an AWT Button component.) One of the advantages of Swing components is that because the components are not rendered on the screen by the operating system, the look and feel of a component does not change as the application or applet is executed on different platforms runni ng under different operating systems. Furthermore, it is possible to cause Swing components to mimic the look and feel of a specific platform no matter what platform the program is running on. This is known as plu ggable look and feel. Swing components support the JDK 1.1 Delegation Event Model. From an event handling viewpoint, Swing components opera te the same as AWT components (except that Swing provides a number of new event types). Many Sw ing components don't have an AWT counterpart. A number of new and exciting components are inclu ded in the Swing library that don't exist in the AWT (tooltips, progress bars, trees, etc.) 5) Q: What is Java Beans ? A: According to JavaSoft, "A Java Bean is a reusable software component that can be manipulated visually in a builder tool." 6) Q: What you know about Corba implementation in Java ? A: Java 1.2 promises full CORBA IDL support. 7) Q: What do you know about networking support in Java ? A: Java supports "low-level" and "high-level" classes. "Low-level" classes provi de support for socket programming: Socket, DatagramSocket, and ServerSocket classes. "High-level" clas ses provide "Web programming": URL, URLEncoder, and URLConnection classes. Networking programming classes ease the programming of network applications, but do not substitute your knowledge of networking. Java networking like anything else in Java is platform-independent. 8) Q: What is it object serialization ? A: Serialization is a way to convert objects (including complex data structures such as lists and trees) into a stream of bytes. 9) Q: How to make application thread-safe ? A: You should use the word synchronized to mark the critical section of code. Yo u may also use other methods of thread synchronization (see wait(), notify(), notifyAll() etc. 10) Q: What is it reflection (introspection) ? Why is reflection possible in the Java language? A: Reflection (introspection) is querying a class about its properties, and oper ating on methods and fields by the name for a given object instance. Reflection is possible in the Ja va language because of late binding. 11) Q: Why are Java ARchive (JAR) files important?

A: JAR files bundle .class files and optimize applet downloads. Following answer may not be correct 12) Describe what happens when an object is created in Java Several things happen in a particular order to ensure the object is constructed properly: 1. Memory is allocated from heap to hold all instance variables and implementati on-specific data of the object and its superclasses. Implemenation-specific data includes pointers to cl ass and method data. 2. The instance variables of the objects are initialized to their default values . 3. The constructor for the most derived class is invoked. The first thing a cons tructor does is call the consctructor for its superclasses. This process continues until the constrcutor for java.lang.Object is called, as java.lang.Object is the base class for all objects in java. 4. Before the body of the constructor is executed, all instance variable initial izers and initialization blocks are executed. Then the body of the constructor is executed. Thus, the constructo r for the base class completes first and constructor for the most derived class completes last. 13) In Java, You can create a String object as below : String str = "abc"; & Str ing str = new String("abc"); Why cant a button object be created as : Button bt = "abc" Why is it compulsory to create a button object as: Button bt = new Button("abc"); Why this is not compulsory in String's case. The main reason you cannot create a button by Button bt1= "abc"; is because "abc" is a literal string (something slightly different than a String object, by-the-way) and bt1 is a Button object. That simple. The only object in Java that can be assigned a lit eral String is java.lang.String. Important to not that you are NOT calling a java.lang.String constuctor when you type String s = "abc"; For example String x = "abc"; String y = "abc"; refer to the same object. While String x1 = new String("abc"); String x2 = new String("abc"); refer to two different objects. 14) What are the main differences between Java and C++? Everything is an object in Java( Single root hierarchy as everything gets derive d from java.lang.Object) Java does not have all the complicated aspects of C++ ( For ex: Pointers, templa tes, unions, operator overloading, structures etc..) The Java language promoters initially said "No pointers!", but when many program mers questioned how you can work without pointers, the promoters began saying "Restricted pointers." You can make up your mind whether it's really a pointer or not. In any event, there's no pointer arit hmetic. There are no destructors in Java. (automatic garbage collection) Java does not support conditional compile (#ifdef/#ifndef type). Thread support is built into java but not in C++. Java does not support default arguments. There's no scope resolution operator :: in Java. Java uses the dot for everything, but can get away with it since you can define elements only

within a class. Even the method definitions must always occur within a class, so there is no need for sco pe resolution there either. There's no "goto " statement in Java. Java doesn't provide multiple inheritance (MI), at least not in the same sense t hat C++ does. Exception handling in Java is different because there are no destructors. Java has method overloading, but no operator overloading. The String class does use the + and += operators to concatenate strings and String expressions use automatic type conve rsion, but that's a special built-in case. Java is interpreted for the most part and hence platform independent. 15) What are interfaces? Interfaces provide more sophisticated ways to organize and control the objects i n your system. The interface keyword takes the abstract concept one step further. You could thi nk of it as a "pure" abstract class. It allows the creator to establish the form for a class: method names, ar gument lists, and return types, but no method bodies. An interface can also contain fields, but The inter face keyword takes the abstract concept one step further. You could think of it as a "pure" abstract cl ass. It allows the creator to establish the form for a class: method names, argument lists, and return types, but no method bodies. An interface can also contain fields, but An interface says: "This is what all classes that implement this particular inte rface will look like." Thus, any code that uses a particular interface knows what methods might be called for that interface, and that's all. So the interface is used to establish a "protocol" between classes. (Some o bject-oriented programming languages have a keyword called protocolto do the same thing.) 15) How can you achieve Multiple Inheritance in Java? Java's interface mechanism can be used to implement multiple inheritance, with o ne important difference from c++ way of doing MI: the inherited interfaces must be abstract. This obviat es the need to choose between different implementations, as with interfaces there are no implementatio ns. 16) What is the difference between StringBuffer and String class? A string buffer implements a mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of character s, but the length and content of the sequence can be changed through certain method calls. The String class represents character strings. All string literals in Java progr ams, such as "abc" are constant and implemented as instances of this class; their values cannot be changed after they are created. 17) Describe, in general, how java's garbage collector works? The Java runtime environment deletes objects when it determines that they are no longer being used. This process is known as garbage collection. The Java runtime environment supports a garbage collector that periodically free s the memory used by objects that are no longer needed. The Java garbage collector is a mark-sweep ga rbage collector that scans

Java's dynamic memory areas for objects, marking those that are referenced. Afte r all possible paths to objects are investigated, those objects that are not marked (i.e. are not refere nced) are known to be garbage and are collected. 18) What's the difference between == and equals method? The equals method can be considered to perform a deep comparison of the value of an object, whereas the == operator performs a shallow comparison. The equals() method compares the characters inside a string object. == operator compares two object references to check whether they refer to the same instances or not. 19) What are abstract classes, abstract methods? Simply speaking a class or a method qualified with "abstract" keyword is an abst ract class or abstract method. You create an abstract class when you want to manipulate a set of classes throug h a common interface. All derived-class methods that match the signature of the base-class declaration wil l be called using the dynamic binding mechanism. An abstract method is an incomplete method. It has only a declaration and no met hod body. Here is the syntax for an abstract method declaration: abstract void f(); 20) How can you force all derived classes to implement a method present in the b ase class? Creating and implementing an interface would be the best way for this situation. Just create an interface with empty methods which forces a programmer to implement all the methods presen t under it. Another way of achieving this task is to declare a class as abstract with all it s methods abstract. 21) What is the difference between an Applet and an Application? 1. Applets can be embedded in HTML pages and downloaded over the Internet wherea s Applications have no special support in HTML for embedding or downloading. 2. Applets can only be executed inside a java compatible container, such as a br owser or appletviewer whereas Applications are executed at command line by java.exe or jview.exe. 3. Applets execute under strict security limitations that disallow certain opera tions(sandbox model security) whereas Applications have no inherent security restrictions. 4. Applets don't have the main() method as in applications. Instead they operate on an entirely different mechanism where they are initialized by init(),started by start(),stopped by sto p() or destroyed by destroy(). 22) Java says "write once, run anywhere". What are some ways this isn't quite tr ue? Any time you use system calls specific to one operating system and do not create alternative calls for another operating system, your program will not function correctly. Solaris systems and Intel systems order the bits of an integer differently. (You may have heard of little endian vs. big endian) If your code uses bit shifting, or other binary operators, they will not work on systems that have opposide endianism. 23) Describe java's security model. Java's security model is one of the most interesting and unique aspects of the l anguage. For the most part

it's broken into two pieces: the user adjustable security manager that checks va rious API operations like file access, and the byte code verifier that asserts the validity of compiled byte co de. public abstract class SecurityManager java.lang.SecurityManager is an abstract c lass which different applications subclass to implement a particular security policy. It allows an ap plication to determine whether or not a particular operation will generate a security exception. 24) What is the difference between a Vector and an Array. Discuss the advantages and disadvantages of both? The vector container class generalizes the concept of an ordinary C array. Like an array, a vector is an indexed data structure, with index values that range from 0 to one less than the number of elements contained in the structure. Also like an array, values are most commonly assigne d to and extracted from the vector using the subscript operator. However, the vector differs from an array i n the following important respects: The size of the vector can change dynamically. New elements can be inserted on t o the end of a vector, or into the middle. It is important to note, however, that while these abilities ar e provided, insertion into the middle of a vector is not as efficient as insertion into the middle of a list. A vector has more "self-knowledge" than an ordinary array. In particular, a vect or can be queried about its size, about the number of elements it can potentially hold (which may be differe nt from its current size), and so on. A vector can only hold references to objects and not primitive types. Vector Implementaions are usually slower then array because of all the functiona lity that comes with them. As implemented in Java, vector is a thread-safe class and hence all methods are synchronous methods, which makes them considerably slow. 25) How many different types of JDBC drivers are present? Discuss them. Type 1: JDBC-ODBC Bridge plus ODBC Driver: The first type of JDBC driver is the JDBC-ODBC Bridge. It is a driver that provi des JDBC access to databases through ODBC drivers. The ODBC driver must be configured on the client for the bridge to work. This driver type is commonly used for prototyping or when there is no JDBC driver available for a particular DBMS. Type 2: Native-API partly-Java Driver: The Native to API driver converts JDBC commands to DBMS-specific native calls. T his is much like the restriction of Type 1 drivers. The client must have some binary code loaded on i ts machine. These drivers do have an advantage over Type 1 drivers because they interface directly with th e database. Type 3: JDBC-Net Pure Java Driver: The JDBC-Net drivers are a three-tier solution. This type of driver translates J DBC calls into a databaseindependent network protocol that is sent to a middleware server. This server then translate s this DBMSindependent protocol into a DBMS-specific protocol, which is sent to a particular database. The results are

then routed back through the middleware server and sent back to the client. This type of solution makes it possible to implement a pure Java client. It also makes it possible to swap data bases without affecting the client. Type 4: Native-Protocol Pur Java Driver These are pure Java drivers that communicate directly with the vendor's database . They do this by converting JDBC commands directly into the database engine's native protocol. Th is driver has no additional translation or middleware layer, which improves performance tremendou sly. 26) What does the keyword "synchronize" mean in java. When do you use it? What a re the disadvantages of synchronization? Synchronize is used when u want to make ur methods thread safe. The disadvantage of synchronise is it will end up in slowing down the program. Also if not handled properly it will en d up in dead lock. 1. Only use (and minimize it's use)synchronization when writing multithreaded co de as there is a speed (up to five to six time slower, depending on the execution time of the synchronized/ non-synchronized method ) cost associated with its use. 2. In case of syncronized method modifier, the byte code generated is the exact same as non-syncronized method. The only difference is that a flag called ACC_SYNCRONIZED property flag in method's method_info structure is set if the syncronized method modifier is present. 3. Also, syncronized keyword can make the code larger in size if used in the bod y of the method as bytecode for monitorenter/monitorexit is generated in addition to any exception handling. 27) What are native methods? How do you use them? Native methods are methods that are defined as public static methods within a ja va class, but whose implementation is provided in another programming language such as C. 28) What is RMI? RMI stands for Remote Method Invocation. Traditional approaches to executing cod e on other machines across a network have been confusing as well as tedious and error-prone to imple ment. The nicest way to think about this problem is that some object happens to live on another machine, and that you can send a message to the remote object and get a result as if the object lived on your loc al machine. This simplification is exactly what Java Remote Method Invocation (RMI) allows you to do. 29) What is JDBC? Describe the steps needed to execute a SQL query using JDBC. The JDBC is a pure Java API used to execute SQL statements. It provides a set of classes and interfaces that can be used by developers to write database applications. The steps needed to execute a SQL query using JDBC: 1. Open a connection to the database. 2. Execute a SQL statement. 3. Process th results. 4. Close the connection to the database. 30) Access specifiers: "public", "protected", "private", nothing? Public - any other class from any package can instantiate and execute the classe s and methods

Protected - only subclasses and classes inside of the package can access the cla sses and methods Private - the original class is the only class allowed to executed the methods. 31) What does the "final" keyword mean in front of a variable? A method? A class ? FINAL for a variable : value is constant FINAL for a method : cannot be overridden FINAL for a class : cannot be derived 32) Does Java have "goto"? no 33) Why "bytecode"? Can you reverse-engineer the code from bytecode? 34) What synchronization constructs does Java provide? How do they work? 35) Are constructors inherited? Can a subclass call the parent's class construct or? When? You cannot inherit a constructor. That is, you cannot create a instance of a sub class using a constructor of one of it's superclasses. One of the main reasons is because you probably don't want to overide the superclasses constructor, which would be possible if they were inherited. By giv ing the developer the ability to override a superclasses constructor you would erode the encapsulation abilities of the language. 36) Does Java have destructors? No garbage collector does the job working in the background 37) What does the "abstract" keyword mean in front of a method? A class? Abstract keyword declares either a method or a class. If a method has a abstract keyword in front of it,it is called abstract method.Abstract method hs no body.It has only arguments and retu rn type.Abstract methods act as placeholder methods that are implemented in the subclasses. Abstract classes can't be instantiated.If a class is declared as abstract,no obj ects of that class can be created.If a class contains any abstract method it must be declared as abstract 38) Name four methods every Java class will have. public String toString(); public Object clone(); public boolean equals(); public int hashCode(); 39) Given a text file, input.txt, provide the statement required to open this file with the appropriate I/O stream to be able to read and process this fi le. 40) Discuss the differences between creating a new class, extending a class and implementing an interface; and when each would be appropriate. *Creating a new class is simply creating a class with no extensions and no implementations. The signature is as follows public class MyClass() { } *Extending a class is when you want to use the functionality of another class or classes. The extended class inherits all of the functionality of the previous cl ass. An example of this when you create your own applet class and extend from java.applet.Applet. This gives you all of the functionality of the java.applet.A pplet class. The signature would look like this public class MyClass extends MyBaseClass { } *Implementing an interface simply forces you to use the methods of the interface

implemented. This gives you two advantages. This forces you to follow a standard (forces you to use certain methods) and in doing so gives you a channel for polymorphism. This isn't the only way you can do polymorphism but this is one of the ways. public class Fish implements Animal { } 40) What's the difference between the == operator and the equals() method? What test does Object.equals() use, and why? The == operator would be used, in an object sense, to see if the two objects wer e actually the same object. This operator looks at the actually memory address to see if it actually the same object. The equals() method is used to compare the values of t he object respectively. This is used in a higher level to see if the object values are equal. Of course the the equals() method would be overloaded in a meaningful way for whatever object that you were working with. 41) why do you create interfaces, and when MUST you use one. You would create interfaces when you have two or more functionalities talking to each other. Doing it this way help you in creating a protocol between the parties involved. 42) What is the difference between instanceof and isInstance? instanceof is used to check to see if an object can be cast into a specified typ e without throwing a cast class exception. isInstance() Determines if the specified Object is assignment-compatible with the object repr esented by this Class. This method is the dynamic equivalent of the Java language instan ceof operator. The method returns true if the specified Object argument is non-null a nd can be cast to the reference type represented by this Class object without raising a ClassCastException. It returns false otherwise. 43) How many methods do u implement if implement the Serializable Interface? The Serializable interface is just a "marker" interface, with no methods of its own to implement. Are there any other 'marker' interfaces? java.rmi.Remote java.util.EventListener 44) *What are the advantages of developing an n-tiered system? 45) *Why is it often difficult to separate the business layer from the data acce ss layer? 46) . Diff between ArrayList and Vector 47) Variable shadowing with example 1. What is the diffrence between an Abstract class and Interface ? 2. What is user defined exception ? 3. What do you know about the garbate collector ? 4. What is the difference between C++ & Java ? 5. Explain RMI Architecture? 6. How do you communicate in between Applets & Servlets ? 7. What is the use of Servlets ? 8. What is JDBC? How do you connect to the Database ? 9. In an HTML form I have a Button which makes us to open another page in 15 sec onds. How will do you that ?

10. What is the difference between Process and Threads ? 11. What is the difference between RMI & Corba ? 12. What are the services in RMI ? 13. How will you initialize an Applet ? 14. What is the order of method invocation in an Applet ? 15. When is update method called ? 16. How will you pass values from HTML page to the Servlet ? 17. Have you ever used HashTable and Dictionary ? 18. How will you communicate between two Applets ? 19. What are statements in JAVA ? 20. What is JAR file ? 21. What is JNI ? 22. What is the base class for all swing components ? 23. What is JFC ? 24. What is Difference between AWT and Swing ? 25. Considering notepad/IE or any other thing as process, What > will happen if you start notepad or IE 3 times? Where 3 processes are started or 3 threads are started ? 26. How does thread synchronization occurs inside a monitor ? 27. How will you call an Applet using a Java Script function ? 28. Is there any tag in HTML to upload and download files ? 29. Why do you Canvas ? 30. How can you push data from an Applet to Servlet ? 31. What are 4 drivers available in JDBC ? 32. How you can know about drivers and database information ? 33. If you are truncated using JDBC, How can you know ..that how much > > > data is truncated ? 34. And What situation , each of the 4 drivers used ? 35. How will you perform transaction using JDBC ? 36. In RMI, server object first loaded into the memory and then the stub referen ce is sent to the client ? or whether a stub reference is directly sent to the client ? 37. Suppose server object is not loaded into the memory, and theclient request f or it , what will happen? 38. What is serialization ? 39. Can you load the server object dynamically? If so, what are the major 3 step s involved in it ? 40. What is difference RMI registry and OSAgent ? 41. To a server method, the client wants to send a value 20, with this value exc eeds to 20,. a message should be sent to the client ? What will you do for achieving for this ? 42. What are the benefits of Swing over AWT ? 43. Where the CardLayout is used ? 44. What is the Layout for ToolBar ? 45. What is the difference between Grid and GridbagLayout ? 46. How will you add panel to a Frame ? 47. What is the corresponding Layout for Card in Swing ? 48. What is light weight component ? 49. Can you run the product development on all operating systems ? 50. What is the webserver used for running the Servlets ? 51. What is Servlet API used for conneting database ? 52. What is bean ? Where it can be used ? 53. What is difference in between Java Class and Bean ? 54. Can we send object using Sockets ? 55. What is the RMI and Socket ? 56. How to communicate 2 threads each other ? 57. What are the files generated after using IDL to Java Compilet ? 58. What is the protocol used by server and client ? 59. Can I modify an object in CORBA ? 60. What is the functionality stubs and skeletons ?

61. What is the mapping mechanism used by Java to identify IDL language ? 62. Diff between Application and Applet ? 63. What is serializable Interface ? 64. What is the difference between CGI and Servlet ? 65. What is the use of Interface ? 66. Why Java is not fully objective oriented ? 67. Why does not support multiple Inheritance ? 68. What it the root class for all Java classes ? 69. What is polymorphism ? 70. Suppose If we have variable ' I ' in run method, If I can create one or more thread each thread will occupy a separate copy or same variable will be shared ? 71. In servlets, we are having a web page that is invoking servlets username and password ? which is cheks in the database ? Suppose the second page also If we want to verify the same inf ormation whether it will connect to the database or it will be used previous information? 72. What are virtual functions ? 73. Write down how will you create a binary Tree ? 74. What are the traverses in Binary Tree ? 75. Write a program for recursive Traverse ? 76. What are session variable in Servlets ? 77. What is client server computing ? 78. What is Constructor and Virtual function? Can we call Virtual funciton in a constructor ? 79. Why we use OOPS concepts? What is its advantage ? 80. What is the middleware ? What is the functionality of Webserver ? 81. Why Java is not 100 % pure OOPS ? ( EcomServer ) 82. When we will use an Interface and Abstract class ? 83. What is an RMI? 84. How will you pass parameters in RMI ? Why u serialize? 85. What is the exact difference in between Unicast and Multicast object ? Where we will use ? 86. What is the main functionality of the Remote Reference Layer ? 87. How do you download stubs from a Remote place ? 88. What is the difference in between C++ and Java ? can u explain in detail ? 89. I want to store more than 10 objects in a remote server ? Which methodology will follow ? 90. What is the main functionality of the Prepared Statement ? 91. What is meant by static query and dynamic query ? 92. What are the Normalization Rules ? Define the Normalization ? 93. What is meant by Servelet? What are the parameters of the service method ? 94. What is meant by Session ? Tell me something about HTTPSession Class ? 95. How do you invoke a Servelt? What is the difference in between doPost and do Get methods ? 96. What is the difference in between the HTTPServlet and Generic Servlet ? Expa lin their methods ? Tell me their parameter names also ? 97. Have you used threads in Servelet ? 98. Write a program on RMI and JDBC using StoredProcedure ? 99. How do you sing an Applet ? 100. In a Container there are 5 components. I want to display the all the compon ents names, how will you do that one ? 101. Why there are some null interface in java ? What does it mean ? Give me som e null interfaces in JAVA ? 102. Tell me the latest versions in JAVA related areas ? 103. What is meant by class loader ? How many types are there? When will we use them ?

104. How do you load an Image in a Servlet ? 105. What is meant by flickering ? 106. What is meant by distributed Application ? Why we are using that in our app lications ? 107. What is the functionality of the stub ? 108. Have you used any version control ? 109. What is the latest version of JDBC ? What are the new features are added in that ? 110. Explain 2 tier and 3 -tier Architecture ? 111. What is the role of the webserver ? 112. How have you done validation of the fileds in your project ? 113. What is the main difficulties that you are faced in your project ? 114. What is meant by cookies ? Explain ? Make sure you have a copy of your resume in front of you. OK to have a cheat she et or two - just don't let anyone hear papers shuffling. Know your OOA&D definitions, such as polymorphism, inheritance, etc. Know the difference between an interface and an abstract class. Know that Java does not support multiple inheritance the way C++ does. Know that you implement an interface (can implement more than one). Know that you extend an abstract class (can only extend more than one). Know about the access modifiers: public/friendly(default)/protected/private. Be able to explain in one or two sentences for each case. This is where you can get tangled up in a phone con versation and confuse the heck out of the interviewer and yourself. Know AWT Event Model - tough to do over the phone - but you may get hit on a que stion. Know the two ways to start a thread - "extending Thread" or "implementing Runnab le". Know that the method is "run" but to run a thread you use "start". 1. How can I improve the performance of a java application, what are the java op timization techniques. That question is about as meaningful as "how do you code stuff?" There's no one right answer, and the interviewer probably just wanted to see if you knew *anything* about optimizatio n. The answer is to go to the Performance thread and read the postings. If you search there for "books", y ou should find some good references which will get you started. You should also search for "tools". quote: 2. What should you do to ensure that your applet works exactly the same way on b oth IE and netscape. Short answers include: make sure they use the same JVM, don't use complex GUIs, and most importantly test to be certain! Personally, I'd question the benefit of the applet and ask i f could be done with JSPs. Q - What is difference btweeen abstract class and interface In Java, under what circumstances would you use abstract classes instead of interfaces? When you declare a method as abstract, can other nonabstract methods access it? In general, could you explain what abstract classes are and when you might use them? Those are all excellent questions: the kind that everyone should ask as they begin to dig deeper into the Java language and object-oriented programming in general. Yes, other nonabstract methods can access a method that you declare as

abstract. But first, let's look at when to use normal class definitions and when to use interfaces. Then I'll tackle abstract classes. Class vs. interface Some say you should define all classes in terms of interfaces, but I think recommendation seems a bit extreme. I use interfaces when I see that something in my design will change frequently. For example, the Strategy pattern lets you swap new algorithms and processes into your program without altering the objects that use them. A media player might know how to play CDs, MP3s, and wav files. Of course, you don't want to hardcode those playback algorithms into the player; that will make it difficult to add a new format like AVI. Furthermore, your code will be littered with useless case statements. And to add insult to injury, you will need to update those case statements each time you add a new algorithm. All in all, this is not a very object-oriented way to program. With the Strategy pattern, you can simply encapsulate the algorithm behind an object. If you do that, you can provide new media plug-ins at any time. Let's call the plug-in class MediaStrategy. That object would have one method: playStream(Stream s). So to add a new algorithm, we simply extend our algorithm class. Now, when the program encounters the new media type, it simply delegates the playing of the stream to our media strategy. Of course, you'll need some plumbing to properly instantiate the algorithm strategies you will need. This is an excellent place to use an interface. We've used the Strategy pattern, which clearly indicates a place in the design that will change. Thus, you should define the strategy as an interface. You should generally favor interfaces over inheritance when you want an object to have a certain type; in this case, MediaStrategy. Relying on inheritance for type identity is dangerous; it locks you into a particular inheritance hierarchy. Java doesn't allow multiple inheritance, so you can't extend something that gives you a useful implementation or more type identity. Interface vs. abstract class Choosing interfaces and abstract classes is not an either/or proposition. If you need to change your design, make it an interface. However, you may have abstract classes that provide some default behavior. Abstract classes are excellent candidates inside of application frameworks. Abstract classes let you define some behaviors; they force your subclasses to provide others. For example, if you have an application framework, an abstract class may provide default services such as event and message handling. Those services allow your application to plug in to your application framework. However, there is some application-specific functionality that only your application can perform. Such functionality might include startup and shutdown tasks, which are often application-dependent. So instead of trying to define that behavior itself, the abstract base class can declare abstract shutdown and startup methods. The base class knows that it needs those methods, but an abstract class lets your class admit that it doesn't know how to perform those actions; it only knows that it must initiate the actions. When it is time to start up, the abstract class can call the startup method. When the base

class calls this method, Java calls the method defined by the child class. Many developers forget that a class that defines an abstract method can call that method as well. Abstract classes are an excellent way to create planned inheritance hierarchies. They're also a good choice for nonleaf classes in class hierarchies. * Can a main() method of class be invoked in another class? * What is the difference between java command line arguments and C command line arguments? * What is the difference between == & .equals * What is the difference between abstract class & Interface. * What is singleton class & it's implementation. * 1. Use of static,final variable 2. Examples of final class * Difference between Event propagation & Event delegation * Difference between Unicast & Multicast model * 1. What is a java bean 2. What is synchronized keyword used for. * What are the restrictions of an applet & how to make the applet access the loc al machines resources. * What is reflect package used for & the methods of it. * What is serialization used for * Can methods be overloaded based on the return types ? * Why do we need a finalze() method when Garbage Collection is there ? * Difference between AWT and Swing compenents ? * Is there any heavy weight component in Swings ? * Can the Swing application if you upload in net, be compatible with your browse r? * What should you do get your browser compatible with swing components? * 1. What are the methods in Applet ? 2. When is init(),start() called ? * When you navigate from one applet to another what are the methods called? * What is the difference between Trusted and Untrusted Applet ? * 1. What is Exception ? 2 What are the ways you can handle exception ? * 1. When is try,catch block used ? 2. What is finally method in Exceptions ? * What are the types of access modifiers ? * What is protected and friendly ? 2. What are the other modifiers ? * Is synchronised modifier ? 2. What is meant by polymorphism ? * What is inheritance ? 2. What is method Overloading ? What is this in OOPS ? * What is method Overriding ? What is it in OOPS ? * Does java support multi dimensional arrays ? * Is multiple inheritance used in Java ? * How do you send a message to the browser in JavaScript ? * Does javascript support multidimensional arrays ? * Is there any tool in java that can create reports ? * What is meant by Java ? 2. What is meant by a class ? * What is meant by a method ? 2. What are the OOPS concepts in Java ? * What is meant by encapsulation ? Explain with an example * What is meant by inheritance ? Explain with an example * What is meant by polymorphism ? Explain with an example * Is multiple inheritance allowed in Java ? Why ? * What is meant by Java interpreter ? * What is meant by JVM ? 2. What is a compilation unit ? * What is meant by identifiers ? 2.What are the different types of modifiers ? * What are the access modifiers in Java ? * What are the primitive data types in Java ? * What is meant by a wrapper class ? * What is meant by static variable and static method ? * What is meant by Garbage collection ? * What is meant by abstract class

* What is meant by final class, methods and variables ? * What is meant by interface ? 2.What is meant by a resource leak ? * What is the difference between interface and abstract class ? * What is the difference between public private, protected and static * What is meant by method overloading ? 2. What is meant by method overriding ? * What is singleton class ? 2. What is the difference between an array and a vec tor ? * What is meant by constructor ? 2.What is meant by casting ? * What is the difference between final, finally and finalize ? * What is meant by packages ? 2. What are all the packages ? * Name 2 calsses you have used ? * Name 2 classes that can store arbitrary number of objects ? * What is the difference between java.applet.* and java.applet.Applet ? * What is a default package ? * What is meant by a super class and how can you call a super class ? * What is anonymous class ? 2.Name interfaces without a method ? * What is the use of an interface ? 2.What is a serializable interface ? * How to prevent field from serialization ? 2.What is meant by exception ? * How can you avoid the runtime exception ? * What is the difference between throw and throws ? * What is the use of finally ? * Can multiple catch statements be used in exceptions ? * Is it possible to write a try within a try statement ? * What is the method to find if the object exited or not ? * What is meant by a Thread ? 2.What is meant by multi-threading ? * What is the 2 way of creating a thread ? Which is the best way and why? * What is the method to find if a thread is active or not ? * What are the thread-to-thread communcation ? * What is the difference between sleep and suspend ? * Can thread become a member of another thread ? * What is meant by deadlock ? 2.How can you avoid a deadlock ? * What are the three typs of priority ? * What is the use of synchronizations ? * Garbage collector thread belongs to which priority ? * What is meant by time-slicing ? 2.What is the use of 'this' ? * How can you find the length and capacity of a string buffer ? * How to compare two strings ? * What are the interfaces defined by Java.lang ? * What is the purpose of run-time class and system class * What is meant by Stream and Types ? * What is the method used to clear the buffer ? * What is meant by Stream Tokenizer ? * What is serialization and de-serialisation ? * What is meant by Applet ? * How to find the host from which the Applet has originated ? * What is the life cycle of an Applet ? * How do you load an HTML page from an Applet ? * What is meant by Applet Stub Interface ? * What is meant by getCodeBase and getDocumentBase method ? * How can you call an applet from a HTML file * What is meant by Applet Flickering ? * What is the use of parameter tag ? * What is audio clip Interface and what are all the methods in it ? * What is the difference between getAppletInfo and getParameterInfo ? * How to communicate between applet and an applet ? * What is meant by event handling ? * What are all the listeners in java and explain ? * What is meant by an adapter class ? * What are the types of mouse event listeners ? * What are the types of methods in mouse listeners ?

* What is the difference between panel and frame ? * What is the default layout of the panel and frame ? * What is meant by controls and types ? * What is the difference between a scroll bar and a scroll panel. * What is the difference between list and choice ? * How to place a component on Windows ? * What are the different types of Layouts ? * What is meant by CardLayout ? * What is the difference between GridLayout and GridBagLayout * What is the difference between menuitem and checkboxmenu item. * What is meant by vector class, dictionary class , hash table class,and propert y class ? * Which class has no duplicate elements ? * What is resource bundle ? * What is an enumeration class ? * What is meant by Swing ? * What is the difference between AWT and Swing ? * What is the difference between an applet and a Japplet * What are all the components used in Swing ? * What is meant by tab pans ? * What is the use of JTree ? * How can you add and remove nodes in Jtree. * What is the method to expand and collapse nodes in a Jtree * What is the use of JTable ? * What is meant by JFC ? * What is the class in Swing to change the appearance of the Frame in Runtime. * How to reduce flicking in animation ? * What is meant by Javabeans ? * What is JAR file ? * What is meant by manifest files ? * What is Introspection ? * What are the steps involved to create a bean ? * Say any two properties in Beans ? * What is persistence ? * What is the use of beaninfo ? * What are the interfaces you used in Beans ? * What are the classes you used in Beans ? * What is the diffrence between an Abstract class and Interface * What is user defined exception ? * What do you know about the garbate collector ? * What is the difference between C++ & Java ? * How do you communicate in between Applets & Servlets ? * What is the use of Servlets ? * In an HTML form I have a Button which makes us to open another page in 15 seco nds. How will do you that ? * What is the difference between Process and Threads ? * How will you initialize an Applet ? * What is the order of method invocation in an Applet ? * When is update method called ? * How will you communicate between two Applets ? * Have you ever used HashTable and Dictionary ? * What are statements in JAVA ? * What is JAR file ? * What is JNI ? * What is the base class for all swing components ? * What is JFC ? * What is Difference between AWT and Swing ? * Considering notepad/IE or any other thing as process, What will Happen if you start notepad or IE 3 times? Where 3 processes are started or 3 threads are star ted ?

* How does thread synchronization occurs inside a monitor ? * How will you call an Applet using a Java Script function ? * Is there any tag in HTML to upload and download files ? * Why do you Canvas ? * How can you push data from an Applet to Servlet ? * What are the benefits of Swing over AWT ? * Where the CardLayout is used ? * What is the Layout for ToolBar ? * What is the difference between Grid and GridbagLayout ? * How will you add panel to a Frame ? * What is the corresponding Layout for Card in Swing ? * What is light weight component ? * What is bean ? Where it can be used ? * What is difference in between Java Class and Bean ? * What is the mapping mechanism used by Java to identify IDL language ? * Diff between Application and Applet ? * What is serializable Interface ? * What is the difference between CGI and Servlet ? * What is the use of Interface ? * Why Java is not fully objective oriented ? * Why does not support multiple Inheritance ? * What it the root class for all Java classes ? * What is polymorphism ? * Suppose If we have variable ' I ' in run method, If I can create one or More thread each thread will occupy a separate copy or same variable will be shared ? * What is Constructor and Virtual function? Can we call Virtual * Funciton in a constructor ? * Why we use OOPS concepts? What is its advantage ? * What is the difference in between C++ and Java ? can u explain in detail? * What is the exact difference in between Unicast and Multicast object ? Where w e will use ? * How do you sing an Applet ? * In a Container there are 5 components. I want to display the all the componen ts names, how will you do that one ? * Why there are some null interface in java ? What does it mean ? * Give me some null interfaces in JAVA ? * Tell me the latest versions in JAVA related areas ? * What is meant by class loader ? How many types are there? When will we use the m ? * What is meant by flickering ? * What is meant by cookies ? Explain ? * Problem faced in your earlier project * How OOPS concept is achieved in Java * Features for using Java * How does Java 2.0 differ from Java 1.0 * Public static void main - Explain * What are command line arguments * Explain about the three-tier model * Difference between String & StringBuffer * Wrapper class. Is String a Wrapper Class * What are the restriction for static method Purpose of the file class * Default modifier in Interface * Difference between Interface & Abstract class * Can abstract be declared as Final * Can we declare variables inside a method as Final Variables * What is the package concept and use of package * How can a dead thread be started * Difference between Applet & Application * Life cycle of the Applet

* Can Applet have constructors * Differeence between canvas class & graphics class * Explain about Superclass & subclass * What is AppletStub * Explain Stream Tokenizer * What is the difference between two types of threads * Checked & Unchecked exception * Use of throws exception * What is finally in exception handling Vector class * What will happen to the Exception object after exception handling * Two types of multi-tasking * Two ways to create the thread * Synchronization * I/O Filter * Can applet in different page communicate with each other * Why Java is not 100 % pure OOPS ? ( EcomServer ) * When we will use an Interface and Abstract class ? * How to communicate 2 threads each other ? Java Language Questions--What is a platform? A platform is the hardware or software environment in which a program runs. Most platforms can be described as a combination of the operating system and hardwar e, like Windows 2000/XP, Linux, Solaris, and MacOS. -------------------------------------------------------------------------------What is the main difference between Java platform and other platforms? The Java platform differs from most other platforms in that it's a software-only platform that runs on top of other hardware-based platforms. The Java platform has two components: The Java Virtual Machine (Java VM) The Java Application Programming Interface (Java API) -------------------------------------------------------------------------------What is the Java Virtual Machine? The Java Virtual Machine is a software that can be ported onto various hardwarebased platforms. ------------------------------------------------------------------------------What is the Java API? The Java API is a large collection of ready-made software components that provid e many useful capabilities, such as graphical user interface (GUI) widgets. ------------------------------------------------------------------------------What is the package? The package is a Java namespace or part of Java libraries. The Java API is group ed into libraries of related classes and interfaces; these libraries are known a s packages. ------------------------------------------------------------------------------What is native code? The native code is code that after you compile it, the compiled code runs on a s pecific hardware platform. -------------------------------------------------------------------------------Is Java code slower than native code? Not really. As a platform-independent environment, the Java platform can be a bi t slower than native code. However, smart compilers, well-tuned interpreters, an d just-in-time bytecode compilers can bring performance close to that of native code without threatening portability. -------------------------------------------------------------------------------What is the serialization? The serialization is a kind of mechanism that makes a class or a bean persistenc e by having its properties or fields and state information saved and restored to and from storage. --------------------------------------------------------------------------------

How to make a class or a bean serializable? By implementing either the java.io.Serializable interface, or the java.io.Extern alizable interface. As long as one class in a class's inheritance hierarchy impl ements Serializable or Externalizable, that class is serializable. -------------------------------------------------------------------------------how many methods in the Serializable interface? There is no method in the Serializable interface. The Serializable interface act s as a marker, telling the object serialization tools that your class is seriali zable. -------------------------------------------------------------------------------How many methods in the Externalizable interface? There are two methods in the Externalizable interface. You have to implement the se two methods in order to make your class externalizable. These two methods are readExternal() and writeExternal(). -------------------------------------------------------------------------------What is the difference between Serializalble and Externalizable interface? When you use Serializable interface, your class is serialized automatically by d efault. But you can override writeObject() and readObject() two methods to contr ol more complex object serailization process. When you use Externalizable interf ace, you have a complete control over your class's serialization process. -------------------------------------------------------------------------------What is a transient variable? A transient variable is a variable that may not be serialized. If you don't want some field to be serialized, you can mark that field transient or static. -------------------------------------------------------------------------------which containers use a border layout as their default layout? The Window, Frame and Dialog classes use a border layout as their default layout . -------------------------------------------------------------------------------How are Observer and Observable used? Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its obse rvers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects. -------------------------------------------------------------------------------What is synchronization and why is it important? With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often causes dirty data and leads to significant errors. -------------------------------------------------------------------------------What are synchronized methods and synchronized statements? Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for t he method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acqui red the lock for the object or class referenced in the synchronized statement. -------------------------------------------------------------------------------What are three ways in which a thread can enter the waiting state? A thread can enter the waiting state by invoking its sleep() method, by blocking on I/O, by unsuccessfully attempting to acquire an object's lock, or by invokin g an object's wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method. -------------------------------------------------------------------------------Can a lock be acquired on a class? Yes, a lock can be acquired on a class. This lock is acquired on the class's Cla ss object. -------------------------------------------------------------------------------What's new with the stop(), suspend() and resume() methods in JDK 1.2?

The stop(), suspend() and resume() methods have been deprecated in JDK 1.2. -------------------------------------------------------------------------------What is the preferred size of a component? The preferred size of a component is the minimum component size that will allow the component to display normally. -------------------------------------------------------------------------------What method is used to specify a container's layout? The setLayout() method is used to specify a container's layout. -------------------------------------------------------------------------------Which containers use a FlowLayout as their default layout? The Panel and Applet classes use the FlowLayout as their default layout. -------------------------------------------------------------------------------What is thread? A thread is an independent path of execution in a system. -------------------------------------------------------------------------------What is multithreading? Multithreading means various threads that run in a system. -------------------------------------------------------------------------------How does multithreading take place on a computer with a single CPU? The operating system's task scheduler allocates execution time to multiple tasks . By quickly switching between executing tasks, it creates the impression that t asks execute sequentially. -------------------------------------------------------------------------------How to create multithread in a program? You have two ways to do so. First, making your class "extends" Thread class. Sec ond, making your class "implements" Runnable interface. Put jobs in a run() meth od and call start() method to start the thread. -------------------------------------------------------------------------------Can Java object be locked down for exclusive use by a given thread? Yes. You can lock an object by putting it in a "synchronized" block. The locked object is inaccessible to any thread other than the one that explicitly claimed it. -------------------------------------------------------------------------------Can each Java object keep track of all the threads that want to exclusively acce ss to it? Yes. -------------------------------------------------------------------------------What state does a thread enter when it terminates its processing? When a thread terminates its processing, it enters the dead state. -------------------------------------------------------------------------------What invokes a thread's run() method? After a thread is started, via its start() method of the Thread class, the JVM i nvokes the thread's run() method when the thread is initially executed. -------------------------------------------------------------------------------What is the purpose of the wait(), notify(), and notifyAll() methods? The wait(),notify(), and notifyAll() methods are used to provide an efficient wa y for threads to communicate each other. -------------------------------------------------------------------------------what are the high-level thread states? The high-level thread states are ready, running, waiting, and dead. -------------------------------------------------------------------------------What is the Collections API? The Collections API is a set of classes and interfaces that support operations o n collections of objects. -------------------------------------------------------------------------------What is the List interface? The List interface provides support for ordered collections of objects. -------------------------------------------------------------------------------How does Java handle integer overflows and underflows? It uses those low order bytes of the result that can fit into the size of the ty

pe allowed by the operation. -------------------------------------------------------------------------------What is the Vector class? The Vector class provides the capability to implement a growable array of object s -------------------------------------------------------------------------------What modifiers may be used with an inner class that is a member of an outer clas s? A (non-local) inner class may be declared as public, protected, private, static, final, or abstract. -------------------------------------------------------------------------------If a method is declared as protected, where may the method be accessed? A protected method may only be accessed by classes or interfaces of the same pac kage or by subclasses of the class in which it is declared. -------------------------------------------------------------------------------What is an Iterator interface? The Iterator interface is used to step through the elements of a Collection. -------------------------------------------------------------------------------How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters ? Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents char acters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patte rns. -------------------------------------------------------------------------------What is the difference between yielding and sleeping? When a task invokes its yield() method, it returns to the ready state. When a ta sk invokes its sleep() method, it returns to the waiting state. -------------------------------------------------------------------------------Is sizeof a keyword? The sizeof operator is not a keyword in Java. -------------------------------------------------------------------------------What are wrapped classes? Wrapped classes are classes that allow primitive types to be accessed as objects . -------------------------------------------------------------------------------Does garbage collection guarantee that a program will not run out of memory? No, it doesn't. It is possible for programs to use up memory resources faster th an they are garbage collected. It is also possible for programs to create object s that are not subject to garbage collection -------------------------------------------------------------------------------What is the difference between preemptive scheduling and time slicing? Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors. -------------------------------------------------------------------------------Name Component subclasses that support painting. The Canvas, Frame, Panel, and Applet classes support painting. -------------------------------------------------------------------------------What is a native method? A native method is a method that is implemented in a language other than Java. -------------------------------------------------------------------------------How can you write a loop indefinitely? for(;;)--for loop; while(true)--always true, etc. -------------------------------------------------------------------------------Can an anonymous class be declared as implementing an interface and extending a class?

An anonymous class may implement an interface or extend a superclass, but may no t be declared to do both. -------------------------------------------------------------------------------What is the purpose of finalization? The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected. -------------------------------------------------------------------------------Which class is the superclass for every class. Object -------------------------------------------------------------------------------What is the difference between the Boolean & operator and the && operator? If an expression involving the Boolean & operator is evaluated, both operands ar e evaluated. Then the & operator is applied to the operand. When an expression i nvolving the && operator is evaluated, the first operand is evaluated. If the fi rst operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped. Operator & has no chance to skip both sides evaluation and && operator does. If asked why, give details as above. -------------------------------------------------------------------------------What is the GregorianCalendar class? The GregorianCalendar provides support for traditional Western calendars. -------------------------------------------------------------------------------What is the SimpleTimeZone class? The SimpleTimeZone class provides support for a Gregorian calendar. -------------------------------------------------------------------------------Which Container method is used to cause a container to be laid out and redisplay ed? validate() -------------------------------------------------------------------------------What is the Properties class? The properties class is a subclass of Hashtable that can be read from or written to a stream. It also provides the capability to specify a set of default values to be used. -------------------------------------------------------------------------------What is the purpose of the Runtime class? the purpose of the Runtime class is to provide access to the Java runtime system . -------------------------------------------------------------------------------What is the purpose of the System class? The purpose of the System class is to provide access to system resources. -------------------------------------------------------------------------------What is the purpose of the finally clause of a try-catch-finally statement? The finally clause is used to provide the capability to execute code no matter w hether or not an exception is thrown or caught. -------------------------------------------------------------------------------What is the Locale class? The Locale class is used to tailor program output to the conventions of a partic ular geographic, political, or cultural region. -------------------------------------------------------------------------------What must a class do to implement an interface? It must provide all of the methods in the interface and identify the interface i n its implements clause. -------------------------------------------------------------------------------What is an abstract method? An abstract method is a method whose implementation is deferred to a subclass. O r, a method that has no implementation (an interface of a method). -------------------------------------------------------------------------------What is a static method? A static method is a method that belongs to the class rather than any object of

the class and doesn't apply to an object or even require that any objects of the class have been instantiated. -------------------------------------------------------------------------------What is a protected method? A protected method is a method that can be accessed by any method in its package and inherited by any subclass of its class. -------------------------------------------------------------------------------What is the difference between a static and a non-static inner class? A non-static inner class may have object instances that are associated with inst ances of the class's outer class. A static inner class does not have any object instances. -------------------------------------------------------------------------------What is an object's lock and which object's have locks? An object's lock is a mechanism that is used by multiple threads to obtain synch ronized access to the object. A thread may execute a synchronized method of an o bject only after it has acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object. -------------------------------------------------------------------------------When can an object reference be cast to an interface reference? An object reference be cast to an interface reference when the object implements the referenced interface. -------------------------------------------------------------------------------What is the difference between a Window and a Frame? The Frame class extends Window to define a main application window that can have a menu bar. -------------------------------------------------------------------------------What do heavy weight components mean? Heavy weight components like Abstract Window Toolkit (AWT), depend on the local windowing toolkit. For example, java.awt.Button is a heavy weight component, whe n it is running on the Java platform for Unix platform, it maps to a real Motif button. In this relationship, the Motif button is called the peer to the java.aw t.Button. If you create two Buttons, two peers and hence two Motif Buttons are a lso created. The Java platform communicates with the Motif Buttons using the Jav a Native Interface. For each and every component added to the application, there is an additional overhead tied to the local windowing system, which is why thes e components are called heavy weight. -------------------------------------------------------------------------------Which package has light weight components? javax.Swing package. All components in Swing, except JApplet, JDialog, JFrame an d JWindow are lightweight components. -------------------------------------------------------------------------------What are peerless components? The peerless components are called light weight components. -------------------------------------------------------------------------------What is the difference between the Font and FontMetrics classes? The FontMetrics class is used to define implementation-specific properties, such as ascent and descent, of a Font object. -------------------------------------------------------------------------------What happens when a thread cannot acquire a lock on an object? If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available. -------------------------------------------------------------------------------What is the difference between the Reader/Writer class hierarchy and the InputSt ream/OutputStream class hierarchy? The Reader/Writer class hierarchy is character-oriented, and the InputStream/Out putStream class hierarchy is byte-oriented. --------------------------------------------------------------------------------

What classes of exceptions may be caught by a catch clause? A catch clause can catch any exception that may be assigned to the Throwable typ e. This includes the Error and Exception types. -------------------------------------------------------------------------------What is the difference between throw and throws keywords? The throw keyword denotes a statement that causes an exception to be initiated. It takes the Exception object to be thrown as argument. The exception will be ca ught by an immediately encompassing try-catch construction or propagated further up the calling hierarchy. The throws keyword is a modifier of a method that designates that exceptions may come out of the mehtod, either by virtue of the method throwing the exception i tself or because it fails to catch such exceptions that a method it calls may th row. -------------------------------------------------------------------------------If a class is declared without any access modifiers, where may the class be acce ssed? A class that is declared without any access modifiers is said to have package or friendly access. This means that the class can only be accessed by other classe s and interfaces that are defined within the same package. -------------------------------------------------------------------------------What is the Map interface? The Map interface replaces the JDK 1.1 Dictionary class and is used associate ke ys with values. -------------------------------------------------------------------------------does a class inherit the constructors of its superclass? A class does not inherit constructors from any of its superclasses. -------------------------------------------------------------------------------Name primitive Java types. The primitive types are byte, char, short, int, long, float, double, and boolean . -------------------------------------------------------------------------------Which class should you use to obtain design information about an object? The Class class is used to obtain information about an object's design. -------------------------------------------------------------------------------how can a GUI component handle its own events? A component can handle its own events by implementing the required event-listene r interface and adding itself as its own event listener. -------------------------------------------------------------------------------How are the elements of a GridBagLayout organized? The elements of a GridBagLayout are organized according to a grid. However, the elements are of different sizes and may occupy more than one row or column of th e grid. In addition, the rows and columns may have different sizes. -------------------------------------------------------------------------------What advantage do Java's layout managers provide over traditional windowing syst ems? Java uses layout managers to lay out components in a consistent manner across al l windowing platforms. Since Java's layout managers aren't tied to absolute sizi ng and positioning, they are able to accommodate platform-specific differences a mong windowing systems. -------------------------------------------------------------------------------What are the problems faced by Java programmers who don't use layout managers? Without layout managers, Java programmers are faced with determining how their G UI will be displayed across multiple windowing systems and finding a common sizi ng and positioning that will work within the constraints imposed by each windowi ng system. -------------------------------------------------------------------------------What is the difference between static and non-static variables? A static variable is associated with the class as a whole rather than with speci fic instances of a class. Non-static variables take on unique values with each o bject instance.

-------------------------------------------------------------------------------What is the difference between the paint() and repaint() methods? The paint() method supports painting via a Graphics object. The repaint() method is used to cause paint() to be invoked by the AWT painting thread. -------------------------------------------------------------------------------What is the purpose of the File class? The File class is used to create objects that provide access to the files and di rectories of a local file system. ------------------------------------------------------------------------------What restrictions are placed on method overloading? Two methods may not have the same name and argument list but different return ty pes. -------------------------------------------------------------------------------What restrictions are placed on method overriding? Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides. The overr iding method may not throw any exceptions that may not be thrown by the overridd en method. -------------------------------------------------------------------------------What is casting? There are two types of casting, casting between primitive numeric types and cast ing between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Ca sting between object references is used to refer to an object by a compatible cl ass, interface, or array type reference. -------------------------------------------------------------------------------Name Container classes. Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane -------------------------------------------------------------------------------What class allows you to read objects directly from a stream? The ObjectInputStream class supports the reading of objects from input streams. -------------------------------------------------------------------------------How are this() and super() used with constructors? this() is used to invoke a constructor of the same class. super() is used to inv oke a superclass constructor. -------------------------------------------------------------------------------How is it possible for two String objects with identical values not to be equal under the == operator? The == operator compares two objects to determine if they are the same object in memory. It is possible for two String objects to have the same value, but locat ed indifferent areas of memory. -------------------------------------------------------------------------------What an I/O filter? An I/O filter is an object that reads from one stream and writes to another, usu ally altering the data in some way as it is passed from one stream to another. -------------------------------------------------------------------------------What is the Set interface? The Set interface provides methods for accessing the elements of a finite mathem atical set. Sets do not allow duplicate elements. -------------------------------------------------------------------------------What is the List interface? The List interface provides support for ordered collections of objects. -------------------------------------------------------------------------------What is the purpose of the enableEvents() method? The enableEvents() method is used to enable an event for a particular object. No rmally, an event is enabled when a listener is added to an object for a particul ar event. The enableEvents() method is used by objects that handle events by ove rriding their event-dispatch methods. -------------------------------------------------------------------------------

What is the difference between the File and RandomAccessFile classes? The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data c ontained in any part of a file. -------------------------------------------------------------------------------What interface must an object implement before it can be written to a stream as an object? An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object. -------------------------------------------------------------------------------What is the ResourceBundle class? The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program's appearance to the particular locale in which it is being run. -------------------------------------------------------------------------------What is the difference between a Scrollbar and a ScrollPane? A Scrollbar is a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling. -------------------------------------------------------------------------------What is a Java package and how is it used? A Java package is a naming context for classes and interfaces. A package is used to create a separate name space for groups of classes and interfaces. Packages are also used to organize related classes and interfaces into a single API unit and to control accessibility to these classes and interfaces. -------------------------------------------------------------------------------What are the Object and Class classes used for? The Object class is the highest-level class in the Java class hierarchy. The Cla ss class is used to represent the classes and interfaces that are loaded by a Ja va program. ------------------------------------------------------------------------------What is Serialization and deserialization? Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects. -------------------------------------------------------------------------------what is tunnelling? Tunnelling is a route to somewhere. For example, RMI tunnelling is a way to make RMI application get through firewall. In CS world, tunnelling means a way to tr ansfer data. -------------------------------------------------------------------------------Does the code in finally block get executed if there is an exception and a retur n statement in a catch block? If an exception occurs and there is a return statement in catch block, the final ly block is still executed. The finally block will not be executed when the Syst em.exit(1) statement is executed earlier or the system shut down earlier or the memory is used up earlier before the thread goes to finally block. -------------------------------------------------------------------------------How you restrict a user to cut and paste from the html page? Using javaScript to lock keyboard keys. It is one of solutions. -------------------------------------------------------------------------------Is Java a super set of JavaScript? No. They are completely different. Some syntax may be similar. -------------------------------------------------------------------------------What is a Container in a GUI? A Container contains and arranges other components (including other containers) through the use of layout managers, which use specific layout policies to determ ine where components should go as a function of the size of the container. -------------------------------------------------------------------------------how the object oriented approach helps us keep complexity of software developmen t under control?

We can discuss such issue from the following aspects: Objects allow procedures to be encapsulated with their data to reduce potential interference. Inheritance allows well-tested procedures to be reused and enables changes to ma ke once and have effect in all relevant places. The well-defined separations of interface and implementation allows constraints to be imposed on inheriting classes while still allowing the flexibility of over riding and overloading. -------------------------------------------------------------------------------What is polymorphism? Polymorphism allows methods to be written that needn't be concerned about the sp ecifics of the objects they will be applied to. That is, the method can be speci fied at a higher level of abstraction and can be counted on to work even on obje cts of yet unconceived classes. -------------------------------------------------------------------------------What is design by contract? The design by contract specifies the obligations of a method to any other method s that may use its services and also theirs to it. For example, the precondition s specify what the method required to be true when the method is called. Hence m aking sure that preconditions are. Similarly, postconditions specify what must b e true when the method is finished, thus the called method has the responsibilit y of satisfying the post conditions. In Java, the exception handling facilities support the use of design by contract , especially in the case of checked exceptions. The assert keyword can be used t o make such contracts. -------------------------------------------------------------------------------What are use cases? A use case describes a situation that a program might encounter and what behavio r the program should exhibit in that circumstance. It is part of the analysis of a program. The collection of use cases should, ideally, anticipate all the stan dard circumstances and many of the extraordinary circumstances possible so that the program will be robust. -------------------------------------------------------------------------------What is the difference between interface and abstract class? interface contains methods that must be abstract; abstract class may contain con crete methods. interface contains variables that must be static and final; abstract class may c ontain non-final and final variables. members in an interface are public by default, abstract class may contain non-pu blic members. interface is used to "implements"; whereas abstract class is used to "extends". interface can be used to achieve multiple inheritance; abstract class can be use d as a single inheritance. interface can "extends" another interface, abstract class can "extends" another class and "implements" multiple interfaces. interface is absolutely abstract; abstract class can be invoked if a main() exis ts. interface is more flexible than abstract class because one class can only "exten ds" one super class, but "implements" multiple interfaces. if given a choice, use interface instead of abstract class. -------------------------------------------------------------------------------BIG QUESTIONS BIG ANSWERS --------------------------------------------------------------------------------

ADVANCED JAVA + SQL Related + JDBC QUESTIONS

1. What is JDBC? JDBC is a layer of abstraction that allows users to choose between databases. It allows you to change to a different database engine and to write to a single AP I. JDBC allows you to write database applications in Java without having to conc ern yourself with the underlying details of a particular database. 2. What are the two major components of JDBC? One implementation interface for database manufacturers, the other implementatio n interface for application and applet writers. 3. What is JDBC Driver interface? The JDBC Driver interface provides vendor-specific implementations of the abstra ct classes provided by the JDBC API. Each vendors driver must provide implementa tions of the java.sql.Connection,Statement,PreparedStatement, CallableStatement, ResultSet and Driver. 4. What are the common tasks of JDBC? o Create an instance of a JDBC driver or load JDBC drivers through jdbc.drivers o Register a driver o Specify a database o Open a database connection o Submit a query o Receive results 5. What packages are used by JDBC? There are 8 packages: java.sql.Driver, Connection,Statement, PreparedStatement, CallableStatement, ResultSet, ResultSetMetaData, DatabaseMetaData. 6. What are the flow statements of JDBC? A URL string -->getConnection-->DriverManager-->Driver-->Connection-->Statement->executeQuery-->ResultSet. 7. What are the steps involved in establishing a connection? This involves two steps: (1) loading the driver and (2) making the connection. 8. How can you load the drivers? Loading the driver or drivers you want to use is very simple and involves just o ne line of code. If, for example, you want to use the JDBC-ODBC Bridge driver, t he following code will load it: Eg. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Your driver documentation will give you the class name to use. For instance, if the class name is jdbc.DriverXYZ , you would load the driver with the following line of code: E.g. Class.forName("jdbc.DriverXYZ"); 9. What Class.forName will do while loading drivers? It is used to create an instance of a driver and register it with the DriverMana ger. When you have loaded a driver, it is available for making a connection with a DBMS. 10. How can you make the connection? In establishing a connection is to have the appropriate driver connect to the DB MS. The following line of code illustrates the general idea: E.g. String url = "jdbc:odbc:Fred"; Connection con = DriverManager.getConnection(url, "Fernanda", "J8"); 11. How can you create JDBC statements? A Statement object is what sends your SQL statement to the DBMS. You simply crea te a Statement object and then execute it, supplying the appropriate execute met hod with the SQL statement you want to send. For a SELECT statement, the method to use is executeQuery. For statements that create or modify tables, the method to use is executeUpdate. E.g. It takes an instance of an active connection to cr eate a Statement object. In the following example, we use our Connection object con to create the Statement object stmt : Statement stmt = con.createStatement(); 12. How can you retrieve data from the ResultSet?

First JDBC returns results in a ResultSet object, so we need to declare an insta nce of the class ResultSet to hold our results. The following code demonstrates declaring the ResultSet object rs. E.g. ResultSet rs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES"); Second: String s = rs.getString("COF_NAME"); The method getString is invoked on the ResultSet object rs , so getString will r etrieve (get) the value stored in the column COF_NAME in the current row of rs 13. What are the different types of Statements? 1.Statement (use createStatement method) 2. Prepared Statement (Use prepareState ment method) and 3. Callable Statement (Use prepareCall) 14. How can you use PreparedStatement? This special type of statement is derived from the more general class, Statement . If you want to execute a Statement object many times, it will normally reduce execution time to use a PreparedStatement object instead. The advantage to this is that in most cases, this SQL statement will be sent to the DBMS right away, w here it will be compiled. As a result, the PreparedStatement object contains not just an SQL statement, but an SQL statement that has been precompiled. This mea ns that when the PreparedStatement is executed, the DBMS can just run the Prepar edStatement 's SQL statement without having to compile it first. E.g. PreparedStatement updateSales = con.prepareStatement("UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?"); 15. How to call a Stored Procedure from JDBC? The first step is to create a CallableStatement object. As with Statement an and PreparedStatement objects, this is done with an open Connection object. A Calla bleStatement object contains a call to a stored procedure; E.g. CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}"); ResultSet rs = cs.executeQuery(); 16. How to Retrieve Warnings? SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions d o; they simply alert the user that something did not happen as planned. A warnin g can be reported on a Connection object, a Statement object (including Prepared Statement and CallableStatement objects), or a ResultSet object. Each of these c lasses has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object E.g. SQLWarning warning = stmt.getWarnings(); if (warning != null) { while (warning != null) { System.out.println("Message: " + warning.getMessage()); System.out.println("SQLState: " + warning.getSQLState()); System.out.print("Vendor error code: "); System.out.println(warning.getErrorCode()); warning = warning.getNextWarning(); } } 17. How to Make Updates to Updatable Result Sets? Another new feature in the JDBC 2.0 API is the ability to update rows in a resul t set using methods in the Java programming language rather than having to send an SQL command. But before you can take advantage of this capability, you need t o create a ResultSet object that is updatable. In order to do this, you supply t he ResultSet constant CONCUR_UPDATABLE to the createStatement method. E.g. Connection con = DriverManager.getConnection("jdbc:mySubprotocol:mySubName"); Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

ResultSet uprs = ("SELECT COF_NAME, PRICE FROM COFFEES"); 1. Create a table named tTempTable that contains two columns: TempId and TempName. Use DDL to create the table. After you have created the table, go into the SQL Central utility and make TempId an AutoIncrement column. When you have finished creating the table, drop the table using DDL. A. Create Table tTempTable { TempId int, TempName char(20) } drop table tTempTable 2. Write a stored procedure that lets you pass a last name to the procedure and get the number of employees who have that last name back as an OUT parameter. A. The procedure will need to look similar to the following: procedure getCount (varchar emp IN, int count OUT) select count(*) from tEmployee where LastName = emp 3. Create a dynamic SQL statement that deletes items from tEmployee based on the employee's Social Security number. A. The SQL statement should look like this: Delete from tEmployee where SSN = ? 4. Create a dynamic SQL statement that lets you specify the FirstName, LastName, MiddleInitial and SSN columns through the setXXX() methods of the PreparedStatement object. A. The SQL statement should look like this: Insert into tEmployee(FirstName, MiddleInitial, LastName, SSN) Values (?, ?, ?, ?) You can then use the setString() methods to set each column value. 5. Add functionality to the Select object to enable the user to get the names of the columns in the result set. A. Create a getColumnName() method that will get a value from an array that contains the column names. The array should be populated by theretrieve() method with the column names retrieved from the ResultSetMetaData object. 6. Change the component so that the data labels can be edited. (Note: You will need to make the objects into text fields) A. Change the data array from Label objects to TextField objects, and then in retrieve(), create TextField objects for display. 7. Create a setVisible(int, boolean) method that will enable you to determine whether certain columns are displayed. The object you create should implement another array that contains Boolean values for each column. If the value is false, then methods to display column data should not display particular columns. 8. Create a frame with two different list boxes. Display different PopupMenu

objects for each list. A. Create two lists on a frame and then create two different pop-up menus for the frame. In the mouseClicked() method, click for which component generated the event and display the appropriate pop-up menu. 9. Modify the View Employee dialog box to allow editing of employee information. You will need to add a new server port ot allow update information to be sent. You also will need to make the View dialog box be editable so that the user can enter new information. A. Change the fields in the View dialog to be editable and then create a new server port that will accept the update information and send it to the database. 1. What are some of the advantages of using Java? A. You can use garbage collection, it is multiplatform, easy to learn object-oriented and has no pointers. 2. What are some of the disadvantages of using java? A. Limited GUI and no database access. 3. What language(s) does Java resemble? A. C and C++ 4. What is Garbage collection in Java? A. Garbage collection removes unused objects from memory. 5. What is the difference between an application and an applet? A. An application is usually run on a local computer, whereas an applet is run using a browser. 6. What does the Statement interface enable you to do? A. It enables you to execute static SQL statements. 7. What does the executeQuery() method do? A. It executes a SQL Select statement and returns a result set. 8. What is stored in a ResultSet object? A. The cursor for a SQL Select statement. 9. What three exceptions can be thrown in JDBC applications? A. SQLException, SQLWarning, and DataTruncation. 10. What methods usually throw the SQLException exception? A. All JDBC methods. 11. What is a primary key? A. A column(or columns) that uniquely identifies each row in a table.

12. What is a foreign key? A. A column(or columns) from one table that is included in the primary key of another table. 13. What is a VarChar column? A. A column data type that uses only the amount of space needed to hold the data value contained within it. 14. What is the difference between decimal and numeric columns? A. Decimal columns enable you to place floating point numbers, but numeric columns enable you to specify how many digits of precision should be used. 15. What three types of parameters can you pass into a stored procedure? A. IN, OUT and INOUT parameters. 16. When can triggers can be executed? A. Before or after execution of SQL statements. 17. What is the difference between row-level and statement-level triggers? A. Row-level triggers are executed once for every row updated; statementlevel triggers are executed once for the entire SQL statement. 18. What is Data Definition Language(DDL)? A. DDL enables you to define the characteristics of the database. 19. What is the syntax for dropping a table using DDL? A. DROP TABLE 20. What information doesthe system table contain? A. It contains information about the various objects in the database, tables, columns,and so on. 21. Create a stored procedure that takes in an IN parameter value and returns it in an OUT parameter value. A. Create a basic stored procedure that takes two parameters: one an IN and the other an OUT. 22. Create a table named tTempTable that contains two columns: TempId and TempName. Use DDL to create the table. After you have created the table, go into the finished creating table, drop the table using DDL . A. Create Table tTempTable { TempId int, TempName char(20) } drop table tTempTable

23. Display the system tables for the current database. After the tables are displayed, look at the data contained in the SYSTABLE table. A. Use SQL Anywhere to view the system tables for the current database. 24. In what package does dbAnywhere store the JDBC API? A. symjava.sql 25. Why is the JDBC API stored in a different package than the proposed package? A. Browsers provide security that will not load java.* packages. 26. What method of Driver object will create a connection to the database? A. connect(); 27. What method will get the properties needed to connect to the database? A. getPropertyInfo(); 28. What is the login timeout? A. The time the driver will wait for a connection to the database before returning an error. 29. What method can change the logging/tracing stream used by the Driver Manager? A. setLogStream(); 30. What does a driver need to support in order to be JDBC-compliant? A. JDBC API. 31. In what system property does the DriverManager object look for Driver objects? A. jdbc.drivers 32. List the three different methods that the DriverManager can use to create a connection to the database. A. getConnection(String), getConnection(String, Properties), getConnection(String, String, String) 33. For what type of applications should Sybase SQL Anywhere be used? A. Smaller to mid-size applications having less than 100 users. 34. What is a logical unit of work? A. A statement or a group of statements that performs one general function. 35. What is contained within a transaction log? A. The list of statements executed against the database since the last commit or rollback.

36. What setting of AutoCommit will force a commit after every SQL statement? A. TRUE(on) 37. Describe the difference between the commit and rollback? A. commit will clear the log and make the settings permanent; rollback will clear the log and reset the database to its original state. 38. What does the CEILING function do? A. Returns the smallest integer larger than the specified number. 39. What would be the FLOOR function return if passed 7.4? A. 7 40. What does the SOUNDEX function do? A. Returns an integer value that represents the string. 41. What does the TRIM function do? A. Removes all leading and trailing spaces. 42. What does the DATALENGTH function return? A. Returns the size of the column, in bytes for a table. 43. What does the NOW function return? A. Returns the current data and time. 44. What is the difference between a connection and a statement? A. A connection is a link to a database; a statement is used to send commands to a database. 45. Why would you use the execute() method of the Statement object? A. If the SQL statement returned multiple results. 46. What is the difference between having AutoCommit on or off? A. AutoCommit on will commit after every statement; off will force the user to issue commits. 47. Describe the effects of commit and rollback. A. commit will clear the log and make changes permanent; rollback will clear the log and reset the database to its original state. 48. Is a Statement object used for static or dynamic SQL statements? A. It is used for static statements. 49. What is the difference between ExecuteQuery() and ExecuteUpdate()? A. ExecuteQuery() will execute a SQL Select statement. ExecuteUpdate()

will execute SQL Insert, Delete and Update statement. 50. How do you create a DatabaseMetaData object? A. Use the getMetaData() method. 51. What are the different types of database tables? A. User tables and system tables. 52. What is the syntax for getting a list of columns for a table? A. getColumns() 53. What is the difference between getExportKeys() and getImportKeys()? A. Exported keys are primary keys in a table that are used in other tables, Imported keys are columns used in a table that are a part of the primary key in another table. 54. What character do you use to indicate a dynamic parameter? A. The ? character. 55. What three different types of parameters can be passed to a stored procedure? A. IN, OUT and INOUT. 56. What method is used to create a PreparedStatement object? A. preparedStatement(String) 57. What method is used to create a CallableStatement object? A. prepareCall(String) 58. What does the registerOutParameter() method do? A. It labels a parameter as being an OUT parameter so that it can be accessed after execution. 59. What does the wasNull() method tell you? A. Determines whether the last item read was NULL. 60. What are some advantages to using stored procedures? A. Allows for execution of multiple SQL statements, faster processing and simplified development. 61. What are some advantages to using dynamic SQL statements? A. They execute the same SQL statement with different parameters. 62. What is an INOUT parameter? A. A parameter that contains a value going into the procedure but can contain a different value when the procedure is finished.

63. What is the difference between an IN and OUT parameter? A. IN procedures have values going into the procedure; OUT parameters have values coming out of the procedure. 64. In what two ways can you specify a column when you use the getxxx() method? A. By name or by index. 65. How can you delete a record using the ResultSet object'c cursor? A. Use getCursorName(). 66. On what record is the cursor initially positioned in the ResultSet object? A. The cursor is positioned on a NULL record before the first record. 67. What method moves you to the next record in the result set? A. next() 68. Is there any way to move the cursor to the previous record? If so, what is it? A. No. 69. What is the AutoIncrementing column? A. A column that automatically inserts a new number into the column. 70. How is the column name different from the column label? A. The column nameis the name as listed in the table schema; the label is what should be displayed to the user. 71. What is the precision of a column? A. The number of digits each data value will contain. 72. What does the getColumnDisplaySize() method do? A. Gets the number of characters that are needed to display the full column. 73. How do you determine whether a column can accept SQL NULL values? A. isNULLable() 74. How many sections does a standard SQL Select statement contain? A. Three. 75. In a Select statement, what does the From clause specify? A. The tables that should be looked through. 76. What does the setRow() method do?

A. Sets the row for the object. 77. How would you determine which row the Select object is currently on? A. The getRow() method. 78. What is the difference between specifying columns and not specifying columns in the first section of the Insert statement? A. Not specifying columns means that you have to include all column data values in the correct order. 79. Why should you always specify columns in an Insert statement? A. So that you will be insulated from database changes. 80. What would be the syntax to delete all records from tMyTable? A. Delete from tMyTable 81. How would you delete all records from tMyTable using the Delete object? A. Use the deleteAll(String) method. 82. What is specified in the Set section of the SQL Update statement? A. The column that will be updated. 83. If getSuccess() returns false, was the execution of the SQL statement successful or not? A. The execution was not successful. 84. What are the four data interfaces that you will be using to build the data components? A. DataConnection, DataComponent, DataUpdate and DataNavigation. 85. What is the difference between the two different setConnection() methods? A. One will reset the component, whereas the other gives the user the option to reset the component. 86. What value does the retrieve() method return? A. The number of records retreived. 87. What are the four SQL types that are used in the DataUpdate interface? A. DELETE, INSERT, UPDATE and SELECT 88. What is the purpose of the previewStatement() method? A. It enables the user to add application-specific business logic. 89. What does the reset() method do? A. Clears all settings for the component.

90. What method would you use to set the record position to the fifth record? A. setRow() 91. What value does the getColumnType() method return? A. An integer that contains a predefined constant identifying the data type. 92. List the two ways in which you can move the record position to the initial record. A. first() and setRow(1). 93. List the two ways in which you can move the record position to the last record. A. last() and setRow(getRow()) 94. What constructor gives you the most initial options to specify? A. DataField(length, Connection, sql, boolean) 95. What is the difference between the two setConnection() methods? A. One enables the user to reset the component, whereas the other forces a reset of the component. 96. What does the retrieve() method do? A. It retrieves data from database. 97. Describe what the setRow() method does? A. It moves the current record to a specified valid record. 98. What does the getColumnType() method return? A. It returns the type of the column specified. 99. What two values are passed to the previewStatement() method? A. The SQL statement to be executed and the typeof statement. 100. What does returning a false from the previewStatement() do? A. Cancels the execution of a particular SQL statement. 101. Name two ways to set the record to the initial record immediately. A. first() and setRow(1) 102. What does setItem() enable you to do? A. Set the data value for a particular item. 103. How do you specify an update table to be tEmployeeAddress? A. setUpdateTable("tEmployeeAddress")

104. List all of the constructor methods for the DataList component. A. DataList(), DataList(int), DataList(int, Connection, string), DataList(int, Connection, String, boolean) 105. How do you have the component retreive data without calling the retrieve() method? A. Use the DataList(int, Connection, String, boolean)method and pass it a true value. 106. What method enables you to change the Connection object? A. setConnection() 107. How would you change the Connection object without resetting the component? A. setConnection(Connection, false) 108. How would you get the number of records in the component? A. rowCount() 109. What two items must be specified for an update to occur? A. Update the table name and at least one update column. 110. What does the previewStatement() method return and what does it mean? A. It returns a Boolean value indicating whether the SQL statement should be executed. 111. Initially, are the records in the component and the items in the list same? A. Yes. 112. How can you add new items to the list for display? A. addItem() 113. How can you display the last column in the component(there are two ways)? A. last(), setRow(getRow()) 114. What are the two variables that indicate on and off for the component? A. onCheck and offCheck 115. What does the DataCheckBox(String label) constructor method do? A. Create the check box object with a label. 116. What does the setConnection(Connection, boolean) method do?

A. Changes the Connection object and resets or doesn't reset the component depending on the Boolean value. 117.How can you change the Connection object without resetting the other variables in the component? A. setConnection(Connection, false) 118. How can you specify the SQL statement for the component? A. setSQL() 119. What is the difference between the User and Original Hashtable objects? A. The original object stores the data values retrieved from the database the User object stores values entered by the user. 120. What method would you call to reset the component? A. reset() 121. What will happen if you call the next() method and no next record exists? A. The component will remain on the current record. 122. What will happen if you call update() method and have not specified an update table? A. The update will not occur. 123. What does the getColumnType() method return? A. This method returns the column type as a predefined integer value. 124. Why doesn't the DataNavigator implement someof the data interfaces? A. Not all of the functionality is required for the component. 125. How does the DataNavigator store the connected components? A. In a hash table of objects. 126. Name the four buttons on the DataNavigator component. A. First, Previous, Next and Last. 127. How would you hide the Last button? A. showLast(false); 128. How would you show the Last button? A. showLast(true); 129. How would add a component to the DataNavigator? A. addComponent()

130. What method does the DataNavigator implement from the DataUpdate interface? A. update() 131. What does the retrieve() method return? A. The maximum number of records retrieved from any component. 132. What is stored in the max variable? A. The maximum number of records retrieved from any component. 133. Name some differences between the DataNavigator component and the other data components. A. This component does not directly store any data values. 134. How is the DataPanel component different from the other components? A. It displays more than one column's data values. 135. What method enables you to get the number of records that are in the result set? A. recordCount() 136. What is displayed in the description labels on the panel? A. The column name. 137. What does the retrieve() method do differently than the other components? A. Adds the Label components to the panel. 138. What layout does the component use to display the Label objects? A. GridLayout. 139. Why are you using the same Connection object for all windows? A. So that you don't have to create multiple connections to the database. 140. What does the dbConnect() method do? A. It connects the application to the database. 141. Why do you clear all articles before adding new items in the getArticle() method? A. So that duplicate articles do not appear in the list. 142. Why is it important to always close the Statement object after you use it? A. So that the resources used by the object are released back to the system. 143. What event handles all of the user's actions on the window?

A. handleEvent() 144. Why do you change the cursor before displaying a new window? A. So that the user has some indication that the process is working. 145. What is the purpose of the displaySearchArticles() method? A. To display articles that match a specified keyword. 146. Why do you use a splash screen? A. To give the user something to be occupied with while the application loads. 147. What method gets the current Toolkit object for the component? A. getToolkit() 148. What method draws an image on the component? A. drawImage() 149. What information does the About dialog box display? A. Application and company information. 150. Where is the About dialog box called from? A. From the Help menu. 151. What does the Resources Choice object display? A. The application and/or technologies that an article is associated with. 152. What is entered into the article keyword edit field? A. Keywords that will be identified with the article. 153. What two items are checked to ensure that the user has entered values in the Add dialog box? A. Article title and article text. 154. What Java object is used to parse the keywords entered by the user? A. StringTokenizer 155. What does the hasMoreTokens() method tell you? A. Whether there are more keywords left to process. 156. What must the Layout Manager be set to in order to alter component sizes manually? A. NULL 157. What is the method used to change the size and placement of a component manually?

A. reshape() 158. What is a modal window? A. A window that is active until it is closed. 159. If a dialog box is modal, can the user switch between the application window and the dialog box window? A. No. 160. What three arguments are passed to the constructor for the Dialog class? A. Parent frame, a title, and a Boolean value indicating modal state. 161. Why is it always a good idea to close a Statement object manually? A. To free resources that are used by an object. 162. What is an orphaned record? A. A record that is left in the database but has no parent information. 163. Why should you always delete child records before deleting the main record? A. To prevent orphaned records. 164. What table contains the keywords that the user entered for the article? A. tKeyword. 165. What is the method called by the Search Articles dialog box to display the articles in themain window? A. displaySearchArticles() 166. What interface in Java1.1 enables you to "listen" for normal mouse events? A. MouseListener 167. What method adds an ActionListener interface to listen to events for a specified component? A. addActionListener() 168. What method returns the name of the menu item selected? A. getActionCommand() 169. What method displays a pop-up menu to the user? A. show() 170. What is passed to the show() method of the PopupMenu object?

A. A container object and the position to display at. 171. Name the two objects used to allow serialization in Java. A. ObjectOutputStream and ObjectInputStream 172. What method enables you to write an integer to a stream using ObjectOutputStream? A. writeInt() 173. What method enables you to read an object from a stream using ObjectInputStream? A. readObject() 174. What parameter does the MenuShortcut constructor take? A. An integer value identifying an ASCII character. 175. What does RMI stand for? A. Remote Method Invocation. 176. How many thread objects will the object server use for client connections? A. Seven. 177. What is the URL for the database we are using? A. jdbc:odbc:JDBC 178. What method of the IDList component returns the employee ID for the selected item? A. getSelectedID() 179. What object is used to listen for client connectioins? A. ServerSocket 180. What method connects a client to a server? A. accept() 181.What method is used to get the output stream for a socket object? A. getOutputStream() 182. What method is used to read String objects from an object stream? A. readObject() 183. What method clears the contents of an object output stream to ensure that the client receives the data? A. flush() 184. What is the purpose of the Delete object?

A. To delete specified employees from the database. 185. What object is used to send the deleteEmployeeDialog to the client? A. ObjectOutputStream 1. What's the JDBC 2.0 API? The JDBC 2.0 API is the latest update of the JDBC API. It contains many new feat ures, including scrollable result sets and the new SQL:1999 (formerly SQL 3) dat a types. There are two parts to the JDBC 2.0 API: the JDBC 2.0 core API (the java.sql package), which is included in the JavaTM 2 SDK, Standard Edition the JDBC 2.0 Optional Package API (the javax.sql package), which is available se parately or as part of the Java 2 SDK, Enterprise Edition 2. Does the JDBC-ODBC Bridge support the new features in the JDBC 2.0 API? No, the JDBC-ODBC Bridge that is included in the Java 2 Platform initial release does not support the new features in the JDBC 2.0 API. However, Sun and Merant are working to produce a new version of the Bridge that does support the new fea tures. Note that we do not recommend using the Bridge except for experimental pu rposes or when you have no other driver available. 3. Can the JDBC-ODBC Bridge be used with applets? Use of the JDBC-ODBC bridge from an untrusted applet running in a browser, such as Netscape Navigator, isn't allowed. The JDBC-ODBC bridge doesn't allow untrust ed code to call it for security reasons. This is good because it means that an u ntrusted applet that is downloaded by the browser can't circumvent Java security by calling ODBC. Remember that ODBC is native code, so once ODBC is called, the Java programming language can't guarantee that a security violation won't occur . On the other hand, Pure Java JDBC drivers work well with applets. They are ful ly downloadable and do not require any client-side configuration. Finally, we would like to note that it is possible to use the JDBC-ODBC bridge w ith applets that will be run in appletviewer since appletviewer assumes that app lets are trusted. It is also possible to use the JDBC-ODBC bridge with applets t hat are run in the HotJavaTM browser (available from Java Software), since HotJa va provides an option to turn off applet security. In general, it is dangerous t o turn applet security off, but it may be appropriate in certain controlled situ ations, such as for applets that will only be used in a secure intranet environm ent. Remember to exercise caution if you choose this option, and use an all-Java JDBC driver whenever possible to avoid security problems. 4. How do I start debugging problems related to the JDBC API? A good way to find out what JDBC calls are doing is to enable JDBC tracing. The JDBC trace contains a detailed listing of the activity occurring in the system t hat is related to JDBC operations. If you use the DriverManager facility to establish your database connection, you use the DriverManager.setLogWriter method to enable tracing of JDBC operations. If you use a DataSource object to get a connection, you use the DataSource.setL ogWriter method to enable tracing. (For pooled connections, you use the Connecti onPoolDataSource.setLogWriter method, and for connections that can participate i n distributed transactions, you use the XADataSource.setLogWriter method.) 5. How can I use the JDBC API to access a desktop database like Microsoft Access over the network? Most desktop databases currently require a JDBC solution that uses ODBC undernea th. This is because the vendors of these database products haven't implemented a ll-Java JDBC drivers. The best approach is to use a commercial JDBC driver that supports ODBC and the database you want to use. See the JDBC drivers page for a list of available JDBC drivers. The JDBC-ODBC bridge from Sun's Java Software does not provide network access to desktop databases by itself. The JDBC-ODBC bridge loads ODBC as a local DLL, an d typical ODBC drivers for desktop databases like Access aren't networked. The J

DBC-ODBC bridge can be used together with the RMI-JDBC bridge , however, to acce ss a desktop database like Access over the net. This RMI-JDBC-ODBC solution is f ree. 6. Does the JDK include the JDBC API and the JDBC-ODBC Bridge? Yes, the JDK 1.1 and the Java 2 SDK, Standard Edition (formerly known as the JDK 1.2), contain both the JDBC API and the JDBC-ODBC Bridge. The Java 2 SDK, Stand ard Edition, contains the JDBC 2.0 core API, which is the latest version. It doe s not include the JDBC 2.0 Optional Package, which is part of the Java 2 SDK, En terprise Edition, or which you can download separately. Note that the version of the JDBC API and the JDBC-ODBC Bridge provided for sepa rate download on the JDBC download page are only for use with the JDK 1.0.2. 7. What JDBC technology-enabled drivers are available? See our web page on JDBC technology-enabled drivers for a current listing. 8. What documentation is available for the JDBC API? See the JDBC technology home page for links to information about JDBC technology . This page links to information about features and benefits, a list of new feat ures, a section on getting started, online tutorials, a section on driver requir ements, and other information in addition to the specifications and javadoc docu mentation. 9. Are there any ODBC drivers that do not work with the JDBC-ODBC Bridge? Most ODBC 2.0 drivers should work with the Bridge. Since there is some variation in functionality between ODBC drivers, the functionality of the bridge may be a ffected. The bridge works with popular PC databases, such as Microsoft Access an d FoxPro. 10. Does the JDBC-ODBC Bridge work with Microsoft J++? No, J++ does not support the JDBC-ODBC bridge since it doesn't implement the Jav a Native Interface (JNI). Any all-Java JDBC driver should work with J++, however . 11. What causes the "No suitable driver" error? "No suitable driver" is an error that usually occurs during a call to the Driver Manager.getConnection method. The cause can be failing to load the appropriate J DBC drivers before calling the getConnection method, or it can be specifying an invalid JDBC URL--one that isn't recognized by your JDBC driver. Your best bet i s to check the documentation for your JDBC driver or contact yyour JDBC driver v endor if you suspect that the URL you are specifying is not being recognized by your JDBC driver. In addition, when you are using the JDBC-ODBC Bridge, this error can occur if on e or more the the shared libraries needed by the Bridge cannot be loaded. If you think this is the cause, check your configuration to be sure that the shared li braries are accessible to the Bridge. 12. Why isn't the java.sql.DriverManager class being found? This problem can be caused by running a JDBC applet in a browser that supports t he JDK 1.0.2, such as Netscape Navigator 3.0. The JDK 1.0.2 does not contain the JDBC API, so the DriverManager class typically isn't found by the Java virtual machine running in the browser. Here's a solution that doesn't require any additional configuration of your web clients. Remember that classes in the java.* packages cannot be downloaded by mo st browsers for security reasons. Because of this, many vendors of all-Java JDBC drivers supply versions of the java.sql.* classes that have been renamed to jdb c.sql.*, along with a version of their driver that uses these modified classes. If you import jdbc.sql.* in your applet code instead of java.sql.*, and add the jdbc.sql.* classes provided by your JDBC driver vendor to your applet's codebase , then all of the JDBC classes needed by the applet can be downloaded by the bro wser at run time, including the DriverManager class. This solution will allow your applet to work in any client browser that supports the JDK 1.0.2. Your applet will also work in browsers that support the JDK 1.1, although you may want to switch to the JDK 1.1 classes for performance reasons. Also, keep in mind that the solution outlined here is just an example and that other solutions are possible. 13. Why doesn't calling the method Class.forName load my JDBC driver?

There is a bug in the JDK 1.1.x that can cause the method Class.forName to fail. A workaround is to explicitly call the method DriverManager.registerDriver(new YourDriverClass()). The exact problem in the JDK is a race condition in the clas s loader that prevents the static section of code in the driver class from execu ting and registering the driver with the DriverManager. 14. Why do the java.sql and java.math packages fail to download java.* packages? Is there a workaround? For security reasons, browsers will not download java.* packages. In order to us e the JDBC API with browsers that have not been upgraded to JDK1.1 or beyond, we recommend that the java.sql and java.math packages be renamed jdbc.sql and jdbc .math. Most vendors supplying JDBC technology-enabled drivers that are written p urely in the Java programming language already provide versions of these renamed packages. When JDK 1.1 support has been added to your browser, you should conve rt your applets back to the java.* package names. 15. Why is the precision of java.math.BigDecimal limited to 18 digits in the JDK 1.0.2 add-on version of the JDBC API? In JDK 1.1, java.math.BigInteger is implemented in C. It supports a precision of thousands of digits. The same is true for BigDecigmal. The version of BigInteger provided with the JDK 1.0.2 add-on version of the JDBC API is a simplified version written in the Java programming language, and it is limited to 18 digits. Because the implementation of BigDecimal is based on BigI nteger, it also is limited to this precision. In the JDBC 2.0 API, you can use a new version of the method ResultSet.getBigDec imal that does not take a scale parameter and returns a BigDecimal with full pre cision. 16. Can the JDBC API be added to JDK 1.0.2? Yes. Download the JDBC 1.22 API from the JDBC download page and follow the insta llation instructions in the release notes. If you are using any version of the JDK from 1.1 on, the JDBC API is already inc luded, and you should not download the JDBC 1.22 API. 17. How do I retrieve a whole row of data at once, instead of calling an individ ual ResultSet.getXXX method for each column? The ResultSet.getXXX methods are the only way to retrieve data from a ResultSet object, which means that you have to make a method call for each column of a row . It is unlikely that this is the cause of a performance problem, however, becau se it is difficult to see how a column could be fetched without at least the cos t of a function call in any scenario. We welcome input from developers on this i ssue. 18. Why does the ODBC driver manager return 'Data source name not found and no d efault driver specified Vendor: 0' This type of error occurs during an attempt to connect to a database with the br idge. First, note that the error is coming from the ODBC driver manager. This in dicates that the bridge-which is a normal ODBC client-has successfully called OD BC, so the problem isn't due to native libraries not being present. In this case , it appears that the error is due to the fact that an ODBC DSN (data source nam e) needs to be configured on the client machine. Developers often forget to do t his, thinking that the bridge will magically find the DSN they configured on the ir remote server machine 19. Are all the required JDBC drivers to establish connectivity to my database p art of the JDK? No. There aren't any JDBC technology-enabled drivers bundled with the JDK 1.1.x or Java 2 Platform releases other than the JDBC-ODBC Bridge. So, developers need to get a driver and install it before they can connect to a database. We are co nsidering bundling JDBC technology- enabled drivers in the future. 20. Is the JDBC-ODBC Bridge multi-threaded? No. The JDBC-ODBC Bridge does not support concurrent access from different threa ds. The JDBC-ODBC Bridge uses synchronized methods to serialize all of the calls that it makes to ODBC. Multi-threaded Java programs may use the Bridge, but the y won't get the advantages of multi-threading. In addition, deadlocks can occur between locks held in the database and the semaphore used by the Bridge. We are

thinking about removing the synchronized methods in the future. They were added originally to make things simple for folks writing Java programs that use a sing le-threaded ODBC driver. 21. Does the JDBC-ODBC Bridge support multiple concurrent open statements per co nnection? No. You can open only one Statement object per connection when you are using the JDBC-ODBC Bridge. 22. Does the JDBC-ODBC Bridge developed by Merant and Sun support result sets th at contain Japanese Characters (DBCS)? Yes, but we haven't tested this ourselves. The version of the Bridge in the Java 2 SDK, Standard Edition, and Java 2 SDK, Enterprise Edition, also supports a ne w charSet Connection property for specifying the character encoding used by the underlying DBMS. 23. Why can't I invoke the ResultSet methods afterLast and beforeFirst when the method next works? You are probably using a driver implemented for the JDBC 1.0 API. You need to up grade to a JDBC 2.0 driver that implements scrollable result sets. Also be sure that your code has created scrollable result sets and that the DBMS you are usin g supports them. 24. How can I retrieve a String or other object type without creating a new obje ct each time? Creating and garbage collecting potentially large numbers of objects (millions) unnecessarily can really hurt performance. It may be better to provide a way to retrieve data like strings using the JDBC API without always allocating a new ob ject. We are studying this issue to see if it is an area in which the JDBC API should be improved. Stay tuned, and please send us any comments you have on this questi on. 25. There is a method getColumnCount in the JDBC API. Is there a similar method to find the number of rows in a result set? No, but it is easy to find the number of rows. If you are using a scrollable res ult set, rs, you can call the methods rs.last and then rs.getRow to find out how many rows rs has. If the result is not scrollable, you can either count the row s by iterating through the result set or get the number of rows by submitting a query with a COUNT column in the SELECT clause. 26. I would like to download the JDBC-ODBC Bridge for the Java 2 SDK, Standard E dition (formerly JDK 1.2). I'm a beginner with the JDBC API, and I would like to start with the Bridge. How do I do it? The JDBC-ODBC Bridge is bundled with the Java 2 SDK, Standard Edition, so there is no need to download it separately. 27. If I use the JDBC API, do I have to use ODBC underneath? No, this is just one of many possible solutions. We recommend using a pure Java JDBC technology-enabled driver, type 3 or 4, in order to get all of the benefits of the Java programming language and the JDBC API. 28. Once I have the Java 2 SDK, Standard Edition, from Sun, what else do I need to connect to a database? You still need to get and install a JDBC technology-enabled driver that supports the database that you are using. There are many drivers available from a variet y of sources. You can also try using the JDBC-ODBC Bridge if you have ODBC conne ctivity set up already. The Bridge comes with the Java 2 SDK, Standard Edition, and Enterprise Edition, and it doesn't require any extra setup itself. The Bridg e is a normal ODBC client. Note, however, that you should use the JDBC-ODBC Brid ge only for experimental prototyping or when you have no other driver available. -----------------------------------------------------------------------------------What is a JDBC Driver? ---------------------A JDBC driver is the set of classes that implement the JDBC interfaces for a par ticular database.

There are four different types of JDBC driver: A Type 1 driver is a JDBC-ODBC br idge driver; this type of driver enables a client to connect to an ODBC database via Java calls an d JDBC -- neither the database nor middle tier need to be Java compliant.However, ODBC binary code must be installed on each client machine that uses this driver. A Type 2 driver converts JDBC calls into calls for a specific database. This dri ver is referred to as a "native-API, partly Java driver." As with the Type 1 dri ver, some binary code may be required on the client machine, which means this ty pe of driver is not suitable for downloading over a network to a client. A Type 3 driver is a JDBC-Net pure Java driver, which translates JDBC calls into a database -independent net protocol. Vendors of database middleware products c an implement this type of driver into their products to provide interoperability with the greatest number of database servers. Finally, a Type 4 driver, or, "native protocol, pure Java" driver converts JDBC calls into the network protocol used by the database directly. A Type 4 driver requires no client software, so it's ideal for deployment to browsers at runtim e. Each of these driver types has its own optimal usage scenarios, and will affe ct the way you deploy a given Java application. For example, because Type 4 drivers are 100% Java, use Java sockets to connect t o the database, and require no client-side data access code, they are ideal for applets or other download situations inside a firewall. Oracle's JDBC Drivers --------------------Oracle provides both Type 2 and Type 4 drivers. All Oracle JDBC drivers support the full JDBC specification, but in addition, they support the extended capab ilities of the Oracle database. For example, the JDBC specification doesn't sup port LOB data, but the Oracle OCI8 JDBC driver does. Oracle's implementation of the Type 2 JDBC driver is referred to as the Oracle "OCI driver," and the versio n of this driver that supports an Oracle 7 database is the OCI7 driver and the O CI8 supports Oracle 8. These drivers are platform specific; for example, the Win dows NT and Windows 95 version of the driver (oci805jdbc.dll.) is implemented as a dynamic link library (DLL) in C. As mentioned previously, Type 2 drivers may require client code. In the case of the OCI8 driver, the clients must have Oracl e's Net*8 and all other dependent files loaded. A common way to implement Oracle OCI drivers is to use Oracle Application Server with the JWeb cartridge on the middle tier and deploy the client presentation l ogic as an applet; the interaction with the Oracle database is conducted from th e middle tier only, with just the results sent to the client applet as pure HTM L or Java and HTML. All Oracle drivers are compliant with the Java Development K it JDK 1.0 and 1.1.x and support the JDBC 1.22 standard. In addition, all Oracle JDBC drivers support data types such as RAW and LONG RAW, ROWID, and RECURSOR, which are supported in Oracle databases but not part of the JDBC standard. Orac le's drivers also support execution of PL/SQL stored procedures and anonymous bl ocks (for dynamic execution), and include capabilities such as row pre-fetching, execution batching, and defining query columns to reduce the network round trips to Oracle database. In addition, the OCI driver f or Oracle8 supports oracle data types CLOB, BLOB, NCLOB, and BFILE. The screensh ot shows an example of one of the classes in the Oracle JDBC, as part of the cla ss hierarchy from which it descends, as displayed in Oracle's JDeveloper integra ted development environment. As you can see, the OraclePreparedStatement clas s inherits from the java.sql.PreparedStatement class, which in turn inherits fr

om the java.sql.Statement. Oracle also provides a Type 4 JDBC driver, referred to as the Oracle "thin" driv er. This driver includes its own implementation of a TCP/IP version of Oracle's Net8 written entirely in Java, so it is platform independent, can be downloaded to a browser at runtime, and does not require any Oracle software on the clien t side. This driver requires a TCP/IP listener on the server side, and the clien t connection string uses the TCP/IP port address, not the TNSNAMES entry for the database name. 1.Add JDBC classes to your Java application or applet class by adding the follow ing statement to your Java source code: import java.sql.*; To use the extended capabilities of the Oracle database, you must also im port the Oracle JDBC driver. The statement in Java source looks like this: import oracle.JDBC.driver.* 2.Load the JDBC driver by including the following statement in your class. Class.forName("oracle.JDBC.driver.OracleDriver"); You can load the driver from your class-initialization routine. 3.Obtain a connection to an Oracle database by calling the getConnection() method of the JDBC DriverManager class. When you call this method you need to specify t he connection information for the database in the form of a URL. The form the URL will take depends on the driver used. For example, to use the pure Java Type 4 Oracle driver ( the thin driver) to connect to an Oracle7 database, the URL would read: jdbc:oracle:thin@database_name:port_no:SID To connect to an Oracle8 database using the OCI driver, the URL would be more like: jdbc:oracle:oci8@database_name To specify the database for use with an OCI driver, you can use either a SQL*Net namevalue pair, or, if you're using an Oracle Name server, you can use the na me from the tnsname.ora file. (Both of these strings would conclude with the logon in formation as well -specifically the user name and password -- but we've eliminated that from this example.) The preliminary driver and database-connection issues now taken care of, there are still several other things your Java source code must include in order for the compiled code to submit queries to the database and process results. 4.Create a Statement object by calling the createStatement() method of the Connection object you created in the previous step. The following statement cre

ates a Statement object stmt: Statement stmt = conn.createStatement (); 5.Once the Statement object exists (in code), the application can then inc lude code to execute a SQL query by calling the executeQuery() method of the St atement object.The executeQuery() method returns the result of the query in the ResultSet object. The following statement executes a query : ResultSet rset = stmt.executeQuery (SELECT ename from emp where empno = 7 900); 6.Finally, call the next() method of a ResultObject to retrieve a row and display it. Use a loop if the query returns more then one row from the database. For example, the following statements get the name of an employee from th e ResultSet object and display it in the java.awt text control placed on the GUI. rset.next(); enameTxtb.setText = ((String)rset.getString(1)); ---------------------------------------------------------------------------------------------------1. What is JDBC ? what are its advantages ? A. It is an API .The latest version of jdbc api is (3.0). The JDBC 3.0 API is divided into two packages: (1) java.sql and (2) javax.sql. Both packages are included in the J2SE and J2EE platforms. advantages: --------------The JDBC API can be used to interact with multiple data sources in a distr ibuted, heterogenous environment. It can connect to any of the database from java language. It can switch over to any backend database without changing java code or b y minute changes. 2. How many JDBC Drivers are there ? what are they? A. There are 4 types of JDBC drivers. a. JDBC-ODBC Bridge Driver(Type-1 driver) b. Native API Partly Java Driver(Type-2 driver) c. Net protocol pure Java Driver(Type-3 driver) d. Native protocol Pure Java Driver(Type-4 driver) 3. Explain about JDBC-ODBC driver(Type-1) ? When this type of driver is used ? A. In this mechanism the flow of execution will be Java code(JDBC API)JDBC-ODBC bridge driverODBC APIO DBC LayerDataBase This type of JDBC Drivers provides a bridge between JDBC API and ODBC API. This Bridge(JDBC-ODBC bridge) translates standard JDBC calls to Corresponding ODBC Calls, and send them to ODBC database via ODBC Libraries. The JDBC API is based on ODBC API. ODBC(Open Database Connectivity)is Microsoft's API for Database drivers. ODBC is based on X/Open Call Level Interface(CLI)specification for database a

ccess. The URL and class to be loaded for this type of driver are Class :- sun.jdbc.odbc.JdbcOdbcDriver URL :- jdbc:odbc:dsnname 4. Explain about Type-2 driver ? When this type of driver is used ? A. The Drivers which are written in Native code will come into this category In this mechanism the flow of Execution will be java code(JDBC API)Type-2 driver(jdbc driver)Native API(vend or specific)DataBase When database call is made using JDBC,the driver translates the request into vendor-specific API calls. The database will process the requet and sends the results back through the N ative API ,which will forward them back to the JDBC dirver. The JDBC driver will format the results to conform to the JDBC standard and return them to the application. 5. Explain about Type-3 driver ? When this type of driver is used ? A. In this mechanism the flow of Execution will be java code(JDBC API)JDBC driverJDBC driver serverNa tive driverDataBase The Java Client Application sends the calls to the Intermediate data access s erver(jdbc driver server) The middle tier then handles the requet using other driver(Type-II or Type-IV drivers) to complete the request. 6. Explain about Type-4 driver ? When this type of driver is used ? A. This is a pure java driver(alternative to Type-II drivers). In this mechanism the flow of Execution will be java code(JDBC API)Type-4 driver(jdbc driver)DataBase These type of drivers convert the JDBC API calls to direct network calls usin g vendor specific networking protocal by making direct socket connection with database. examples of this type of drivers are 1.Tabular Data Stream for Sybase 2.Oracle Thin jdbc driver for Oracle 7. What are the Advantages & DisAdvantages of Type-2 ,Type-4 Drivers over JDBC-O DBC bridge driver(Type-1)? A. Type-2 & Type-4 are given 8. Which Driver is preferable for using JDBC API in Applets? A. Type-4 Drivers. 9.Write the Syntax of URL to get connection ? Explain? A.Syntax:- jdbc:: jdbc -----> is a protocal .This is only allowed protocal in JDBC. ----> The subprotocal is used to identify a database driver,or the

name of the database connectivity mechanism, choosen by the database driver p roviders. -------> The syntax of the subname is driver specific. The driver may choose any syntax appropriate for its implementation ex: jdbc:odbc:dsn jdbc:oracle:oci8:@ database name. jdbc:orale:thin:@ database name:port number:SID 10.How do u Load a driver ? A. Using Driver Class.forName(java.lang.String driverclass) or registerDriver(Dr iver driver) . 11.what are the types of resultsets in JDBC3.0 ?How you can retrieve information of resultset? A. ScrollableResultSet and ResultSet.We can retrieve information of resultset by using java.sql.ResultSetMetaData interface.You can get the instance by calling the method getMetaData() on ResulSet object. 12.write the steps to Connect database? A. Class.forName(The class name of a spasific driver); Connection c=DriverManager.getConnection(url of a spasific driver,user name,p assword); Statement s=c.createStatement(); (or) PreparedStatement p=c.prepareStatement(); (or) CallableStatement cal=c.prpareCall(); Depending upon the requirement. 13.Can java objects be stored in database? how? A.Yes.We can store java objects, BY using setObject(),setBlob() and setClob() me thods in PreparedStatement 14.what do u mean by isolation level? A. Isolation means that the business logic can proceed without consideration for the other activities of the system. 15.How do u set the isolation level? A. By using setTransactionIsolation(int level) in java.sql.Connection interface. level MEANS:static final static final static final epeatable read. static final epeatable read &

int TRANSACTION_READ_UNCOMMITTED //cannot prevent any reads. int TRANSACTION_READ_COMMITTED //prevents dirty reads int TRANSACTION_REPEATABLE_READ //prevents dirty reads & non-r int TRANSACTION_SERIALIZABLE phantom read.

//prevents dirty reads , non-r

These are the static final fields in java.sql.Connection interface. 16. what is a dirty read? A. A Dirty read allows a row changed by one transaction to be read by another transaction before any change in the row have been committed.

This problem can be solved by setting the transaction isolation level to TRANSACTION_READ_COMMITTED 17. what is a non-repeatable read ? A. A non-repeatable read is where one transaction reads a row, a second transaction alters or deletes the row, and the first transaction re-reads the row,getting different values the second time. This problem can be solved by setting the transaction isolation level to TRANSACTION_REPEATABLE_READ 18. what is phantom read? A. A phantom read is where one transaction reads all rows that satisfy a WHERE condition,a second transaction inserts a row that satisfies that WHERE condition,and the first transaction re-reads for the same condition,retrieving the additional 'phantom' row in the second read This problem can be solved by setting the transaction isolation level to TRANSACTION_SERIALIZABLE 19.What is the difference between java.sql.Statement & java.sql.PreparedStatement ? write the appropriate situations to use these statements? A. 20.How to retrieve the information about the database ? A.we can retrieve the info about the database by using inerface java.sql.DatabaseMetaData we can get this object by using getMetaData() method in Connection interface. 21.what are the Different types of exceptions in jdbc? A. BatchUpdateException DataTruncation SQLException SQLWarning 22.How to execute no of queries at one go? A. By using a batchUpdate's (ie throw addBAtch() and executeBatch()) in java.sql.Statement interface,or by using procedures. 23. what are the advantages of connection pool. A. Performance 24.In which interface the methods commit() & rollback() are defined ? A.java.sql.Connection interface 25.How to store images in database? A. Using binary streams (ie getBinaryStream() ,setBinaryStream()).But it is not visable in database ,it is stored in form of bytes ,to make it visable we have t o use any one frontend tool. 26.How to check null value in JDBC? A. By using the method wasNull() in ResultSet ,it returns boolean value. Returns whether the last column read had a value of SQL NULL. Note that you must first call one of the getXXX methods on a column to try to read its value and then call the method wasNull to see if the value read was SQ L NULL.

27.Give one Example of static Synchronized method in JDBC API? A. getConnection() method in DriverManager class.Which is used to get object of Connection interface. 28.What is a Connection? A. Connection is an interface which is used to make a connection between client and Database (ie opening a session with a particular database). 29.what is the difference between execute() ,executeUpdate() and executeQuery() ? where we will use them? A. execute() method returns a boolean value (ie if the given query returns a resutset then it returns true else false),so depending upon the return value we can get the ResultSet object (getResultset())or we can know how many rows have bean affected by our query (getUpdateCount()).That is we can use this method for Fetching queries and Non-Fetching queries. Fetching queries are the queries which are used to fetch the records from dat abase (ie which returns resutset) ex: Select * from emp. Non-Fetching queries are the queries which are used to update,insert,create o r delete the records from database ex: update emp set sal=10000 where empno=7809. executeUpdate() method is used for nonfetching queries.which returns int valu e. executeQuery() method is used for fetching queries which returns ResulSet obj ect ,Which contains methods to fetch the values. 30.How is jndi useful for Database connection? A. JNDI (java naming directory interface) ====================================== 1. what are the uses of jndi? A. The role of the JNDI API in the J2EE platform is two fold. a) It provides the means to perform standard operations to a directory service resource such as LDAP (Lightweight Directory Access Protocal),Novell Directory Sevices, or Netscape Directory Services. b) A J2EE applicatin utilizes JNDI to look up interfaces used to create,amongs t other things,EJBs,and JDBC connection. 2. How vendor Naming registry supports JNDI? A. JMS (JAVA MESSAGING SERVICE) ============================ 1. What is JMS ? A. JMS (JAVA MESSAGING SERVICE) is an API .It is a specification with one package javax.jms .It is a technology which can pass the information synchronously or asynchronously . 2. On what technology is JMS based ?

A. JMS is based on Message-Oriented MiddleWare (MOM). 3. What was the technology for messaging services before JMS was released? A. Before JMS API specification was released by javasoft ,there was IBM's MQSeries implementation of MOM (Message-Oriented MiddleWare). 4. What is MOM (Message-Oriented MiddleWare) ? A. MOM is a software infrastructure that asynchronously connects multiple system's through the production and consumption of data message. 5. How many types of data passing does JMS specification allows ?What are they? A. JMS specification allows two types of data passing. a)publish/subscribe [pub/sub model] b)point-to-point [p-t-p model] 6. In real time which type of data passing is used ? A. Mostly in real time applications we use both types of data passing combinedly . 7. How jndi is used in JMS ? A. While writing JMS application (pub/sub or p-t-p) we need TopicConnection or QueueConnection . we use jndi to get this connections . 8. Write the steps to write pub/sub model application ? A. steps to write Publisher (sender) application :----------------------------------------------a)We have to get the TopicConnection through jndi. b)Create TopicSession by invoking a method createTopicSession() . c)create a Topic object by invoking createTopic() on TopicSession interface. d)create a TopicPublisher object of a Topic by invoking createPublisher(java x.jms.Topic t) on TopicSession.(t is a Topic object that specifies the Topic we want to s ubscribe to). e)create TextMessage object and set the text to be published . f)publish the message by using a method publish() in Publisher interface . steps to write subscriber (receiver) application :-------------------------------------------------a)We have to get the TopicConnection through jndi. b)Create TopicSession by invoking a method createTopicSession() . c)create a Topic object by invoking createTopic() on TopicSession interface. d)create a TopicSubscriber object of a Topic by invoking createSubscriber(ja vax.jms.Topic) or createDurableSubscriber(javax.jms.Topic t,String name,String messageselect or,boolean nolocal) on TopicSession. t ------> is a Topic object that specifies the Topic we want to subscribe to. name ---> is a String that indicates the name under which to mai ntain the Durable Subscribtion to the specified topic. messageselector --> is a String that defines selection criteria. nolocal -------> is a boolean if it is true the Subscriber will not rec ive messages that were published by the client application . 9. What is the diffrence between DurableSubscription and non-DurableSubscription ? A. DurableSubscription :-------------------

DurableSubscription indicates that the client wants to recive all the messa ges published to a topic, including messages published when the client connection is not active. Non-DurableSubscription :----------------------Non-DurableSubscription will not recive the messages published when the cli ent connection is not active. 10. Write the steps to write p-to-p model application ? A. steps to write Sender application :--------------------------------a)We have to get the QueueConnection through jndi. b)Create QueueSession by invoking a method createQueueSession() . c)Create a Queue object by invoking createQueue() on QueueSession interface. d)Create a QueueSender object of a Queue by invoking createSender(javax.jms. Queue q) on QueueSession. e)Create TextMessage object and set the text to be send . f)Send the message by using a method send() . steps to write Receiver application :-----------------------------------a)We have to get the QueueConnection through jndi. b)Create QueueSession by invoking a method createQueueSession() . c)Create a Queue object by invoking createQueue() on QueueSession interface. d)Create a QueueReceiver object of a Queue by invoking createReceiver(javax. jms.Queue) on QueueSession. JTA (JAVA TRANSACTION API) ========================== 1. what is JTS? A. JTS (JAVA TRANSACTION SERVICE) is the java implementation of CORBA's OTS (OBJECT TRANSACTION SERVICE). 2. what is JTA ? A. JTA (JAVA TRANSACTION API) is the API released by javasoft under J2EE. It was released after the release of JTS . 3. what are the advantages of JTA over JTS? A. JTA (JAVA TRANSACTION API) is more flexible and simple to use by the programer .The JTA API is divided into two parts a)high-level X/Open Call Level Interface(CLI) b)low-level XA Call Level Interface(CLI) As a programmer using JTA he has to concentrate on high-level x/open interface .The low-level XA operations are taken care by the server which is giving the implementation to JTA API. The user will never perform XA operations directly.This makes the user more simple to manipulate with transactions. 4. How JTA or JTS is used by client ? A. client uses UserTransaction interface in both the cases(JTA/JTS). -------------------------------------------------------------------------------------------------------------JSP

1. I wrote a JSP and then changed the code, but it still appears the same in the browser. Why? A. Try stopping Tomcat and then starting it up again. Tomcat does not support Servlet reloading, and sometimes your JSP will not get updated. 2. What are the benefits of using JSPs over Servlets? A. There are several benefits of using JSPs. One of the major benefits of using JSPs over Servlets is that you dont have to be a very experienced Java programmer. You only need to understand the basics of Java in order to add the dynamic content. Also, JSPs are easier for presentation purposes. You can create your HTML page and make it look pretty, or your geographical department at work can do this. Then you can add the dynamic content. A great benefit of JSPs over Servlets is the separation of roles. 3. What directory structure should I use if I am using Tomcat? A. If you decide to use TOmcat for some of the examples, you will want to to use the directory structure c:\tomcat\webapps\myJSPs\HourXX. This type of directory structure helps you keep your files organized. 4. Does it matter where I registere the JSPServlet and configure its initial arguments in the weblogic.properties file? A. No, it does not matter. You can register the Servlet anywhere and configure the initial arguments anywhere. If you put your configuration and arguments at the top of the file, it will be easy for you to locate them. 5. What is the difference between a JSP declaration tag and the JSP scriptlet tag? I understand that you can declare variables in the declaration tag but can you declare them in the scriptlet tag? A. As far as variable declaration and initialization is concerned, declaration and scriptlet tags are identical. The difference lies in the declaration of methods. YOu can only declare methods in a JSP declaration tag. These methods are not executed until referenced from within JSP scriptlet tags. Declaring variables in a JSP declaration tag is just a good programming practice of organizing your code so that it is easier to read. 6. I don't understand the need for JavaBeans. What can you do with JavaBeans that you can't do with JSPs? A. JSPs can basically do everything a JavaBean can do, but these technologies were designed to complement one another and are specialized in their particular domain. JSPs are meant to quickly create dynamic content and interact with users at the presentation layer. JavaBeans used from JSPs are meant to process requests from the presentation layer and translate them into actions that affect the underlying infrastructure of a business, such as databases, other machines, other services printers and so on. 7. What happens if several browsers try to access my JSP all at once? A. Each browser request will be handled by a separate thread, and they will all try to execute the Servlet code generated from compiling the JSP. Variables and methods in declarations have class scope. This means that objects that you declare in a declaration are shared between multiple threads executing in the same Servlet instance. If you are knowledgeable about thread programming you should synchronize class scope objects. If you are not thread-programming savvy, I suggest that you declare your JSP

as not threadsafe by using the following directive within your JSP: By default, a JSP is set to threadsafe--that is, isThreadSafe=true. Declaring your JSP as not threadsafe forces the corresponding Servlet to implement the SingleThreadModel interface, which prevents multiple threads to execute in the same Servlet instance. 8. Can I use recursive methods in JSPs? A. Yes; everything you can do Java, you can do in JSPs. At certain times, a solution to a problem is best expressed in terms of the solution to smaller instances of the same problem. 9. How do I declare my own data types? A. You can declare your own data types by creating a class that best represents the data you want to handle and then using the class within your JSP code. For instance, the following class declares a new data type called Employee that captures the data typically associated with an Employee: public class Employee { protected String lastName, firstName, midInitial, title; protected int ssn; protected Date birthDate; hireDate; protected float salary; } In addition to all the data associated with an Employee object, you would typically declare several get and set methods that give you access to the data, as well as a constructor that initializes the object. From within a JSP you can declare employee objects, initialize them, and reference them: A JSP that

10. It seems that the JSP expression tags are limited to evaluating to a string. What if the result of some method call consists of a vector of values or some collection of objects--how could they be properly printed in HTML? A. JSP expressions are meant to be used to generate dynamic content inserted in HTML code. Nonetheless, you could conceive of a complex resulting string that contains HTML code that formats a vector of values into a table or items in a numbered list. Normally, you would first obtain the collection of objects, perhaps as an enumeration,and then use a for loop or a while loop to iterate through each of the elements in the collection using JSP scriptlet tags. You would then use JSP expression tags to evaluate each element of the collection individually to its string representation. 11. The query string in the request is just a list of name/value pairs. This

seems to have its limitations on what can be passed around between browsers and JSPs, or even between JSPs. Is there a way to overcome this limitation? A. Yes, a limitation exists in the amount and type of data that browsers and JSPs send to each other. The limitation is imposed by HTTP. Once you extract the parameters and their values, you can create objects that represent the data in an object-oriented form. These objects can then be stored permanently in hard drives, or temporarily in a user session to be shared between JSPs and other server side application components. Once the request parameters have been converted into objects, the limitation disappears on the server side. 12. HTML FORMS are great for gathering lots of information, but processing all those parameters and their values as strings seems to have its drawbacks. Is there a more appropriate way of processing HTML FORMS? A. Yes there is. You can create a JavaBean that has class variables with the same names as the parameter names and then use the special tag to automatically initialize the class variables of the JavaBean. 13. Can I store my own objects in a session? A. You can store any Java class in a session object. You have just to remember to cast the object back to its original type when you retrieve the object from the session. 14. What are the size limitations of cookies? How many cookies can I use? Where are they stored? A. Limitations on cookies vary from browser to browser. Cookies are typically 50 to 150 bytes in size. The maximum amount of data a cookie can hold is determined by the maximum size of the cookie header of an HTTP message, which is 4KB. Netscape browsers impose a maximum number of 20 cookies per server and a total maximum of 300 cookies. Internet Explorer stores cookies in the Temporary Internet Files directory for each user. Netscape stores cookies in a file called cookies.txt under its root installation directory. 15. Why are we initializing the Servlets in a configuration file? Why not put the initialization values in the JSP source code and forget the configuration file? A. Putting the initialization parameters in the JSP source code is an alternative to putting them inthe configuration file. The benefit of using a configuration file is that the source code does not need to change when the initialization parameters need to change. This makes the source code more portable and reusable. Also note that changes in the source code means that the resulting Servlet needs to be recompiled and redeployed. 16. When I change the source code of a JSP I can usually see the changes right away when I reload the JSP in my browser. This doesn't seem to apply for JSPs that have been converted to Servlets. Why? A. Yes, when you convert a JSP to a Servlet you lose the convenience of being able to change the JSP and see the changes immediately. The reason is

that Servlets from a JSP are like any other Servlet--they must be deployed and configured in the configuration file and the classes that implement them are loaded only once by the application server. This means that if you want a change in a JSP to reflect on its corresponding Servlet, you will need to reboot the application server. Some application servers allow hot deployment of some or all of its different services, including Servlets. Hot deployment means that some or all of the pieces of an application can be inserted or modified without shutting down the application server. Hot deployment together with deployment tools help the process of reconfiguring JSPs quickly but can't beat the versatility of just changing the source and having those changes take effect on-the-fly. Hr14 17. Would exceptions be useful in validating parameters from a form? How would that be done? A. Exceptions would certainly be useful in validating parameters submitted with forms. To process the parameters you would need to enumerate the fields of the form and the ranges or policies of each field. If the values of the submitted fields don't match the ranges or policies for the fields, an exception would be raised. The exception could contain an enumeration of the fields that had trouble and a message that politely asks the user to complete the highlighted fields appropriately. The enumeration of the troubled fields would be used to highlight the fields by either bolding them or setting their color to red. 18. What should I do if the applet does not load and execute? A. The first thing you can do is look at the code of the HTML file. One way to do this is to right-click in the browser and select View Source. If the plugin action tag is still there then it is not being interpreted by the JSP compiler. If this is the case, make sure that the parameter values have double quotes around them, that the tags are nested properly, and that there is a close tag for each of your open tag. If the embed tag is there and the fallback text is showing, make sure you have Java enabled in your browser. 19. Variables in a JavaBean can be set or read using the method calls or the setProperty and getProperty tags. Why the redundancy? A. Variables in a JavaBean are accessible to a JSP in three ways. You can access a variable directly from a scriptlet by referencing its name as in myBean.myVariable. You can also use the appropriate set or get method to set or access the variable's value. Finally you can use the JSP tags setProperty and getProperty. Referencing the variables or using methods give you the most flexibility, allowing you to combine the variables' value in expressions, statements and method calls. The tags give you simplicity and allow tools to easily manipulate JavaBeans. Tags in general HTML, XML or JSP make it easier to create development tools to manipulate documents and source code. 20. How do I connect to my Access database? A. To connect to an Access database you can use the Type 1 driver by Sun Microsystems. The driver class name is com.sun.jdbc.odbc.Driver and its URL is jdbc:odbc:DSNEntry. The driver class is in the jdbc.sql package.

The DSNEntry is a virtual name that refers to a real database through ODBC. In Windows 2000 you can use the ODBC Data Source Administrator to create these entries. To do this, assume you have an Access database called c:\myDB.mdb. From the Start Menu, select settings, Control Panel Administrative Tools, Data Sources. Once in the ODBC Data Source Administrator window, select the User DSN tab, MS Access Database, and then click the Add button. 21. What is the difference between the include directive and the include action? A. The include directive allows you to insert pre-parsed text into your JSPs, while the include action inserts the output of other JSPs. The include directive looks at the included file as a static object; the include action sees the included file as a dynamic object that takes a request. 22. When is the code from the included file inserted into the JSP? A. The code is inserted into the JSP at translation time. The include directive treats the included file as a static document and inserts the file's code at the location of the include directive in the JSP. 23. Why are custom action tags helpful in JSPs? A. One of the goals of JavaServer Pages is to separate the responsibilities and to allow beginner Java programmers to write these pages. With the custom tags, non-Java programmers can create dynamic content on the Web by writing JSPs with custom action tags instead of needing to write the code. 24. Why is a use case diagram helpful? A. Use case diagrams are used to graphically display the entities that can invoke an activity in the application and also what those entities can do. 25. What database is this application using? A. BEA WebLogic Server comes with an evaluation copy of Informix Cloudscape. This application is going to use that database for all its needs. ---------------------------------------------------------------------------An entity bean instance's life starts when the container creates the instance us ing newInstance(). The container then invokes the setEntityContext() method to pass the instance a reference to the EntityContext interface. The EntityContext interface allows the instance to invoke services provided by the container and to obtain the informa tion about the caller of a client-invoked method. The ejbFindByPrimaryKey() method is executed on the beans which are in the pool. With the execution of this call back method the instance does NOT move from the pool state to the ready state. The container invokes the ejbFind(...) method on an instance when a clie nt invokes a matching find(...) method on the entity bean's home interfa ce. The container must pick an instance that is in the pooled state for the exec ution of the ejbFind(...) method. If there is no instance in the pooled state, the container creates one and calls the setEntity-Context(...) method on the instance before dispatching the finder method.

If the ejbFind method is declared to return a single primary key, the co ntainer creates an entity EJBObject reference for the primary key and returns it to the client. If the ejbFind method is declared to return a collection of primary keys, the container creates a collection of entity EJBObject referen ces for the primary keys returned from the ejbFind, and returns the c ollection to the client. The instances in the pool are not associtaed with any entity object identity. Al l instances in the pool are considered equivalent. The bean travels from the pool state to the ready state when the Cr selects that instance to service a Client call to an entity object. The bean can traverse from the pooled state to the ready state in 2 ways: 1) ejbCreate(), ejbPostCreate() 2) ejbActivate() When Client calls create() on the home the Cr invokes ejbCreate(), ejbPostCreate () on the bean in the pool state. The container invokes the ejbActivate() method on an instance when an instance n eeds to be activated to service an invocation on an existing entity object this occurs because there is no suitable instance in the ready state to service the c lient's call. When an entity bean instance is in the ready state, the instance is associated w ith a specific entity object identity. While the instance is in the ready state, the container can synchronize the state of the instance with the state of the e ntity in the underlying data source whenever it determines the need to, in the process invoking the ejbLoad() and ejbStore() methods zero o r more times. A business method can be invoked on the instance zero or more time s. Before calling the ejbPassivate() the Cr calls ejbStore() on the bean in the rea dy state. This allows the instance to prepare itself for the synchronization of the database state with the instance's state, and to allow the persistence manag er to store the instance's state to the database. Now the instance moves from th e ready state to the pooled state. There are 3 ways for the instance to travel from the ready state to the pooled s tate: 1) ejbPassivate() 2) ejbRemove() 3) because of a transaction rollback for ejbCreate(), ejbPostCreate(), or ejbRemove(). ejbPassivate() is invoked by the container when it wants to disassociate the ins tance from the entity object identity without removing the entity object. ejbRemove() is called when the client calls remove() on the home interface or th e remote interface. When ejbRemove() is called the Cr removes the entity object. The instance can still obtain the identity of the entity object via the getPrim aryKey() or getEJBObject() method of the EntityContext interface. ejbCreate, ejbPostCreate() or ejbRemove() is called and the transaction rolls ba ck, the container will transition the bean instance to the pooled state. When the instance is put back into the pool, it is no longer associated with an entity object identity. The container can assign the instance to any entity obje

ct within the same entity bean home. The container can remove an instance in the pool by calling the unsetEntityConte xt() method on the instance. A RuntimeException thrown from any method of the entity bean class (including th e business methods and the callbacks invoked by the container) results in the tr ansition to the does not exist state. The container must not invoke any method o n the instance after a RuntimeException has been caught. From the client perspec tive, the corresponding entity object continues to exist. The client can continu e accessing the entity object through its remote interface because the container can use a different entity bean instance to delegate the client's requests. What resources the instance has claimed thru ejbActivate(), those resources shou ld be released by ejbPassivate(). If the Bean Provider has assigned dependent objects to instance variables (i.e., to non-container-managed fields of the bean instance), the Bean Provider should discard the references by setting the instance variables to null. Entity Bean object - object of the implementation class of EJBObject (Remote). Entity Bean Instance - object of the bean class which we write. Entity object identity remote reference ---------------------------------------------------------------------1. The database's initialization file often known as ________ which contains a series of parameters, many of which are used to size the various components of the SGA. A. INIT.ORA 2. A _____ is the smallest logical allocation of storage that Oracle8 can read from or write to the database at any one time. A. Block. 3. __________ is another vital part of the shared pool which contains structural information (metadata) about the database itself. (P.12) A. Data dictionary cache. 4. ______ redo log is a file to which Oracle writes redo entries from the redo log buffer. (P.15) A. active. 5. The SGA and background threads are collectively referred to as an Oracle ________ (P.17) A. Instance. 6. _________ is the combination of the instance and the database. (P.17) A. DBMS 7. The archived redo log files that have been generated must be saved. True/

false. (P.22) A. False. In fact you only need to keep the ones that have been generated since the last backup of the database has been taken. 8. What are the phases involved in two-phase commit protocol? (P.24) A. The two phases involved in the two-phase commit protocol are: --The prepared phase--All databases involved in the transaction signal they are indeed ready to commit. --The commit phase--All databases commit their individual portion of the distributed transaction, and then report that the commit occurred successfully. 9. What are the phases that occur when an SQL statement is executed? (P.25) A. Whenever an SQL statement of any kind is executed, three distinct phases occur: Parse -- The SQL statement is validated, and the syntax, semantics and so on are checked. If the statement is valid and executable, then the statement can be forwarded to the next phase. Execute -- The validated statement is executed against the database, and the results are made ready to be returned to the user. Fetch -- The desired rows are returned from the database to the user (assuming the SQL statement issued was a SELECT statement). 10. What are the actions that occur during an update? (P.27) A. Three actions occur simultaneously during an update: --The user makes the change to the appropriate block in the buffer cache. --The fact that the change has been made is recorded in the redo log buffer. --A before-image representation of the changed data is written to rollback segment, indicating that a change has been made but not yet committed. If the user issues a ROLLBACK statement or if there is a system failure, the rollback entry is used to restore the row to its previous condition. 11. Every Oracle8 user connection utilizes a _________ model. (P.28) A. Client/server. 12. ________ is created for a new user in the Oracle service if connected to the database. A. Shadow thread. 13. The bare minimum ______ RAM and ______ RAM will be practical minimum. (P.35) A. 48MB, 64MB. 14. A partition on a disk that does not have any file system on it is ________ (P.39) A. Raw partition. 15. A _________ is any number of Windows NT and Windows 95 machines that

share common resources. (P.41) A. Workgroup. 16. What the following Oracle Instance Manager (ORADIM80.EXE) indicate?(P.50) ORADIM80 -shutdown -sid ORCL -usrpwd oracle -shuttype srvc.inst -shutmode I A. shutdown--Indicates that the database is to be shutdown. sid--Specifies the name of the ORACLE_SID to be shutdown. usrpwd--Represents the INTERNAL password for the database. shuttype--Shuts down the database instance and its Windows NT service. shutmode I--Indicates that it is to be an immediate shutdown, disconnecting all users. 17. _______ is a central repository in which parameters for Windows application and Windows are stored. (P.85) A. Registry. 18. REG_SZ is a text string terminated by a ______ character. (P.87) A. NULL 19. The name of the SQL*Plus program is identified by ________ registry.(P.88) A. EXECUTE_SQL 20. The default value for ORACLE_HOME directory for Oracle Software is _____ A. C:\ORANT 21. Display Name is the name of the service in the Control Panel, such as ________ (P.95) A. OracleServiceORCL. 22. How do you start and stop remote services? (P.100) A. To stop and start remote services from the Server Manager, do the following: a. From the Start menu, select Administrative Tools/Server Manager. The Server Manager utility should start and display a list of computers in the network. b. Click on the computer that you want to manage, then select Computer/ Services from the Server Manager menu. c. The Services dialog box should appear for the remote computer, just as though you had accessed it from the Control Panel of the remote computer. The name of the remote computer should appear at the top of the dialog box. To start a remote service, click on the service name, then click on the Start button. To stop a remote service, click on the service name, then click on the Stop button. d. Click on Close to close the Services dialog box and return to the Server Manager main screen. 23. The service for an Oracle instance to perform IMMEDIATE shutdown can be done by ___________ which is Registry value added to the instance. (P.103) A. ORA_SID_SHUTDOWN

24. The Registry entries for Oracle will appear when __________ window and then_____is selected. A. HKEY_LOCAL_MACHINE, SOFTWARE|ORACLE 25. ________ keeps track of who is changing Oracle's Registry entries. (P.106) A. Registry Auditing. 26. What should be done for saving the current values? (P.108) A. The following has to be done for saving the current values: a. Start the Registry Editor (Start|Run|REGEDT32). The Registry should appear. b. Click on the HKEY_LOCAL_MACHINE window, then navigate to the ORACLE subkey. c. With the ORACLE subkey highlighted, select Registry|Save Key menu. The Save Key dialog box should appear. d. Enter a name for the file to contain the subkey values, then

Editor SOFTWARE| from the click on Save

. 27. Name some of the features included in Windows NT to manage security in the network environment. (P.113) A. Domains and Workgroups, user accounts, groups, profiles, system policies logon scripts, shared folders, and file permissions. 28. A _______ consists of Windows NT workstations in a peer-to-peer relationship. A. Workgroup 29. A ______ domain consists of a group of Windows NT servers and workstations. A. Domain. 30. ______ is a central NT server, where a single profile can be stored. (P.117) A. Roaming profile. 31. _____ is the extension for mandatory profile and ______ is an extension for roaming and personal files. A. .MAN , .USR 32. What are the steps to assign a logon script to a user account? (P.118) A. To assign a logon script to a user account: a. Start the User Manager For Domains (Start|Programs|Adminstrative Tools| User Manager For Domains) b. Double-click on the username to display the User Properties dialog box. c. Click on the Profile button to display the User Environment dialog box Enter the name of the logon script in the Logon Script Name field, then click on OK. d. Click on OK again to close the User Properties dialog box and return to the User Manager for Domains. 33. In a Windows NT network, folders are made available to network users

through creation of a _______. (P.118) A. Folder share. 34. Explain the types of file and folder permissions on NTFS drives. (P.119) A. Permission

Description

No Access

Prohibit all access to the folder. This is the default permission.

List

Allow a user to display the contents of the folder, but not read files or execute programs in the folder.

Read

Allow a user to view the contents of the folder or file, and execute programs.

Add

Allow a user to create new files or subfolders in the folder.

Add&Read

Allow all of the actions granted by the Add and Read permissions.

Change

Allow all of the actions granted by the Read permission, plus the ability to add, change or delete files or folders.

Full Control

Allow all of the actions granted by the Change permission, plus the ability of the user to change permissions or take ownership of the file or folder.

Special Directory Access

Customize permissions for a specified folder.

Special File Access

Customize permissions for a specified file.

35. Permissions are also available for FAT drives. True/false (P.120) A. False. Permissions are not available for FAT drives. 36. ______ and _______ are the categories of data dictionary views. (P.149) A. static and dynamic. 37. _______ and ______ are the two areas of the shared pool. (P.157) A. Library cache and data dictionary cache. 38. _______ indicates the number of misses in the library cache during execution. A. RELOADS. 39. Explain the page faults. (P.163) A. If a process needs to access a page that is not currently in its working set, then a page fault occurs. This can either be soft fault, where the required page is found elsewhere in memory, or a hard fault where the

required page is on disk and has to be read into memory. Soft faults don't cause any noticeable delays in the processing, but hard faults do, if there is a large number of them. 40. What are the benefits of Net8? (P.223) A. Here is a partial listing of Net8 benefits: -- Net8 can support thousands of simulaneous database connections, with a minimum of overhead. This ability is not exactly new, but it has not previously been available under Windows NT. -- Net8 is a protocol-independent. Your applications and the database are entirely insulated from the details of the network. The database and the applications that run against it don't have to worry about such things as packets, ports, or sockets. Net8 will support whatever mix of protocols you currently have in place. And if you decide to run your application and database using different network protocols, nothing has to be rewritten. -- Net8 is a topology- and media-independent. Token Ring? Ethernet? Sure. Thin-wire? Thick-wire? FDDI? No problem. Once again, you can mix and match as needed. -- Net8 and ODBC work together seamlessly. If you write an application that uses ODBC, the ODBC driver makes Net8 calls as needed. Your application will never know the difference. 41. What are the guidelines to be followed when placing archived redo logs? (P.280) A. When placing archived redo logs, follow these guidelines: -- Place archived redo logs on a device separate from the online redo logs to reduce contention between LGWR and ARCH. -- Ensure that there is adequate free space and that the drive is fast enough to allow ARCH to finish archiving an online redo log before LGWR wraps around to it. 42. ________ contain objects that are more frequently accessed than other objects in the database. (P.281) A. Hot tablespaces. 43. _______ is an area of storage in which an Oracle disk sort occurs. A. Temporary segment. 44. If the redo log member is incorrect or incomplete then it is a ______ status. (P.316) A. STALE 45. What are the LOB datatypes that can be stored in an Oracle Database? (P.344) A. There are three different LOB datatypes that can be stored in an Oracle database, each of which is suited for different applications:

--CLOB--Character large object. Used for storage of character data. --BCLOB--Intended for multibyte character data, such as Japanese. --BLOB--Binary large object. BLOBs are useful for storing multimedia data, such as sound, pictures and video. 46. _________ attribute is used to speed up long-running DML statements. (P.389) A. NOLOGGING 47. Explain the extended ROWID components. (P.437) A. The extended ROWID is broken into the following four distinct components: Data object number--six characters Relative file number--three characters Block number--Six characters Row number--three characters 48. Explain the restricted ROWID components. (P.442) A. A restricted ROWID is represented by the following three distinct components: Block number--Eight characters. This represents the block number in the data file that contains a particular row. Oracle8 uses this, combined with the row number and file number, to quickly locate a row in the database. Row number--Four characters. As with the extended ROWID, Oracle8 can locate a specific row once it has the block number and the row number. File number--Four characters. This is the absolute file number where the row is located. Absolute file numbers can be determined by querying the FILE_ID column of the DBA_DATA_FILES data dictionary view. 49. Explain what are storage parameters. (P.444) A. There are two storage parameters PCTFREE and PCTUSED used by Oracle8 to control how individual rows are stored in a block. It's helpful to think of PCTFREE and PCTUSED as a high water mark and a low water mark, respectively, for block storage utilization. PCTFREE controls how much space Oracle8 should reserve for updates to rows in a block, while PCTUSED controls how full a block should be, at a minimum. 50. How do we know which blocks in a table are available for INSERT activity? A. Oracle8 employs free lists to keep track of which blocks in a table are available for INSERT activity. 51. What are the symbols in the Map window? (P.498) A. The symbols in the Map window are as follows: Green Flag -- No worries, mate. Yellow Flag -- A condition exists that should be checked. Red Flag -- A severe condition exists and requires immediate attention Circle With Slash -- A group or object is down or unavailable. This symbol appears only if the UpDown event is registered for the group or object in the map. 52. Objects have status symbols only with registered events. True/False.

A. True. 53. How does the Create A New Map dialog appear? (P.512) A. From the OEM Console Menu, select Map|Create Map, or use the Create Map icon on the OEM Console toolbar. 54. What is the default location for bitmap files? (P.513) A. %ORACLE_HOME%\sysman\bmp 55. When is a database is said to be running and when down? (P. 523) A. When an instance exists the database is said to be running. When an instance does not exist, it is said to be down or unavailable to users. 56. ALTER DATABASE ARCHIVELOG command is available with the help of ______ Startup Mode. A. MOUNT 57. Explain what is SHUTDOWN ABORT. (P.524) A. The SHUTDOWN ABORT is a shutdown mode which stops the instance without rolling back uncommitted transactions or performing a checkpoint. Uncommitted transactions are lost. Instance recovery is required at startup. This mode is used when a NORMAL or IMMEDIATE shutdown fails. A SHUTDOWN ABORT stops the database but does not release the memory allocated to each thread--as much as 40-200K each. To release this memory, stop and restart the Oracle service. 58. What is the command to create a tablespace named APP_DATA? (P.552) A.

CREATE TABLESPACE APP_DATA DATAFILE 'G:\ORADATA\SID\APP1SID.DBF' DEFAULT STORAGE (INITIAL 20K NEXT 10K MINEXTENTS 5 PCTINCREASE 1);

59. What are extents? A. Extents are chunks of data blocks where storage is allocated to segments. 60. Describe the types of Rollback Segments. (P.556) A. Rollback segments can be either online or offline. An online rollback segment is available to transactions. An offline rollback segment is unavailable to transactions but still consumes space in its tablespace. Rollback segments can be either private or public. The difference is important only in the Oracle Parallel Server, where a private rollback segment is owned by one instance but a public one can be acquired by any instance. 61. How does Oracle periodically write message files to the directories? (P.558) A. Oracle periodically writes message files to the directories specified by the following initialization parameters:

BACKGROUND_DUMP_DEST USER_DUMP_DEST CORE_DUMP_DEST 62. What is the database's alert log? A. It is a plain text file named SIDALRT.LOG contained in the BACKGROUND_DUMP_DE ST directory. 63. What is the OEM Storage Manager and explain its areas. (P.559) A. The OEM Storage Manager is a graphical tool used to create, alter and drop tablespaces, data files, and rollback segments. The Storage Manager has three major areas: -- A menu bar at the top of the screen. -- A tree-structured list of tablespaces, data files, and rollback segments on the left side of the screen. -- A window on the right that provides additional detail about the object currently selected in the tree list. 64. What is a schema? (P.588) A. A schema is the set of objects belonging to a single Oracle user account, including the user's tables, indexes, synonyms, views, sequences, and stored PL/SQL programs. 65. When you create a table, you allocate at least one chunk of storage to it, called the ______ extent. A. INITIAL. 66. How is a not null constraint declared? (P.590) A. A not null constraint is declared as follows: CHECK(UPDATED_BY IS NOT NULL) 67. What is a synonym and what are its purposes? (P.594) A. In Oracle, a synonym is a permanent alias for a table or view. There are two primary purposes for synonyms: Hide object ownership--For example, the following synonym eliminates the need to include the owner of the CUSTOMER table when a user other than CUSTMGT references the table: CREATE PUBLIC SYNONYM CUSTOMER FOR CUSTMGT.CUSTOMER; Simplify command entry--For example, the synonym CUST requires less typing than the full name of the CUSTOMER table. CREATE SYNONYM CUST FOR CUSTOMER; 68. What is the command for private synonyms? A. CREATE SYNONYM. 69. What are SUM and COUNT? (P.595)

A. SUM and COUNT are SQL grouping functions which a view uses to combine several tables together or summarize data. 70. Write a CREATE SEQUENCE statement to generate customer IDs for the CUSTOMER table. (P.596) A. CREATE SEQUENCE S_CUSTOMER_ID START WITH 1 INCREMENT BY 1 MAXVALUE 999999 NOCYCLE ORDER CACHE 20; 71. Name the privileges to create a table. (P.607) A. There must be CREATE TABLE privileges to create your own table or CREATE ANY TABLE privileges to create a table in another user's schema. There must also be a quota on the tablespace where you wish to create a table, or you must have the UNLIMITED TABLESPACE system privilege. 72. Give a sample CREATE USER statement to create a user named JOHNS. (P.637) A.

CREATE USER JOHNS IDENTIFIED BY JOHNS_PASS DEFAULT TABLESPACE USER_DATA TEMPORARY TABLESPACE TEMPORARY_DATA QUOTA UNLIMITED ON USER_DATA PROFILE DEFAULT;

73. How can a user logon be authenticated? A. Oracle offers three ways to authenticate a user logon: -- Database authentication using a password. -- External authentication using the operating system or network -- Global authentication using the Oracle Security Service 74. Name some system privileges for creating and altering tables. (P.639) A. System Privilege CREATE TABLE CREATE ANY TABLE ALTER ANY TABLE DROP ANY TABLE

Description Create a table in the user's own schema Create a table in any schema. Use the ALTER TABLE command to modify any table in the database. Drop any table in the database.

75. Name the types of partial exports. (P. 692) A. There are two types of partial exports: Cumulative: Exports all objects that have been modified since the last complete or cumulative export. Incremental: Exports all objects that have been modified since the last complete, cumulative or incremental export. 76. What is the difference between a job and an event? (P.727)

A. A job is a task that is expected to accomplish something, such as load data, back up a database, start up an instance, or execute an SQL script. An event is a predefined exception in an Oracle environment, such as an instance failure, a tablespace running out of space, or users being locked out of a resource that they need. Events are expected to report back to the OEM Console, which can initiate a fixit job in response to the event. ----------------------------------------------------------------------------------SUN FAQ ----------------------------------------------------------------------------------The Java(TM) FAQ - Chapter 1: Classes, Interfaces, and PackagesCHAPTER 1

Objects, Classes, and Methods (Q1.1-Q1-10) Subclassing, Overloading, and Overriding (Q1.11-Q1.19) Interfaces and Abstract Classes (Q1.20-Q1.28) Packages and Access Modifiers (Q1.29-Q1.34) OBJECTS, CLASSES, AND METHODS Q1.1 What is an object? An object is a software unit that combines a structured set of data with a set of operations for inspecting and manipulating that data. Object-oriented programming reverses the function-data relationship familiar from non-object-oriented languages, such as C. Programs in C (similarly Pascal, or Basic) are often based on direct data manipulation: they define data structures and provide functions that inspect or change that data from anywhere else in the program. Intimate knowledge of data structures can be spread throughout the program, and changing a structure in one part can have drastic consequences for many other parts of the program. Object-oriented programming provides standard tools and techniques for reducing dependencies between different parts of a program. An object starts with a structured set of data, but also includes a set of operations for inspecting and manipulating that data. In an object, all operations that require intimate knowledge of the data structure are directly associated with the structure, rather than being spread throughout the program. A class (Q1.2) defines a type of object. It defines the data an object can hold and the methods (Q1.3) for operating on that data. Each object belongs to some class and is called an instance of that class (Q1.7). Grouping operations together with their data permits you to request operations from the object rather than directly manipulating the object's data. This seemingly small step has the great benefit of decoupling the requester of an operation from the performer. The requester (some part of the program) need know only what actions to request; the performer (the object) is responsible for the detailed knowledge of how to fulfill the requests. Parts of a program now depend on each other, not through data structures, but through functionality they promise to provide (sometimes called the "contract" of each participating class). The Java(tm) programming language is object-oriented, which means tha t classes, instances, and methods constitute the core of your program's

design. See also: Q1.2, Q1.3, Q1.7 [TOC] [next] Q1.2 What is a class? A class is a blueprint for objects: it defines a type of object according to the data the object can hold and the operations the object can perform. Classes are the fundamental units of design in object-oriented programming. A class is a pattern that defines a kind of object (Q1.1). It specifies a data structure for the object together with a set of operations for acting on the object's data. A class is usually also a factory that creates objects. You can use a class to create one or more objects (instances of the class) when the program is run (Q1.7). Each instance carries its own data, such that you can change one instance and leave others unaffected. Classes specify capabilities for objects, and objects do the actual work. The Java String class, for example, defines an object type for character strings. A String instance holds a sequence of Unicode characters and provides a large number of methods (Q1.3) for getting information about that string. Although there is just one String class, there can be any number of String instances (objects) in a Java program. A class declaration in Java looks much like a struct declaration in C. It contains at the very least the class keyword, the class's name, an opening brace, and a closing brace. Class declarations also have many optional parts, such as access modifiers (Q1.32), a superclass specification (Q1.12), interface specifications (Q1.20), and various parts in the body of the class. The following simple example defines a class with one piece of data (called a field) and one method for acting on that data: class SimpleClass { int count; // field void incrementCount() { ++count; } } Understanding the difference between a class and an instance is one of the fundamental steps in learning object-oriented programming. Table 1.1 shows a few analogies for this difference: Table 1.1: Class versus InstanceClassInstance cookie recipe and cuttercookie housing tract blueprintspecific house rubber stampstamped image photographic negativeprinted picture Note: From here on, this book follows The Java Language Specification (JLS; p. 38) in using the term object to refer to class instances and arrays (Q2.19). This broader use of the term takes a little getting used to but is clear and consistent. Where only class instances are under discussion, they will be referred to as class instances or simply instances. See also: Q1.1, Q1.3, Q1.7, Q1.12, Q1.20, Q1.32, Q2.19, JLS p. 38 [previous] [TOC] [next] Q1.3 What is a method? A method is the basic unit of functionality in an object-oriented language-a body of executable code that belongs to a class and that can be

applied to (invoked on) a specific object or the class itself. Methods are the object-oriented counterpart to functions or subroutines. Like a function, a method consists of: a name a (possibly empty) list of input names, called parameters, and their types an (optional) output type, called the return type (the void keyword declares that a method has no return type) a body of executable code The following code fragment declares a method whose output (of type double) is the average of its two input values (also of type double): double average(double a, double b) { return (a + b) / 2.0; }Because methods belong to classes (Q1.2), you can define a method only in the body of a class definition. Note that the code fragment, however, follows the convention of this book in not showing the enclosing class definition unless relevant. You usually use a method to inspect or manipulate the data stored in an object. For example, the Java String class provides a length method for determining the length of a String instance. The length method has no parameters and its return value is an int indicating the length of the String instance you invoke it on; for instance: String aString = "Bicycle Shop Quarterly News" ; int howLong = aString.length(); Methods are not simply activated-they a re invoked on a specific object (or on a class; see Q1.6). Consider the following code, which creates two Abstract Window Toolkit (AWT) Button instances and then sets the label for each one: /* in Java: */ Button button1 = new Button(); Button button2 = new Button(); button1.setText("Push Me First"); button2.setText("Push Me Second");Invoking setText on button1 amounts to as king the Button class to look up its definition for setText and then execute that code with respect to the data in button1. Invoking setText on button2 results in the same method lookup, but the resulting code is applied to button2 rather than button1. In a non-object-oriented language, such as C, you might use an equivalent setButtonText function that includes the button explicitly as an argument: /* in C: */ struct Button *button1 = makeButton(); struct Button *button2 = makeButton(); setButtonText(button1, "Push Me First"); setButtonText(button2, "Push Me Second")(For further discussion of the rela tionship between a struct in C and an object in Java, see Q2.10.) Because each class is responsible for its own methods, different classes can use the same name, parameters, and return type, yet still define different methods. For example, the AWT Label class also defines a setText method that takes a String parameter:

/* using Label's setText method rather than Button's: */ Label aLabel = new Label(); aLabel.setText("Read me - I'm a label.");In this example, the Label class p rovides its own definition for setText, and this definition could be entirely different from what the Button class provides. The ability of different methods to look alike from the caller's perspective is a crucial part of object-oriented programming: it separates the request for action from the details of how that request is fulfilled. Your code can invoke a method on an object without having to know the exact class of the object-only that it has a method with the same name, parameter list, and return type (Q1.14). What actual code gets executed is selected by the class of the target object, not by the invoker. See also: Q1.2, Q1.4, Q1.6, Q1.14, Q2.10 [previous] [TOC] [next] Q1.4 What is the signature of a method? The signature of a method is the combination of the method's name and the method's input types (that is, number of parameters and their types). The signature of a method provides precisely enough information to identify a method uniquely within a given class. Put another way, each method signature functions as a distinct lookup key when the class maps from method invocations to executable method bodies. For example, the following are signatures for several methods in the Java AWT Rectangle class (in the JDK 1.1): isEmpty() intersection(Rectangle) setLocation(int, int) contains(int, int) contains(Point) (Note that method signatures as represented here are not valid Java code; they represent only the information in the signature itself.) The method signatures in a, b, and c differ from each other in every way-name, number of parameters, and types of parameters; items c and d differ only in name; and items d and e match in name but differ in number and types of parameters. It is important to remember that a method's output information-its return value or declared exceptions-does not contribute to the method's signature. The compiler uses this information, though, to check the validity of method overriding (Q1.14, Q2.24). See also: Q1.13, Q1.14, Q2.24 [previous] [TOC] [next] Q1.5 What is the difference between an instance variable and a class variable? An instance variable represents a separate data item for each instance of

a class, whereas a class variable represents a single data item shared by the class and all its instances. An instance variable represents data for which each instance has its own copy. An instance variable corresponds roughly to a field of a structure (struct) in C or C++. If your program contains twenty Button instances, for example, each instance has its own label instance variable holding the label string for that button. A class variable, in contrast, belongs to the class as a whole. All instances of the class have access to the same single copy. A class variable can therefore function as a shared resource and an indirect means of communication among the instances of the class. Class variables are declared with the static keyword. The following code fragment declares a class with two instance variables and one class variable: class Example { int i1; // no static keyword, therefore instance variable String s; static int i2; // static keyword, therefore class variable }See also: Q1.6 [previous] [TOC] [next] Q1.6 What is the difference between an instance method and a class method? An instance method has a this instance reference, whereas a class method does not. An instance method always works hand in hand with a class instance. An instance method must be invoked on a specific class instance, and it has special access to the data in that instance. For example: String s1 = "abcde"; // one String instance String s2 = "fgh"; // another String instance int i1 = s1.length(); // i1 = 5 int i2 = s2.length(); // i2 = 3The length method returns the number of cha racters in its target object (s1 or s2 in this example), just as if that target were an argument to a length function (cf. strlen(aString) in C). When defining an instance method, you can use the this keyword to refer to the target instance. Class methods have no target instance and thus no implicit this reference. Class methods can always be used, even if you have no instance of the class on hand. Class methods, like class variables, are declared with the static keyword. For example, the currentThread method in class Thread is a class method. You invoke it on the Thread class itself, and it determines the currently executing thread and returns a reference to it. Thread activeThread = Thread.currentThread(); As alternates to the names instance variable, instance method, class variable, and class method, some Java programmers prefer to use terms such as member, field, static field, method, and static method. Table 1.2 summarizes how the various terms are related. Table 1.2: Names for Elements in a Classmemberfieldinstance variable (or nonstatic field) class variable (or static field) methodinstance method (or nonstatic method) class method (or static method) Note: The term field is useful for distinguishing variables defined in a class, as opposed to local variables, which are defined inside a method. VariableExample.html

See also: Q1.2, Q1.3, Q1.5 [previous] [TOC] [next] Q1.7 How do I create an instance of a class? The usual way to create a class instance is to invoke a constructor for the class. In Java, all objects (class instances and arrays) are created with space allocated from system-managed memory, but you never access that heap directly. The Java language and Virtual Machine manage it for you via the new keyword, the newInstance method in class Class, and automatic garbage collection (Q3.5). The standard way to create a class instance is with the new keyword followed by the name of the class and arguments for one of the class's constructors. For example: Button myButton = new Button("Press Me");This line of code declares a varia ble named myButton, creates a new Button instance labeled Press Me, and sets the myButton variable to refer to that button. Common coding style in Java is to declare a class-type variable and initialize it to point to a newly created instance all in the same line of code. For comparison, if you simply declare an instance variable of type Button, as in: Button myButton;then all you've created is a variable named myButton initia lized with a null reference (by default initialization; see Q1.10). Or if you declare a local variable (that is, a method-internal variable) as above, the compiler will require you to set it to some value before you can use it. You can also create or obtain class instances by invoking methods. Some methods always return a new instance, such as the newInstance method in class Class (Q2.15, Q3.7) and the valueOf method in class Integer (Q10.4). Other methods, such as InetAddress's getByName method (Q10.16), may return an instance, but without any guarantee that the instance is distinct from others it returned earlier. See also: Q1.10, Q2.15, Q3.5, Q3.7, Q10.4, Q10.16 [previous] [TOC] [next] Q1.8 What is an abstract method? An abstract method is a method that defines all aspects of itself except what code it executes. An abstract method declares the method's name, parameter types, return type, and exceptions, but does not provide an implementation for the method. You declare an abstract method with the abstract keyword and with a semicolon in place of the method body. For example: public abstract void drawFigure(); // abstract method declaration Abst ract methods let you design a class with some or all pieces left for subclasses to fill in. A class containing abstract methods is also called abstract, and must also be declared with the abstract keyword (Q1.9). By including an abstract method in a class, you require that anyone who implements a fully functional (concrete) subclass (Q1.11) will have to include an implementation for that method. For example, the Number class in the java.lang package consists entirely of abstract methods. The full JDK (1.0.2 and 1.1) class definition is: /* in Number.java (JDK 1.0.2 and 1.1): */ public abstract class Number {

public public public public }The java.lang

abstract int intValue(); abstract long longValue(); abstract float floatValue(); abstract double doubleValue(); package also contains several concrete subclasses of Number:

Integer, Long, Float, Double, and (starting with the JDK 1.1) Byte and Short. Each of these subclasses defines implementations for the four abstract methods just listed. As another example, the InputStream class in the java.io package provides the base for a large family of subclasses that handle specific types of byte-oriented input streams. The JDK 1.0.2 class definition implements all its methods except one. (In the JDK 1.1, InputStream's available method is also defined as abstract.) The core no-parameter read method, responsible for reading one byte of input, is left abstract so that subclasses must define it: public abstract int read() throws IOException;The other read methods in Inp utStream are defined to eventually result in calls to read(). In this way, when you implement read() in a subclass, the rest of the class is already integrated around your new method definition. See also: Q1.9, Q1.11 [previous] [TOC] [next] Q1.9 What is an abstract class? An abstract class is a class designed with implementation gaps for subclasses to fill in. An abstract class is deliberately incomplete. It defines a skeleton that various subclasses (Q1.11) can flesh out with customized implementation details. The different concrete (nonabstract) subclasses provide a family of variants. An abstract class must be explicitly declared with the abstract keyword. Note that declaring a class as abstract suffices to make it abstract-it need not even have any abstract methods. By declaring it abstract, you signal that it is functionally incomplete, and you ensure that no one can create instances of that class. The AWT Component class (Q5.1), for example, is the abstract superclass for all AWT user-interface elements. Although it provides default implementations for all its methods, it is nevertheless declared abstract. Component is not meant to be instantiated directly. Instead, it provides a common infrastructure within which more specific subclasses, such as Button and TextField, can be defined and instantiated. See also: Q1.8, Q1.11, Q5.1 [previous] [TOC] [next] Q1.10 What is an object reference? An object reference is essentially an object pointer with strong restrictions for integrity and safety. As a Java programmer, you can access objects (class instances and arrays) only by means of object references. Behind the scenes, an object reference provides two kinds of information to the run-time system: a pointer to the object's instance information-its data a pointer to the object's class information-its run-time type and its table of methods

Although pointers exist inside the Java run-time system, you cannot manipulate them directly. The Java language does not expose a numerical notion of references or pointers: you cannot do pointer arithmetic, nor can you fabricate pointers from numeric data. The operations you can perform on an object reference all treat the reference as an opaque entity. Table 1.3, adapted from The Java Language Specification (p. 39), summarizes the possible operations on an object reference: Table 1.3: Possible Operations on an Object Referenceassign the reference to a variable invoke a method on the reference extract a field from the reference cast the reference to another type test the reference's run-time type using the instanceof operator concatenate the reference with a String instance test the reference for equality with another reference using == and != provide the reference as a value in the conditional operator ?: The integrity of object references in Java is a cornerstone of security (protection from malice) and safety (protection from mistakes). As an example, consider the following code fragment: String s1; String s2; s1 = "a string"; s2 = s1;The first two lines declare two String variables; at this stage, s1 and s2 are simply uninitialized local variables. The third line sets s1 to refer to the String instance represented by the string literal "a string" (Q2.8). The fourth line sets s2 to refer to the same object as s1. There is still just one String instance, but now two separate references to it. When you declare a variable of a class, interface, or array type, the value of that variable is always an object reference or the null reference. The following chart compares similar definitions in Java and C++: JavaC++ Button b:Button *b: String s:String *s: See also: Q2.8, JLS p. 39 [previous] [TOC] [next] SUBCLASSING, OVERLOADING, AND OVERRIDING Q1.11 What is a subclass? A subclass is a class defined as an extension or modification of another class. Except for the Object class in the java.lang package, every class in the Java language is a subclass of some other class (called its immediate superclass, or superclass for short). A subclass behaves like its superclass, except where it speci-fies extensions or modifications. A subclass can extend its superclass by defining additional instance variables and methods for the subclass instances, or by defining additional class variables and class methods for the subclass. A subclass can also modify the behavior of its superclass by replacing some of the superclass's method definitions with its own. In both cases, the Java language uses the extends keyword to declare subclass relationships. In the JDK (1.0.2 and 1.1), for example, the FileInputStream class in the java.io package is defined as a subclass of InputStream:

/* in FileInputStream.java (JDK 1.0.2 and 1.1): */ public class FileInputStream extends InputStream { // ... fields and method definitions }If a class definition omits the extends clause, the class is defined as an immediate subclass of the root Object class. The subclass relation is transitive: if class Z is a subclass of class Y, and class Y is a subclass of class X, then class Z is a subclass of class X: Z subclass of Y, Y subclass of X => Z subclass of X By means of transitivity, Object is the ultimate superclass; all other classes are direct or indirect subclasses of Object. Subclasses are fundamental to object-oriented programming. They enable substitutability (also called polymorphism), the property by which a subclass instance can be used anywhere that one of its superclasses is expected: Substitutability (Polymorphism) Using a subclass instance where a superclass type is expectedas the object on which a method is invoked as the argument to a method or constructor as the value assigned to a variable As a final note, the immediate superclass-subclass relationship in the Java language is one-to-many. A subclass has only one immediate superclass (single inheritance; see Q1.25), but a superclass can have any number of subclasses. See also: Q1.12, Q1.25 [previous] [TOC] [next] Q1.12 What is inheritance? Inheritance is the way a subclass uses method definitions and variables from a superclass just as if they belonged to the subclass itself. In general, any instance method or instance variable not defined in a subclass is inherited from its superclass. (There are systematic exceptions to this rule; see Q1.32.) A subclass can use the inherited methods and variables just as if it had defined them itself. Inheritance is a powerful mechanism for reusing code: you can start from existing (and, hopefully, reliable) classes and write code to provide just the extra functionality you require. Inheritance provides a chain in which a class inherits not only from its immediate superclass, but also from any superclass upwards to the Object class. All Java classes ultimately inherit from Object. For example, the Button class in the java.awt package is defined as a subclass of the powerful, generic Component class (Q5.1). The Java language uses the extends keyword to declare this subclass relationship: /* in Button.java, JDK 1.0.2: */ public class Button extends Component { // ... class definition code } The class definition for Button in the JDK 1.0.2 is surprisingly small. The key extensions from Component to Button are one instance variable and two methods: label: a String instance-the button's text label getLabel(): returns the button's text label

setLabel(String): sets the button's text label Nevertheless, a Button instance possesses full Component functionality: you can send events to a Button instance, you can draw it on screen, you can resize and reposition it, you can enable or disable it, and so on. All of this functionality is inherited from the Component class, and is accessed using methods defined in the Component class. See also: Q1.5, Q1.6, Q5.1 [previous] [TOC] [next] Q1.13 What is an overloaded method? An overloaded method, strictly speaking, is more than one method: it is two or more separate methods (defined or inherited) in the same class that share the same name. Methods belong to classes, and methods within a class are distinguished according to their signatures: the combination of method name, number of parameters, and types of parameters (Q1.4). Accordingly, you can use the same name for different methods only if the methods contain different parameter lists. Method overloading allows you to group conceptually similar methods under the same name, and to use simpler names in general. Your method names can reflect the behavior of the methods without having to worry about how many or what types of parameters the methods take. The Math class in the java.lang package illustrates method overloading based on parameter types. It defines four different methods with the name max: max(int, int), returns an int max(long, long), returns a long max(float, float), returns a float max(double, double), returns a double Without method overloading, each max method would need to have its own distinct name, such as maxInt, maxLong, maxFloat, and maxDouble. Using the same method name is simpler and conveys the unity of purpose among these four methods. As a second example, the String class has two methods named substring. One uses two parameters to specify both a starting point and an ending point from which to extract the substring; the other uses one parameter to specify just the starting point: substring(int, int), returns a String instance substring(int), returns a String instance Again, using the same name for both methods highlights their common functionality; the difference in parameter lists makes enough of a distinction. Note: Java, unlike C++, allows inherited methods to coexist with overloaded methods. In a subclass, you can define a method with the same name as a method inherited from a superclass, and the superclass method will be accessible provided the two method signatures are distinct. (If the signatures are the same, you've overridden rather than overloaded the

method; see Q1.14.) See also: Q1.2, Q1.3, Q1.4, Q1.12, Q1.14 [previous] [TOC] [next] Q1.14 What does it mean to override a method? Instead of inheriting a method from its superclass, a subclass can override the method by providing its own definition for it. Overriding complements inheritance (Q1.12): it lets you choose which behaviors of a superclass to accept as is (inherit) and which to replace with code that you need specifically for your subclass (override). Overriding also lets you provide implementations for methods that the superclass declares as abstract. Overriding requires a precise replacement of the superclass's method: the subclass's method must have the same name, parameter list, and return type as the superclass's method. Its declared exceptions must also be compatible with those of the superclass. In the JDK 1.0.2, for example, the Applet class inherits Component's update method (Q5.1, Q8.5), which completely clears the background before redrawing (via paint): /* in Component.java (JDK 1.0.2): */ public void update(Graphics g) { g.setColor(getBackground()); g.fillRect(0, 0, width, height); g.setColor(getForeground()); paint(g); }You can define an Applet subclass and change this behavior by overriding update in that subclass, for instance, to avoid clearing the background first: /* overriding update in an Applet subclass: */ public void update(Graphics g) { paint(g); } A key point is that, from the subclass's perspective, overriding a method completely replaces the superclass's method. Whenever you invoke the method on an instance of the subclass, you execute the subclass's code for the method rather than the superclass's. To include the superclass's implementation as part of your subclass's method, you use the super keyword (Q1.17). OverrideMethodExample.html See also: Q1.4, Q1.12, Q1.16, Q1.17, Q2.26, Q5.1, Q8.5 [previous] [TOC] [next] Q1.15 What is the difference between overloading and overriding? Overloading occurs when two or more methods use the same name (but different parameter lists), such that both methods are available side by side in the same class; overriding occurs when a subclass method and a superclass method use the same name (and matching parameter lists), such that the subclass method blocks out the superclass method. Overloading (Q1.13) and overriding (Q1.14) are often confused with each other, because the words are similar and because they both involve a single method name referring to potentially several different method implementations. There are clear differences, however, when you compare the two point by point, as done in Table 1.4. Table 1.4: Overloading versus OverridingOverloadingOverriding relationship between methods available in the same classrelationship between a superclass method and a subclass method does not block inheritance from the superclassblocks inheritance

from the superclass separate methods share (overload) the same namesubclass method replaces (overrides) the superclass method different method signaturessame method signature may have different return typesmust have matching return types may have different declared exceptionsmust have compatible declared exceptions For example, both the Object class and the String class (an immediate subclass of Object) in the java.lang package define an equals method: in Object: public boolean equals(Object obj) { /* ... */ } in String: public boolean equals(Object obj) { /* ... */ } This is a case of overriding, since String is a subclass of Object, and String's equals method has the same name, parameter types, and return type as Object's equals method. Now suppose that a String2 class defined equals to take a String2 parameter instead of an Object parameter: in Object: public boolean equals(Object obj) hypothetical String2: public boolean equals(String2 str) This would be a case of overloading. The String2 class would have two alternate equals methods: one defined in String2 and one inherited from Object. Even though the two methods have the same name and return type, they differ in what parameter they take. See also: Q1.13, Q1.14, Q1.16 [previous] [TOC] [next] Q1.16 Can I override the equals method or clone method from class Object to take a parameter or return a value of the type that I specify? No; you can override a method from a superclass only if your subclass's method has the same signature and return type. Overriding a method requires a close match between the superclass method and the subclass method: the subclass method and superclass method must have the same signature the subclass method and superclass method must have the same return type

the subclass method's level of access must be equal to or greater than that of the superclass method Note that the native and abstract keywords do not have to match between the subclass and superclass methods. To override Object's equals method, you must define precisely the same return type and parameter type as defined by the Object class. (You are free, though, to vary the parameter name-obj in the following example-since parameter names are not carried over into class files.) For example: /* overriding equals in a subclass of Object: */ public boolean equals(Object obj) { /* ... */ }Similarly, you can override Object's clone method only to return Object: /* overriding clone in a subclass of Object: */

public Object clone() { /* ... */ }Attempting to return any class other th an Object yields a compile-time error: /* failed attempt to override clone: */ public MySubclass clone() { /* ... */ } The Vector class in the java.u til package, for example, overrides Object's clone method and therefore returns Object rather than Vector. To assign the cloned Vector instance to another Vector variable, you must cast the returned value from Object to Vector (Q2.9): Vector vector1 = new Vector(); Vector vector2 = (Vector)vector1.clone(); Note: Method overloading is a n option if you really want to provide a more specific parameter type than Object, but it is not an option for return types. Whether you are overriding or overloading, the return types must match exactly-a compile-time error occurs if they don't. See also: Q1.4, Q1.13, Q1.14, Q1.15, Q2.9 [previous] [TOC] [next] Q1.17 What is the super keyword used for? The super keyword gives a class explicit access to the constructors, methods, and variables of its superclass. The super keyword works hand in hand with inheritance (Q1.12) to connect a class to its superclasses. Inheritance gives a class implicit access to its superclasses. When you invoke an instance method, for example, you automatically get an inherited superclass method implementation if the instance's class doesn't define the method for itself. Implicit access is blocked, though, by method overriding (Q1.14), or by defining instance or class variables with the same names as the superclass versions (called hiding). This is where super comes in. The super keyword gives a class explicit access to its immediate superclass's parts, even if that access is otherwise blocked. The two common uses of super are to access the superclass's constructor and to access the superclass's version of an overridden method. The super keyword is essential to the workings of constructors. Unlike methods, constructors are not inherited; the super keyword thus provides the only means to access a constructor in a superclass. Within a constructor, using super(...) triggers a call to the superclass constructor with a matching parameter list. (The compiler issues an error if the superclass contains no such constructor.) This is how each instance of a class performs a chain of initializations. An instance initializes itself as an Object instance and then steps down from each superclass to an immediate subclass until it finally initializes those parts that are specific to the subclass at the end of the chain. For example, the following Frame subclass defines two constructors to match the two constructors provided by the Frame class: class ExampleFrame extends Frame { public ExampleFrame() { super(); } public ExampleFrame(String title) { super(title); } // ... field and method definitions }Even though the constructors in this example do nothing more than invoke the superclass constructors, you need to include them because constructors are not inherited. (If your constructor invokes the superclass

constructor, this invocation must occur as the first statement in your constructor definition.) The chain of initialization is so important that the Java system automatically includes a call to the superclass constructor if you don't provide one yourself. The automatic superclass constructor is always a no-parameter constructor. For example, the JDK 1.0.2 Button class contains the following constructor code: /* in Button.java (JDK 1.0.2): */ public Button(String label) { this.label = label; }Because of the automatic inclusion of the superclass constructor, the above code is equivalent to: /* Equivalent Button constructor: */ public Button(String label) { super(); this.label = label; }The automatic default constructor has no parameters, but you can use whatever parameter list you need by invoking the superclass constructor explicitly. The second common use of super is within a method definition, to access the superclass version of the same method. This makes sense in a method definition that is overriding the method from its superclass. In this context, super allows you to define an overriding method that builds around its superclass method rather than replacing it outright. The AWT Button class again provides a simple example: /* in Button.java (JDK 1.0.2) */ protected String paramString() { return super.paramString() + ",label=" + label; }Because Button is a subclass of Component, this paramString method will invoke Component's version of paramString, which returns a String instance describing parameters relevant to all components, and will then append the button's label to that string. Invoking paramString on a button thus returns a String instance that includes the button's size and on-screen position (information all components have) together with the button's label (information specific to the Button subclass). Finally, you can use super to access a variable in a superclass that is hidden by a variable in the subclass with the same name. The following code fragment illustrates how, for a variable named foo: class X { int foo = 1; // declares instance variable foo } class SubX { int foo = 2; // declares own version of foo, which hides the // superclass version int getSuperFoo() { return super.foo; // returns 1, not 2 } }SuperExample.html See also: Q1.11, Q1.12 [previous] [TOC] [next] Q1.18 Does the Java language provide virtual methods, like C++? Yes; but Java methods are virtual by default, whereas C++ methods are not. "Virtual methods" are an essential ingredient for taking advantage of

inheritance and polymorphism. Because of inheritance and polymorphism, an object reference need not match exactly the class of the object it refers to: the object can belong to a subclass of the reference's type. For example, the aThread reference below is of type Thread, but the object it refers to is of type MyThread, a subclass of Thread: class MyThread extends Thread { /* ... overrides start() ... */ } class Example { // ... Thread aThread = new MyThread(); myThread.start(); // ... } When you invoke a method on a reference, such as the anObject.start() expression above, the virtual machine must know which class to use for looking up the method definition; there are two basic choices: static binding-use compile-time type of object reference dynamic binding-use run-time type of referred-to object In the preceding Thread example, dynamic binding will pick up the overridden start method in the MyThread subclass, whereas static binding would find only the Thread version. Programmers familiar with C++ will recognize this distinction as the difference between nonvirtual and virtual methods. In the Java language and Virtual Machine, dynamic binding is the default, and there is no virtual keyword. The distinction between dynamic and static binding is generally expressed in terms of whether a method can be overridden: Method overridable?JavaC++ yes[default]use virtual keyword nouse final keyword[default] Note: Besides final methods, two further situations in Java use static rather than dynamic binding. Class methods and method invocations involving the super keyword cannot involve method overriding; hence, they do not require dynamic binding. See also: Q1.10, Q1.12, Q1.14, Q1.19, Q1.26 [previous] [TOC] [next] Q1.19 What is a final class? A final class is a class that is declared with final keyword so that it can never be subclassed. Using the final keyword in the Java language has the general meaning that you define an entity once and cannot change it or derive from it later. More specifically: a final class cannot be subclassed a final method cannot be overridden a final variable cannot change from its initialized value Classes are usually declared final for either performance or security reasons. On the performance side, the compiler can optimize final classes to avoid dynamic method lookup because their method implementations are never overridden. Methods in a final class can work at the speed of straight function calls, or even as inline code, which may be several

times faster than a typical method invocation on current virtual machine implementations. The String class, for instance, is declared final in large part because of the performance optimizations that can be achieved. Note, however, that the performance advantage of final classes (or final methods for that matter) is likely to fade in the next year or two as Java Virtual Machine implementations apply increasingly sophisticated techniques to handle method invocation. Relying heavily on final in your current designs may confine you unnecessarily in the future. On the security side, making a class final is like putting a lock on the class-it prevents other programmers from subclassing a secure class to invoke insecure methods. Note: Making an entire class final is a fairly extreme measure and should be done only in exceptional cases. You most often can achieve the security and performance effects you desire by making selected methods in a class final, while leaving the class available for subclassing. See also: Q1.18 [previous] [TOC] [next] INTERFACES AND ABSTRACT CLASSES Q1.20 What is an interface? In the Java language, an interface is like a stripped-down class: it specifies a set of methods that an instance must handle, but it omits inheritance relations and method implementations. Object-oriented programming is sometimes modeled as communication between objects-one object talks to, or sends a message to, another object by invoking a method on it. In this view, an interface in the Java language specifies the bare minimum one object needs to know in order to talk to another object: a set of abstract methods (Q1.8), that is, methods minus any implementation information. Put another way, an interface specifies how you can talk to an object, but says nothing about what kind of object will handle your messages. It is the job of one or more class instances to provide the substance behind an interface's promise (Q1.21). Interfaces are a close cousin to classes (Q1.2), and their declarations resemble class declarations. For example, the Runnable interface in the java.lang package (JDK 1.0.2 and 1.1) is declared as follows: /* in Runnable.java (JDK 1.0.2 and 1.1): */ public interface Runnable { public abstract void run(); }An interface can also contain static final variables, called class constants; see The Java Language Specification, pp. 186-188, for details. Interfaces provide the minimal level of dependence between interacting objects. An interface focuses purely on the role an object plays-what services it can provide-without making any restrictions on the class of the object (Q1.24). See also: Q1.2, Q1.21, Q1.24, JLS pp. 186-188 [previous] [TOC] [next] Q1.21 How does a class implement an interface? A class implements an interface by declaring that it implements the interface and by providing implementations for all methods contained in the interface. Despite not having any implementation, an interface embodies both form and intent. When you define an interface, you specify the set of

methods in the interface; you should also specify the intended meaning of each method. Correspondingly, implementing an interface requires that a class match the interface in both form and intent: the class provides implementations for all the methods in the interface the class declares explicitly that it implements the interface Because both steps are required, implementing an interface is guaranteed to be a deliberate choice by the class's author. Simply having the same methods as an interface is not sufficient. For example, Applet subclasses commonly implement the Runnable interface in order to run themselves in a separate thread (xQ9.16). The Runnable interface in the java.lang package declares just a single run method taking no parameters (Q1.20). A Runnable Applet subclass must therefore declare that it implements the Runnable interface and must define a run method: public class MyApplet extends java.applet.Applet implements Runnable { // ... public void run() { // ... code to run the applet in a separate thread } } Note: If a class implements an interface, all its subclasses automatically implement the interface, too. Also, you can declare that an abstract class (Q1.9) implements an interface yet omit some of the method declarations. This amounts to a promise (checked by the compiler) that any concrete subclasses of that abstract class will fully declare and implement the methods in the interface. See also: Q1.9, Q1.20, Q1.22, Q9.16 [previous] [TOC] [next] Q1.22 Can I instantiate an interface? You can't; you must instantiate a class that implements the interface. Interfaces specify a vocabulary of methods by which objects can communicate. Instead of instantiating an interface, you instantiate a class (Q1.7) that implements the interface (Q1.21). You can then use that object anywhere the interface type is required. InstantiateInterfaceExample.html See also: Q1.7, Q1.20, Q1.21 [previous] [TOC] [next] Q1.23 Why does a method in an interface appear to be public even though I didn't declare it to be public? The Java language defines all methods and variables in an interface to be public, regardless of whether you use the public keyword or not. The Java language requires that all methods and variables in an interface be public. The compiler thus allows you to omit the public keyword (Q1.32). Similarly, all methods in an interface are abstract (Q1.8), and you do not need to include the abstract keyword in any interface declarations. The compiler will accept public and abstract modifiers on interface methods for compatibility with older code, but you are encouraged as a matter of style to omit them (The Java Language Specification, p. 187). See also: Q1.8, Q1.20, Q1.32, JLS p. 187 [previous] [TOC] [next]

Q1.24 How is an abstract class different from an interface? Although the Java language makes a clear distinction between abstract classes and interfaces, in practice the difference is often a matter of degree and intent. Abstract classes (Q1.9) fill in the wide range between concrete classes and interfaces. Table 1.5 lists several distinctions that are relevant to typical uses. Table 1.5: Concrete Class versus Abstract Class versus InterfaceConcrete ClassAbstract ClassInterface specifies the full set of methods for an objectspecifies the full set of methods for an objectspecifies a subset of methods for an object implements all of its methodsimplements none, some, or all of its methodsimplements none of its methods can have instancescan't have instancescan't have instances can have subclassesmust have subclasses; useless without themcan't have subclasses; must have classes that implement it; useless without them If the differences in Table 1.5 leave you uncertain about whether to use an abstract class or an interface, one further factor may be decisive. A class can have only one immediate superclass, but it can implement any number of interfaces (Q1.25). An abstract class, even one with all abstract methods, ties its subclasses to a particular inheritance hierarchy. An interface, in contrast, leaves an object free to implement other interfaces as needed by the object's class. Beyond the details, it is important to understand how classes and interfaces differ in spirit. Classes generally specify the full identity of an object: who/what it is (its parentage), what roles it can perform (its vocabulary of methods), and how it specifically performs those roles (its implemented behavior). Interfaces specify neither parentage nor behavior for an object-they focus exclusively on the role(s) an object can play. Consider, for example, the Observer interface and Observable class in the java.util package. An Observer object is one that expects to be notified when an object it is watching (an Observable object) changes state. An Observable object is one that knows how to register, unregister, and notify a collection of Observer objects. The Observer interface (JDK 1.0.2 and 1.1) defines a single method: /* in Observer.java (JDK 1.0.2 and 1.1): */ public interface Observer { void update(Observable o, Object arg); }Because Observer is an interface, you can define whatever class you like to implement the interface. For instance, you could define a Button subclass to serve as an Observer: public class ObserverButton extends Button implements java.util.Observer { public static void update(Observable o, Object arg) { // ... respond to notification } }This independence of interfaces from any class hierarchy is a huge benefit. In contrast, Observable is defined as a class, which restricts all

Observable objects to belong to the Observable class or to Observable. Unlike ObserverButton above, you simply cannot ObservableButton as a subclass of Button. Java allows only inheritance, which forces you to choose between one or the inheritance hierarchy (Q1.25). See also: Q1.9, Q1.20, Q1.25 [previous] [TOC] [next]

a subclass of define an single class other

Q1.25 Does the Java language allow multiple inheritance? Yes and no. A class in Java can implement any number of interfaces (multiple interface inheritance) but can extend exactly one immediate superclass, from which it inherits implementations (single class inheritance). Similarly, an interface can have any number of superinterfaces, which are declared with the extends keyword. For example: // ... interfaces Readable, Writable declared elsewhere public interface StreamInputOuput extends Readable, Writable { // ... additional methods not in Readable or Writable } Finally, does an interface have any superclasses? Yes, all interfaces are treated as having one superclass: the Object class. This amounts to a claim that whatever class implements the interface will be a subclass of Object; the Java language guarantees this to be true (Q1.11). See also: Q1.2, Q1.11, Q1.12, Q1.20 [previous] [TOC] [next] Q1.26 What is the instanceof keyword, and what does it do? The instanceof keyword is a two-argument operator that tests whether the run-time type of its first argument is assignment compatible with its second argument. An expression using instanceof, such as X instanceof Y, tests whether the object referred to by X could be assigned to a variable of type Y. If Y is a class, this test checks whether X's object belongs to class Y or to a subclass of Y. If Y is an interface, the test checks if X's object's class implements that interface. The instanceof operator performs tests at both compile time and run time. For example, testing whether a String instance in a String variable can be an instance of Integer fails at compile time: String aString = "abadcafe"; if (aString instanceof Integer) { /* ... */ }The error message from the JD K (1.0.2 and 1.1) compiler is unequivocal: Impossible for java.lang.String to be instance of java.lang.Integer.Failure at compile time signals gross errors, such as checking two class types, neither of which is a subclass of the other. The primary use of instanceof, however, is to check at run time the actual object type (run-time type) of its left-hand argument, regardless of the static type of the reference. For example, the AWT Component class includes a getParent method that returns an object reference of type Container. The actual (run-time) type of the parent object, though, could be Panel, Applet, Frame-any of a number of subclasses of Container. You can then use the instanceof operator to test which specific subclass you have: /* code in your Component subclass: */ // ... myButton has been created and built into a user interface Container cont = myButton.getParent();

if (cont instanceof Frame) { /* ... code to handle Frame ... */ }[previous] [TOC] [next] Q1.27 Why do I get the error message Can't access protected method clone... when I try to clone an object? The clone method in class Object signals an error if you invoke it on an object whose class does not explicitly support cloning. The clone method in class Object creates a new object that is essentially a bit-for-bit copy of the source object. This is a simple but risky behavior for classes in general, so classes are not allowed to inherit it by default. (Remember that any nonprivate method in class Object is potentially inherited by all other Java classes.) Object's clone method thus has two built-in safety measures: clone is protected, which restricts access from outside the java.lang package clone checks that the target object's class implements the cloneable interface The upshot of these restrictions is that you can invoke clone on an object only if that object's class has been designed explicitly to allow cloning. See Q1.28 for a discussion of how to design a class for cloning. Cloning an object from a class set up for cloning, however, is straightforward. You invoke clone on an instance of that class, as in the following hypothetical example: DollarBill genuine = new DollarBill(); DollarBill counterfeit = (DollarBill) genuine.clone();The clone method retu rns an object reference of type Object, which you must cast to the appropriate class. See also: Q1.28, Q1.33 [previous] [TOC] [next] Q1.28 How do I design a class so that it supports cloning? Declare that the class implements the cloneable interface and override Object's clone method with a version suited to your class. Designing a class that supports cloning involves two parts: a promise of cloneability and a clone method to back it up. First, you mark your class as fit for cloning by declaring that it implements the cloneable interface. For example: public class DollarBill implements cloneable { /* ... */ }The cloneable int erface contains no methods; it is purely a flag. Second, you define a clone method that correctly copies the parts within each instance of your class. Some parts of a class may require shallow copying; others may require deep copying. Shallow copying merely copies the value of a data element bit for bit-this is what the default clone method in class Object does. Shallow copying is appropriate when a data element directly represents a value, such as an int, float, or boolean, rather than a reference to a value. Shallow copying may occasionally be used for reference values as well, the result being two references sharing the same referred-to object. Deep copying is often required for reference-type data elements. Deep copying creates both a new reference and a new object for the reference to refer to. The following

code fragment sketches a DollarBill class that performs both shallow and deep copying in its clone method: public class DollarBill implements cloneable { int value = 1; // value of the bill (1, 5, 10, 20, ...) String name; // personalized name given to individual bill // ... constructors and various methods /** * clones a DollarBill by copying its value and making a deep * copy of its String name. */ public Object clone() { DollarBill copy = null; try { copy = (DollarBill) super.clone(); // shallow copy copy.name = new String(this.name); // deep copying } catch (cloneNotSupportedException e) { e.printStackTrace(); } return (Object) copy; } }Clone Example.html See also: Q1.27, Q1.32, Q1.33 [previous] [TOC] [next] PACKAGES AND ACCESS MODIFIERS Q1.29 What are packages, and what are they used for? A package is a collection of classes and interfaces that provides a high-level layer of access protection and name space management. Although the class (Q1.2) is arguably the central unit of design in Java programs, Java language packages provide a vital additional level of support for program modularity. A package groups together a set of classes and interfaces (Q1.20) that needs to work as a coherent whole. The java.io package, for instance, contains classes and interfaces for managing various kinds of input and output. Packages define boundary lines to govern how classes and interfaces may interact with one another. Access control modifiers (Q1.32) use package boundaries to: facilitate a high degree of interaction and interdependency within a package reduce access and interaction across package boundaries For instance, the default access to methods and variables, if you don't specify an access modifier, is that a method or variable defined in one class cannot be used by classes belonging to a different package. Packages also reduce the potential for name clashes, because class names and interface names are ultimately reckoned relative to the package to which they belong (Q1.30). Thus, you could define your own Button class, distinct from the Button class in the java.awt package, provided that you place it in a package other than java.awt. In general, you should not deliberately reuse well-known class names like this; the name space protection provided by packages is more of a safety measure against accidental clashes. Every class and interface belongs to some package. For each

compilation unit (typically a source file), you can declare what package its classes and interfaces belong to with a package declaration at the beginning. For example: package myPackage; // if present, must come first in the file public interface Xyz { /* ... */ } class Uvw { /* ... */ }Any number of source files (compilation units) can be declared to belong to the same package. If you omit the package declaration, the classes and interfaces in that file will be assigned to a system-provided unnamed package. Although the package is nameless, the same rules for package-internal versus package-external access privileges still apply. See also: Q1.2, Q1.20, Q1.30, Q1.32, JLS p. 119 [previous] [TOC] [next] Q1.30 I've seen both java.applet.Applet and Applet used to refer to the Applet class-what's the difference? The shorter name is definitely easier to use, but it requires that you provide an import declaration to specify which package the class belongs to. The name java.applet.Applet is the fully qualified name of the Applet class in the java.applet package. Fully qualified class or interface names come in the form: packageName.simpleClassName packageName.simpleInterfaceNameThe package name itself can be a compound na me with its own internal periods, such as java.applet and java.awt.image. You can always refer to a class or interface by its fully qualified name, but it is more common and more convenient to use just the simple name of the class or interface. To let the compiler know which package a simple name belongs to, you provide an import declaration at the head of your source file (or, strictly speaking, after the package declaration, if there is one). For example: import java.applet.Applet;After this, the compiler will know to treat each occurrence of the simple name Applet the same as if it were the fully qualified name java.applet.Applet. Import declarations let the compiler do the extra name work for you. Using an often called importing An alternate form classes as needed from

import declaration for a class (or interface) is the class (or interface). of import declaration lets you import as many a package. A type import on demand uses an asterisk

(*) in place of a specific class or interface name. For example: import java.awt.*;This form of import declaration makes all the classes and interfaces in the specified package available as simple names. Although package names are hierarchical, import declarations are not. In the example above, the import declaration imports only classes and interfaces from the java.awt package. It does not import from subpackages in java.awt-you must include separate import declarations for each subpackage you want to import; for example: import java.awt.*; // the main AWT package import java.awt.image.*; // the image subpackage import java.awt.event.*; // the event subpackage; in JDK 1.1 Remember: Importing classes and interfaces affects only the names by

which your code refers to classes. It does not send additional code to the compiler, like C's include, or perform other behind-the-scenes manipulations. See also: Q1.29, Q1.31, JLS pp. 120ff [previous] [TOC] [next] Q1.31 Why can I get some simple class names "for free," without using an import declaration? Java language programs automatically imports all classes in the java.lang package. The java.lang package contains classes and interfaces that provide crucial support to the Java language and Virtual Machine, including Class, Exception, Object, Runnable, String, System, and Thread. To ensure that these classes and interfaces are always easily available, and to prevent programs from inadvertently calling on nonstandard versions, the java.lang package is always automatically imported. The compiler treats each source file as if its first import statement were import java.lang.*; // implicit in every Java source file The automati c importing of java.lang class and interface names is one of three sources of simple class names in a source file: automatic importing from java.lang package explicit import declarations classes and interfaces in unnamed package See also: Q1.29, Q1.30, JLS p. 119 [previous] [TOC] [next] Q1.32 Is there a default access modifier for classes and interfaces? For class members (methods, constructors, and fields)? There is no default access modifier; the absence of a modifier, though, signals package-level access, which is access only from classes in the same package. You can assign two different levels of access to classes and interfaces: public and package (also called package private). Public access is marked with the public keyword, and package access has no keyword, as shown in Table 1.6: Table 1.6: Access Levels for Classes and Interfacespublic keywordaccessible to all classes no keywordaccessible only to classes in same package (The Java language has a package keyword, but it is used in a different context, for package declarations; see Q1.29.) Table 1.7 lists the four possible levels of access for class and interface members (methods, constructors, and fields); again, package access has no keyword. Table 1.7: Access Levels for Class and Interface Memberspublic keywordaccessible to all classes no keywordaccessible only to classes in same package protected keywordaccessible to classes in same package and in limited circumstances to subclasses in other packages. (Q1.33) private keywordnot accessible to any other classes Good program design seeks to isolate parts of a program from

unnecessary, unintended, or otherwise unwanted outside influences. Access modifiers provide an explicit and checkable means for the language to control such contact. See also: Q1.27, Q1.29, Q1.33 [previous] [TOC] [next] Q1.33 What does protected access mean? A method, constructor, or field with protected access is accessible to all classes in the same package, and to subclasses in other packages provided that the class granting the access is the same as or a subclass of the class making the access. The protected level of access augments the default package-level access with limited access for subclasses outside the package of the class defining the protected element (call these package-external subclasses). The basic idea is that access from a subclass outside the protected element's package is reckoned relative to the object or class through which the access is occurring-access is allowed only if the target class is the same as or a subclass of the package-external class attempting the access. For example, consider the access facts for the following scenario: package Pcontains class X and class SubX (a subclass of X) class X defines protected method M package Qcontains class Y (a subclass of X) and class SubY (a subclass of Y) First, code in class X or SubX can always invoke M: Method invocationAccess allowed? code in class X or SubX invokes M on instance of class SubXYes; access is from inside the protected element's code in class X or SubX invokes M on instance of class SubYYes; access is from inside the protected element's

X or package Y or package

In contrast, when code in class Y or SubY attempts to invoke M, whether or not access is allowed depends crucially on the target instance: Method invocationAccess allowed? code in class Y invokes M on instance of class X or SubXNo; package-external access allowed from class Y only if target instance belongs to class Y or a subclass of Y. code in class Y invokes M on instance of class Y or SubYYes; package-external access allowed from class Y because target instance belongs to class Y or a subclass of Y. code in class SubY invokes M on instance of class YNo; package-external access allowed from class SubY only if target instance belongs to class SubY or a subclass of SubY. Admittedly, the details of protected access are tricky-for a full specification and further examples, see The Java Language Specification (p. 100). See also: Q1.29, Q1.32, JLS p. 100 [previous] [TOC] [next] Q1.34 What is the accessibility of a public method or field inside a nonpublic class or interface? A public method or field inside a nonpublic class is accessible only inside its package, unless some other public access point-a public

interface or public superclass-can be used. The accessibility of members (methods and fields) within a class or interface is limited by the class or interface through which they are accessed. A nonpublic class receives the default package access so that even public methods or fields inside that class are generally not visible outside the class's package. In two circumstances, though, a public class member can have full public access even though the class that defines it has only package access. First, a public interface can expose methods from a package-private class that implements the interface. When an instance of the class is accessed through the interface (that is, through a reference of the interface type), the methods implementing the interface are visible outside their package. A public superclass with public methods can also expose methods from a package-private subclass. When an instance of the subclass is accessed through a reference of the superclass type, any public method of the superclass is accessible to all classes. By dynamic binding (Q1.18), however, the actual method body invoked will be the one belonging to the package-private subclass. See also: Q1.18, Q1.29, Q1.32 [previous] [TOC] (c) Copyright 1997 Sun Microsystems. The Java(TM) FAQ - Chapter 2: Java LanguageCHAPTER 2

Constants and Expressions (Q2.1-Q2-10) Variables and Methods (Q2.11-Q12.18) Arrays (Q2.19-Q2.21) Exceptions (Q2.22-Q2.26) CONSTANTS AND EXPRESSIONS Q2.1 What is the difference between Integer and int in Java-why do I get the following error: Can't convert java.lang Integer to int? Integer is a class defined in the java.lang package, whereas int is a primitive data type defined in the Java language itself; Java does not automatically convert from one to the other. The Java language makes a fundamental distinction between two kinds of data: reference types and primitive types. A reference type holds a reference to a value rather than the value itself (Q1.10, Q2.11). Reference types comprise all the object-related types of the Java language: Reference types in Java: class types, interface types, array types

Reference types provide an open-ended type system. You can define new types by defining new classes, new interfaces, or arrays containing components from those classes or interfaces. Primitive types hold raw values without any object-oriented support. The primitive types in Java are shown in Table 2.1. Table 2.1: Primitive Types in Javaboolean: binary value, either true or false byte: short, int, long: 8-, 16-, 32-, and 64-bit signed integer

values char: Unicode characters as unsigned 16-bit integer values float, double: 32- and 64-bit IEEE 754 floating point numbers Although the Java language is strongly object-oriented, it includes the primitive types because of their speed, simplicity, and compactness. In this light, consider again the difference between Integer and int. At a basic level, elements of Integer and int both represent a 32-bit signed integer value. Which of these you use depends on what you want to do, as described in Table 2.2. Table 2.2: Using a Class versus Using a Primitive TypeUse Integer (or other numeric class)Use int (or other primitive class) as an argument for a method that requires Objectfor calculations for storage in general-purpose Object containersfor storage in large arrays For example, to store an Integer value as part of a Vector (a class in package java.util), you need to wrap the value in an Integer instance: Vector v = new Vector(); v.addElement(new Integer(5));In contrast, if you want to keep a counter var iable that you increment repeatedly, by all means use an int: int count; // ... ++count; Finally, the Integer class lets you translate back and forth b etween Integer and int representations of the same value: int i = 5; Integer myInteger = new Integer(i); int j = myInteger.intValue(); Note: The extra effort required to conver t between int and Integer can be a nuisance, but is consistent with Java's emphasis on type safety. See also: Q2.11 [TOC] [next] Q2.2 How do I treat all 8 bits of a byte as an unsigned quantity? When the unusual need arises, perform a logical-and of your byte value and the hexadecimal value 0xFF-this counteracts the automatic sign extension that occurs when a byte value undergoes promotion to an int. The Java language strictly defines the sizes and arithmetic properties of its primitive numeric data types. The integral types byte, short, int, and long are all represented in 2's complement form with sizes of 8, 16, 32, and 64 bits, respectively. In several circumstances, the Java language promotes a byte value to an int: assignment conversion: when you assign a byte value to a variable of type int (The Java Language Specification, p. 61) method invocation conversion: when you provide a byte value as an argument to a method that expects an int (JLS, p. 66)

casting conversion: when you explicitly cast a byte value to int (JLS, p. 67) numeric promotion: when you use a byte operand in an arithmetic expression (JLS, p. 72) If you assume, as the Java language does, that a byte represents an 8-bit signed value, these promotions occur without surprising side effects. Promoting byte to int (or short to int, for that matter) occurs by sign extension: the highest bit of the smaller type is copied to all new bits in the larger type. For example, the following display shows the value -4 represented as a byte, and then sign-extended to an int: -4 as an 8-bit signed byte11111100 sign-extend to 32 bits11111111 11111111 11111111 11111100 interpret value as int-4 Suppose, however, that you want to treat the same eight bits as an unsigned value, in which case that value would be 252. As soon as you sign-extend the byte to an int (for any of the reasons above), you're back to the value -4: 252, in 8 unsigned bits11111100 sign-extend to 32 bits11111111 11111111 11111111 11111100 interpret value as int-4 Assuming that you really have a good reason for using the byte as an unsigned value, the fix is to counteract the automatic sign extension by setting the extra bits to zero. Perform the logical-and (&) of your byte value with the hexadecimal constant 0xFF: 252, in 8 unsigned bits11111100 sign-extend to 32 bits11111111 11111111 11111111 11111100 0xFF in 32 bits00000000 00000000 00000000 11111111 logical-and (&)00000000 00000000 00000000 11111100 interpret value as int-4 Note: The Java language provides an unsigned right shift operator, >>>, as another means of averting automatic sign extension. For example, the expression (value >>> 4) shifts value's bits 4 places to the right and fills in the vacated high-order bits with 0s (rather than 1s). Thus, an alternate, and more complex, way to extract an 8-bit unsigned value is ((value >> 24). UnsignedByteExample.html See also: Q2.1, JLS pp. 61-75 [previous] [TOC] [next] Q2.3 How do I work around Java's lack of true enums? Use class constants-they provide symbolic names for integer-like constants. Two of Java's cousin languages, C and C++, contain a notion of enumeration or enumerated type, called enum for short. An enum is a user-defined type that can take symbolic, identifier-like, constant values. Consider, for example, the following two statements, in either C or C++: /* in C or C++ */ enum season {winter, spring, summer, fall};

season now = fall;The first statement defines an enum with the name season, and the second declares a variable of type season and assigns an appropriate enum value to it. The closest match to enum in the Java language is an integer class constant-a final static variable of type int. A class constant has the following properties: It is declared with the keywords final and static. It must be initialized with a value as part of its declaration. It can be used only for its value; it cannot be assigned to. The corresponding season example in Java, therefore, would be: /* in Java: */ public final static int WINTER = 0; public final static int SPRING = 1; public final static int SUMMER = 2; public final static int FALL = 3; int now = FALL;It is conventional to use all capital letters for Java class constant names. See also: Q2.1 [previous] [TOC] [next] Q2.4 Why is goto a reserved keyword in Java- shouldn't it be outlawed? The word goto is reserved in the Java language precisely so that it can be outlawed. The Java language sets aside 47 words as keywords-words reserved by the language itself and therefore not available as names for variables or methods. Here is the list from The Java Language Specification (p. 18): abstract, boolean, break, byte, case, catch, char, class, const, continue, default, do, double, else, extends, final, finally, float, for, goto, if, implements, import, instanceof, int, interface, long, native, new, package, private, protected, public, return, short, static, super, switch, synchronized, this, throw, throws, transient, try, void, volatile, while Two of these are not currently used by the Java language: goto and const. They are deliberately set aside so that a Java-compatible compiler can produce more specific error message if it finds one of these forbidden keywords in a source file. This is intended to help former C or C++ programmers who are migrating code to Java. The Java language retains limited goto powers in the form of labeled statements reachable from break and continue statements. These are especially useful for exiting from multiple layers of loops, as sketched in the following example: topLoop: // label for the following while statement while (checkCondition()) { for (int i = 0; i < max; ++i) { for (int j = 0; j < i; ++j) { // ... if (foundAnswer()) { break topLoop; // exits the top-level while loop }

} } }See also: JLS p. 18, JLS pp. 283-286 [previous] [TOC] [next] Q2.5 What are some guidelines for using uppercase and lowercase letters in my identifiers? Use lowercase letters in general, but capitalize the first letter of class and interface names, as well as the first letter of any non-initial word. Case sensitivity is part of Java's deliberate design choice to maintain compatibility with C programming habits where reasonable. Case distinctions take part in some naming conventions employed by the Java system and standard classes. The Java Language Specification recommends (but does not require) that such conventions be used in all Java programs. For example: "Names of packages intended only for local use should have a first identifier that begins with a lowercase letter." (p. 107) "Names of class types should be descriptive nouns or noun phrases, not overly long, in mixed case with the first letter of each word capitalized." (p. 108) "Method names should be verbs or verb phrases, in mixed case, with the first letter lowercase and the first letter of any subsequent words capitalized." (p. 108) "Names of fields that are not final should be in mixed case with a lowercase first letter and the first letters of subsequent words capitalized." (p. 109) Table 2.3 presents some examples from the JDK 1.1: Table 2.3: Examples of Capitalization in IdentifiersKind of identifierNames in JDK 1.1 classButton, BufferedReader interfaceRunnable, DataInput methodStart(), getAbsolutePath() variableint offset, String anotherString See also: JLS pp. 106-111 [previous] [TOC] [next] Q2.6 Is there any limit to the length of an identifier? Yes; 65,535 characters is the maximum possible identifier length, because identifier names must be representable in Java class files. The Java language in principle does not limit the length of identifiers. According to The Java Language Specification (p. 6), "An identifier is an unlimited-length sequence of Unicode letters and digits, the first of which must be a letter." However, Java source code is compiled into Java class files, and the specification for class files does, in effect, place an upper bound on the size of identifiers. This limit is well beyond the practical needs of human codes, but it is interesting to understand where it comes from. Java class files must store symbolic names for all fields, methods,

classes, and interfaces referenced in a class definition. (In contrast, class files represent method parameters and local variables not by name but by index.) In a class file, the maximum space a single name can take is 65,535 bytes. If the name contains only ASCII characters, then the class file can fit 65,535 Unicode characters into those 65,535 bytes. Unicode characters beyond the ASCII range (that is, values above 127), however, require two or even three bytes of storage apiece, because they are encoded in the UTF-8 format (see The Java Virtual Machine Specification, p. 100, for details). Names containing such characters have a correspondingly lesser maximum length. You could precisely calculate this maximum, depending on the characters in the string, but you should never need to even approach it. See also: JVMS p. 100 [previous] [TOC] [next] Q2.7 Why doesn't Java have user-defined operator overloading? The Java language forgoes the expressive power of user-defined operator overloading for the sake of simplicity and readability. The Java language aims to be powerful and practical, yet simple and readable. It was the experience of the Java language designers that operator overloading too often makes programs hard to read. The code itself no longer tells you which parts have standard meanings and which parts are defined by the author. (This highly contentious issue has received copious discussion on various Java-related mailing lists and newsgroups.) The Java language allows only one very limited case of operator overloading. The + operator doubles as an arithmetic addition operator (when both its operands are numeric) and as a string concatenation operator (when at least one operand is a String instance). The following three statements, for example, contrast the uses of the + operator: String string1 = "box" + (5 + 3); // Result: "box 8" String string2 = ("box" + 5) + 3; // Result: "box 53" String string3 = "box" + 5 + 3; // Result: "box 53"The first line invol ves both the string concatenation operator and the arithmetic addition operator; the second line involves two applications of the string concatenation operator; and the third line shows that it is a good idea to provide explicit parentheses whenever mixing the two uses of the + operator. For the same goals of simplicity and clarity, the Java language also omits typedefs and preprocessor macros. Thus, a piece of Java code, even out of context, makes sense. You know which parts are defined by the language itself and which parts are defined by the author. See also: Q11.1 [previous] [TOC] [next] Q2.8 Why do I have to put an f after a floating point constant? The f (or F) suffix directs the compiler to create a float value from a sequence of characters representing a floating point number (a float literal)-otherwise the compiler would by default create either a double value or an int value. A literal is a string of characters in a source file that the compiler translates directly to a value of a specific type. The Java language recognizes literals for integral numbers, floating point numbers, strings, Unicode characters, boolean values, and null. Table 2.4 shows examples of literals in the Java language, with the types as indicated.

Table 2.4: Examples of Java LiteralsLiteralType 34int 0xFFint 3.14159double 1.25e11double (the value is 1.25Â¥1011) '9'char '\uFF01'char trueboolean falseboolean "Cancel"String (quotes are part of the literal) "null"String nullspecial literal null Numerical literals have the option of containing a suffix as well, which directly specifies the type that the compiler should use when creating the value from the literal, as shown in Table 2.5. Table 2.5: Suffixes on Numerical LiteralsSuffix on literalTypeExamples d or Ddouble34d, 0xffDv f or Ffloat34F, 3.14159f l or Llong34l, 0xffL By default, an integer-like literal (with no decimal point or exponent) creates a value of type int, and a floating point literal creates a value of type double. If you need a nondefault type for the value, use the appropriate suffix on the literal. There are two common cases that require this. First, to specify a long literal outside the range of an int, you cannot count on automatic promotion; you must use the l or L suffix: long valueOne = 1234567890123; /* WRONG */ long valueTwo = 1234567890123L; /* RIGHT */In the first line, the integer literal is silently be treated as an int, with the resulting value of 1,912,276,171 (the int value of the lower 32 bits of the literal). Second, to specify a float literal as an initial value for a float variable or as an argument to a method, again you cannot count on automatic type conversion; you must use the f or F suffix: float floatVal1 = 3.14159; /* WRONG-compiler will complain */ float floatVal2 = 3.14159f; /* RIGHT */ In this case, the compiler iss ues an error message for the first line because the types are incompatible: it cannot assign a value of type double to a variable of type float without an explicit cast (Q2.9). With an explicit cast, the compiler is again satisfied: float floatVal3 = (float) 3.14159; /* OKAY */See also: Q2.9 [previous] [TOC] [next] Q2.9 How and when can I cast from one class to another? You can't change the class of an object, but you can change the class by which a reference accesses an object. A Java object has a fully specified, unchangeable class at run time. (Invoking getClass on an object returns a Class instance describing the object's class; see Q2.15.) Although objects and their classes cannot be cast, object references (Q1.10, Q2.11) can. To cast a reference to a specified class or interface, place the class or interface name in parentheses preceding the reference. For example: String aString = "abadcafe"; Object anObject = (Object) aString; // OKAY anObject = aString; // OKAY Java allows you to cast an

object reference both from subclass (Q1.11) to superclass and from superclass to subclass. An upward cast-subclass to superclass-is checked at compile time. A downward cast (superclass to subclass) works only if the cast passes a run-time type check: the run-time type of the object must be same as (or a subclass of) the type it is being cast to. Any downward cast failing the run-time check will throw a ClassCastException. For example: String aString = "abadcafe"; Object anObject = (Object) aString; // OKAY - compile time String testString = (String) anObject; // OKAY - run time Integer anInteger = newInteger(1); anObject = (Object) anInteger; // OKAY - compile time Integer testInteger = (Integer) anObject; // OKAY - run time testString = (String) anObject; // ClassCastException The cast operator can also apply to interfaces and to Java's primitive numerical types, such as int and double (Q2.8). See also: Q1.10, Q1.26, Q2.8, Q2.11, Q2.15 [previous] [TOC] [next]

Note:

Q2.10 Can I use C-like data structures in Java? If you really want just a structured data container with no methods, then create a class containing nothing but public instance variables. A class (Q1.2) in the Java language provides a structured data container together with executable code (methods; see Q1.3) for inspecting and manipulating that data. A structured data container. If Java class to look and behave /* a structured data container class Point { public int x; public int y; }

structure (struct) in C provides merely the you really want to, you can strip down a much like a structure in C. For example: in Java: */

/* a structured data container in C: */ struct point { int x; int y; } ; However, once you have your data nicely packaged like this, it almo st always makes sense to add some functionality to manipulate the data held in such a container. In object-oriented programming, this means defining one or more methods in the class. See also: Q1.1, Q1.2, Q1.3 [previous] [TOC] [next] VARIABLES AND METHODS Q2.11 Are Java objects pointers? No; Java objects are objects (typed containers for data plus associated methods), but the Java language lets you access objects only via references. The Java runtime is filled with objects-created by the system and by your program. An object is a programming entity that holds data and is associated with a class; the class defines both the data and services that

its objects support. Although objects are the heart of your Java program, you never get direct access to them. The Java language lets you handle only object references-values that refer to objects but completely lack arithmetic (pointer-like) properties (Q1.10). Whenever a variable, method argument, or method return value appears to work with an object, it is in fact working indirectly through an object reference. See also: Q1.1, Q1.2, Q1.10, Q2.1, Q2.12, Q2.13 [previous] [TOC] [next] Q2.12 In a method invocation, does Java pass arguments by reference or by value? Java method invocations pass arguments by value. Java method invocations pass all arguments by value-primitive data types and reference data types alike (Q2.1). This means that the value of each argument is copied to a corresponding method-internal variable before the method's code is executed. The method's code can act only on this internal copy of the data. Consider the following minimal class, which defines and invokes a zeroIt method: class Example { static void zeroIt(int intVal) { intVal = 0; } public static void main(String[] args) { int myInt = 5; zeroIt(myInt); System.out.println("Does myInt equal 0 or 5? " + myInt); } }Running this class shows that the int argument is unchanged: > java Example Does myInt equal 0 or 5? 5Because zeroIt's int argument is passed by value , zeroIt zeroes only its internal copy of the int value; it doesn't affect the original int value stored in myInt. What about objects, then? The key here is that the Java language provides only reference-type (pointer-like) variables for objects (Q1.10, Q2.11). The values of such variables are not objects, but references to objects. When you invoke a method with object-like arguments, the object references are passed by value; in other words, the reference itself is copied to a corresponding method-internal variable. The result is that two different references now refer to the same object. Copying references still allows you to affect the referred-to object from inside the method, as long as the internal reference copy keeps referring to the original object. Consider a slightly different class, ZeroItExample2, that works on StringBuffer instances (modifiable character strings; Q11.1): class Example2 { static void zeroIt(StringBuffer buf) { buf.setLength(0); buf.append("0"); } public static void main(String[] args) { StringBuffer myStringBuffer = new StringBuffer("abc"); zeroIt(myStringBuffer);

System.out.println("Does myStringBuffer equal abc or 0? " + myStringBuffer); } }The answer this time is: > java Example2 Does myStringBuffer equal abc or 0? 0Here, the zeroIt method does affect d ata outside the method, but only because it could reach it indirectly, via the reference copied in. As a final exercise, try replacing zeroIt in Example2 with the following tryToZeroIt method: static void tryToZeroIt(StringBuffer buf) { buf = new StringBuffer("0"); }Why does this version not affect the value of myStringBuffer? (Hint: Consider which operations in zeroIt and tryToZeroIt affect references and which affect referred-to objects.) See also: Q1.10, Q2.1, Q2.11, Q11.1 [previous] [TOC] [next] Q2.13 If the Java language lacks pointers, how do I implement classic pointer structures like linked lists? Use object references in place of pointers. Object references in Java are like object pointers minus the arithmetic. The Java language lets you point to (refer to) objects; it just doesn't let you change numbers into references, references into numbers, or otherwise treat references in any numerical way (Q1.10, Q2.11). This property makes it straightforward to implement classic pointer-dependent data structures such as lists and trees. The following example shows a minimal linked-list implementation of a stack: /** A bare-bones stack class that holds objects of any class. */ public class SimpleStack { LinkedObject stackTop = null; public void push(Object obj) { if (obj != null) { stackTop = new LinkedObject(obj, stackTop); } } public Object pop() { if (stackTop != null) { Object oldTop = stackTop.value; stackTop = stackTop.nextObject; return oldTop; } return null; } } /** A bare-bones class for linking objects of any class. */ class LinkedObject { Object value; LinkedObject nextObject; LinkedObject(Object obj, LinkedObject next) { value = obj; nextObject = next; } } Even better, you often don't need to reinvent the wheel; you can use a class that's already been designed to provide the behavior you need. A Stack class already exists in the java.util package, for example. The java.util package also provides a Vector class, which represents a

growable array for Object instances that you can use in place of a linked list, at least for some applications. The above code, for instance, could be rewritten as: import java.util.Vector; public class VectorStack { Vector stackElements; public void push(Object obj) { if (obj != null) { stackElements.addElement(obj); } } public Object pop() { if (stackElements.isEmpty()) { return null; } Object oldTop = stackElements.lastElement(); stackElements.removeElementAt(stackElements.size() - 1); return oldTop; } } See also: Q1.10, Q2.11, Q2.12 [previous] [TOC] [next] Q2.14 What does the following error message mean: Can't make a static reference to nonstatic variable? The compiler is complaining that you are trying to reference the implicit instance variable this from within a class method. The Java language lets you define three kinds of variables: class variables, instance variables, and local variables (Q1.5). Class variables are defined on a per-class basis, and all instances of a class can access them. Instance variables are defined on a one-per-object basis, and you can access them only in connection with some specific instance of a class. Local variables are defined inside individual methods and can be accessed only from inside that same method. The "Can't make a static reference ..." error message most commonly arises in a class's main(String[]) method, which the Java language requires to be a class method (declared with the static keyword; see Q1.6). The following code exemplifies the error: /* The compiler will complain about this: */ class StaticError { String myString = "hello"; public static void main(String[] args) { System.out.println(myString); } } The myString variable is an instance variable; you cannot access it unless you have created one or more instances of the class. There are therefore two minimal ways to fix the example: either change the variable to be a class variable, or create an instance of the class in order to access the instance variable. The first fix simply requires that you use the static keyword when defining the variable: /* This works. */ class NoStaticError { static String myString = "hello"; public static void main(String[] args) { System.out.println(myString);

} }The second fix requires creation of an instance of the class: /* This also works. */ class NoStaticError2 { String myString = "hello"; public static void main(String[] args) { NoStaticError2 obj = new NoStaticError2(); System.out.println(obj.myString); } }See also: Q1.5, Q1.6 [previous] [TOC] [next] Q2.15 In a class method, how can I get the name of the class, or create a new instance of the class? You can't, in general; these operations require that you obtain an instance of class Class representing the current class, which in turn requires that you either (a) already know the name of the class, or (b) already have an instance of the class. The Java platform includes a special class, the Class class, that lets your program inspect Java data types at run time. Each instance of class Class represents a different class or interface type that has been loaded into the current Java Virtual Machine. You can query a Class instance for many kinds of information about the class. In the JDK 1.0.2, you can query the class's name, class loader, superclass, and interfaces; you can also create a new instance of the class with the newInstance method. The JDK 1.1 opens much more to inspection, including the class's fields, methods (Q2.16), and constructors. One way to obtain a Class instance is to ask for it by name, using the forName method (Q3.7). The following code, for example, fetches three distinct Class instances from the virtual machine: Class c1 = null; Class c2 = null; Class c3 = null; try { c1 = Class.forName("java.lang.Thread"); c2 = Class.forName("java.lang.String"); c3 = Class.forName("java.lang.Integer"); } catch (ClassNotFoundException e) { e.printStackTrace(); }Note that the forName method requires that you provide the fully qualified name of the class, that is, the class's simple name preceded by the name of the package containing the class (Q1.30). In the JDK 1.1, if you know the class's name at compile time, you can get the Class instance more directly, by means of a class literal: /* using JDK 1.1: */ Class c1 = Thread.class; Class c2 = String.class; Class c3 = Integer.class; Alternatively, if you have an object and want to get at its corresponding Class instance, you can invoke the getClass method on the object. For example: Class c4 = "a string".getClass(); Finally, what about accessing the Cla ss instance for the class of the currently executing method? If the method is an instance method, there is

a simple, general way to get the Class object-use the ever-present this field, which refers to the object the method was invoked on: /* works inside an instance method: */ Class thisClass = this.getClass();Even simpler, you can take advantage of t he fact that this can be left implicit: Class thisClass = getClass(); // same as this.getClass() Class methods , however, have no notion of a current instance (no this), so you must manually provide an instance (or the class's name) before you can fetch the Class instance. This requirement, unfortunately, often forces the cart before the horse. See also: Q1.30, Q2.16, Q3.7 [previous] [TOC] [next] Q2.16 Can I write a method that delivers dynamically (at run time) all public methods of an object? Don't write this yourself; use the getMethods method in class Class, available in the JDK 1.1. The JDK 1.1 enhances the ability of class Class to inspect Java classes at run time, by means of classes in the java.lang.reflect package: Method: instances of this class let you inspect and manipulate a specific method of a class. Field: instances of this class let you inspect and manipulate a specific field of a class. Constructor: instances of this class let you inspect and manipulate a specific constructor of a class. Following are several of the new (1.1) methods in class Class: getMethods(): returns an array of Method objects corresponding to the public methods of this class. getFields(): returns an array of Field objects corresponding to the public fields (variables) of this class. getConstructors(): returns an array of Constructor objects corresponding to the public constructors of this class. Thus, inspecting methods, fields, or constructors at run time requires that you obtain the Class instance for the class you're interested in, then invoke the appropriate accessor methods. The following example method takes an object argument and prints out all the accessible methods, fields, and constructors in the class of that object: public static void printClassInfo(Object obj) { Class c = obj.getClass(); Method[] methods = c.getMethods(); Field[] fields = c.getFields(); Constructor[] constructors = c.getConstructors(); System.out.println("\nMethods:"); for (int i = 0; i < methods.length; ++i) { System.out.println(" " + methods[i]);

}

} System.out.println("\nFields:"); for (int i = 0; i < fields.length; ++i) { System.out.println(" " + fields[i]); } System.out.println("\nConstructors:"); for (int i = 0; i < constructors.length; ++i) { System.out.println(" " + constructors[i]); } Note: The getMethods method returns all public methods belonging to a class-the methods declared by the class together with the methods inherited from superclasses. getMethod11Example.html See also: Q2.17, Q2.18 [previous] [TOC] [next] Q2.17 Can I invoke methods dynamically, from names (String instances) that are determined at run time? Yes; the reflection API in the JDK 1.1 lets you invoke methods by means of run-time strings representing method names, but use of this facility is not recommended as a general design strategy. Starting in the JDK 1.1, the Class class and the new java.lang.reflect package expand your ability to inspect and manipulate classes and methods at run time. The preceding FAQ (Q2.16) illustrates how to inspect class information at run time using Class's getMethods, getFields, and getConstructors methods. The reflection API also lets you pull out individual elements from a class or class instance and act on them. You can: invoke a method by means of a Method instance fetched at run time (using Method's invoke method) change the value of a field by means of a Field instance fetched at run time (using one of Field's set... methods) create a new class instance by means of a Constructor object fetched at run time (using Constructor's newInstance method) These capabilities are essential for component integration frameworks, such as JavaBeans(tm), and for application builder tools. Let's focus now on methods. Invoking a method dynamically requires two basic steps: Obtain a Method instance using Class's getMethod method.

Invoke the invoke method on that Method instance. (The English description is almost comical here because of the multiple levels of reference to object-oriented constructs.) As an example of step 1, the following code obtains a Method instance representing the substring(int, int) method in class String: /* Get Method instance representing String.substring(int, int). */ Class theClass = String.class; Class[] parameters = {int.class, int.class}; Method theMethod = null; try {

theMethod = theClass.getMethod("substring", parameters); } catch (NoSuchMethodException e) { // ... handle exception } A significant restriction in using getMethod is that getMethod requires a Class object to represent each method parameter. If the parameter is already of a class or interface type, this step is straightforward. However, if the method parameter has a primitive data type, such as int or double, you need to provide an instance of class Class specially designed to represent that primitive type. Table 2.6 lists the Class objects and corresponding class literals (introduced in the JDK 1.1) that you can use to represent the primitive types. Table 2.6:Class Instances and Class Literals for the Primitive TypesPrimitive typeClass instanceClass literal doubleDouble.TYPEdouble.class floatFloat.TYPEfloat.class longLong.TYPElong.class intInteger.TYPEint.class shortShort.TYPEshort.class byteByte.TYPEbyte.class charCharacter.TYPEchar.class booleanBoolean.TYPEboolean.class voidVoid.TYPEvoid.class Note that void, strictly speaking, is not a type, but it still needs a Class instance representing it for use with the java.lang.reflect classes. Once you obtain the Method instance, you can invoke the invoke method on it. Just as getMethod requires an array of Class instances to represent the parameter types, Method's invoke method requires an array of Object instances to represent the actual arguments to the method when you invoke it. If a method argument is a primitive data type, you must use one of the wrapper classes in the java.lang package, such as Integer or Double, to place the argument value inside an appropriate class instance: /* Execute "123".substring(1, 2). */ Object[] arguments = {new Integer(1), new Integer(2)}; String s1 = null; try { s1 = (String) method.invoke("123", arguments); } catch (InvocationTargetException e) { // ... handle exception } catch (IllegalArgumentException e) { // ... handle exception } These examples also illustrate the kinds of exceptions (Q2.22, Q2.23) that the methods can throw: getMethods can throw NoSuchMethodException, and invoke can throw InvocationTargetException and IllegalArgumentException. Invoking methods dynamically from string names is an important piece of flexibility in the Java system. However, this capability circumvents Java's many built-in mechanisms for compile-time name checking and type checking-it should be used sparingly and with caution. InvokeMethodDynamically11Example.html See also: Q2.1, Q2.16, Q2.22, Q2.23 [previous] [TOC] [next]

Q2.18 How can I accomplish the equivalent of function pointers in Java, for instance, for use in an array? To treat executable code as an assignable, run-time swappable unit, you need to package it in a (small) class; the inner class facility added to the Java language starting with the JDK 1.1 simplifies this work. In the Java language, the smallest unit of code that you can treat in an object-like fashion is the class. ("The quanta of behavior are classes," is James Gosling's terser version of this idea.) To encapsulate code so that you can assign it to variables, pass it from object to object, and so on, you need to create one or more classes to contain the code. You can use either an interface or a simple superclass as the type for the code objects you want to manipulate. The following sample code shows one simple way to accomplish this, within the JDK 1.0.2 Java language: interface DoIt { public void doIt(); } class PrintMonth implements DoIt { public void doIt() { String[] monthNames = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; int monthIndex = new java.util.Date().getMonth(); System.out.println(monthNames[monthIndex]); } } class PrintDay implements DoIt { public void doIt() { String[] dayNames = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; int dayIndex = new java.util.Date().getDay(); System.out.println(dayNames[dayIndex]); } } class Demonstration_1_0_2 { public static void main(String[] args) { DoIt[] thingsToDo = {new PrintMonth(), new PrintDay()}; for (int i = 0; i < thingsToDo.length; ++i) { thingsToDo[i].doIt(); } } } The JDK 1.1 release augments the Java language with the notion of inner classes: classes and interfaces that can be declared as members of another class. Inner classes, especially anonymous inner classes, make it significantly easier to define small classes (Q7.2). See also: Q7.2 [previous] [TOC] [next] ARRAYS Q2.19 Can I allocate an array dynamically?

Yes and no; you can create an array with a size determined at run time, but you cannot change the size of an array once you've created it. Arrays in Java are full-fledged, object citizens of the language. Like other Java objects, they are created dynamically at run time, and their storage space is allocated from the virtual machine's system storage. Because arrays are created at run time, you don't have to prespecify an array's size at compile time. There are two ways to create an array: with an array initializer when declaring an array-type variable, or with an array creation expression. An array initializer specifies the complete set of values to be stored in an array. For example, the following declaration and initializer create an array holding 5 int values: int[] myInts = {5, 4, 3, 2, 1}; // int myInts[]... also allowed A pla in array creation expression, using the new keyword, creates an array filled with default values for the element type in the array. You specify the size of the array with any expression that evaluates to an int. The following code, for instance, creates an array of sine values; the array's size is specified by the method's argument: public static float[] sineArray(int size) { float[] sineVals = new float[size]; for (int i = 0; i < sineVals.length; ++i) { sineVals[i] = (float) Math.sin( (i * 2 * Math.PI) / size); } return sineVals; } Starting with the JDK 1.1, you can also include an array initializer directly in an array creation expression. For example: /* using JDK 1.1: */ // int[] myInts declared elsewhere myInts = new int[] {5, 4, 3, 2, 1}; Once a Java array is created, its s ize is fixed for the lifetime of the array. If you need more dynamism-an array-like object that can grow as needed when you use it-consider using the Vector class in the java.util package. See also: Q2.20, JLS p. 193 [previous] [TOC] [next] Q2.20 How do I initialize an array of objects? Write a loop that initializes the base elements of your array one by one. In the Java language, what looks like an array of objects is really an array of object references- basically, pointers to objects (Q2.11). The objects themselves are stored separately in space managed by the Java Virtual Machine. When you create an object-type array, you are in fact creating an array of object references. Unless you explicitly initialize the array, moreover, each object reference receives the default initial value of null. In other words, creating an object array in Java automatically gives you an array filled with null object references. After creating an array, you need to set each object reference to refer to some bona fide object. The usual technique for this is to allocate and initialize objects in a loop through the array, as illustrated: String[] sArray = new String[10]; for (int i = 0; i < sArray.length; ++i) { sArray[i] = "string at index " + i; } The behavior of arrays containing objects follows from the fact that Java array components are in fact nameless variables (The Java Language

Specification, p. 193). These nameless variables are related to their array in much the same way that (named) instance variables are related to the class instance containing them. Table 2.7 compares arrays and class instances as two different kinds of object; you might find this alternate view of Java arrays a surprising yet useful one. Table 2.7: Class versus Array as Two Kinds of ObjectClass instance (obj)Array instance (arr) stores per-object data in named instance variablesstores per-object data in nameless (but numbered) variables can have variables of different types in one objectall variables in object have same type accesses variables by name: obj.fieldNameaccesses variables by index: arr[index] reference-type variables hold object references[same as class instance] instance variables have default initialization[same as class instance] See also: Q2.11 [previous] [TOC] [next] Q2.21 If arrays are objects, why can't I use a length method to determine an array's size? Such a method would be reasonable, but it doesn't exist; the Java language designers decided to expose array length like a public final instance variable rather than a method. In Java, arrays are objects. They are created dynamically from central, system-managed memory like other objects; they all have Object as a superclass; and you can invoke any Object method on them. Given this, it would have been possible to define a length instance method on arrays to return the length of the array, much like the length method in class String. However, the Java language designers chose to represent length simply as an instance variable of the array. The length variable is always accessible but never changeable; its value is fixed at the time the array is created. [previous] [TOC] [next] EXCEPTIONS Q2.22 What is an exception? An exception is a condition (typically an error condition) that transfers program execution from a thrower (at the source of the condition) to a catcher (handler for the condition); information about the condition is passed as an Exception or Error object. An exception provides a communication channel between one portion of code that detects and signals an (error) condition, and another portion of code that responds to the condition. Exceptions in some ways resemble method invocations, as highlighted in Table 2.8. In both cases, information and control of execution pass from one portion of code to another. And in both cases, the initiator of the exchange typically doesn't know, and doesn't need to know, precisely what code will respond (Q1.1, Q1.18).

Table 2.8: Throwing an Exception versus Invoking a MethodInstigator/RequesterCommunication mechanismResponder/Performer throw statementException objectexecutes catch clause method invocation expressiondynamic method lookup; arguments and return valueexecutes method body It is important to remember, however, that exceptions should be used only for exceptional control flow needs. Exceptions typically signal unexpected error conditions, such as: IllegalArgumentException: a method argument violates some requirement NullPointerException: a method is invoked on a null reference ArrayIndexOutOfBoundsException: an array index is too small or too large The Java language represents exceptions as objects, all of which belong to the Throwable class or one of its subclasses. Because exceptions belong to classes, you can readily define your own exception types by subclassing an existing exception class. There are four main ways to interact with Java's exception system, listed below in a common order that programmers learning Java encounter them: catching exceptions thrown by other people's code writing your own code to throw exceptions declaring exceptions that a method can throw defining your own Exception classes What follows is a bare-bones how-to introduction for each of these facets. To catch an exception, you specify a body of code to watch, a type of exception to watch for, and a body of code to execute if an appropriate exception type is thrown within the watched body of code. For example: int anIntValue; String str = solicitStringFromUser(); try { anIntValue = Integer.parseInt(str); } catch (NumberFormatException e) { reportError("string could not be parsed as an Integer.") } To throw an exception, use the throw statement and provide a newly created Exception instance, which can include a message providing information about this particular exception: int speed; // an instance variable public void setSpeed(int value) throws IllegalSpeedException { if (value < 0) { throw new IllegalSpeedException( "speed cannot be negative"); } speed = value; // executed only for valid speed values.

}The above code also illustrates how to declare an exception: you provide a throws declaration following the method's parameter list. Note that both methods and constructors can throw and declare exceptions. Finally, to define a new Exception class, subclass Exception or one of its subclasses, and provide appropriate constructors. The IllegalSpeedException used in the previous example is not a predefined Java class; you could define it yourself: class IllegalSpeedException extends Exception { public IllegalSpeedException() { super(); } public IllegalSpeedException(String s) { super(s); } }See also: Q2.23 [previous] [TOC] [next] Q2.23 Why does the compiler complain about InterruptedException when I try to use Thread's sleep method? The compiler is complaining, as it is required to do, that your code invokes a method that might throw a checked exception, but your code is not prepared to handle that exception; to stop the compiler from complaining, your method must either declare or catch the InterruptedException that Thread's sleep method can throw. InterruptedException belongs to the set of checked exceptions- a subset of exceptions that a Java compiler is required to track through any source code it handles (Q2.22). One of the compiler's restrictions is that a method declare all the checked exceptions that it might throw. A method can throw an exception either by an explicit throw statement or by invoking another method that throws the exception. Thread's sleep method declares that it can throw an InterruptedException; therefore, the compiler will examine any method that invokes sleep to check whether the exception is being dealt with. You have two options when writing a method that invokes sleep: declare that your method can throw InterruptedException catch the exception inside your run code To declare the exception, add a throws clause to your method definition: public void myMethod() throws InterruptedException { /* ... */ }This is a s imple fix, but it also means that you are leaving it up to some other method to catch and deal with the exception. It is often better to catch an exception right at the point it is generated, where you usually have more information about what triggered the exception. To catch the exception, surround your call to sleep in a try-catch block: try { Thread.sleep(sleepTime); } catch (InterruptedException e) { // ... handle the exception here (good) // or leave this blank to ignore the exception (risky) // but still satisfy the compiler }See also: Q2.22, Q2.24 [previous] [TOC] [next] Q2.24 Why do methods have to declare the exceptions they can throw?

The simple answer is that the Java language requires it; the more meaningful answer is that the language requires exception declarations because they enhance the usability and robustness of code as part of an API. The Java language requires that a method declare any checked exceptions that the method might throw. Whether an exception is checked or not depends on the exception's class. As shown in Table 2.9, the base Throwable class splits into two main subclass branches, Error and Exception. All Exception subclasses are checked exceptions except for RuntimeException and its subclasses (Q2.25). Table 2.9: Checked Expections versus Unchecked ExceptionsClass hierarchy under ThrowableChecked? ThrowableError and its subclassesno ExceptionRuntimeException and its subclassesno all other Exception subclassesyes The intent of checked exceptions is that you declare exceptions as a meaningful part of your class's programming interface. Together with a method's return value, exceptions define the output behavior of the method. Any code that invokes a method must be prepared to handle either of these: the method's return value, if the method completes normally any of the method's checked exceptions, if the method terminates abnormally Checked exceptions thus complement the return value as indicators of a method's exit status. For example, the InputStream class in the java.io package includes a read method that is declared as follows: public byte read() throws IOException; This means that any method invoking this read method must be prepared to handle two kinds of outcome from the method: a byte return value if the read succeeds, or an IOException if the read fails. The invoking method itself must therefore either catch the exception or declare that it, too, throws IOException (Q2.23). The requirement that checked exceptions be declared or caught is not just good programming practice-it is a rule enforced by the Java compiler. More specifically, the compiler enforces the following condition: If method X invokes method Y, and method Y can throw a checked exception, then either method X must catch the exception, or method X must declare the exception (or a superclass of the exception). The real power of this check is that the compiler performs it transitively, following the often-complex chain of possible method invocations (method X invokes method Y, which in turn might invoke method Z, and so on). This moderate degree of automated error checking provides surprisingly strong help in writing robust, error-tolerant code. One example comes from the development of Java and HotJava themselves. When exception declarations and exception checking were added to the language, this immediately turned up a number of cases in which the HotJava developers hadn't noticed they needed to catch certain important types of exceptions. Instead of being caught further down the road as tricky run-time bugs, these mistakes were now being flagged as compile-time errors. The developers thus were able to find and fix the problems much

more efficiently. The extra effort of declaring checked exceptions was repaid many times. Such experiences advise against circumventing these built-in checks without strong reason (and even then, think twice). See also: Q2.22, Q2.23, Q2.25 [previous] [TOC] [next] Q2.25 What's the difference between a runtime exception and a plain exception-why don't runtime exceptions have to be declared? The Java language specifies that all runtime exceptions are exempted from the standard method declarations and compiler checks; such exceptions belong more to the system as a whole than to the method that happens to be executing when the exception is thrown. The Java language lets you signal conditions (usually error conditions) by throwing an object at one point in your code, such that an enclosing block can catch the object and infer from it the trigger condition. The object you throw must belong to the Throwable class or one of its subclasses. The class hierarchy under Throwable further classifies the nature of the unusual condition. Throwable subdivides into two subclasses, which The Java Application Programming Interface (Vol. 1) demarcates nicely: Error: "indicates serious problems that a reasonable application should not try to catch." (p. 175) Exception: "indicates conditions that a reasonable application might want to catch." (p. 162) Errors are never declared-they are entirely unexpected and practically always fatal. When an Error instance is thrown and not caught, it works its way up the method invocation stack until the Java Virtual Machine detects it, prints out a diagnostic error message (usually including a useful stack trace), and then kills that thread. (Uncaught Exception instances have this same behavior.) Exceptions come in two basic varieties-those that can be ascribed to the execution of a single method and those that belong more to the system as a whole: Exception (in general): meaningful, specific, recoverable condition that can be expected to arise occasionally in the execution of this method (for instance, a NumberFormatException thrown when trying to parse a String instance as an Integer value). RuntimeException: a condition that can arise in principle anytime, largely independent of which particular method happens to be executing (for instance, an ArrayIndexOutOfBoundsException). Exceptions in general must be declared by methods (and by constructors) and are checked by the compiler (Q2.24). Runtime exceptions are exempted from this because the Java designers judged that having to declare them would be too much work, would involve too many methods, and would not pay back the extra effort sufficiently in terms of increased program robustness. The difference between runtime exceptions and other exceptions is not always clear-cut- it requires human judgment as to the relative merits of including the exception as a method-specific condition versus a can happen-anytime general condition. Nevertheless, making the distinction reflects Java's pragmatic streak:

It presents a balance between theoretical purity and practical needs. It helps developers write convenient yet robust code. Recommendation: Use general (declared) exceptions wherever possible. In the experience of many Java developers, the benefits of automatic compile-time checking more than offset the extra effort of declaring or catching exceptions. See also: Q2.22, Q2.23, Q2.24, Q2.26 [previous] [TOC] [next] Q2.26 Given a method that doesn't declare any exceptions, can I override that method in a subclass to throw an exception? No; subclasses must honor the API contract established by their superclasses, and this includes the types of checked exceptions that a method can throw. An API (application programming interface) establishes a contract of intent, not just of form or interpretation. To borrow terminology from linguistics and philosophy, an API contract involves both extension and intension: the boundaries of the current state of the world (extension) as well as the intended boundaries for other possible states of the world (intension: possible future implementations). In object-oriented programming, a common source of "possible future implementations" is subclassing from an existing class in an API. A method defines a contract for any subclass method that would override it; it constrains possible implementations that a subclass could provide. In Java, the bare minimum contract for a method's inputs and outputs is the following: A method's parameter list is fixed; an overriding method in a subclass must declare precisely the same number and types of arguments. A method's return type is fixed; an overriding method in a subclass must declare precisely the same return type. The set of checked exceptions a method can throw (the method's declared exception classes and all their subclasses) establishes an upper bound. An overriding method in a subclass cannot throw any checked exceptions outside of that; it can, however, throw fewer exception types, or even none at all. Note that the contract on exceptions concerns only checked exceptions; errors and runtime exceptions (that is, Error, RuntimeException, and their subclasses; see Q2.25) are always permitted. If a method, such as Object's toString method, is declared as throwing no checked exceptions, any overriding method you define must live within those bounds. You cannot define your own subclass of Exception and have your toString method throw that. In such a case, if you really need some exception to be thrown, you can resort to a subclass of RuntimeException, which is not checked or constrained by the compiler. See also: Q2.24, Q2.25 [previous] [TOC] (c) Copyright 1997 Sun Microsystems. The Java(TM) FAQ - Chapter 3: Virtual MachineCHAPTER 3

Virtual Machine (Q3.1-Q3.9) VIRTUAL MACHINE Q3.1 When, and by whom, is the main method of a class invoked? Normally, you don't invoke main yourself; the Java Virtual Machine invokes it for you if it uses your class as its starting point of execution. A Java Virtual Machine always starts execution from the main method of some class. Even a large Java application, such as the HotJava(tm) browser, starts execution in one class's main method. The main method must be declared as public and static, it must have no return value, and it must declare a String array as its sole parameter: public static void main(String[] args) { // ... }You can include such a main method in any class you define. The Java compiler does not complain about classes containing unused main methods. How you as a user start a Java Virtual Machine can vary in different implementations. In some implementations, such as the JDK (1.0.2 and 1.1) on Solaris and Win32, you start the virtual machine with a command line that specifies a class and an optional list of strings for your program to start with. For example, suppose that your Java Virtual Machine is stored in a command named java, and you have written and compiled the following CountWords class: public class CountWords { public static void main(String[] args) { System.out.println(args.length); } }If you now issue the command: java CountWords argyle baldric corral deliriumthe Java Virtual Machine star ts up by seeking and loading your CountWords class, checking that it has an appropriate main method, and invoking that main method with an array of four strings ("argyle", "baldric", "corral", and "delirium") as its sole argument. In this example case, the main method merely prints out the number of strings in the argument String array. Most classes are never meant to provide the starting point for an application, but it is often useful to include a main method in them anyway. You can use main as a convenient way to test your class repeatedly as you develop it. When you later integrate your class into an application containing other classes, these extra main methods are automatically ignored, except for the single class you use as your application's starting point. MainExample.html, SimpleTimer.html See also: Q1.2, Q1.3 [TOC] [next] Q3.2 What are bytecodes? Java bytecodes are a language of machine instructions understood by the Java Virtual Machine and usually generated (compiled) from Java language source code.

Java bytecodes encode instructions for the Java Virtual Machine. These instructions specify both operations and operands, always in the following format: opcode (1 byte): specifies what operation to perform operands (0-n bytes): specify data for the operation The 1-byte opcode is simply a number that the Java Virtual Machine interprets as a specific instruction. For instance, opcode value 104 (0x68 in hexadecimal representation) is the instruction to multiply two int values-it instructs the virtual machine to take the top two values off the Java operand stack, multiply them, and push the product back on the stack. In addition to its numerical value, each opcode has a conventional short name, called its mnemonic. The mnemonic for opcode 104 is imul. Following each opcode come any operands the opcode may require. The Java Virtual Machine uses the opcode to determine just how many following bytes are operands for that opcode. In some cases, such as the imul instruction, the opcode's single byte represents the entire instruction-no operands are needed. In other cases, the opcode may require one or more operands. For example, the fload instruction (opcode value 23, or 0x17 in hexadecimal) loads a float value from a local variable, and it uses an index operand to specify which local variable to load from. If the local variable of interest is at index 5, the complete instruction would have the following two bytes: 23 5 [fload from local variable at index 5] There are different appr oaches for learning more about Java Virtual Machine instructions. If you want the comprehensive, detailed picture, read The Java Virtual Machine Specification (Tim Lindholm and Frank Yellin, 1996, Addison Wesley). It covers each virtual machine instruction-its name (mnemonic), what it does, what operands it takes, how it interacts with the operand stack, and more. It's not light reading, but it's a wonderful resource when you need it. You can also learn by experimentation, using javap, as described in Q3.3. See also: Q3.3 [previous] [TOC] [next] Q3.3 What is javap? The javap program is a class file disassembler that comes with the JDK (1.0.2 and 1.1). The JDK (1.0.2 and 1.1) provides a Java class file disassembler, the javap program, which can translate from binary opcodes and operands to a human-readable format with opcode mnemonics, decimal numbers, and so on. javap is a simple, useful tool for exploring compiled class files and for learning about the Java Virtual Machine instruction set. The rest of this answer uses javap to explore the bytecodes generated from the following Java source file: public class BytecodeExample { public float multiply(byte a, short b, int c, float d) { return a * b * c * d; } } After you compile this source file to a class file, run the javap

program on the resulting class (use the -c option to see the virtual machine instructions): javap -c ByteCodeExample(Note that you provide just the class name, not the full name of the file containing the class.) The output from this command on the JDK 1.1 includes the virtual machine instructions for the multiply method: Method float multiply(byte,short,int,float) 0 iload_1 1 iload_2 2 imul 3 iload_3 4 imul 5 i2f 6 fload 4 8 fmul 9 freturn Following are the same instructions, explained one by one; in each case the stack referred to is the Java operand stack. iload_1load int value of first method argument onto stack iload_2load int value of second method argument onto stack imultake two int values from top of stack, multiply them, place product (int value) on stack iload_3load int value of third method argument onto stack imultake two int values from top of stack, multiply them, place product (int value) on stack i2fconvert int value on top of stack to float value fload 4load float value of fourth method argument onto stack fmultake two float values from top of stack, multiply them, place product (float value) on stack freturntake float value from top of stack, return it as value from this method To appreciate the convenience provided by the javap program, consider the same 10 bytes of the multiply method in plain numerical (decimal) form: 27 28 104 29 104 134 23 4 106 174See also: Q3.2 [previous] [TOC] [next] Q3.4 What does it mean to say that Java is interpreted? Several implementations of the Java Virtual Machine, including the JDK (1.0.2 and 1.1), interpret compiled Java code (virtual machine instructions)-for each instruction, the virtual machine carries out the specified behavior before reading the next instruction. Java technology uses both compilation and interpretation. Compilation is the process of translating content (such as code) from one language to another, and storing the results of that translation for later use. Many well-known programming languages, such as C, Pascal, and Fortran, are usually compiled straight from source code to native machine code. In contrast, the Java programming language is compiled into Java class files, which contain architecture-independent instructions for the Java Virtual Machine (see Q3.2 and The Java Virtual Machine Specification, Ch. 4). Interpretation also involves translating code from one language to another, except you directly execute the translation instead of storing it. Languages (or language families) such as Lisp and Basic are typically interpreted straight from source code to execution. In many Java implementations, interpretation picks up where compilation left off. Java

Virtual Machine instructions, which were compiled from source code, are interpreted by the virtual machine-converted on the fly into native machine code, which is then executed rather than stored. Interpreting virtual machine instructions is common on existing implementations of the Java Virtual Machine (such as the JDK 1.0.2 and 1.1), but is not required by either The Java Language Specification or The Java Virtual Machine Specification. A virtual machine implementation may also use just-in-time (JIT) compilation: translating virtual machine instructions into native machine code at run time on the local platform, and then executing from that stored machine code. (It is even possible to have hardware that directly implements the Java Virtual Machine instruction set; such machines would then run compiled Java code natively.) Interpreted code is generally more flexible and adaptive than compiled code, but you usually pay a considerable price in execution speed because of the extra translation work performed as the program executes. This point is especially clear when you consider code with loops. The example below shows Java source code for a simple loop to sum integers from 1 to 1000: int sum = 0; for (int i = 1; i
View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF