core java q's

Embed Size (px)

Citation preview

  • 8/3/2019 core java q's

    1/67

    Q1. What is the difference between an Abstract class and Interface?1. Abstract classes may have some executable methods and methods leftunimplemented. Interfaces contain no implementation code.2. An class can implement any number of interfaces, but subclass at most one abstract class.3. An abstract class can have nonabstract methods. All methods of an interface are

    abstract.4. An abstract class can have instance variables. An interface cannot.5. An abstract class can define constructor. An interface cannot.6. An abstract class can have any visibility: public, protected, private or none(package). An interface's visibility must be public or none (package).7. An abstract class inherits from Object and includes methods such as clone() andequals().

    Q2.What are checked and unchecked exceptions?Java defines two kinds of exceptions : Checked exceptions : Exceptions that inherit from the Exception class are

    checked exceptions. Client code has to handle the checked exceptions thrown bythe API, either in a catch clause or by forwarding it outward with the throws clause.Examples - SQLException, IOxception. Unchecked exceptions : RuntimeException also extends from Exception. However,all of the exceptions that inherit from RuntimeException get special treatment.There is no requirement for the client code to deal with them, and hence they arecalled unchecked exceptions. Example Unchecked exceptions areNullPointerException, OutOfMemoryError, DivideByZeroException typically,programming errors.

    Q3.What is a user defined exception?

    User-defined exceptions may be implemented by defining a class to respond to the exception and embedding a throw statement in the try block where the exception can occur ordeclaring that the method throws the exception (to another method where it ishandled).The developer can define a new exception by deriving it from the Exception class as follows:public class MyException extends Exception {/* class definition of constructors (but NOT the exception handling code) goes here publicMyException() {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 thesyntax.throw new MyException("I threw my own exception.")

  • 8/3/2019 core java q's

    2/67

    To handle the exception within the method where it is thrown, a catch statement that handlesMyException, must follow the try block. If the developer does not want to handle the exceptionin the method itself, the method must pass the exception using the syntax:public myMethodName() throws MyException

    Q4.What is the difference between C++ & Java?Well as Bjarne Stroustrup says "..despite the syntactic similarities, C++ and Java are verydifferent languages. In many ways, Java seems closer to Smalltalk than to C++..". Here are few Idiscovered: Java is multithreaded Java has no pointers Java has automatic memory management (garbage collection) Java is platform independent (Stroustrup may differ by saying "Java is a platform" Java has built-in support for comment documentation Java has no operator overloading 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 completeunit of execution. The following types of expressions can be made into a statement byterminating the expression with a semicolon Assignment expressions Any use of ++ or -- Method calls Object creation expressionsThese kinds of statements are called expression statements. In addition to these kinds of

    expression statements, there are two other kinds of statements. A declaration statementdeclares a variable. A control flow statement regulates the order in which statements getexecuted. The for loop and the if statement are both examples of control flow statements.

    Q6.What is JAR file?JavaARchive files are a big glob of Java classes, images, audio, etc., compressed to makeone simple, smaller file to ease Applet downloading. Normally when a browser encountersan 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 inother languages from Java. Following are its advantages and disadvantages.Advantages: You want to use your existing library which was previously written in otherlanguage. You want to call Windows API function. For the sake of execution speed. You want to call API function of some server product which is in c or c++ from java

  • 8/3/2019 core java q's

    3/67

    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 Applet.

    Q8.What is serialization?Quite simply, object serialization provides a program the ability to read or write a whole objectto and from a raw byte stream. It allows Java objects and primitives to be encoded into a bytestream suitable for streaming to some type of network or to a file-system, or more generally, to atransmission medium or storage facility. A seralizable object must implement the Serilizableinterface. We use ObjectOutputStream to write this object to a stream and ObjectInputStream toread it from the stream.

    Q9.Why there are some null 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 betreated differently..some marker interfaces are : Serializable, Remote, Cloneable

    Q10. Is synchronised a modifier?indentifier??what is it??It's a modifier. Synchronized methods are methods that are used to control access to an object. Athread only executes a synchronized method after it has acquired the lock for the method's objector class. Synchronized statements are similar to synchronized methods. A synchronizedstatement can only be executed after a thread has acquired the lock for the object or classreferenced in the synchronized 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. Otherobjects can get a reference to this instance through a static method (class constructor is keptprivate). Why do we need one? Sometimes it is necessary, and often sufficient, to create a singleinstance of a given class. This has advantages in memory management, and for Java, in garbagecollection. Moreover, restricting the number of instances may be necessary or desirable fortechnological or business reasons--for example, we may only want a single instance of a pool ofdatabase 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. Wrapper classes like (Integer) exist for each primitivetype. They can be used to convert 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, object oriented, and familiar

  • 8/3/2019 core java q's

    4/67

    Robust and secure Architecture neutral and portable High performance Interpreted, threaded, and dynamicThe reasons for omitting multiple inheritance from the Java language mostly stem from the

    "simple, object oriented, and familiar" goal. As a simple language, Java's creators wanted alanguage that most developers could grasp without extensive training. To that end, they workedto make the language as similar to C++ as possible (familiar) without carrying over C++'sunnecessary complexity (simple).In the designers' opinion, multiple inheritance causes more problems and confusion than itsolves. So they cut multiple inheritance from the language (just as they cut operatoroverloading). The designers' extensive C++ experience taught them that multiple inheritance justwasn't worth the headache.

    Q15.Why java is not a 100% oops?Many people say this because Java uses primitive types such as int, char, double. But then all the

    rest are objects. Confusing question.

    Q16.What is a resource bundle?In its simplest form, a resource bundle is represented by a text file containing keys and a textvalue for each key.

    Q17.What is transient variable?Transient variable can't be serialize. For example if a variable is declared as transient in aSerializable class and the class is written to an ObjectStream, the value of the variable can't bewritten to the stream instead when the class is retrieved from the ObjectStream the value of thevariable becomes null.

    Q18.What is Collection API?The Collection API is a set of classes and interfaces that support operation on collections ofobjects. These classes and interfaces are more flexible, more powerful, and more regular than thevectors, arrays, and hashtables if effectively replaces.Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.Example of interfaces: Collection, Set, List and Map.

    Q19.Is Iterator 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 Abstractclass and Interface?

    Differences are as follows: Interfaces provide a form of multiple inheritance. A class can extend only one otherclass. Interfaces are limited to public methods and constants with no implementation.Abstract classes can have a partial implementation, protected parts, static methods,etc. A Class may implement several interfaces. But in case of abstract class, a class may extend

  • 8/3/2019 core java q's

    5/67

    only one abstract class. Interfaces are slow as it requires extra indirection to to find corresponding methodin in the actual class. Abstract classes are fast.Similarities: Neither Abstract classes or Interface can be instantiated.

    Q21.What is a transient variable?A transient variable is a variable that may not be serialized.

    Q22.Which containers use a border Layout as their defaultlayout?The window, Frame and Dialog classes use a border layout as their default layout.

    Q23.Why do threads block on I/O?Threads block on i/o (that is enters the waiting state) so that other threads may execute while thei/o Operation is performed.

    Q24.How are Observer and Observable used?Objects that subclass the Observable class maintain a list of observers. When an Observableobject is updated it invokes the update() method of each of its observers to notify the observersthat it has changed state. The Observer interface is implemented by objects that observeObservable objects.

    Q21.What is a transient variable?A transient variable is a variable that may not be serialized.

    Q22.Which containers use a border Layout as their defaultlayout?The window, Frame and Dialog classes use a border layout as their default layout.

    Q23.Why do threads block on I/O?Threads block on i/o (that is enters the waiting state) so that other threads may execute while thei/o Operation is performed.

    Q24.How are Observer and Observable used?Objects that subclass the Observable class maintain a list of observers. When an Observableobject is updated it invokes the update() method of each of its observers to notify the observersthat it has changed state. The Observer interface is implemented by objects that observeObservable objects.

    Q29. What is the preferred size of a component?The preferred size of a component is the minimum component size that will allow thecomponent to display normally.

    Q30. What method is used to specify a container's layout?The setLayout() method is used to specify a container's layout.

  • 8/3/2019 core java q's

    6/67

    Q31. Which containers use a FlowLayout as their defaultlayout?The Panel and Applet classes use the FlowLayout as their default layout.

    Q32. What state does a thread enter when it terminates itsprocessing?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 interfaces that support operations on collections ofobjects.

    Q34. Which characters may be used as the second character

    of an identifier, but not as the first character of anidentifier?The digits 0 through 9 may not be used as the first character of an identifier but they may be usedafter the first character of an identifier.

    Q35. What is the List interface?

    The List interface provides support for ordered collections of objects.

    Q36. How does Java handle integer overflows andunderflows?It uses those low order bytes of the result that can fit into the size of the type allowed by theoperation.

    Q37. What is the Vector class?The Vector class provides the capability to implement a growable array of objects

    Q38. What modifiers may be used with an inner class that isa member of an outer class?A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.

    Q39. What is an Iterator interface?The Iterator interface is used to step through the elements of a Collection.

    Q40. What is the difference between the >> and >>>operators?The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have beenshifted out.

    Q41. Which method of the Component class is used to setthe position and size of acomponent?setBounds()

    Q42. How many bits are used to represent Unicode, ASCII,UTF-16, and UTF-8characters?Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bitpatterns. UTF-16 uses 16-bit and larger bit patterns.

  • 8/3/2019 core java q's

    7/67

    Q43. What is the difference between yielding and sleeping? When a task invokes its yield() method, it returns to the ready state. When a task invokes itssleep() method, it returns to the waiting state.

    Q44. Which java.util classes and interfaces support eventhandling?

    The EventObject class and the EventListener interface support event processing.

    Q45. Is sizeof a keyword?The sizeof operator is not a keyword.

    Q46. What are wrapped classes?Wrapped classes are classes that allow primitive types to be accessed as objects.

    Q47. Does garbage collection guarantee that a program willnot run out of memory?Garbage collection does not guarantee that a program will not run out of memory. It is possiblefor 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 location of apackage statement within a sourcecode file?A package statement must appear as the first line in a source code file (excluding blank lines andcomments).

    Q49. 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 the object is stillreachable. However, an object's finalize() method may be invoked by other objects.

    Q50. What is the immediate superclass of the Applet class? Panel

    Q51. What is the difference between preemptive schedulingand time slicing?Under preemptive scheduling, the highest priority task executes until it enters the waiting or deadstates or a higher priority task comes into existence. Under time slicing, a task executes for apredefined slice of time and then reenters the pool of ready tasks. The scheduler then determineswhich task should execute next, based on priority and other factors.

    Q52 Name three Component subclasses that supportpainting.The Canvas, Frame, Panel, and Applet classes support painting.

    53. What value does readLine() return when it hasreached 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 Dialog class?Window

  • 8/3/2019 core java q's

    8/67

    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 native method is a method that is implemented in a language other than Java.

    Q57. Can a for statement loop indefinitely?Yes, a for statement can loop indefinitely. For example, consider the following: for(;;) ;

    Q58. What are order of precedence and associativity, andhow are they used?Order of precedence determines the order in which operators are evaluated in expressions.Associatity determines whether an expression is evaluated left-to-right or right-to-left

    Q59. When a thread blocks on I/O, what state does itenter?A thread enters the waiting state when it blocks on I/O.

    Q60. To what value is a variable of the String typeautomatically initialized?The default value of an String type is null.

    Q61. What is the catch or declare rule for methoddeclarations?If a checked exception may be thrown within the body of a method, the method must either catchthe exception or declare it in its throws clause.

    Q62. What is the difference between a MenuItem and aCheckboxMenuItem?The CheckboxMenuItem class extends the MenuItem class to support a menu item that may bechecked or unchecked.

    Q63. What is a task's priority and how is it used inscheduling?A task's priority is an integer value that identifies the relative order in which it should beexecuted with respect to other tasks. The scheduler attempts to schedule higher priority tasksbefore lower priority tasks.

    Q64. 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 hierarchy.

    Q65. When a thread is created and started, what is its initialstate?A thread is in the ready state after it has been created and started.

    Q66. Can an anonymous class be declared as implementing an interface and extending aclass?An anonymous class may implement an interface or extend a superclass, but may not be declaredto do both.

    Q67. What is the range of the short type?The range of the short type is -(2^15) to 2^15 - 1.

  • 8/3/2019 core java q's

    9/67

    Q68. What is the range of the char type?The range of the char type is 0 to 2^16 - 1.

    Q69. In which package are most of the AWT events thatsupport the event-delegationmodel defined?

    Most of the AWT-related events of the event-delegation model are defined in thejava.awt.event package. The AWTEvent class is defined in the java.awt package.

    Q70. What is the immediate superclass of Menu?MenuItem

    Q71. What is the purpose of finalization?The purpose of finalization is to give an unreachable object the opportunity to perform anycleanup processing before the object is garbage collected.

    Q72. Which class is the immediate superclass of theMenuComponent class.

    Object

    Q73. What invokes a thread's run() method?After a thread is started, via its start() method or that of the Thread class, the JVM invokes thethread's run() method when the thread is initially executed.

    Q74. What is the difference between the Boolean & operatorand the && operator?If an expression involving the Boolean & operator is evaluated, both operands areevaluated. 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 truethen 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.

    Q75. Name three subclasses of the Component class.Box.Filler, Button, Canvas, Checkbox, Choice, Container, Label, List, Scrollbar, orTextComponent

    Q76. What is the GregorianCalendar class?The GregorianCalendar provides support for traditional Western calendars.

    Q77. Which Container method is used to cause a containerto 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 object's finalize() method beinvoked by the garbagecollector?An object's finalize() method may only be invoked once by the garbage collector.

  • 8/3/2019 core java q's

    10/67

    Q80. What is the purpose of the finally clause of a try-catchfinally statement? The finally clause is used to provide the capability to execute code no matter whether or not anexception is thrown or caught.

    Q81. What is the argument type of a program's main()method?

    A program's main() 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 particulargeographic, political, or cultural region.

    Q84. Can a double value be cast to a byte?Yes, a double value can be cast to a byte.

    Q85. 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 applies (switch, for, do,or while). A continue statement is used to end the current loop iteration and return control to theloop statement.

    Q86. What must a class do to implement an interface?It must provide all of the methods in the interface and identify the interface in itsimplements clause.

    Q87. What method is invoked to cause an object to beginexecuting as a separate thread?

    The start() method of the Thread class is invoked to cause an object to begin executing as aseparate thread.

    Q88. Name two subclasses of the TextComponent class.TextField and TextArea

    Q89. What is the advantage of the event-delegation modelover the earlier eventinheritancemodel?The event-delegation model has two advantages over the event-inheritance model. First, itenables event handling to be handled by objects other than the ones that generate the events (ortheir containers). This allows a clean separation between a component's design and its use. The

    other advantage of the event-delegation model is that it performs much better in applicationswhere many events are generated. This performance improvement is due to the fact that theevent-delegation model does not have to repeatedly process unhandled events, as is the case ofthe event-inheritance model.

    Q90. Which containers may have a MenuBar?Frame

  • 8/3/2019 core java q's

    11/67

    Q91. How are commas used in the intialization and iterationparts of a for statement?Commas are used to separate multiple statements within the initialization and iteration parts of afor statement.

    Q92. What is the purpose of the wait(), notify(), and notifyAll() methods?

    The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads towait for a shared resource. When a thread executes an object's wait() method, it enters thewaiting state. It only enters the ready state after another thread invokes the object's notify() ornotifyAll() methods..

    Q93. What is an abstract method?An abstract 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 thefile. A source code file may contain at most one public class or interface. If a public class or

    interface is defined within a source code file, then the source code file must take the name of thepublic class or interface. If no public class or interface is defined within a source code file, thenthe file must take on a name that is different than its classes and interfaces. Source code files usethe .java extension.

    Q95. What is the relationship between the Canvas class andthe Graphics class?A Canvas object provides access to a Graphics object via its paint() method.

    Q96. What are the high-level thread states?The high-level thread states are ready, running, waiting, and dead.

    Q97. What value does read() return when it has reached theend 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 to a primitive value.

    Q99. What is the difference between a static and a nonstaticinner class?A non-static inner class may have object instances that are associated with instances of the class'souter class. A static inner class does not have any object instances.

    Q100. What is the difference between the String andStringBuffer classes?

    String objects are constants. StringBuffer objects are not.

    Q101. If a variable is declared as private, where may thevariable be accessed?A private variable may only be accessed within the class in which it is declared.

    Q102. What is an object's lock and which object's havelocks?An object's lock is a mechanism that is used by multiple threads to obtain synchronized access tothe object. A thread may execute a synchronized method of an object only after it has acquired

  • 8/3/2019 core java q's

    12/67

    the object's lock. All objects and classes have locks. A class's lock is acquired on the class'sClass object.

    Q103. What is the Dictionary class?The Dictionary class provides the capability to store key-value pairs.

    Q104. How are the elements of a BorderLayout organized?The elements of a BorderLayout are organized at the borders (North, South, East, and West) andthe center of a container.

    Q105. What is the % operator?It is referred to as the modulo or remainder operator. It returns the remainder of dividing the firstoperand by the second operand.

    Q106. When can an object reference be cast to an interfacereference?An object reference be cast to an interface reference when the object implements the referenced

    interface.

    Q107. What is the difference between a Window and aFrame?The Frame class extends Window to define a main application window that 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 collected while it is stillreachable?A reachable object cannot be garbage collected. Only unreachable objects may be garbagecollected..

    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 andFontMetrics classes?The FontMetrics class is used to define implementation-specific properties, such as ascent anddescent, of a Font object.

    Q112. How is rounding performed under integer division?The fractional part of the result is truncated. This is known as rounding toward zero.

    Q113. What happens when a thread cannot acquire a lockon an object?If a thread attempts to execute a synchronized method or synchronized statement and is unable toacquire an object's lock, it enters the waiting state until the lock becomes available.

    Q114. What is the difference between the Reader/Writerclass hierarchy and theInputStream/OutputStream classhierarchy?

  • 8/3/2019 core java q's

    13/67

    The Reader/Writer class hierarchy is character-oriented, and the InputStream/ OutputStreamclass hierarchy is byte-oriented.

    Q115. What classes of exceptions may be caught by a catchclause?A catch clause can catch any exception that may be assigned to the Throwable type. This

    includes the Error and Exception types.

    Q116. 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 meansthat the class can only be accessed by other classes and interfaces that are defined within thesame package.

    Q117. What is the SimpleTimeZone class?The SimpleTimeZone class provides support for a Gregorian calendar.

    Q118. What is the Map interface?

    The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values.

    Q119. Does a class inherit the constructors of itssuperclass?A class does not inherit constructors from any of its superclasses.

    Q120. For which statements does it make sense to use alabel?The only statements for which it makes sense to use a label are those statements that can enclosea break or continue statement.

    Q121. What is the purpose of the System class?The purpose of the System class is to provide access to system resources.

    Q122. Which TextComponent method is used to set aTextComponent to the read-onlystate?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 cards.

    Q124. Is &&= a valid Java operator?No, it is not.

    Q125. Name the eight primitive Java types?The eight primitive types are byte, char, short, int, long, float, double, and boolean.

    Q126. Which class should you use to obtain designinformation about an object?The Class class is used to obtain information about an object's design.

  • 8/3/2019 core java q's

    14/67

    Q127. What is the relationship between clipping andrepainting?When a window is repainted by the AWT painting thread, it sets the clipping regions to the areaof the window that requires repainting.

    Q128. Is "abc" a primitive value?

    The String literal "abc" is not a primitive value. It is a String object.

    Q129. What is the relationship between an event-listenerinterface and an event-adapterclass?An event-listener interface defines the methods that must be implemented by an event handlerfor a particular kind of event. An event adapter provides a default implementation of an event-listener interface.

    Q130. What restrictions are placed on the values of eachcase of a switch statement?During compilation, the values of each case of a switch statement must evaluate to a value thatcan be promoted to an int value.

    Q131. What modifiers may be used with an interfacedeclaration?An interface may be declared as public or abstract.

    Q132. Is a class a subclass of itself?A class is a subclass of itself.

    Q133. What is the highest-level event class of the eventdelegationmodel?The java.util.EventObject class is the highest-level class in the event-delegation class hierarchy.

    Q134. What event results from the clicking of a button?

    The ActionEvent event 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 interfaceand adding itself as its own event listener.

    Q136. What is the difference between a while statementand a do statement?A while statement checks at the beginning of a loop to see whether the next loop iteration shouldoccur. A do statement checks at the end of a loop to see whether the next iteration of a loopshould occur. The do statement 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 organized according to a grid. However, the elements areof different sizes and may occupy more than one row or column of the grid. In addition, the rowsand columns may have different sizes.

    Q138. What advantage do Java's layout managers provideover traditional windowingsystems?Java uses layout managers to lay out components in a consistent manner across all windowing

  • 8/3/2019 core java q's

    15/67

    platforms. Since Java's layout managers aren't tied to absolute sizing and positioning, they areable to accomodate platform-specific differences among windowing systems.

    Q139. What is the Collection interface?The Collection interface provides support for the implementation 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 inner 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 whole rather than with specific instances of aclass. Non-static variables take on unique values with each object instance.

    Q142. What is the difference between the paint() andrepaint() 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.

    Q143. What is the purpose of the File class?The File class is used to create objects that provide access to the files and directories of a localfile system.

    Q144. Can an exception be rethrown?Yes, an exception can be rethrown.

    Q145. Which Math method is used to calculate the absolutevalue 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 operating system's task scheduler allocates execution time to multiple tasks. By quicklyswitching between executing tasks, it creates the impression that tasks execute sequentially.

    Q147. When does the compiler supply a default constructorfor 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-finallystatement 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 theContainer class?Component

    Q150. If a method is declared as protected, where may themethod be accessed?A protected method may only be accessed by classes or interfaces of the same package or bysubclasses of the class in which it is declared.

  • 8/3/2019 core java q's

    16/67

    Q151. How can the Checkbox class be used to create a radio button?By associating Checkbox objects with a CheckboxGroup.

    Q152. Which non-Unicode letter characters may be used asthe first character of anidentifier?

    The non-Unicode letter characters $ and _ may appear as the first character of an identifier

    Q153. What restrictions are placed on method overloading?Two methods may not have the same name and argument list but different return types.

    Q154. What happens when you invoke a thread's interruptmethod while it is sleeping orwaiting?When a task's interrupt() method is executed, the task enters the ready state. The next time thetask enters the running state, an InterruptedException is thrown.

    Q155. What is casting?

    There are two types of casting, casting between primitive numeric types and casting betweenobject references. Casting between numeric types is used to convert larger values, such as doublevalues, to smaller values, such as byte values. Casting between object references is used to referto an object by a compatible class, interface, or array type reference.

    Q156. What is the return type of a program's main()method?A program's main() method has a void return type.

    Q157. Name four Container classes.

    Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane

    Q158. 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 ofavailable choices. Only one item may be selected from a Choice. A List may be displayed insuch a way that several List items are visible. A List supports the selection of one or more Listitems.

    Q159. What class of exceptions are generated by the Javarun-time system?The Java runtime system generates RuntimeException and Error exceptions.

    Q160. What class allows you to read objects directly from astream?The ObjectInputStream class supports the reading of objects from input streams.

    Q161. What is the difference between a field variable and alocal variable?A field variable is a variable that is declared as a member of a class. A local variable is a variablethat is declared local to a method.

  • 8/3/2019 core java q's

    17/67

    Q162. Under what conditions is an object's finalize()method invoked by the garbagecollector?The garbage collector invokes an object's finalize() method when it detects that the object hasbecome 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 superclassconstructor.

    Q164. What is the relationship between a method's throwsclause and the exceptions thatcan be thrown during themethod's execution?A method's throws clause must declare any checked exceptions that are not caught within thebody of the method.

    165. What is the difference between the JDK 1.02 eventmodel and the event-delegationmodel introduced withJDK 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, theevent is inherited by (or bubbled up to) the component's container. The container then eitherhandles the event or it is bubbled up to its container and so on, until the highest-level containerhas been tried..In the event-delegation model, specific objects are designated as event handlersfor GUI components. These objects implement event-listener interfaces. The event-delegationmodel is more efficient than the event-inheritance model because it eliminates the processingrequired to support the bubbling of unhandled events.

    Q166. How is it possible for two String objects withidentical values not to be equal underthe == operator?

    The == operator compares two objects to determine if they are the same object in memory. It ispossible for two String objects to have the same value, but located indifferent areas of memory.

    Q167. Why are the methods of the Math class static?So they can be invoked as if they are a mathematical code library.

    Q168. What Checkbox method allows you to tell if aCheckbox 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 the instanceofoperator?The left operand is an object reference or null value and the right operand is a class, interface, orarray type.

    Q171. How are the elements of a GridLayout organized?The elements of a GridBad layout are of equal size and are laid out using the squares of a grid.

  • 8/3/2019 core java q's

    18/67

    Q172. What an I/O filter?An I/O filter is an object that reads from one stream and writes to another, usually altering thedata in some way as it is passed from one stream to another.

    Q173. If an object is garbage collected, can it becomereachable again?

    Once an object is garbage collected, it ceases to exist. It can no longer become reachable again.

    Q174. What is the Set interface?

    The Set interface provides methods for accessing the elements of a finite mathematical set. Setsdo not allow duplicate elements.

    Q175. What classes of exceptions may be thrown by a throwstatement?A throw statement may throw any expression that may be assigned to the Throwable type.

    Q176. What are E and PI?

    E is the base of the natural logarithm and PI is mathematical 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 indicates that a method does not return a value.

    Q179. What is the purpose of the enableEvents() method?The enableEvents() method is used to enable an event for a particular object. Normally, an eventis 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 eventdispatch methods.

    Q180. What is the difference between the File andRandomAccessFile classes?The File class encapsulates the files and directories of the local file system. TheRandomAccessFile class provides the methods needed to directly access data contained in anypart of a file.

    Q181. What happens when you add a double value to aString?The result is a String object.

    Q182. What is your platform's default character encoding?

    If you are running Java on English Windows platforms, it is probably Cp1252. If you are runningJava on English Solaris platforms, it is most likely 8859_1..

    Q183. Which package is always imported by default?The java.lang package is always imported by default.

    Q184. What interface must an object implement before it can be written to a stream as anobject?

  • 8/3/2019 core java q's

    19/67

    An object must implement the Serializable or Externalizable interface before it can be written toa 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 and

    methods of the superclass of the current object instance.

    Q186. What is the purpose of garbage collection?The purpose of garbage collection is to identify and discard objects that are no longer needed bya program so that their resources may be reclaimed and reused.

    Q187. What is a compilation unit?A compilation unit is a Java source code file.

    Q188. What interface is extended by AWT event listeners?All AWT event listeners extend the java.util.EventListener interface.

    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 andmethods of the superclass of the current object instance.

    Q186. What is the purpose of garbage collection?The purpose of garbage collection is to identify and discard objects that are no longer needed bya program so that their resources may be reclaimed and reused.

    Q187. What is a compilation unit?A compilation unit is a Java source code file.

    Q188. What interface is extended by AWT event listeners?All AWT event listeners extend the java.util.EventListener interface.

    Q193. Which arithmetic operations can result in thethrowing of an ArithmeticException?Integer / and % can result in the throwing of an ArithmeticException.

    Q194. What are three ways in which a thread can enter thewaiting state?A thread can enter the waiting state by invoking its sleep() method, by blocking on I/O, byunsuccessfully attempting to acquire an object's lock, or by invoking an object's wait() method. Itcan 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 ResourceBundle class?

    The ResourceBundle class is used to store locale-specific resources that can be loaded by aprogram to tailor the program's appearance to the particular locale in which it is being run.

  • 8/3/2019 core java q's

    20/67

    Q197. What happens if a try-catch-finally statement doesnot have a catch clause to handle

    an exception that isthrown within the body of the try statement?

    The exception propagates up to the next higher level try-catch statement (if any) or results in theprogram's termination.

    Q198. What is numeric promotion?Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so thatinteger and floating-point operations may take place. In numerical promotion, byte, char, andshort values are converted to int values. The int values are also converted to long values, ifnecessary. The long and float values are converted to double values, as required.

    Q199. What is the difference between a Scrollbar and aScrollPane?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.

    Q200. What is the difference between a public and a nonpublicclass?A public class may be accessed outside of its package. A non-public class may not be accessedoutside of its package.

    Q201. To what value is a variable of the boolean typeautomatically 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 postfixforms of the ++ operator?

    The prefix form performs the increment operation and returns the value of the incrementoperation. The postfix form returns the current value all of the expression and then performs theincrement 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 to create aseparate name space for groups of classes and interfaces. Packages are also used to organizerelated classes and interfaces into a single API unit and to control accessibility to these classesand interfaces.

    Q206. What modifiers may be used with a top-level class? A top-level class may be public, abstract, or final.

  • 8/3/2019 core java q's

    21/67

    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 torepresent the classes and interfaces that are loaded by a Java program..

    Q208. How does a try statement determine which catchclause should be used to handle an

    exception?When an exception is thrown within the body of a try statement, the catch clauses of the trystatement are examined in the order in which they appear. The first catch clause that is capable ofhandling the exception is executed. The remaining catch clauses are ignored.

    Q209. Can an unreachable object become reachable again?An unreachable object may become reachable again. This can happen when the object's finalize()method is invoked and the object performs an operation which causes it to become accessible toreachable objects.

    Q210. When is an object subject to garbage collection?

    An object is subject to garbage collection when it becomes unreachable to the program in whichit 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 implementthe Runnable interface.

    Q212. What methods are used to get and set the text labeldisplayed by a Button object?getLabel() and setLabel()

    Q213. Which Component subclass is used for drawing andpainting?

    Canvas

    Q214. What are synchronized methods and synchronizedstatements?Synchronized methods are methods that are used to control access to an object. A thread onlyexecutes a synchronized method after it has acquired the lock for the method's object or class.Synchronized statements are similar to synchronized methods. A synchronized statement canonly be executed after a thread has acquired the lock for the object or class referenced in thesynchronized statement.

    Q215. What are the two basic ways in which classes thatcan be run as threads may bedefined?

    A thread class may be declared as a subclass of Thread, or it may implement the Runnableinterface.

    Q216. What are the problems faced by Java programmerswho don't use layout managers?Without layout managers, Java programmers are faced with determining how their GUI will bedisplayed across multiple windowing systems and finding a common sizing and positioning thatwill work within the constraints imposed by each windowing system.

  • 8/3/2019 core java q's

    22/67

    Q217. What is the difference between an if statement and aswitch statement?The if statement is used to select among two alternatives. It uses a boolean expression to decidewhich alternative should be executed. The switch statement is used to select among multiplealternatives. It uses an int expression to determine which alternative should be executed.

    Q218. What happens when you add a double value to aString?The result is a String object.

    Q219. What is the List interface?The List interface provides support for ordered collections of objects.

    Q1. What is Multitasking?Ans. Executing several task simultaneously is called multitasking.

    Q2. What is the difference between process-based and Thread-based Multitasking?Ans.Process-based multitasking:- Executing several task simultaneously where each task is a

    separate independent process such type of multitasking is called process based Multitasking.Example:-While typing a program in the editor we can listen MP3 audio songs. At the same timewe download a file from the net. all these task are executing simultaneously and each task isa separate independent program. hence it is process based multitasking. It is best suitable atoperating system level. Thread-based multitasking:- Executing several task simultaneouslywhere each task is a separate independent part of the same program is called Thread-basedmultitasking. and every independent part is called a thread. This type of multitasking is bestsuitable at programmatic level.

    Q3. What is Multithreading and explain its application areas?Ans. Executing several thread simultaneously where each thread is a separate independent part of

    the same program is called multithreading. Java language provides inbuilt support formultithreading by defining a reach library, classes and interfaces like Thread, ThreadGroup,Runnable etc. The main important application area of multithreading are video gamesimplementation, animation development, multimedia graphics etc.

    Q4.What is advantage of Multithreading?Ans. The main advantage of multithreading is reduces response time and improves performanceof the system.

    Q5. When compared with C++ what is the advantage in java with respect to Multithreading?Ans.Java language provides inbuilt support for multithreading by defining a reach library, classesand interfaces like Thread, ThreadGroup, Runnable etc. But in c++ there is no inbuilt support formultithreading.Q6. In how many ways we can define a Thread? Among extending Thread and implementingRunnable which is recommended?Ans. We can define a Thread in the following two ways:

    1. by extending Thread class or2. by implementing Runnable interface.

  • 8/3/2019 core java q's

    23/67

    Among the two ways of defining a thread implementing Runnable mechanism is alwaysrecommended. In the first approach as our Thread class already extending Thread there is nochance of extending any other. Hence, we missing the key benefit of oops(inheritanceproperties).

    Q7. What is the difference between t.start() and t.run() method?

    Ans. In the case of t.start() method, a new thread will be created which is responsible for theexecution of run() method.

    But in the case of t.run() method no new thread will be created main thread executesrun() method just like a normal method call.Q8. Explain about Thread Scheduler?

    Ans. If multiple threads are waiting for getting the chance for executing then which thread willget chance first decided by Thread Scheduler. It is the part of JVM and its behavior is vendordependent and we cant expect exact output.Whenever the situation comes to multithreading the

    guarantee behavior is very- very low.

    Q9. If we are not overriding run() method what will happened?Ans.If we are not overriding run() method then Thread class run() method will executed whichhas empty implementation and hence we will not get any output.

    Q10.Is overloading of run() method is possible?Ans.Yes, we can overload run() method but Thread class start() method always invokes no-argument run() method only. The other run() method we have to call explicitly then only will beexecuted.

    Q11.Is it possible to override start() method?Ans. Yes it is possible. But not recommended.

    Q12.If we are overriding start() method then what will happen?Ans. It we are overriding start() method then our own start() method will be executed just like anormal method call. In this case no new Thread will be created.

    Q13. Explain life cycle of a Thread?

    Ans. Once we create a Thread object then the Thread is said to be in New/Born state once wecall t.start() method now the Thread will be entered into ready/Runnable state that is Thread isready to execute. If Thread Scheduler allocates CPU now the Thread will entered into theRunning state and start execution of run() method. After completing run() method the Threadentered into Dead State.

    Q14. What is the importance of Thread class start() method?Ans. Start() method present in Thread class performing all low level joining formalities for the

  • 8/3/2019 core java q's

    24/67

    newly created thread like registering thread with Thread Scheduler etc and then start() methodinvoking run() method.As the start() method is doing all low level mandatory activities,Programmer has to concentrate only on run() method to define the job. Hence, start() method is abig assistant to the programmer.Without executing Thread class start() method there is no chanceof starting a new Thread.

    Q15. After starting a Thread if we trying to restart the same thread once again what will happen?Ans. After starting a Thread restarting of the same Thread once again is not allowed violationleads to Runtime Exception saying IllegalThreadStateException.Q16. Explain Thread class constructors?Ans. There are eight constructors are available in Thread class:1. Thread t=new Thread();2. Thread t=new Thread(Runnable r);3. Thread t=new Thread(String name);4.Thread t=new Thread(Runnable r, String name);5.Thread t=new Thread(ThreadGroup g, String name);6.Thread t=new Thread(ThreadGroup g, Runnable r);

    7.Thread t=new Thread(ThreadGroup g, Runnable r, String name);8.Thread t=new Thread(ThreadGroup g, Runnable r, String name, long stacksize);

    Q17. How to get and set name of a Thread?Ans. For every Thread in java there is a name. To set and get the name of a Thread we can usethe following methods. All methods are final.1.Public final void setName(String name); - To set the name of a Thread2.Public final String getName(); - To get the name of a Thread.

    Q18. What is the range of Thread priority in java?Ans. The valid range of a Thread priority is 1-10. (1 is least priority and 10 is highest priority).Q19. Who uses Thread priority?Ans. Thread Scheduler uses priorities while allocating CPU. The Thread which is havinghighest priority will get chance first for execution.

    Q20. What is the default priority of the Thread?Ans. The default priority only for the main thread is 5 but for all remaining threads defaultpriority will be inheriting from parent to child. Whatever priority parent thread has the same willbe inherited to the child thread.

    Q21. Once we created a new Thread what about its priority?Ans. Whatever priority parent thread has the same will be inherited to the new child thread.Q22. How to get and set priority of a Thread?Ans. To get and set priority of a Thread, Thread class defines the following two methods:;

    1. Public final intgetPriority();

  • 8/3/2019 core java q's

    25/67

    2. Public final void setPriority(int priority);

    Q23. If we are trying to set priority of a Thread as 100 what will happen?Ans. If we are trying to set priority of a Thread as 100 then we will not get any compile timeerror but at the runtime we will get Runtime exception IllegalArgumentException. Because the

    valid range of the Thread priority is (1-10) only.

    Q24. If two threads having same priority then which thread will get chance first for execution?Ans. If two threads having same priority then which thread will get the chance first forexecution decided by Thread Scheduler. It is the part of JVM and its behavior is vendordependent and we cant expect exact output.

    Q25. If two threads having different priority then which thread will get chance first forexecution?Ans. If two threads having different priority then the Thread which is having highest priority willget chance first for execution.

    Q26 .How we can prevent a thread from execution?Ans. We can prevent a Thread from executin by using the following methods:

    1. Yield()2. Join()3. Sleep()

    Q27. What is yield() method? Explain its purpose?Ans. yield() method causes the current executing thread to pause execution and give the chancefor waiting thread are same priority. If there is no waiting thread or all the remaining waiting

    thread have low priority then the same thread will get chance once again for execution. TheThread which is yielded when it will get chance once again for execution depends upon mercy ofThread scheduler.Public static native void yield();

    Q28.What is purpose of join() method?Ans. If a Thread wants to wait until some other Thread completion then we should go for join()method.

    Example: if a Thread t1 execute t2.join() ; then t1 will entered into waiting state until t2Thread completion.

    Q29. Is join() method is overloaded?Ans. Yes join() method is overloaded method.

    Public final void join() throws InterruptedExceptionBy using this method thread will wait up to another thread completion .

    Public final void join(long ms) throws InterruptedExceptionBy using this method thread will wail upto sometime what we are passing as a argument inmillisecondPublic final void join(long ms, int ns)throws InterruptedExceptionBy using this method thread will wait up to sometime what we are passing as a argument in

  • 8/3/2019 core java q's

    26/67

    millisecond and nanosecond.

    Q30 What is the purpose of sleep() method?Ans. If a Thread dont want to perform any operation for a particular amount of time then weshould go for sleep() method.Whenever we are using sleep() method compulsory we should

    handle InterruptedException either by using try-catch or by using throws keyword otherwise wewill get compile time error.

    Q31. What is synchronized keyword? Explain its advantages and disadvantages.Ans. Synchronized keyword is applicable for method and blocks only. We cant use forvariables and classes.

    If a method declared as a synchronized then at a time only one Thread is allow toexecute that method on the given object.

    The main advantages of synchronized keyword are, we can prevent data inconsistencyproblems and we can provide Threadsafty.

    But the main limitation of synchronized keyword is it increases waiting time of

    Threads and effect performance of the system. Hence if there is no specific requirement it is notrecommended to use synchronized keyword.

    Q32.Where we can use synchronized keyword?Ans. Synchronization concept is applicable whenever multiple Threads are operating on thesame object simultaneously. But whenever multiple Threads are operating on different objectsthen there is no impact of synchronization.

    Q33. What is object lock? Explain when it is required?Ans. Every object in java has a unique lock whenever we are using synchronization conceptthen only lock concept will coming to the picture.If a Thread wants to execute a synchronized method first it has to get the lock of the object. Oncea Thread got the lock then it is allow to execute any synchronized method on that object. Aftercompleting synchronized method execution Thread releases the lock automatically.While aThread executing synchronized method on the given object the remaining Threads are not allowto execute any synchronized method on that object simultaneously. But remaining Threads areallow to execute any non-synchronized method simultaneously. (Lock concept is implementedbased on object but not based on method.)Q34.What is the class level lock? Explain its purpose.Ans. Every class in java has a unique lock if a Thread wants to execute static synchronizedmethod that Thread has to get class level lock once a Thread got class level lock then only it isallow to execute static synchronized method.While a Thread executing any static synchronized method then remaining Threads are not allowto execute any static synchronized method of the same class simultaneously. But the remainingThreads are allow to execute the following method simultaneously:

    1. Any static non-synchronized method.2. Synchronized instance methods3. Non-synchronized instance method.

  • 8/3/2019 core java q's

    27/67

    There is no relationship between object lock and class level lock, both are independent.

    Q35. While a thread executing any synchronized method on the given object is it possible toexecute remaining synchronized method of the same object simultaneously by any other thread?Ans. No, it is no possible.

    Q36. What is the difference between synchronized method and static synchronized method?Ans. If a Thread wants to execute a synchronized method first it has to get the lock of theobject. Once a Thread got the lock then it is allow to execute any synchronized method on thatobject.If a Thread wants to execute static synchronized method that Thread has to get classlevel lockonce a Thread got class level lock then only it is allow to execute static synchronizedmethod.

    Q37. What is the advantage of synchronized block over synchronized method?Ans. If very few lines of the code required synchronization then declaring entire method as thesynchronized is not recommended. We have to declare those few lines of the code insidesynchronized block. This approach reduces waiting time of the Thread and improves

    performance of the system.

    Q38. What is synchronized statement?Ans. The Statement which is inside the synchronized area (synchronized method orsynchronized block) is called synchronized statement.

    Q39. How we can declare synchronized block to get class level lock?Ans. To get the class level lock we can declare synchronized block as follows:

    synchronized(Display.class){}

    Q40. How two thread will communicate with each other?Ans. Two Threads will communicate with each other by using wait(), notify(), notifyAll()methods.

    Q41.wait(), notify(), notifyAll() method can available in which class?Ans. These methods are defined in Object class.

    Q42.Why wait(), notify(), notifyAll() method defines in object class instead of Thread class?Ans. These methods are defined in Object class but not in Thread because Threads are callingthis method on the shared object.

    Q43.If a waiting thread got notification then it will entered into which state?Ans. It will entered into another waiting state to get lock.

    Q44.In which method threads can release the lock?Ans. Once a Thread calls wait() method it immediately releases the lock of that object and thenentered into waiting state similarly after calling notify() method Thread releases the lock but may

  • 8/3/2019 core java q's

    28/67

    not immediately. Except these three methods( wait(), notify(), notifyAll() ) method Thread neverreleases the lock anywhere else.

    Q45. Explain wait(), notify(), notifyAll() method uses.Ans. Two Threads will communicate with each other by using wait(), notify() or notifyAll()

    methods.These methods are defined in Object class but not in Thread because Threads are callingthis method.

    Q46. What is the difference between notify() and notifyAll()?Ans. To give notification to the single waiting Thread. We use notify() method and to givenotification to all waiting thread we use notifyAll() method.

    Q47. Once a Thread got the notification then which waiting thread will get chance?Ans. It is depends on the Thread Scheduler.

    Q48. How a thread can interrupt another thread?

    Ans. A Thread can interrupt another Thread by using interrupt() method.

    Q49. What is DeadLock? Is it possible to resolve DeadLock situation?Ans. If two Threads are waiting for each other forever such type of situation is calledDeadLock.

    For the DeadLock, there are no resolution techniques but prevention techniques areavailable.

    Q50. Which keyword causes DeadLock situation?Ans. Synchronized keyword is the thing to causes of DeadLock. If we are not using properlysynchronized keyword the program will entered into DeadLock situation.

    Q51. How we can stop a thread explacitly?Ans. Thread class defines stop() method by using this method we can stop a Thread. But it isdeprecated. And hence not recommended to use.

    Q52. Explain about suspend() and resume() method?Ans. A Thread can suspend another Thread by using suspend() method.A Thread can resume a suspended Thread by using resume() method.

    Q53.What is Starvation()? And Explain the difference between Deadlock and Starvation?Ans. A long waiting Thread is said to be in starvation (because of least priority) but after certaintime defiantly it will get the chance for execution. But in the case of Deadlock two Threads willwait for each other forever. It will never get the chance for execution.Q54. What is race condition?Ans. Multiple Threads are accessing simultaneously and causing data inconsistency problem iscalled race condition, we can resolve this by using synchronized keyword.

  • 8/3/2019 core java q's

    29/67

    Q55. What is Daemon Thread? And give an example?Ans. The Threads which are running in the background are called Daemon Thread.

    Example: Garbage collector.Q56. What is the purpose of a Daemon Thread?Ans. The main purpose of Daemon Threads is to provide support for non-daemon Threads.

    Q57. How we can check Daemon nature of a Thread?Ans. We can check Daemon nature of a Thread by using isDaemon() method.Q58. Is it possible to change a Daemon nature of a Thread?Ans. Yes, we can change Daemon nature of a Thread by using setDaemon() method.Q59. Is main thread is Daemon or non-daemon?Ans. By default main thread is always non-daemon nature.Q60. Once we created a new thread is it daemon or non-daemon.Ans. Once we created a new Thread, The Daemon nature will be inheriting from parent tochild. If the parent is Daemon the child is also Daemon and if the parent is non-daemon thenchild is also non-daemon.

    Q61. After starting a thread is it possible to change Daemon nature?Ans. We can change the Daemon nature before starting the Thread only. Once Thread started weare not allow to change Daemon nature otherwise we will get RuntimeException syingIllegalThreadStateException.Q62. When the Daemon thread will be terminated?Ans. Once last non-daemon Thread terminates automatically every Daemon Thread will beterminated.Q63. What is green Thread?Ans. A green thread refers to a mode of operation for the Java Virtual Machine (JVM) in whichall code is executed in a single operating system thread. If the Java program has any concurrent

    threads, the JVM manages multi-threading internally rather than using other operating systemthreads.There is a significant processing overhead for the JVM to keep track of thread states and swapbetween them, so green thread mode has been deprecated and removed from more recent Javaimplementations.Q64.Explain about Thread group?Ans. Every Java thread is a member of a thread group. Thread groups provide a mechanism forcollecting multiple threads into a single object and manipulating those threads all at once, ratherthan individually. For example, you can start or suspend all the threads within a group with asingle method call. Java thread groups are implemented by the ThreadGroup api class in thejava.lang package.

    Q65.What is the Thread Local?Ans. It's a way for each thread in multi-threaded code to keep its own copy of an instancevariable. Generally, instance variable are shared between all threads that use an object;ThreadLocal is a way for each thread to keep its own copy of such a variable. The purposemight be that each thread keeps different data in that variable, or that the developer wants toavoid the overhead of synchronizing access to it.Q66. In your previous project where you used multithreading concept?

  • 8/3/2019 core java q's

    30/67

    1: What is the difference between Database and Database management system?Ans: Database is a collection of interrelated data. Database management system is a softwarewhich can be used to manage the data by storing it on to the data base and by retrieving it fromthe data base. And DBMS is a collection of interrelated data and some set of programs to accessthe data.

    There are 3 types of Database Management Systems.

    y Relational DataBase Management Systems(RDBMS): It is a software system, which canbe used to represents data in the form of tables. RDBMS will use SQL2 as a Querieslanguage.

    y Object Oriented DataBase Management Systems(OODBMS): It is a software system,which can be used to represent the data in the form of objects. This DBMS will use OQLas a Query language.

    y Object Relational DataBase Management Systems(ORDBMS): It is a DBMS which willrepresents some part of the data in the form of tables and some other part of the data in

    the form of objects. This management system will use SQL3 as a Query Language, it is acombination of SQL2 and OQL.

    2: How a query could be executed when we send a query to Database?When we send an SQL Query from SQL prompt to the DataBaseEngine, then Database Enginewill take the following steps.

    y Query Tokenization: This phase will take SQL query as an input and devide into streamof tokens.

    y Query Parsing: This phase will take stream of tokens as an input, with them it tried toconstruct a query tree. If query parser constructs query tree successfully then it was an

    indication that no grammatical mistakes in the taken SQL query. Otherwise there aresome syntactical errors in the taken SQL query.y Query Optimization: This phase will take query tree as an input and performs number of

    query optimization mechanisms to reduce execution time and memory utilization.y Query Execution: This phase will take optimized query as an input and executes that

    SQL query by using interpreters internally as a result we will get some output on the SQLprompt.

    3: What is Driver? How many Drivers are available in JDBC? What are the types?

    y It is a process of interacting with the database from a java application.y In JDBC applications we must specify the complete database logic in java application as

    for the java API representations, later on we need to send java represented database logicto the database engine(DBE).

    y DBE must execute the database logic but it was configured as per the java representationsbut DBE able to understand only Query Language representations.

    y At the above situation if we want to execute our database logic, we need to use oneinterface in between java application and the database, that interface must convert java

  • 8/3/2019 core java q's

    31/67

    representations to query language representations and query language representations tojava representations. Now this interface is called as a Driver.

    Driver:

    yIt is a software or an interface existed in between a java application and database, whichwill map java api calls with query language api calls and vice versa.

    y Initially sun Microsystems has provided driver interface to the market with this sunMicrosystems has given an intimation to all the database vendors to have their ownimplementation as per their requirements for the Driver interface.

    y As a response all the database vendors are providing their own implementation for theDriver interface inorder to interact with the respective databases from a java application.

    y The users of the respective databases they must get the respective database providedDriver implementation from the database software and make use as part of the JDBCapplications to interact with the respective databases form a java application.

    Types of Drivers:There are 180+ number of Drivers in the market. But all these Drivers could be classifiedinto the following 4 types.

    y Type 1 Drivery Type 2 Drivery Type 3 Drivery Type 4 Driver

    Type 1 Driver:

    oType 1 Driver is also called as Jdbc-Odbc Driver or Bridge Driver.

    o Jdbc-Odbc Driver is an implementation to Driver interface provided by the sunMicrosystems along with the java software.

    o Jdbc-Odbc Driver internally depends on the Microsoft product Odbc Driver.o Odbc is nothing but open database connectivity. It is a open specification which

    can be used to interact with any type of databases.

    Advantages:

    y This Driver is already available with java software thats why no need to bother abouthow to get the Driver implementation explicitily.

    yAllmost all the databases could support this Driver.

    Dis advantages:

    y This Driver internally depends on Odbc Driver thats why it is not suitable for internet orweb applications or network applications.

    y This Driver is a slower Driver, why because Jdbc-Odbc Driver will convert java calls toOdbc calls. Then Odbc Driver has to convert Odbc calls to query language calls.

  • 8/3/2019 core java q's

    32/67

    y This driver is not portable Driver why because it was not complete the javaimplementations in Jdbc-Odbc Driver.

    y It we want to use Jdbc-Odbc Driver in our jdbc applications then we must require toinstall Odbc-Native Library.

    Type 2 Driver:

    Type 2 Driver is also called as part java part native Driver. i.e., this Driver wasdesigned by using some part of the java implementations and some other part of the databasevendor provided native implementations. This Driver is also called as native driver.

    Advantages:When compared to Type 1 driver it is efficient driver why because Type 2 driver directly

    will convert java api calls to database vendor api calls.

    Dis advantages:

    y If we want to use Type 2 Driver in our Jdbc applications then we must require to installdatabase vendor native api.

    y It is a costful Driver.y It is not suitable for web applicadtions, distributed applications and web applications.y Type 2 Driver performance is low when compared to Type 3 and Type 4 drivers.y This driver is not portable driver. Why because this driver was not designed completely

    in java technology.

    Type 3 Driver:

    oIt is also called as middleware database access server driver.

    o This driver could be used to interact with multiple databases from the multipleclients.

    o This driver could be used in collaboration with application server.o This driver is suggestable for network applications.

    Advantages:

    y It is a fastest driver among all the drivers available in the market.y To use Type 3 driver in our jdbc applications it is not required to install odbc native

    library and database native library.y

    It is very much suitable for network applications.

    Dis advantages:

    y This driver is not suitable for simple jdbc applications.y This driver requires minimum 3-Tier Architecture.y When compared to Type1 and Type2 drivers.. Type3 driver is efficient and portable. But

    when compared to Type4 driver, Type3 driver is not portable.

  • 8/3/2019 core java q's

    33/67

    Type 4 Driver:

    o This driver is also called as pure java driver i.e, this driver was completelyimplemented by using java technology.

    o When compared to Type1, Type2 and Type3 drivers.. Type4 driver is portabledriver.

    o Type4 driver can be used for any kind of applications.o Type4 driver is a cheapest driver when compared to all the drivers thats why it is

    frequently used driver.

    4: What is JDBC and What are the steps to write a JDBC application?

    The process of interacting with the database from a java application is called as JDBC(JavaDatabase Connectivity)To interact with the database from a java application we will use the following five steps.

    1. load and register the driver.2. Establish a connection between java application and the database.3. prepare either statement object or PreparedStatement object or CallebleStatement object

    as per the application requirements.4. write and executer the sql queries.5. terminate the connection which we have established.

    5: How to load a JDBC driver?

    o In general sun Microsystems has provided Driver interface for this all thedatabase vendors has provided their own implementation.

    o If we want to use the database vendor provided Driver implementation to our jdbcapplication, first we need to make the availability of the respective Drivers.class file to JVM, for this we need to set class path environment variable to thelocation where we have the driver implementation.

    o Sun Microsystems is also provided an implementation to the Driver interface inthe form of JdbcOdbcDriver class as part of the java software.

    o If we want to use JdbcOdbcDriver in our jdbc applications no need to set classpath environment variable. Why because it was already available in the javasoftwares pre-defined library.

    o JdbcOdbcDriver internally depends on the mocrosoft product Odbc driver. If wewant to use the JdbcOdbcDriver in our jdbc applications first we must configureOdbc driver, for this we will use the following path.

    Start/ conrlol panel / performance and maintenance / administrative tools / data source(Odbc)/user dsn / click on Add / select microsofr Odbc for oracle / finish / provide data source nameonly / click on ok / ok.

    y To load the drivers class byte code to the memory we will use the following method.

  • 8/3/2019 core java q's

    34/67

    Public void forName(String class name)

    Eg: Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);

    Where forName() is a static method, which can be used to load the respective driver class

    byte code to the memory.

    y Each and every driver class has already a static block at the time of loading the respectivedriver class byte code to the memory automatically the available static block could beexecuted, by this DriverManager.registerDriver(.) method will be executed as part ofthe static block.

    y By the execution of the registerDriver(.) method automatically the specified driver willbe register to the jdbc application.

    y If you want to design any jdbc application, we need to use some pre-defined library,which was provided by the Jdbc API in the form of java.sql package, thats why we needto import java.sql package in our jdbc application.

    Note:- The best alternative for Class.forName(..) isDriverManagre.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver());To register the driver.

    6: How to establish a Database connection between java application and Database?

    If we want to establish a connection between java application and the database we will thefollowing piece of code.

    Connection con=

    DriverManager.getConnection(jdbc:odbc:nag,nag,system,manager);

    Where getConnectin() is a static method from DriverManager class, which can be used to returnconnection object.

    7: Basically Connection is an interface, how getConnection() will create an object forConnection interface?

    Ans: Connection is an interface from java.sql package, for which getConnection(_) was returnan anonymous inner class object of the Connection interface.

    Note:- Anonymous inner class is a nameless inner class, which can be sued to provide an

    implementation either for the interfaces or for abstract classes.

    Eg: interface I{

    void m1();}

    Class Outer{

  • 8/3/2019 core java q's

    35/67

    I i = new I(){public void m1(){

    }

    public void m2(){

    }}

    }Outer o = new Outer();o.i.m1(); correcto.i.m2(); wrong

    getConnection(_) is a static method from DriverManager class, which will call

    internally connect() method, this connect() will establish a virtual socket connection in betweenthe java application and the database.8: What is the requirement to use Statement object?

    y After establishing a connection between java application and the database we need towrite the sql queries and we need to execute them.

    y To execute the sql queries we will use some pre-defined library, which was defined in theform of Statement object, PreparedStattement object and CallableStatement object.

    y As per the application requirements we need to create either Statement object orCallableStatement object and PreparedStatement object.

    y To create Statement object dwe will use the following method from connection object. public Statement createStatement()Eg: Statement st = con.createStatement();9: How to execute SQL Queries from a java application?

    To execute the sql queries we will use the following methods from Statement object.

    y st.executeQuery()y st.executeUpdate()y st.execute()

    10: What are the differences between executeQuery(), executeUpdate() and execute()methods?Ans: where executeQuery() can be used to execute selection group sql queries to fetch the datafrom database.When we use selection group sql query with executeQuery() then JVM will send that sql queryto the database engine, database engine will execute it, by this database engine(DBE) will fetchthe data from database and send back to the java application.

  • 8/3/2019 core java q's

    36/67

    Java is a purely object oriented technology. Thats why the jdbc application will maintain thefetched data from database, in the form of an object at heap memory, called as ResultSet object.

    public ResultSet executeQuery(String sqlquery)

    where executeUpdate() can be used to execute updation group sql query to update thedatabase. When we provide updation group sql query as a parameter to executeUpdate(), thenJVM will send that sql query to DBE, here DBE will execute it and perform updations on thedatabase, by this DBE will identify the number of records got updated value called as recordsupdated count and return back to the java application.

    public int executeUpdate(String sqlquery)

    where execute() can be used to execute either selection group sql queries or updationgroup queries.

    When we use selection group sql query with the execute() then we will get ResultSet

    object at heap memory with the fetched data. But execute() will return true as a Boolean value.When we use updation group sql query with execute() then we will get records updatedcount value at jdbc application. But execute() will return false as a Boolean value.

    public boolean execute(String sqlquery)

    11: How to create a table dynamically from a jdbc application?.

    //import sectionimport java.sql.*;import java.io.*;

    public class CreateTableEx{

    public static void main(String[] args)throws Exception{

    //create buffered reader objectBufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    //load and register the driverClass.forName(sun.jdbc.odbc.JdbcOdbcDriver);

    //establish connectionConnection con = DriverManager.getConnection(jdbc:odbc:nag,system,durga);

    //create statement objectStatement st = con.createStatement();

  • 8/3/2019 core java q's

    37/67

    //take table name as dynamic inputSystem.out.println(Enter table name);String tname = br.readLine();

    //execute sql query

    St.executeUpdate(create table+tname+(eno number,ename varchar2(10),esalnumber,eaddr varchar2(10)));

    System.out.println(table created successfully);

    //closing the connectioncon.close();

    }}

    12: How to insert records into a table from a JDBC application?

    import java.sql.*;import java.io.*;public class InsertTableEx{

    public static void main(String[] args) throws Exception{

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));Class.forName(oracle.jdbc.driver.OracleDriver);

    Connection con =DriverManager.getConnection(jdbc:oracle:thin:@localhost:1521:xe,system,durga);

    Statement st = con.createStatement();while(true){

    System.out.println(Enter emp number);Int eno = Integer.parseInt(br.readLine());System.out.println(Enter emp name);String ename = br.readLine();System.out.println(Enter emp sal);Float esal = Float.parseFloat(br.readLine());System.out.println(Enter emp address);String eaddr = br.readLine();

    st.executeUpdate(insert into emp1 values(+eno+,+ename+,+esal+,+eaddr+));System.out.println(read successfully inserted);System.out.println(one more record[y/n]);String option = br.readLine();If(option.equals(n))

    break;}

  • 8/3/2019 core java q's

    38/67

    }}

    13: How to update a table from a jdbc application?.

    import java.sql.*;public class UpdateTableEx{

    public static void main(String[] args)throws Exception{

    //load n register the driver in alternative way to Class.forNameDriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());

    Connection con =DriverManager.getConnection(jdbc:oracle:thin:@localhost:1521:xee,system,durga);

    Statement st = con.createStatement();int updateCount = st.executeUpdate(update emp1 set esal = esal+500 where esal=7000);

    System.out.println(records deleted+updateCount);

    con.close();}

    }

  • 8/3/2019 core java q's

    39/67

    15:What is ment by ResultSet object and How to Fetch the Data from Database?.

    ResultSet:-

    ResultSet is an Object which can be used to maintain the fetched data from database in the JDBC

    applications

    When we execute a selection group sql query, either with executeQuety() or with execute()automatically a ResultSet object will be created at heap memory with the fetched data fromdatabase.

    y To get the ResultSet object reference directly we will use executeQuery(..).y When we create a ResultSet object automatically a cursor will be create called as

    ResultSet cursor to read the data from ResultSet object.y When we create the ResultSet object by default ResultSet cursor will be created before

    the first record.y

    If we want to read the data from ResultSet object every time we need to check whetherthe next record is available or not. If the next record is available automatically we need tomove that ResultSet cursor to next record position.

    y To perform this work we will use the following method from ResultSet interface.public boolean next()

    y After getting ResultSet cursor to a record position then we need to get the data fromrespective fields of the particular record, for this we will use following method.

    public xxx getXxx(int fno)(or)

    public xxx getXxx(String fname)

    where xxx is byte, shor, int, long, float, double, char.

    Eg: while(rs.next()){

    System.out.println(rs.getInt(1)+ +rs.getString(2)+ +rs.getFloat(3)+ +rs.getString(4));}

    The following example demonstrates how to fetch the data from database through

    ResultSet object.

    import java.sql.*;public class FetchEx

  • 8/3/2019 core java q's

    40/67

    {public static void main(String[] args)throws Exception{

    Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);

    Connection con = DriverManager.getConnection(jdbc:odbc:nag,system,durga);

    Statement st = con.createStatement();ResultSet rs = st.executeQuery(select * from emp1);System.out.println(ENO ENAME ESAL EADDR);System.out.println(********************************);while(rs.next()){

    System.out.println(rs.getInt(1)++rs.getString(2)+ +rs.getFloat(3)++rs.getString(4));

    }

    }}

    16:Ingeneral execute() method can be used to execute selectiongroup SQl queries forgetting

    the data from Database , but execute() return a boolean value true so here how it possible to

    fetch the data from database?

    y Execute() can be used to execute both selection group sql query and updation group sqlquery.

    y If we use execute() to execute a selection group sql query then DBE(Database engine)will execute that sql query and send back the fetched data from database to java

    application. Now java application will prepare a ResultSet object with the fetched databut execute() will return true as a Boolean value.y At this situation to get the reference of the ResultSet object explicitily, we will use the

    following method from Statement object.

    public ResultSet getResultSet()

    Eg: