CORE-JAVA

download CORE-JAVA

If you can't read please download the document

description

core java

Transcript of CORE-JAVA

CORE JAVA 1. What is the difference between an Abstract class and Interface? Abstract Class is a class which must have at least one abstract method. Interface is a class which is having all abstract methods. By default interface methods are public abstract. Q2.What are checked and unchecked exceptions? Java defines two kinds of exceptio ns : Checked exceptions : Exceptions that inherit from the Exception class are c hecked exceptions. Client code has to handle the checked exceptions thrown By th e API, either in a catch clause or by forwarding it outward with the throws clau se. Examples - SQLException, IOxception. Unchecked exceptions : RuntimeException also extends from Exception. However, all of the exceptions that inherit from R untimeException get special treatment. There is no requirement for the client co de to deal with them, and hence they are called unchecked exceptions. Example Un checked exceptions are NullPointerException, OutOfMemoryError, DivideByZeroExcep tion typically, programming errors. Q3.What is a user defined exception? User-de fined exceptions may be implemented by defining a class to respond to the except ion and embedding a throw statement in the try block where the exception can o c cur or declaring that the method throws the exception (to another method where i t is handled). The developer can define a new exception by deriving it from the Exception class as follows: public class MyException extends Exception { /* clas s definition of constructors (but NOT the exception handling code) goes here pub lic MyException() { super(); } public MyException( String errorMessage ) { super ( errorMessage ); } } The throw statement is used to signal the occurance of the exception within a try block. Often,

exceptions are instantiated in the same statement in which they are thrown using the syntax. throw new MyException("I threw my own exception.") To handle the ex ception within the method where it is thrown, a catch statement that handles MyE xception, must follow the try block. If the developer does not want to handle th e exception in the method itself, the method must pass the exception using the s yntax: public myMethodName() throws MyException Q4.What is the difference betwee n C++ & Java? Well as Bjarne Stroustrup says "..despite the syntactic similariti es, C++ and Java are very different languages. In many ways, Java seems closer t o Smalltalk than to C++..". Here are few I discovered: Java is multithreaded Jav a has no pointers Java has automatic memory management (garbage collection) Java is platform independent (Stroustrup may differ by saying "Java is a platform" J ava has built-in support for comment documentation Java has no operator overload ing Java doesnt provide multiple inheritance There are no destructors in Java Q5. What are statements in JAVA ? Statements are equivalent to sentences in natural languages. A statement forms a complete unit of execution. The following types o f expressions can be made into a statement by terminating the expression with a semicolon Assignment expressions Any use of ++ or - Method calls Object creation expressions These kinds of statements are called expression statements. In addit ion to these kinds of expression statements, there are two other kinds of statem ents. A declaration statement declares a variable. A control flow statement regu lates the order in which statements get executed. The for loop and the if statem ent are both examples of control flow statements. Q6.What is JAR file? JavaARchi ve files are a big glob of Java classes, images, audio, etc., compressed to make one simple, smaller file to ease Applet downloading. Normally when a browser en counters an applet, it goes and downloads all the files, images, audio, used by the Applet separately. This can lead to slower downloads. Q7.What is JNI? JNI is an acronym of Java Native Interface. Using JNI we can call functions which are written in other languages from Java. Following are its advantages and disadvant ages. Advantages:

You want to use your existing library which was previously written in other lang uage. You want to call Windows API function. For the sake of execution speed. Yo u want to call API function of some server product which is in c or c++ from jav a client. Disadvantages: You cant say write once run anywhere. Difficult to debug runtime error in native code. Potential security risk. You cant call it from App let. Q8.What is serialization? Quite simply, object serialization provides a pro gram the ability to read or write a whole object to and from a raw byte stream. It allows Java objects and primitives to be encoded into a byte stream suitable for streaming to some type of network or to a file-system, or more generally, to a transmission medium or storage facility. A seralizable object must implement the Serilizable interface. We use ObjectOutputStream to write this object to a s tream and ObjectInputStream to read it from the stream. Q9.Why there are some nu ll interface in java ? What does it mean ? Give me some null interfaces in JAVA? Null interfaces act as markers..they just tell the compiler that the objects of this class need to be treated differently..some marker interfaces are : Seriali zable, Remote, Cloneable Q10. Is synchronised a modifier?indentifier??what is it ?? Its a modifier. Synchronized methods are methods that are used to control ac cess to an object. A thread only executes a synchronized method after it has acq uired the lock for the methods object or class. Synchronized statements are sim ilar to synchronized methods. A synchronized statement can only be executed afte r a thread has acquired the lock for the object or class referenced in the synch ronized statement. Q11.What is singleton class?where is it used? Singleton is a design pattern meant to provide one and only one instance of an object. Other ob jects can get a reference to this instance through a static method (class constr uctor is kept private). Why do we need one? Sometimes it is necessary, and often sufficient, to create a single instance of a given class. This has advantages i n memory management, and for Java, in garbage collection. Moreover, restricting the number of instances may be necessary or desirable for technological or busin ess reasons--for example, we may only want a single instance of a pool of databa se connections. Q12.What is a compilation unit? The smallest unit of source code that can be compiled, i.e. a .java file.

Q13.Is string a wrapper class? String is a class, but not a wrapper class. Wrapp er classes like (Integer) exist for each primitive type. They can be used to con vert a primitive data value into an object, and viceversa. Q14.Why java does not have multiple inheritance? The Java design team strove to make Java: Simple, ob ject oriented, and familiar Robust and secure Architecture neutral and portable High performance Interpreted, threaded, and dynamic The reasons for omitting mul tiple inheritance from the Java language mostly stem from the "simple, object or iented, and familiar" goal. As a simple language, Javas creators wanted a langu age that most developers could grasp without extensive training. To that end, th ey worked to make the language as similar to C++ as possible (familiar) without carrying over C++s unnecessary complexity (simple). In the designers opinion, multiple inheritance causes more problems and confusion than it solves. So they cut multiple inheritance from the language (just as they cut operator overloadin g). The designers extensive C++ experience taught them that multiple inheritanc e just wasnt worth the headache. Q15.Why java is not a 100% oops? Many people s ay this because Java uses primitive types such as int, char, double. But then al l the rest are objects. Confusing question. Q16.What is a resource bundle? In it s simplest form, a resource bundle is represented by a text file containing keys and a text value for each key. Q17.What is transient variable? Transient variab le cant be serialize. For example if a variable is declared as transient in a S erializable class and the class is written to an ObjectStream, the value of the variable cant be written to the stream instead when the class is retrieved from the ObjectStream the value of the variable becomes null. Q18.What is Collection API? The Collection API is a set of classes and interfaces that support operati on on collections of objects. These classes and interfaces are more flexible, mo re powerful, and more regular than the vectors, arrays, and hashtables if effect ively replaces. Example of classes: HashSet, HashMap, ArrayList, LinkedList, Tre eSet and TreeMap. Example of interfaces: Collection, Set, List and Map. Q19.Is I terator a Class or Interface? What is its use? Iterator is an interface which is used to step through the elements of a Collection.

Q20.What is similarities/difference between an Abstract class and Interface? Dif ferences are as follows: Interfaces provide a form of multiple inheritance. A cl ass can extend only one other class. Interfaces are limited to public methods an d constants with no implement ation. Abstract classes can have a partial impleme ntation, protected parts, static methods, etc. A Class may implement several int erfaces. But in case of abstract class, a class may extend only one abstract cla ss. Interfaces are slow as it requires extra indirection to to find correspondin g method in in the actual class. Abstract classes are fast. Similarities: Neithe r Abstract classes or Interface can be instantiated. Q21.What is a transient var iable? A transient variable is a variable that may not be serialized. Q22.Which containers use a border Layout as their default layout? The window, Frame and Di alog classes use a border layout as their default layout. Q23.Why do threads blo ck on I/O? Threads block on i/o (that is enters the waiting state) so that other threads may execute while the i/o Operation is performed. Q24.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() metho d of each of its observers to notify the observers that it has changed state. Th e Observer interface is implemented by objects that observe Observable objects. Q25.What is synchronization and why is it important? With respect to multithread ing, 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 updati ng that objects value. This often leads to significant errors. Q26. Can a lock be acquired on a class? Yes, a lock can be acquired on a class. This lock is acq uired on the classs Class object. Q27. Whats new with the stop(), suspend() an d resume() methods in JDK 1.2? The stop(), suspend() and resume() methods have b een deprecated in JDK 1.2. Q28. Is null a keyword? The null value is not a keywo rd.

Q29. What is the preferred size of a component? The preferred size of a componen t is the minimum component size that will allow the component to display normall y. Q30. What method is used to specify a containers layout? The setLayout() met hod is used to specify a containers layout. Q31. Which containers use a FlowLay out as their default layout? The Panel and Applet classes use the FlowLayout as their default layout. Q32. What state does a thread enter when it terminates its processing? When a thread terminates its processing, it enters the dead state. Q33. What is the Collections API? The Collections API is a set of classes and in terfaces that support operations on collections of objects. Q34. Which character s may be used as the second character of an identifier, but not as the first cha racter of an identifier? The digits 0 through 9 may not be used as the first cha racter of an identifier but they may be used after the first character of an ide ntifier. Q35. What is the List interface? The List interface provides support fo r ordered collections of objects. Q36. How does Java handle integer overflows an d underflows? It uses those low order bytes of the result that can fit into the size of the type allowed by the operation. Q37. What is the Vector class? The Ve ctor class provides the capability to implement a growable array of objects Q38. What modifiers may be used with an inner class that is a member of an outer cla ss? A (non-local) inner class may be declared as public, protected, private, sta tic, final, or abstract. Q39. What is an Iterator interface? The Iterator interf ace is used to step through the elements of a Collection. Q40. What is the diffe rence between the >> and >>> operators? The >> operator carries the sign bit whe n shifting right. The >>> zero-fills bits that have been shifted out.

Q41. Which method of the Component class is used to set the position and size of a component? setBounds() Q42. How many bits are used to represent Unicode, ASCI I, UTF-16, and UTF-8 characters? Unicode requires 16 bits and ASCII require 7 bi ts. 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 bit patterns. UTF-16 uses 16-bit and larger bit patterns. Q43. What is the difference between yieldi ng and sleeping? When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state. Q44. Which java.util classes and interfaces support event handling? The EventOb ject class and the EventListener interface support event processing. Q45. Is siz eof a keyword? The sizeof operator is not a keyword. Q46. What are wrapped class es? Wrapped classes are classes that allow primitive types to be accessed as obj ects. Q47. 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 is also possible for programs to create objects that are not subject to garbage collection Q48. What restrictions are placed on the l ocation of a package statement within a source code file? A package statement mu st appear as the first line in a source code file (excluding blank lines and com ments). Q49. Can an objects finalize() method be invoked while it is reachable? An objects finalize() method cannot be invoked by the garbage collector while the object is still reachable. However, an objects finalize() method may be inv oked by other objects. Q50. What is the immediate superclass of the Applet class ? Panel Q51. What is the difference between preemptive scheduling and time slici ng? Under preemptive scheduling, the highest priority task executes until it ent ers the waiting or dead states or a higher priority task comes into existence. U nder time slicing, a task executes for a predefined slice of time and then reent ers the pool of ready tasks. The scheduler then determines which task should exe cute next, based on priority and other factors.

Q52 Name three Component subclasses that support painting. The Canvas, Frame, Pa nel, and Applet classes support painting. Q53. 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. Q54. What is the immediate superclass of the D ialog class? Window Q55. What is clipping? Clipping is the process of confining paint operations to a limited area or shape. Q56. What is a native method? A nat ive method is a method that is implemented in a language other than Java. Q57. C an a for statement loop indefinitely? Yes, a for statement can loop indefinitely . For example, consider the following: for(;;) ; Q58. What are order of preceden ce and associativity, and how are they used? Order of precedence determines the order in which operators are evaluated in expressions. Associatity determines wh ether an expression is evaluated left-to-right or right-to-left Q59. When a thre ad blocks on I/O, what state does it enter? A thread enters the waiting state wh en it blocks on I/O. Q60. To what value is a variable of the String type automat ically initialized? The default value of an String type is null Q61. What is the catch or declare rule for method declarations? If a checked exception may be th rown within the body of a method, the method must either catch the exception or declare it in its throws clause. Q62. What is the difference between a MenuItem and a CheckboxMenuItem? The CheckboxMenuItem class extends the MenuItem class to support a menu item that may be checked or unchecked. Q63. What is a tasks pri ority and how is it used in scheduling? A tasks priority is an integer value th at identifies the relative order in which it should be executed with respect to other tasks. The scheduler attempts to schedule higher priority tasks before low er priority tasks. Q64. What class is the top of the AWT event hierarchy? The ja va.awt.AWTEvent class is the highest-level class in the AWT event-class hierarch y.

Q65. When a thread is created and started, what is its initial state? A thread i s in the ready state after it has been created and started. Q66. Can an anonymou s class be declared as implementing an interface and extending a class? An anony mous class may implement an interface or extend a superclass, but may not be dec lared to do both. Q67. What is the range of the short type? The range of the sho rt type is -(2^15) to 2^15 - 1. Q68. What is the range of the char type? The ran ge of the char type is 0 to 2^16 - 1. Q69. In which package are most of the AWT events that support the event-delegation 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. Q70. What is the immediat e superclass of Menu? MenuItem Q71. What is the purpose of finalization? The pur pose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected. Q72. Which class is the immediate superclass of the MenuComponent class. Object Q73. What invoke s a threads run() method? After a thread is started, via its start() method or that of the Thread class, the JVM invokes the threads run() method when the thr ead is initially executed. Q74. What is the difference between the Boolean & ope rator and the && operator? If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the op erand. When an expression involving the && operator is evaluated, the first oper and is evaluated. If the first operand returns a value of true then the second o perand is evaluated. The && operator is then applied to the first and second ope rands. If the first operand evaluates to false, the evaluation of the second ope rand is skipped. Q75. Name three subclasses of the Component class. Box.Filler, Button, Canvas, Checkbox, Choice, Container, Label, List, Scrollbar, or TextComp onent

Q76. What is the GregorianCalendar class? The GregorianCalendar provides support for traditional Western calendars. Q77. Which Container method is used to cause a container to be laid out and redisplayed? validate() Q78. What is the purpose of the Runtime class? The purpose of the Runtime class is to provide access to the Java runtime system. Q79. How many times may an objects finalize() method b e invoked by the garbage collector? An objects finalize() method may only be in voked once by the garbage collector. Q80. What is the purpose of the finally cla use of a try-catchfinally statement? The finally clause is used to provide the c apability to execute code no matter whether or not an exception is thrown or cau ght. Q81. What is the argument type of a programs main() method? A programs ma in() method takes an argument of the String[] type. Q82. Which Java operator is right associative? The = operator is right associative. Q83. What is the Locale class? The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region. Q84. Can a double value b e cast to a byte? Yes, a double value can be cast to a byte. Q85. What is the di fference between a break statement and a continue statement? A break statement r esults in the termination of the statement to which it applies (switch, for, do, or while). A continue statement is used to end the current loop iteration and r eturn control to the loop statement. Q86. What must a class do to implement an i nterface? It must provide all of the methods in the interface and identify the i nterface in its implements clause. Q87. What method is invoked to cause an objec t to begin executing as a separate thread? The start() method of the Thread clas s is invoked to cause an object to begin executing as a separate thread. Q88. Na me two subclasses of the TextComponent class. TextField and TextArea

Q89. What is the advantage of the event-delegation model over the earlier eventi nheritance model? The event-delegation model has two advantages over the event-i nheritance model. First, it enables event handling to be handled by objects othe r than the ones that generate the events (or their containers). This allows a cl ean separation between a components design and its use. The other advantage of the event-delegation model is that it performs much better in applications where many events are generated. 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. Q90. Which containers may have a MenuBar? Frame Q91. How are commas used in the intialization and iteration par ts of a for statement? Commas are used to separate multiple statements within th e initialization and iteration parts of a for statement. Q92. What is the purpos e of the wait(), notify(), and notifyAll() methods? The wait(),notify(), and not ifyAll() methods are used to provide an efficient way for threads to wait for a shared resource. When a thread executes an objects wait() method, it enters the waiting state. It only enters the ready state after another thread invokes the objects notify() or notifyAll() methods.. Q93. What is an abstract method? An a bstract method is a method whose implementation is deferred to a subclass. Q94. How are Java source code files named? A Java source code file takes the name of a public class or interface that is defined within the file. A source code file may contain at most one public class or interface. If a public class or interfac e is defined within a source code file, then the source code file must take the name of the public class or interface. If no public class or interface is define d 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. Q95 . What is the relationship between the Canvas class and the Graphics class? A Ca nvas object provides access to a Graphics object via its paint() method. Q96. Wh at are the high-level thread states? The high-level thread states are ready, run ning, waiting, and dead. Q97. 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.

Q98. Can a Byte object be cast to a double value? No, an object cannot be cast t o a primitive value. Q99. What is the difference between a static and a nonstati c inner class? A non-static inner class may have object instances that are assoc iated with instances of the classs outer class. A static inner class does not h ave any object instances. Q100. What is the difference between the String and St ringBuffer classes? String objects are constants. StringBuffer objects are not. Q101. 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 . Q102. What is an objects lock and which objects have locks? An objects lock is a mechanism that is used by multiple threads to obtain synchronized access t o the object. A thread may execute a synchronized method of an object only after it has acquired the objects lock. All objects and classes have locks. A class s lock is acquired on the classs Class object. Q103. What is the Dictionary cla ss? The Dictionary class provides the capability to store key-value pairs. Q104. How are the elements of a BorderLayout organized? The elements of a BorderLayou t are organized at the borders (North, South, East, and West) and the center of a container. Q105. What is the % operator? It is referred to as the modulo or re mainder operator. It returns the remainder of dividing the first operand by the second operand. Q106. When can an object reference be cast to an interface refer ence? An object reference be cast to an interface reference when the object impl ements the referenced interface. Q107. What is the difference between a Window a nd a Frame? The Frame class extends Window to define a main application window t hat can have a menu bar. Q108. Which class is extended by all other classes? The Object class is extended by all other classes. Q109. Can an object be garbage c ollected while it is still reachable? A reachable object cannot be garbage colle cted. Only unreachable objects may be garbage collected..

Q110. Is the ternary operator written x : y ? z or x ? y : z ? It is written x ? y : z. Q111. What is the difference between the Font and FontMetrics classes? T he FontMetrics class is used to define implementation-specific properties, such as ascent and descent, of a Font object. Q112. How is rounding performed under i nteger division? The fractional part of the result is truncated. This is known a s rounding toward zero. Q113. What happens when a thread cannot acquire a lock o n an object? If a thread attempts to execute a synchronized method or synchroniz ed statement and is unable to acquire an objects lock, it enters the waiting st ate until the lock becomes available. Q114. What is the difference between the R eader/Writer class hierarchy and the InputStream/OutputStream class hierarchy? T he Reader/Writer class hierarchy is character-oriented, and the InputStream/ Out putStream class hierarchy is byte-oriented. Q115. 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 type. This includes the Error and Exception types. Q1 16. 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 access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package. Q117. What is the Simpl eTimeZone class? The SimpleTimeZone class provides support for a Gregorian calen dar. Q118. What is the Map interface? The Map interface replaces the JDK 1.1 Dic tionary class and is used associate keys with values. Q119. Does a class inherit the constructors of its superclass? A class does not inherit constructors from any of its superclasses. Q120. 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 sta tements that can enclose a break or continue statement. Q121. What is the purpos e of the System class? The purpose of the System class is to provide access to s ystem resources.

Q122. Which TextComponent method is used to set a TextComponent to the read-only state? setEditable() Q123. How are the elements of a CardLayout organized? The elements of a CardLayout are stacked, one on top of the other, like a deck of ca rds. Q124. Is &&= a valid Java operator? No, it is not. Q125. Name the eight pri mitive Java types? The eight primitive types are byte, char, short, int, long, f loat, double, and boolean. Q126. Which class should you use to obtain design inf ormation about an object? The Class class is used to obtain information about an objects design. Q127. What is the relationship between clipping and repainting ? When a window is repainted by the AWT painting thread, it sets the clipping re gions to the area of the window that requires repainting. Q128. Is "abc" a primi tive value? The String literal "abc" is not a primitive value. It is a String ob ject. Q129. What is the relationship between an event-listener interface and an event-adapter class? An event-listener interface defines the methods that must b e implemented by an event handler for a particular kind of event. An event adapt er provides a default implementation of an eventlistener interface. Q130. What r estrictions are placed on the values of each case of a switch statement? During compilation, the values of each case of a switch statement must evaluate to a va lue that can be promoted to an int value. Q131. What modifiers may be used with an interface declaration? An interface may be declared as public or abstract. Q1 32. Is a class a subclass of itself? A class is a subclass of itself. Q133. What is the highest-level event class of the eventdelegation model? The java.util.Ev entObject class is the highest-level class in the event-delegation class hierarc hy. Q134. What event results from the clicking of a button? The ActionEvent even t is generated as the result of the clicking of a button.

Q135. How can a GUI component handle its own events? A component can handle its own events by implementing the required event-listener interface and adding itse lf as its own event listener. Q136. What is the difference between a while state ment 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 e nd of a loop to see whether the next iteration of a loop should occur. The do st atement will always execute the body of a loop at least once. Q137. How are the elements of a GridBagLayout organized? The elements of a GridBagLayout are organ ized according to a grid. However, the elements are of different sizes and may o ccupy more than one row or column of the grid. In addition, the rows and columns may have different sizes. Q138. What advantage do Javas layout managers provid e over traditional windowing systems? Java uses layout managers to lay out compo nents in a consistent manner across all windowing platforms. Since Javas layout managers arent tied to absolute sizing and positioning, they are able to accom odate platform-specific differences among windowing systems. Q139. What is the C ollection interface? The Collection interface provides support for the implement ation of a mathematical bag an unordered collection of objects that may contain duplicates. Q140. What modifiers can be used with a local inner class? A local i nner class may be final or abstract. Q141. What is the difference between static and non-staticvariables? A static variable is associated with the class as a wh ole rather than with specific instances of a class. Non-static variables take on unique values with each object instance. Q142. What is the difference between t he paint() and repaint() methods? The paint() method supports painting via a Gra phics object. The repaint() method is used to cause paint() to be invoked by the AWT painting thread. Q143. What is the purpose of the File class? The File clas s is used to create objects that provide access to the files and directories of a local file system. Q144. Can an exception be rethrown? Yes, an exception can b e rethrown. Q145. Which Math method is used to calculate the absolute value of a number? The abs() method is used to calculate absolute values.

Q146. How does multithreading take place on a computer with a single CPU? The op erating systems task scheduler allocates execution time to multiple tasks. By q uickly switching between executing tasks, it creates the impression that tasks e xecute sequentially. Q147. When does the compiler supply a default constructor f or a class? The compiler supplies a default constructor for a class if no other constructors are provided. Q148. When is the finally clause of a try-catch-final ly 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. Q149. Which class is the immediate superclass of the Container class? Component Q150. If a method is declared as pr otected, where may the method be accessed? A protected method may only be access ed by classes or interfaces of the same package or by subclasses of the class in which it is declared. Q151. How can the Checkbox class be used to create a radi o button? By associating Checkbox objects with a CheckboxGroup. Q152. Which nonUnicode letter characters may be used as the first character of an identifier? T he non-Unicode letter characters $ and _ may appear as the first character of an identifier Q153. What restrictions are placed on method overloading? Two method s may not have the same name and argument list but different return types. Q154. What happens when you invoke a threads interrupt method while it is sleeping o r waiting? When a tasks interrupt() method is executed, the task enters the rea dy state. The next time the task enters the running state, an InterruptedExcepti on is thrown. Q155. What is casting? There are two types of casting, casting bet ween primitive numeric types and casting between object references. Casting betw een numeric types is used to convert larger values, such as double values, to sm aller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference. Q1 56. What is the return type of a programs main() method? A programs main() met hod has a void return type.

Q157. Name four Container classes. Window, Frame, Dialog, FileDialog, Panel, App let, or ScrollPane Q158. What is the difference between a Choice and a List? A C hoice is displayed in a compact form that requires you to pull it down to see th e 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 supp orts the selection of one or more List items. Q159. What class of exceptions are generated by the Java run-time system? The Java runtime system generates Runtim eException and Error exceptions. Q160. What class allows you to read objects dir ectly from a stream? The ObjectInputStream class supports the reading of objects from input streams. Q161. 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. Q162 . Under what conditions is an objects finalize() method invoked by the garbage collector? The garbage collector invokes an objects finalize() method when it d etects that the object has become unreachable. Q163. How are this() and super() used with constructors? this() is used to invoke a constructor of the same class . super() is used to invoke a superclass constructor. Q164. What is the relation ship between a methods throws clause and the exceptions that can be thrown duri ng the methods execution? A methods throws clause must declare any checked exc eptions that are not caught within the body of the method. Q165. What is the dif ference between the JDK 1.02 event model and the event-delegation model introduc ed 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, the event is inherited by (or bubbled up to) the components 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 e vent handlers for GUI components. These objects implement event-listener interfa ces. The event-delegation model is more efficient than the event-inheritance mod el because it eliminates the processing required to support the bubbling of unha ndled events.

Q166. 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 i f they are the same object in memory. It is possible for two String objects to h ave the same value, but located indifferent areas of memory. Q167. Why are the m ethods of the Math class static? So they can be invoked as if they are a mathema tical code library. Q168. What Checkbox method allows you to tell if a Checkbox is checked? getState() Q169. What state is a thread in when it is executing? An executing thread is in the running state. Q170. What are the legal operands of t he instanceof operator? The left operand is an object reference or null value an d the right operand is a class, interface, or array type. Q171. How are the elem ents of a GridLayout organized? The elements of a GridBad layout are of equal si ze and are laid out using the squares of a grid. Q172. What an I/O filter? An I/ O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another. Q173. 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 aga in. Q174. What is the Set interface? The Set interface provides methods for acce ssing the elements of a finite mathematical set. Sets do not allow duplicate ele ments. Q175. What classes of exceptions may be thrown by a throw statement? A th row statement may throw any expression that may be assigned to the Throwable typ e. Q176. What are E and PI? E is the base of the natural logarithm and PI is mat hematical value pi. Q177. Are true and false keywords? The values true and false are not keywords. Q178. What is a void return type? A void return type indicate s that a method does not return a value.

Q179. What is the purpose of the enableEvents() method? The enableEvents() metho d is used to enable an event for a particular object. Normally, an event is enab led when a listener is added to an object for a particular event. The enableEven ts() method is used by objects that handle events by overriding their eventdispa tch methods. Q180. 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 acce ss data contained in any part of a file. Q181. What happens when you add a doubl e value to a String? The result is a String object. Q182. What is your platform s default character encoding? If you are running Java on English Windows platfor ms, it is probably Cp1252. If you are running Java on English Solaris platforms, it is most likely 8859_1.. Q183. Which package is always imported by default? T he java.lang package is always imported by default. Q184. What interface must an object implement before it can be written to a stream as an object? An object m ust implement the Serializable or Externalizable interface before it can be writ ten to a stream as an object. Q185. How are this and super used? this is used to refer to the current object instance. super is used to refer to the variables a nd methods of the superclass of the current object instance. Q186. What is the p urpose of garbage collection? The purpose of garbage collection is to identify a nd discard objects that are no longer needed by a program so that their resource s may be reclaimed and reused. Q187. What is a compilation unit? A compilation u nit is a Java source code file. Q188. What interface is extended by AWT event li steners? All AWT event listeners extend the java.util.EventListener interface. Q 189. What restrictions are placed on method overriding? Overridden methods must have the same name, argument list, and return type. The overriding method may no t limit the access of the method it overrides. The overriding method may not thr ow any exceptions that may not be thrownby the overridden method.

Q190. How can a dead thread be restarted? A dead thread cannot be restarted. Q19 1. What happens if an exception is not caught? An uncaught exception results in the uncaughtException() method of the threads ThreadGroup being invoked, which eventually results in the termination of the program in which it is thrown. Q192 . What is a layout manager? A layout manager is an object that is used to organi ze components in a container. Q193. Which arithmetic operations can result in th e throwing of an ArithmeticException? Integer / and % can result in the throwing of an ArithmeticException. Q194. What are three ways in which a thread can ente r 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 objects wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method. Q195. Can an abstract class be final? An abstract class may not be declared as final. Q196. What is the Res ourceBundle class? The ResourceBundle class is used to store locale-specific res ources that can be loaded by a program to tailor the programs appearance to the particular locale in which it is being run. Q197. What happens if a try-catch-f inally statement doesnot have a catch clause to handle an exception that is thro wn 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 programs terminati on. Q198. What is numeric promotion? Numeric promotion is the conversion of a sm aller numeric type to a larger numeric type, so that integer and floating-point operations may take place. In numerical promotion, byte, char, and short values are converted to int values. The int values are also converted to long values, i f necessary. The long and float values are converted to double values, as requir ed. Q199. What is the difference between a Scrollbar and a ScrollPane? A Scrollb ar is a Component, but not a Container. A ScrollPane is a Container. A ScrollPan e handles its own events and performs its own scrolling.

Q200. What is the difference between a public and a nonpublic class? A public cl ass may be accessed outside of its package. A non-public class may not be access ed outside of its package. Q201. To what value is a variable of the boolean type automatically initialized? The default value of the boolean type is false. Q202 . Can try statements be nested? Try statements may be tested. Q203. What is the difference between the prefix and postfix forms of the ++ operator? The prefix f orm performs the increment operation and returns the value of the increment oper ation. The postfix form returns the current value all of the expression and then performs the increment operation on that value. Q204. What is the purpose of a statement block? A statement block is used to organize a sequence of statements as a single statement group. Q205. 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 t o create a separate name space for groups of classes and interfaces. Packages ar e also used to organize related classes and interfaces into a single API unit an d to control accessibility to these classes and interfaces. Q206. What modifiers may be used with a top-level class? A top-level class may be public, abstract, or final. Q207. What are the Object and Class classes used for? The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program.. Q20 8. How does a try statement determine which catch clause should be used to handl e an exception? When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they a ppear. The first catch clause that is capable of handling the exception is execu ted. The remaining catch clauses are ignored. Q209. Can an unreachable object be come reachable again? An unreachable object may become reachable again. This can happen when the objects finalize() method is invoked and the object performs a n operation which causes it to become accessible to reachable objects.

Q210. When is an object subject to garbage collection? An object is subject to g arbage collection when it becomes unreachable to the program in which it is used . Q211. 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 Runnab le interface. Q212. What methods are used to get and set the text label displaye d by a Button object? getLabel() and setLabel() Q213. Which Component subclass i s used for drawing and painting? Canvas Q214. What are synchronized methods and synchronized statements? Synchronized methods are methods that are used to contr ol access to an object. A thread only executes a synchronized method after it ha s acquired the lock for the methods object or class. Synchronized statements ar e similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement. Q215. 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 subcla ss of Thread, or it may implement the Runnable interface. Q216. What are the pro blems faced by Java programmers who dont use layout managers? Without layout ma nagers, Java programmers are faced with determining how their GUI will be displa yed across multiple windowing systems and finding a common sizing and positionin g that will work within the constraints imposed by each windowing system. Q217. What is the difference between an if statement and a switch statement? The if st atement is used to select among two alternatives. It uses a boolean expression t o decide which alternative should be executed. The switch statement is used to s elect among multiple alternatives. It uses an int expression to determine which alternative should be executed. Q218. What happens when you add a double value t o a String? The result is a String object. Q219. What is the List interface? The List interface provides support for ordered collections of objects. 1. Why is t he main method static ?

Ans: So that it can be invoked without creating an instance of that class 2. Wha t is the difference between class variable, member variable and automatic(local) variable ? Ans: - class variable is a static variable and does not belong to in stance of class but rather shared across all the instances - member variable bel ongs to a particular instance of class and can be called from any method of the class - automatic or local variable is created on entry to a method and has only method scope 3. When are static and non static variables of the class initializ ed ? Ans: The static variables are initialized when the class is loaded Non stat ic variables are initialized just before the constructor is called 4. When are a utomatic variable initialized ? Ans: Automatic variable have to be initialized e xplicitly 5. What is a modulo operator % ? Ans: This operator gives the value wh ich is related to the remainder of a divisione.g x=7%4 gives remainder 3 as an a nswer 6. How is an argument passed in java, by copy or by reference What is a mo dulo operator % ? Ans: This operator gives the value which is related to the rem ainder of a divisione.g x=7%4 gives remainder 3 as an answer 7. What is garbage collection ? Ans: The runtime system keeps track of the memory that is allocated and is able to determine whether that memory is still useable. This work is usu ally done in background by a low-priority thread that is referred to as garbage collector. When the gc finds memory that is no longer accessible from any live t hread it takes steps to release it back to the heap for reuse 8. Does System.gc and Runtime.gc() guarantee garbage collection ? Ans: No 9. What are different ty pes of operators in Java ? Ans: - Uniary ++, , +, -, |, ~, () - Arithmetic *, /, %,+, -Shift , >>> - Comparison =, instanceof, = =,!=Bitwise &, ^, |Short C ircuit &&, || Ternary ?:Assignment = 10. How does bitwise (~) operator work ? An s: It converts all the 1 bits in a binary value to 0s and all the 0 bits to 1s, e.g 11110000 coverts to 00001111 11. Can shift operators be applied to float typ es ? Ans: No, shift operators can be applied only to integer or long types 12. W hat happens to the bits that fall off after shifting ? Ans: They are discarded 1 3. What values of the bits are shifted in after the shift ? Ans: In case of sign ed left shift >> the new bits are set to zero. But in case of signed

right shift it takes the value of most significant bit before the shift, that is if the most significant bit before shift is 0 it will introduce 0, else if it i s 1, it will introduce 1 14. What are access modifiers ? Ans: These public, prot ected and private, these can be applied to class, variables, constructors and me thods. But if you dont specify an access modifier then it is considered as Friendly 15. Can protected or friendly features be accessed from different packages ? An s: No when features are friendly or protected they can be accessed from all the classes in that package but not from classes in another package 16. How can you access protected features from another package ? Ans: You can access protected f eatures from other classes by subclassing the that class in another package, but this cannot be done for friendly features 17. What are the rules for overriding ? Ans: Private method can be overridden by private, friendly, protected or publ ic methods. Friendly method can be overridden by friendly, protected or public m ethods. Protected method can be overridden by protected or public methods. Publi c method can be overridden by public method 18. Can you change the reference of the final object ? Ans: No the reference cannot be change, but the data in that object can be changed 19. Can abstract modifier be applied to a variable ? Ans: No it is applied only to class and methods 20. Can abstract class be instantiate d ? Ans: No abstract class cannot be instantiated i.e you cannot create a new ob ject of this class 21. When does the compiler insist that the class must be abst ract ? Ans: If one or more methods of the class are abstract. If class inherits one or more abstract methods from the parent abstract class and no implementatio n is provided for that method If class implements an interface and provides no i mplementation for those methods 22. How is abstract class different from final c lass ? Ans: Abstract class must be subclassed and final class cannot be subclass ed 23. Where can static modifiers be used ? Ans: They can be applied to variable s, methods and even a block of code, static methods and variables are not associ ated with any instance of class 24. When are the static variables loaded into th e memory ? Ans: During the class load time 25. When are the non static variables loaded into the memory ? Ans: They are loaded just before the constructor is ca lled 26. How can you reference static variables ? Ans: Via reference to any inst ance of the class Code: Computer comp = new Computer (); comp.harddisk where har disk is a static variable comp.compute() where compute is a method

Via the class name Code: Computer.harddisk Computer.compute() 27. Can static met hod use non static features of there class ? Ans: No they are not allowed to use non static features of the class, they can only call static methods and can use static data 28. What is static initializer code ? Ans: A class can have a block of initializer code that is simply surrounded by curly braces and labeled as st atic e.g. Code: public class Demo{ static int =10; static{ System.out.println(Hello world); } } And this code is executed exactly once at the time of class load 29. W here is native modifier used ? Ans: It can refer only to methods and it indicate s that the body of the method is to be found else where and it is usually writte n in non java language 30. What are transient variables ? Ans: A transient varia ble is not stored as part of objects persistent state and they cannot be final o r static 31. What is synchronized modifier used for ? Ans: It is used to control access of critical code in multithreaded programs 32. What are volatile variabl es ? Ans: It indicates that these variables can be modified asynchronously 33. W hat are the rules for primitive arithmetic promotion conversion ? Ans: For Unary operators : If operant is byte, short or a char it is converted to an int. If i t is any other type it is not converted For binary operands : If one of the oper ands is double, the other operand is converted to double Else If one of the oper ands is float, the other operand is converted to float Else If one of the operan ds is long, the other operand is converted to long Else both the operands are co nverted to int 34. What are the rules for casting primitive types ? Ans: You can cast any non Boolean type to any other non boolean type. You cannot cast a bool ean to any other type; you cannot cast any other type to a boolean 35. What are the rules for object reference assignment and method call conversion ? Ans: An i nterface type can only be converted to an interface type or to object. If the ne w type is an interface, it must be a superinterface of the old type. A class typ e can be converted to a class type or to an interface type. If converting to a

class type the new type should be superclass of the old type. If converting to a n interface type new type the old class must implement the interface. An array m aybe converted to class object, to the interface cloneable, or to an array. Only an array of object references types may be converted to an array, and the old e lement type must be convertible to the new element 36. What are the rules for Ob ject reference casting ? Ans: Casting from Old types to Newtypes Compile time ru les : - When both Oldtypes and Newtypes are classes, one should be subclass of t he other - When both Oldtype ad Newtype are arrays, both arrays must contain ref erence types (not primitive), and it must be legal to cast an element of Oldtype to an element of Newtype - You can always cast between an interface and a non-f inal object Runtime rules : - If Newtype is a class. The class of the expression being converted must be Newtype or must inherit from Newtype - If NewType is an interface, the class of the expression being converted must implement Newtype 3 7. When do you use continue and when do you use break statements ? Ans: When con tinue statement is applied it prematurely completes the iteration of a loop. Whe n break statement is applied it causes the entire loop to be abandoned. 38. What is the base class from which all exceptions are subclasses ? Ans: All exception s are subclasses of a class called java.lang.Throwable 39. How do you intercept and thereby control exceptions ? Ans: We can do this by using try/catch/finally blocks You place the normal processing code in try block You put the code to dea l with exceptions that might arise in try block in catch block Code that must be executed no matter what happens must be place in finally block 40. When do we s ay an exception is handled ? Ans: When an exception is thrown in a try block and is caught by a matching catch block, the exception is considered to have been h andled 41. When do we say an exception is not handled ? Ans: There is no catch b lock that names either the class of exception that has been thrown or a class of exception that is a parent class of the one that has been thrown, then the exce ption is considered to be unhandled, in such condition the execution leaves the method directly as if no try has been executed 42. In what sequence does the fin ally block gets executed ? Ans: If you put finally after a try block without a m atching catch block then it will be executed after the try block If it is placed after the catch block and there is no exception then also it will be executed a fter the try block If there is an exception and it is handled by the catch block then it will be executed after the catch block 43. What can prevent the executi on of the code in finally block ?

Ans: - The death of thread - Use of system.exit() - Turning off the power to CPU - An exception arising in the finally block itself What are the rules for catch ing multiple exceptions - A more specific catch block must precede a more genera l one in the source, else it gives compilation error - Only one catch block, tha t is first applicable one, will be executed 44. What does throws statement decla ration in a method indicate ? Ans: This indicates that the method throws some ex ception and the caller method should take care of handling it 45. What are check ed exception ? Ans: Checked exceptions are exceptions that arise in a correct pr ogram, typically due to user mistakes like entering wrong data or I/O problems 4 6. What are runtime exceptions ? Ans: Runtime exceptions are due to programming bugs like out of bond arrays or null pointer exceptions. 47. What is difference between Exception and errors ? Ans: Errors are usually compile time and exceptio ns can be runtime or checked 48. How will you handle the checked exceptions ? An s: You can provide a try/catch block to handle it. OR Make sure method declarati on includes a throws clause that informs the calling method an exception might b e thrown from this particular method When you extend a class and override a meth od, can this new method throw exceptions other than those that were declared by the original method No it cannot throw, except for the subclasses of those excep tions 49. Is it legal for the extending class which overrides a method which thr ows an exception, not o throw in the overridden class ? Ans: Yes it is perfectly legal 50. Explain modifier final ? Ans: Final can be applied to classes, method s and variables and the features cannot be changed. Final class cannot be subcla ssed, methods cannot be overridden. 1 What is translator? Translator is a progra m that converts any computer program into machine code They are 3 types INTERPRE TER COMPILER ASSEMBLER INTERPRETER It will be converts line by line

2 3 4 COMPILER It will be converts the entire program in a single step. ASSEMBLER It w ill be converts assembly language program into machine code what is object code? Object code is nothing but machine code equlient of source code. what is excute code(x.exe)? exe=obj+headerfile code. Exe file is a full fleged file to run the program. what is first microprocess ? 4004 mp 5 6 7 java se (standard edition)? Java se deals with developing standard all one appli cation, application for a network and also exploring java library. java EE(enter prise edition) java ee deals will developing businee solution for a network/inte rnet. java me(microedition)? Java me deals with developing embedded system and w ireless application COREJAVA 1. What is the most important feature of Java? Java is a platform indep endent language. 2. What do you mean by platform independence? Platform independ ence means that we can write and compile the java code in one platform (eg Windo ws) and can execute the class in any other supported platform eg (Linux,Solaris, etc). 3. What is a JVM? JVM is Java Virtual Machine which is a run time environm ent for the compiled java class files. 4. Are JVMs platform independent?

JVMs are not platform independent. JVMs are platform specific run time impleme ntation provided by the vendor. 5. What is the difference between a JDK and a JV M? JDK is Java Development Kit which is for development purpose and it includes execution environment also. But JVM is purely a run time environment and hence y ou will not be able to compile your source files using a JVM. 6. What is a point er and does Java support pointers? Pointer is a reference handle to a memory loc ation. Improper handling of pointers leads to memory leaks and reliability issue s hence Java doesnt support the usage of pointers. 7. What is the base class of all classes? java.lang.Object 8. Does Java support multiple inheritance? Java d oesnt support multiple inheritance. 9. Is Java a pure object oriented language? Java uses primitive data types and hence is not a pure object oriented language . 10. Are arrays primitive data types? In Java, Arrays are objects. 11. What is difference between Path and Classpath? Path and Classpath are operating system l evel environment variales. Path is used define where the system can find the exe cutables(.exe) files and classpath is used to specify the location .class files. 12. What are local variables? Local varaiables are those which are declared wit hin a block of code like methods. Local variables should be initialised before a ccessing them. 13. What are instance variables? Instance variables are those whi ch are defined at the class level. Instance variables need not be initialized be fore using them as they are automatically initialized to their default values.

14. How to define a constant variable in Java? The variable should be declared a s static and final. So only one copy of the variable exists for all instances of the class and the value cant be changed also. static final int PI = 2.14; is a n example for constant. 15. Should a main() method be compulsorily declared in a ll java classes? No not required. main() method should be defined only if the so urce class is a java application. 16. What is the return type of the main() meth od? Main() method doesnt return anything hence declared void. 17. Why is the ma in() method declared static? main() method is called by the JVM even before the instantiation of the class hence it is declared as static. 18. What is the argue ment of main() method? main() method accepts an array of String object as arguem ent. 19. Can a main() method be overloaded? Yes. You can have any number of main () methods with different method signature and implementation in the class. 20. Can a main() method be declared final? Yes. Any inheriting class will not be abl e to have its own default main() method. 21. Does the order of public and stati c declaration matter in main() method? No. It doesnt matter but void should alw ays come before main(). 22. Can a source file contain more than one class declar ation? Yes a single source file can contain any number of Class declarations but only one of the class can be declared as public. 23. What is a package? Package is a collection of related classes and interfaces. package declaration should b e first statement in a java class.

24. Which package is imported by default? java.lang package is imported by defau lt even without a package declaration. 25. Can a class declared as private be ac cessed outside its package? Not possible. 26. Can a class be declared as protec ted? A class cant be declared as protected. only methods can be declared as pro tected. 27. What is the access scope of a protected method? A protected method c an be accessed by the classes within the same package or by the subclasses of th e class in any package. 28. What is the purpose of declaring a variable as final ? A final variables value cant be changed. final variables should be initializ ed before using them. 29. What is the impact of declaring a method as final? A m ethod declared as final cant be overridden. A sub-class cant have the same met hod signature with a different implementation. 30. I dont want my class to be i nherited by any other class. What should i do? You should declared your class as final. But you cant define your class as final, if it is an abstract class. A class declared as final cant be extended by any other class. 31. Can you give f ew examples of final classes defined in Java API? java.lang.String, java.lang.Ma th are final classes. 32. How is final different from finally and finalize()? fi nal is a modifier which can be applied to a class or a method or a variable. fin al class cant be inherited, final method cant be overridden and final variable cant be changed. finally is an exception handling code section which gets exec uted whether an exception is raised or not by the try block code segment.

finalize() is a method of Object class which will be executed by the JVM just be fore garbage collecting object to give a final chance for resource releasing act ivity. 33. Can a class be declared as static? No a class cannot be defined as st atic. Only a method, a variable or a block of code can be declared as static. 34 . When will you define a method as static? When a method needs to be accessed ev en before the creation of the object of the class then we should declare the met hod as static. 35. What are the restriction imposed on a static method or a stat ic block of code? A static method should not refer to instance variables without creating an instance and cannot use "this" operator to refer the instance. 36. I want to print "Hello" even before main() is executed. How will you acheive tha t? Print the statement inside a static block of code. Static blocks get executed when the class gets loaded into the memory and even before the creation of an o bject. Hence it will be executed before the main() method. And it will be execut ed only once. 37. What is the importance of static variable? static variables ar e class level variables where all objects of the class refer to the same variabl e. If one object changes the value then the change gets reflected in all the obj ects. 38. Can we declare a static variable inside a method? Static varaibles are class level variables and they cant be declared inside a method. If declared, the class will not compile. 39. What is an Abstract Class and what is its purpo se? A Class which doesnt provide complete implementation is defined as an abstr act class. Abstract classes enforce abstraction. 40. Can a abstract class be dec lared final? Not possible. An abstract class without being inherited is of no us e and hence will result in compile time error.

41. What is use of a abstract variable? Variables cant be declared as abstract. only classes and methods can be declared as abstract. 42. Can you create an obj ect of an abstract class? Not possible. Abstract classes cant be instantiated. 43. Can a abstract class be defined without any abstract methods? Yes its possi ble. This is basically to avoid instance creation of the class. 44. Class C impl ements Interface I containing method m1 and m2 declarations. Class C has provide d implementation for method m2. Can i create an object of Class C? No not possib le. Class C should provide implementation for all the methods in the Interface I . Since Class C didnt provide implementation for m1 method, it has to be declar ed as abstract. Abstract classes cant be instantiated. 45. Can a method inside a Interface be declared as final? No not possible. Doing so will result in compi lation error. public and abstract are the only applicable modifiers for method d eclaration in an interface. 46. Can an Interface implement another Interface? In tefaces doesnt provide implementation hence a interface cannot implement anothe r interface. 47. Can an Interface extend another Interface? Yes an Interface can inherit another Interface, for that matter an Interface can extend more than on e Interface. 48. Can a Class extend more than one Class? Not possible. A Class c an extend only one class but can implement any number of Interfaces. 49. Why is an Interface be able to extend more than one Interface but a Class cant extend more than one Class? Basically Java doesnt allow multiple inheritance, so a Cla ss is restricted to extend only one Class. But an Interface is a pure abstractio n model and doesnt have inheritance hierarchy like

classes(do remember that the base class of all classes is Object). So an Interfa ce is allowed to extend more than one Interface. 50. Can an Interface be final? Not possible. Doing so so will result in compilation error. 51. Can a class be d efined inside an Interface? Yes its possible. 52. Can an Interface be defined i nside a class? Yes its possible. 53. What is a Marker Interface? An Interface w hich doesnt have any declaration inside but still enforces a mechanism. 54. Whi ch object oriented Concept is achieved by using overloading and overriding? Poly morphism. 55. Why does Java not support operator overloading? Operator overloadi ng makes the code very difficult to read and maintain. To maintain code simplici ty, Java doesnt support operator overloading. 56. Can we define private and pro tected modifiers for variables in interfaces? No. 57. What is Externalizable? Ex ternalizable is an Interface that extends Serializable Interface. And sends data into Streams in Compressed Format. It has two methods, writeExternal(ObjectOupu t out) and readExternal(ObjectInput in) 58. What modifiers are allowed for metho ds in an Interface? Only public and abstract modifiers are allowed for methods i n interfaces. 59. What is a local, member and a class variable? Variables declar ed within a method are "local" variables.

Variables declared within the class i.e not within any methods are "member" vari ables (global variables). Variables declared within the class i.e not within any methods and are defined as "static" are class variables. 60. What is an abstrac t method? An abstract method is a method whose implementation is deferred to a s ubclass. How to Install Java These instructions are to help you download and install Java on your personal computer. You must install Java before installing Eclipse, and you will need both. Downloading and Installing Java On Windows: Prevent Errors like --> javac is not recognized as an internal or external command 1. Go to h ttp://java.sun.com and download the latest Version of Jave SDK or any Jace SDK a s per your requirement and install on your system. 2. Accept all of the defaults and suggestions, but make sure that the location where Java will be installed i s at the top level of your C: drive. Click on "Finish." You should have a direct ory (folder) named C:\j2sdk1.5.0_04, with subfolders C:\j2sdk1.5.0_04\bin and C: \j2sdk1.5.0_04\lib 4. Modify your system variable called "PATH" (so that program s can find where Java is located). To do this for Windows 2000 or XP, either rig ht-click on the My Computer icon or select "System" on the control panel. When t he window titled "System Properties" appears, choose the tab at the top named "A dvanced." Then, click on "Environment Variables." In the bottom window that show s system variables, select "Path" and then click on "Edit..." Add C:\j2sdk1.5.0_ 04\bin as the first item in the list. Note that all items are separated by a sem icolon, with no spaces around the semicolon. You should end up with a path varia ble that looks something like C:\j2sdk1.5.0_04\bin;C:\WINNT\system32;C:\WINNT;C: \WINNT\system32\Wbem For Windows 98 or ME, open the file AUTOEXEC.BAT in Notepad . You should find a line in this file that begins SET PATH=... Modify this line to add C:\j2sdk1.5.0_04\bin; immediately after the equals sign.

5. Modify or create a system variable called "CLASSPATH," as follows. In the low er "System Variables" pane choose "New..." and type in Variable Name "CLASSPATH" and value (note that it begins with dot semicolon) .;C:\j2sdk1.5.0_04\lib 6. To test Java to see if everything is installed properly, open a command window (a DOS window) and type the command "javac" The result should be information about the Usage of javac and its options. If you get a result that "javac is not rec ognized as an internal or external command, operable program or batch file" then there is a problem and Java will not work correctly. Java is an object-oriented programming language developed by James Gosling and c olleagues at Sun Microsystems in the early 1990s. Unlike conventional languages which are generally designed either to be compiled to native (machine) code, or to be interpreted from source code at runtime, Java is intended to be compiled t o a bytecode, which is then run (generally using JIT compilation) by a Java Virt ual Machine. object-oriented programming: Object-oriented programming (OOP) is a programming paradigm that uses "objects" to design applications and computer pr ograms. It utilizes several techniques from previously established paradigms, in cluding inheritance, modularity, polymorphism, and encapsulation. Today, many po pular programming languages (such as Ada, C++, Delphi, Java, Lisp, SmallTalk, Pe rl, PHP, Python, Ruby, VB.Net, Visual FoxPro, and Visual Prolog) support OOP. Ob ject-oriented programmings roots reach all the way back to the 1960s, when the nascent field of software engineering had begun to discuss the idea of a softwar e crisis. As hardware and software became increasingly complex, how could softwa re quality be maintained? Objectoriented programming addresses this problem by s trongly emphasizing modularity in software. The Simula programming language was the first to introduce the concepts underlying objectoriented programming (objec ts, classes, subclasses, virtual methods, coroutines, garbage collection and dis crete event simulation) as a superset of Algol. Smalltalk was the first programm ing language to be called "object-oriented". Object-oriented programming may be seen as a collection of cooperating objects, as opposed to a traditional view in which a program may be seen as a list of instructions to the computer. In OOP, each object is capable of receiving messages, processing data, and sending messa ges to other objects. Each object can be viewed as an independent little machine with a distinct role

or responsibility. Object-oriented programming came into existence because human consciousness, understanding and logic are highly object-oriented. By way of "o bjectifying" software modules, it is intended to promote greater flexibility and maintainability in programming, and is widely popular in large-scale software e ngineering. By virtue of its strong emphasis on modularity, object oriented code is intended to be simpler to develop and easier to understand later on, lending itself to more direct analysis, coding, and understanding of complex situations and procedures than less modular programming methods. A survey of computing literature, identified a number of "quarks," or fundamenta l concepts, identified in the strong majority of definitions of OOP. They are: C lass A class defines the abstract characteristics of a thing (object), including the things characteristics (its attributes or properties) and the things it ca n do (its behaviors or methods or features). For example, the class Dog would co nsist of traits shared by all dogs, for example breed, fur color, and the abilit y to bark. Classes provide modularity and structure in an objectoriented compute r program. A class should typically be recognizable to a non-programmer familiar with the problem domain, meaning that the characteristics of the class should m ake sense in context. Also, the code for a class should be relatively self-conta ined. Collectively, the properties and methods defined by a class are called mem bers. Object A particular instance of a class. The class of Dog defines all poss ible dogs by listing the characteristics that they can have; the object Lassie i s one particular dog, with particular versions of the characteristics. A Dog has fur; Lassie has brown-and-white fur. In programmer jargon, the object Lassie is an instance of the Dog class. The set of values of the attributes of a particul ar object is called its state. Method An objects abilities. Lassie, being a Dog , has the ability to bark. So bark() is one of Lassies methods. She may have ot her methods as well, for example sit() or eat(). Within the program, using a met hod should only affect one particular object; all Dogs can bark, but you need on e particular dog to do the barking. Message passing "The process by which an obj ect sends data to another object or asks the other object to invoke a method." I nheritance In some cases, a class will have "subclasses," more specialized versi ons of a class. For example, the class Dog might have sub-classes called Collie, Chihuahua, and GoldenRetriever. In this case, Lassie would be an instance of th e Collie subclass. Subclasses inherit attributes and behaviors

from their parent classes, and can introduce their own. Suppose the Dog class de fines a method called bark() and a property called furColor. Each of its sub-cla sses (Collie, Chihuahua, and GoldenRetriever) will inherit these members, meanin g that the programmer only needs to write the code for them once. Each subclass can alter its inherited traits. So, for example, the Collie class might specify that the default furColor for a collie is brown-and-white. The Chihuahua subclas s might specify that the bark() method is high-pitched by default. Subclasses ca n also add new members. The Chihuahua subclass could add a method called tremble (). So an individual chihuahua instance would use a high-pitched bark() from the Chihuahua subclass, which in turn inherited the usual bark() from Dog. The chih uahua object would also have the tremble() method, but Lassie would not, because she is a Collie, not a Chihuahua. In fact, inheritance is an "is-a" relationshi p: Lassie is a Collie. A Collie is a Dog. Thus, Lassie inherits the members of b oth Collies and Dogs. When an object or class inherits its traits from more than one ancestor class, and neither of these ancestors is an ancestor of the other, then its called multiple inheritance. Encapsulation Conceals the exact details of how a particular class works from objects that use its code or send messages to it. So, for example, the Dog class has a bark() method. The code for the bar k() method defines exactly how a bark happens (e.g., by inhale() and then exhale (), at a particular pitch and volume). Timmy, Lassies friend, however, does not need to know exactly how she barks. Encapsulation is achieved by specifying whi ch classes may use the members of an object. The result is that each object expo ses to any class a certain interface those members accessible to that class. The reason for encapsulation is to prevent clients of an interface from depending o n those parts of the implementation that are likely to change in future, thereby allowing those changes to be made more easily, that is, without changes to clie nts. For example, an interface can ensure that puppies can only be added to an o bject of the class Dog by code in that class. Members are often specified as pub lic, protected or private, determining whether they are available to all classes , sub-classes or only the defining class. Some languages go further: Java uses t he protected keyword to restrict access also to classes in the same package, and C++ allows one to specify which classes may access any member. Abstraction Simp lifying complex reality by modeling classes appropriate to the problem, and work ing at the most appropriate level of inheritance for a given aspect of the probl em. For example, Lassie the Dog may be treated as a Dog much of the time, a Coll ie when necessary to access Collie-specific attributes or behaviors, and as an A nimal (perhaps the parent class of Dog) when counting Timmys pets. Polymorphism Polymorphism is the ability of behavior to vary based on the conditions in whic h the behavior is invoked, that is, two or more methods, as well as operators (s uch as +, -, *, among others) can fit to many different conditions. For example, if a Dog is commanded to speak() this may elicit a Bark; if a Pig is commanded to speak() this may elicit an Oink. This is expected because Pig has a particula r implementation inside the speak() method. The same happens to class Dog.

Considering both of them inherit speak() from Animal, this is an example of Over riding Polymorphism. Another good example is about Overloading Polymorphism, a v ery common one considering operators, like "+". Once defined an operator used to add numbers, given a class Number and also given two other classes that inherit s from Number, such as Integer and Double. Any programmer expects to add two ins tances of Double or two instances of Integer in just the same way, and more than this: Any programmer expects the same behavior to any Number. In this case, the programmer must overload the concatenation operator, "+", by making it able to operate with both Double and Integer instances. The way it is done varies a litt le bit from one language to another and must be studied in more details accordin g to the programmer interest. Most of the OOP languages support small difference s in method signatures as polymorphism. its very useful, once it improves code readability, to enable implicit conversions to the correct handling method when apply add() method to integers, like in add(1,2), or to strings like in add("foo ","bar") since the definitions of these signatures are available. In many OOP la nguages, such method signatures would be, respectively, very similar to add(int a, int b) and add(String a, String b). This is an example of Parametric Polymorp hism. The returned type and used modifiers, of course, depend on the programmer interests and intentions. History The concept of objects and instances in comput ing had its first major breakthrough with the PDP-1 system at MIT which was the earliest example of capability based architecture. Another early example was Ske tchpad made by Ivan Sutherland in 1963; however, this was an application and not a programming paradigm. Objects as programming entities were introduced in the 1960s in Simula 67, a programming language designed for making simulations, crea ted by Ole-Johan Dahl and Kristen Nygaard of the Norwegian Computing Center in O slo. Such an approach was a simple extrapolation of concepts earlier used in ana log programming. On analog computers, such direct mapping from real-world phenom ena/objects to analog phenomena/objects (and conversely), was (and is) called s imulation. Simula not only introduced the notion of classes, but also of instan ces of classes, which is probably the first explicit use of those notions. The S malltalk language, which was developed in the 1970s, introduced the term Objecto riented programming to represent the pervasive use of objects and messages as th e basis for computation. Smalltalk creators were influenced by the ideas introdu ced in Simula 67, but Smalltalk was designed to be a fully dynamic system in whi ch classes could be created and modified dynamically rather than simply using st atic ones. The ideas in Simula 67 were also used in many other languages, from d erivatives of Lisp to Pascal. Object-oriented programming developed as the domin ant programming methodology during the mid-1980s, largely due to the influence o f C++. Its dominance was further cemented by the rising popularity of graphical user interfaces, for which object-oriented programming is wellsuited. OOP toolki ts also enhanced the popularity of "event-driven programming". Some feel that as sociation with GUIs (real or perceived) was what propelled OOP into the programm ing

mainstream. OOP also became increasingly popular for developing computer games d uring the 1990s. As the complexity of games grew, as faster hardware became more widely available and compilers matured, more and more games and their engines w ere written in OOP languages. Since almost all video games feature virtual envir onments which contain many, often thousands of objects that interact with each o ther in complex ways, OOP languages are particularly suited for game development . Object-oriented features have been added to many existing languages during tha t time, including Ada, BASIC, Lisp, Fortran, Pascal, and others. Adding these fe atures to languages that were not initially designed for them often led to probl ems with compatibility and maintainability of code. In the past decade Java has emerged in wide use partially because of its similarity to C++, but perhaps more importantly because of its implementation using a virtual machine that is inten ded to run code unchanged on many different platforms. This last feature has mad e it very attractive to larger development shops with heterogeneous environments . Microsofts .NET initiative has a similar objective and includes/supports seve ral new languages, or variants of older ones. Besides Java, probably the most co mmercially important recent object-oriented languages are Visual Basic .NET and C# designed for Microsofts .NET platform. Just as procedural programming led to refinements of techniques such as structured programming, modern object-oriente d software design methods include refinements such as the use of design patterns , design by contract, and modeling languages. OOP in scripting In recent years, object-oriented programming has become especially popular in scripting programmi ng languages. Python and Ruby are scripting languages built on OOP principles, w hile Perl and PHP have been adding object oriented features since Perl 5 and PHP 4. The Document Object Model of HTML, XHTML, and XML documents on the Internet have bindings to the popular JavaScript/ECMAScript language. JavaScript is perha ps the best known prototype-based programming language. Problems and patterns Th ere are a number of programming challenges which a developer encounters regularl y in object-oriented design. There are also widely accepted solutions to these p roblems. The best known are the design patterns codified by Gamma et al, but in a more general sense the term "design patterns" can be used to refer to any gene ral, repeatable solution to a commonly occurring problem in software design. Som e of these commonly occurring problems have

implications and solutions particular to object-oriented development. Gang of Fo ur design patterns Design Patterns: Elements Reusable Object-Oriented Software i s an influential book published in 1995 by Erich Gamma, Richard Helm, Ralph John son and John Vlissides, sometimes casually called the "Gang of Four." Along with exploring the capabilities and pitfalls of object-oriented programming, it desc ribes 23 common programming problems and patterns for solving them. Object-orien tation and databases Both object-oriented programming and relational database ma nagement systems (RDBMSs) are extremely common in software today. Since relation al databases dont store objects directly (though some RDBMSs have object-orient ed features to approximate this), there is a general need to bridge the two worl ds. There are a number of widely used solutions to this problem. One of the most common is object-relational mapping, as found in libraries like Java Data Objec ts, and Ruby on Rails ActiveRecord. There are also object databases which can b e used to replace RDBMSs, but these have not been as commercially successful as RDBMSs. Matching real world OOP can be used to translate from real-world phenome na to program elements (and vice versa). OOP was even invented for the purpose o f physical modelling in the Simula-67 programming language. However, not everyon e agrees that direct real-world mapping is facilitated by OOP, or is even a wort hy goal; Bertrand Meyer argues in Object-Oriented Software Construction that a p rogram is not a model of the world but a model of a model of some part of the wo rld; "Reality is a cousin twice removed". Formal definition There have been seve ral attempts at formalizing the concepts used in object-oriented programming. Th e following concepts and constructs have been used as interpretations of OOP con cepts: coalgebraic datatypes existential quantification and modules recursion re cords and record extensions F-bounded polymorphism Attempts to find a consensus definition or theory behind objects have not proven very successful, and often d iverge widely. For example, some definitions focus on mental activities, and som e on mere program structuring. One of the simpler definitions is that OOP is the act of using "map" data structures or arrays that can contain functions and poi nters to other maps, all with some syntactic and scoping sugar on top. Inheritan ce can be performed by cloning the maps (sometimes called "prototyping").

Java Virtual Machine (JVM), Java Virtual Machine (JVM), originally developed by Sun Microsystems, is a virtual machine that executes Java bytecode. This code is most often generated by Java language compilers, although the JVM has also been targeted by compilers of other languages. The JVM is a crucial component of the Java Platform. The availability of JVMs