Java Interview Questions

Question-1. What is difference between JDK,JRE and JVM ?

Answer-
JVM

JVM is an acronym for Java Virtual Machine, it is an abstract machine which provides the runtime
 environment in which java bytecode can be executed. It is a specification.

JVMs are available for many hardware and software platforms (so JVM is platform dependent).

JRE

JRE stands for Java Runtime Environment. It is the implementation of JVM.

JDK

JDK is an acronym for Java Development Kit. It physically exists. It contains JRE + development tools.
                            

Question-2. How many types of memory areas are allocated by JVM ?

Answer-
a.  Class(Method) Area
b.  Heap
c.  Stack
d.  Program Counter Register
e.  Native Method Stack
                            

Question-3. What is platform ?

Answer- A platform is basically the hardware or software environment in which a program runs. There are two types of platforms software-based and hardware-based. Java provides software-based platform.

Question-4. What is the main difference between Java platform and other platforms ?

Answer- The Java platform differs from most other platforms in the sense that it's a software-based platform that runs on top of other hardware-based platforms.It has two components:
a.  Runtime Environment
b.  API(Application Programming Interface)
                            

Question-5. What is constructor ?

Answer- Constructor is just like a method that is used to initialize the state of an object. It is invoked at the time of object creation.

Question-6. What is the purpose of default constructor ?

Answer- The default constructor provides the default values to the objects. The java compiler creates a default constructor only if there is no constructor in the class.

Question-7. Does constructor return any value ?

Answer- Yes, that is current instance (You cannot use return type yet it returns a value).

Question-8. Is constructor inherited ?

Answer- No, constructor is not inherited.

Question-9. Can you make a constructor final ?

Answer- No, constructor can't be final.

Question-10. What is static variable ?

Answer- static variable is used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees,college name of students etc. static variable gets memory only once in class area at the time of class loading.

Question-11. What is static method ?

Answer- A static method belongs to the class rather than object of a class. A static method can be invoked without the need for creating an instance of a class. static method can access static data member and can change the value of it.

Question-12. Why main method is static ?

Answer- because object is not required to call static method if It were non-static method,jvm creats object first then call main() method that will lead to the problem of extra memory allocation.

Question-13. What is static block ?

Answer- Is used to initialize the static data member. It is excuted before main method at the time of classloading.

Question-14. Can we execute a program without main() method ?

Answer- Yes, one of the way is static block.

Question-15. What if the static modifier is removed from the signature of the main method ?

Answer- Program compiles. But at runtime throws an error "NoSuchMethodError".

Question-16. What is this in java ?

Answer- It is a keyword that that refers to the current object.

Question-17. What is Inheritance ?

Answer- Inheritance is a mechanism in which one object acquires all the properties and behaviour of another object of another class. It represents IS-A relationship. It is used for Code Resusability and Method Overriding.

Question-18. Which class is the superclass for every class ?

Answer- Object class.

Question-19. Why multiple inheritance is not supported in java ?

Answer- To reduce the complexity and simplify the language, multiple inheritance is not supported in java in case of class.

Question-20. What is composition ?

Answer- Holding the reference of the other class within some other class is known as composition.

Question-21. What is difference between aggregation and composition ?

Answer- Aggregation represents weak relationship whereas composition represents strong relationship. For example: bike has an indicator (aggregation) but bike has an engine (compostion).

Question-22. Why Java does not support pointers ?

Answer- Pointer is a variable that refers to the memory address. They are not used in java because they are unsafe(unsecured) and complex to understand.

Question-23. What is super in java ?

Answer- It is a keyword that refers to the immediate parent class object.

Question-24. Can you use this() and super() both in a constructor ?

Answer- No. Because super() or this() must be the first statement.

Question-25. What is object cloning ?

Answer- The object cloning is used to create the exact copy of an object.

Question-26. What is method overloading ?

Answer- If a class have multiple methods by same name but different parameters, it is known as Method Overloading. It increases the readability of the program

Question-27. Why method overloading is not possible by changing the return type in java ?

Answer- Because of ambiguity.

Question-28. Can we overload main() method ?

Answer- Yes, You can have many main() methods in a class by overloading the main method.

Question-29. What is method overriding ?

Answer- If a subclass provides a specific implementation of a method that is already provided by its parent class, it is known as Method Overriding. It is used for runtime polymorphism and to provide the specific implementation of the method.

Question-30. Can we override static method ?

Answer- No, you can't override the static method because they are the part of class not object.

Question-31. Why we cannot override static method ?

Answer- It is because the static method is the part of class and it is bound with class whereas instance method is bound with object and static gets memory in class area and instance gets memory in heap.

Question-32. Can we override the overloaded method ?

Answer- Yes.

Question-33. Can you have virtual functions in Java ?

Answer- Yes, all functions in Java are virtual by default.

Question-34. What is covariant return type ?

Answer- Now, since java5, it is possible to override any method by changing the return type if the return type of the subclass overriding method is subclass type. It is known as covariant return type.

Question-35. What is final variable ?

Answer- If you make any variable as final, you cannot change the value of final variable(It will be constant).

Question-36. What is final method ?

Answer- Final methods can't be overriden.

Question-37. What is final class ?

Answer- Final class can't be inherited.

Question-38. What is blank final variable ?

Answer- A final variable, not initalized at the time of declaration, is known as blank final variable.

Question-39. Can we intialize blank final variable ?

Answer- Yes, only in constructor if it is non-static. If it is static blank final variable, it can be initialized only in the static block.

Question-40. Can you declare the main method as final ?

Answer- Yes, such as, public static final void main(String[] args){}.

Question-41. What is Runtime Polymorphism ?

Answer- Runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time. In this process, an overridden method is called through the reference variable of a super class. The determination of the method to be called is based on the object being referred to by the reference variable.

Question-42. Can you achieve Runtime Polymorphism by data members ?

Answer- No.

Question-43. What is the difference between static binding and dynamic binding? ?

Answer- In case of static binding type of object is determined at compile time whereas in dynamic binding type of object is determined at runtime.

Question-44. What is abstraction ?

Answer- Abstraction is a process of hiding the implementation details and showing only functionality to the user. Abstraction lets you focus on what the object does instead of how it does it.

Question-45. What is the difference between abstraction and encapsulation ?

Answer- Abstraction hides the implementation details whereas encapsulation wraps code and data into a single unit.

Question-46. What is abstract class ?

Answer- A class that is declared as abstract is known as abstract class. It needs to be extended and its method implemented. It cannot be instantiated.

Question-46. Can there be any abstract method without abstract class? ?

Answer- No, if there is any abstract method in a class, that class must be abstract.

Question-47. Can you use abstract and final both with a method ?

Answer- No, because abstract method needs to be overridden whereas you can't override final method.

Question-48. Is it possible to instantiate the abstract class ?

Answer-No, abstract class can never be instantiated.

Question-49. What is interface ?

Answer-Interface is a blueprint of a class that have static constants and abstract methods. It can be used to achieve fully abstraction and multiple inheritance.

Question-50. Can you declare an interface method static ?

Answer- No, because methods of an interface is abstract by default, and static and abstract keywords can't be used together.

Question-51. Can an Interface be final ?

Answer- No, because its implementation is provided by another class.

Question-52. What is marker interface ?

Answer- An interface that have no data member and method is known as a marker interface. For example Serializable, Cloneable etc.

Question-53. Explain the following line used under Java Program: public static void main(String args[]) ?

Answer- The following shows the explanation individually −
• public − it is the access specifier.

• static − it allows main() to be called without instantiating a particular instance of a class.

• void − it affirns the compiler that no value is returned by main().

• main() − this method is called at the beginning of a Java program.

• String args[ ] − args parameter is an instance array of class String
                            

Question-54. What are wrapper classes ?

Answer- These are classes that allow primitive types to be accessed as objects. Example: Integer, Character, Double, Boolean etc.

Question-55. What is the difference between static and non-static variables ?

Answer- A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.

Question-56. What are use cases ?

Answer- It is part of the analysis of a program and describes a situation that a program might encounter and what behavior the program should exhibit in that circumstance.

Question-57. Can we define private and protected modifiers for variables in interfaces ?

Answer- No, they are implicitly public.

Question-58. When can an object reference be cast to an interface reference ?

Answer- An object reference can be cast to an interface reference when the object implements the referenced interface.

Question-59. What is package ?

Answer- A package is a group of similar type of classes interfaces and sub-packages. It provides access protection and removes naming collision.

Question-60. Do I need to import java.lang package any time? Why ?

Answer- No. It is by default loaded internally by the JVM.

Question-61. Can I import same package/class twice? Will the JVM load the package twice at runtime ?

Answer- One can import the same package or same class multiple times. Neither compiler nor JVM complains about it. But the JVM will internally load the class only once no matter how many times you import the same class.

Question-62. What is static import ?

Answer- By static import, we can access the static members of a class directly, there is no to qualify it with the class name.

Quedtion-63. What is Exception Handling

Answer- Exception Handling is a mechanism to handle runtime errors.It is mainly used to handle checked exceptions.

Question-64. What is difference between Checked Exception and Unchecked Exception ?

Answer-
 1)Checked Exception

The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions 
e.g.IOException,SQLException etc. Checked exceptions are checked at compile-time.

2)Unchecked Exception

The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException,
NullPointerException etc. Unchecked exceptions are not checked at compile-time.

Question-65. What is the base class for Error and Exception ?

Answer- Throwable.

Question-66. Is it necessary that each try block must be followed by a catch block ?

Answer- It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method.

Question-67. What is finally block? ?

Answer- finally block is a block that is always executed.

Question-68. Can finally block be used without catch ?

Answer- Yes, by try block. finally must be followed by either try or catch.

Question-69. Is there any case when finally will not be executed ?

Answer- finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).

Question-70. What is difference between throw and throws ?

Answer-
throw:  It is explicitly used to throw an exception.
    throw is followed by an instance.
    It is used within a method.
    You cannot throw multiple exceptions.

throws: Used to declare an exception.
      It is followed by a class.
      Used within a method signature.
You can declare multiple exception e.g. public void method()throws IOException,SQLException.

Question-71. What is NullPointerException ?

Answer- A NullPointerException is thrown when calling the instance method of a null object, accessing or modifying the field of a null object etc.

Question-72. When is ArrayStoreException thrown ?

Answer- When copying elements between different arrays, if the source or destination arguments are not arrays or their types are not compatible, an ArrayStoreException will be thrown.

Question-73. When is ArithmeticException thrown ?

Answer- The ArithmeticException is thrown when integer is divided by zero or taking the remainder of a number by zero. It is never thrown in floating-point operations.

Question-74. What is the difference between an Interface and Abstract Class ?

Answer- An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation.

Question-75. What is the difference between an error and an exception ?

Answer- An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. Exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist.

Question-76. What is dynamic binding(late binding) ?

Answer- Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding means that the code associated with a given procedure call is not known until the time of the call at run-time.

Question-77. What are the advantages of ArrayLists over arrays ?

Answer- ArrayList can grow dynamically and provides more powerful insertion and search mechanisms than arrays.

Question-78. Why deletion in LinkedList is faster than ArrayList ?

Answer- Deletion in linked list is fast because it involves only updating the next pointer in the node before the deleted node and updating the previous pointer in the node after the deleted node.

Question-79. How do you decide when to use ArrayList and LinkedList ?

Answer- If you need to frequently add and remove elements from the middle of the list and only access the list elements sequentially, then LinkedList should be used. If you need to support random access, without inserting or removing elements from any place other than the end, then ArrayList should be used.

Question-80. What is dot operator ?

Answer- The dot operator(.) is used to access the instance variables and methods of class objects. It is also used to access classes and sub-packages from a package.

Question-81. What is type casting ?

Answer- Type casting means treating a variable of one type as though it is another type.

Question-82. Describe the lifecycle of a thread ?

Answer- A thread is a execution in a program. The life cycle of a thread include −
• Newborn state
• Runnable state
• Running state
• Blocked state
• Dead state
                            

Question-83. Does Java allow Default Arguments ?

Answer- No, Java does not allow Default Arguments.

Question-84. Define Network Programming ?

Answer- It refers to writing programs that execute across multiple devices (computers), in which the devices are all connected to each other using a network.

Question-85. What is Socket ?

Answer- Sockets provide the communication mechanism between two computers using TCP. A client program creates a socket on its end of the communication and attempts to connect that socket to a server.

Question-86. Advantages and Disadvantages of Sockets ?

Answer-
Advantages: Sockets are flexible and sufficient. Efficient socket based programming can be easily implemented
 for general communications. It cause low network traffic.
Disadvantages: Socket based communications allows only to send packets of raw data between applications. Both the client-side and server-side have to provide mechanisms to make the data useful in any way.

Question-87. Which class is used by server applications to obtain port and listen to client requests ?

Answer- java.net.ServerSocket class is used by server applications to obtain a port and listen for client requests

Question-88. Why Generics are used is Java ?

Answer- Generics provide compile-time type safety that allows programmers to catch invalid types at compile time. Java Generic methods and generic classes enable programmers to specify, with a single method declaration, a set of related methods or, with a single class declaration, a set of related types.

Question-89. What is daemon thread ?

Answer- Daemon thread is a low priority thread, which runs intermittently in the back ground doing the garbage collection operation for the java runtime system.

Question-90. Which method is used to create daemon thread? ?

Answer- setDaemon method is used to create a daemon thread.

Question-91. What is the GregorianCalender class ?

Answer- The GregorianCalendar provides support for traditional Western calendars.

Question-92. What is an enumeration ?

Answer- An enumeration is an interface containing methods for accessing the underlying data structure from which the enumeration is obtained. It allows sequential access to all the elements stored in the collection.

Question-93. What is the difference between Path and Classpath ?

Answer- Path and Classpath are operating system level environment variales. Path is defines where the system can find the executables(.exe) files and classpath is used to specify the location of .class files.

Question-94. What is constructor chaining and how is it achieved in Java? ?

Answer- A child object constructor always first needs to construct its parent. In Java it is done via an implicit call to the no-args constructor as the first statement.

Question-95. What is the difference between innerclass and nested class ?

Answer- When a class is defined within a scope of another class, then it becomes inner class. If the access modifier of the inner class is static, then it becomes nested class.

Question-96. Why restrictions are placed on method overriding ?

Answer- Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides.

Question-97. If a method is declared as protected, where may the method be accessed ?

Answer- A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared.

Question-98. What are order of precedence and associativity and how they are used ?

Answer- Order of precedence determines the order in which operators are evaluated in expressions. Associativity determines whether an expression is evaluated left-to-right or right-to-left.

Question-99. What is downcasting ?

Answer- It is the casting from a general to a more specific type, i.e. casting down the hierarchy.

Question-100. Define class ?

Answer- A class is a blue print from which individual objects are created. A class can contain fields and methods to describe the behavior of an object.

Question-101. What is Local Variable ?

Answer- Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and it will be destroyed when the method has completed.

Question-102. What is Instance Variable? ?

Answer- Instance variables are variables within a class but outside any method. These variables are instantiated when the class is loaded.

Question-103. What is Class Variable ?

Answer- These are variables declared with in a class, outside any method, with the static keyword.

Question-104. What do you mean by access modifier ?

Java provides access modifiers to set access levels for classes, variables, methods and constructors. A member has package or default accessibility when no accessibility modifier is specified.

Question-105. What is protected access modifier ?

Answer- Variables, methods and constructors which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.

Question-106. Why is String class considered immutable ?

Answer- The String class is immutable, so that once it is created a String object cannot be changed. Since String is immutable it can safely be shared between many threads ,which is considered very important for multithreaded programming.

Question-107. Why is StringBuffer called mutable ?

Answer- The String class is considered as immutable, so that once it is created a String object cannot be changed. If there is a necessity to make alot of modifications to Strings of characters then StringBuffer should be used.

Question-108. What is difference between StringBuffer and StringBuilder class? ?

Answer- Use StringBuilder whenever possible because it is faster than StringBuffer. But, if thread safety is necessary then use StringBuffer objects.

Question-109. What is finalize() method ?

Answer- It is possible to define a method that will be called just before an object's final destruction by the garbage collector. This method is called finalize( ), and it can be used to ensure that an object terminates cleanly.

Question-110. What is an Exception ?

Answer- An exception is a problem that arises during the execution of a program. Exceptions are caught by handlers positioned along the thread's method invocation stack.

Question-111. What do you mean by Checked Exceptions ?

Answer- It is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation.

Question-112. Explain Runtime Exceptions ?

Answer- It is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation.

Question-113. When super keyword is used ?

Answer- If the method overrides one of its superclass's methods, overridden method can be invoked through the use of the keyword super. It can be also used to refer to a hidden field.

Question-114. What is Polymorphism ?

Answer- Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.

Question-115. What is abstraction ?

Answer- It refers to the ability to make a class abstract in OOP. It helps to reduce the complexity and also improves the maintainability of the system.

Question-116. What is encapsulation? ?

Answer- It is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. Therefore encapsulation is also referred to as data hiding.

Question-117. What is Abstract class ?

Answer- These classes cannot be instantiated and are either partially implemented or not at all implemented. This class contains one or more abstract methods which are simply method declarations without a body.

Question-118. When Abstract methods are used ?

Answer- If you want a class to contain a particular method but you want the actual implementation of that method to be determined by child classes, you can declare the method in the parent class as abstract.

Question-119. What is an Interface ?

Answer- An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface.

Question-120. What do you mean by Multithreaded Program ?

Answer- A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.

Question-121. What is an applet ?

Answer- An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java application because it has the entire Java API at its disposal.

Question-122. What is JIT compiler ?

Answer- Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation. Here the term “compiler” refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.

Question-123. Why Java is considered dynamic ?

Answer- It is designed to adapt to an evolving environment. Java programs can carry extensive amount of run-time information that can be used to verify and resolve accesses to objects on run-time.

Question-124. What is Singleton class ?

Answer- Singleton class control object creation, limiting the number to one but allowing the flexibility to create more objects if the situation changes.

Question-125. How is finally used under Exception Handling ?

Answer- The finally keyword is used to create a block of code that follows a try block. A finally block of code always executes, whether or not an exception has occurred.

Question-126. When is super keyword used ?

Answer- If the method overrides one of its superclass's methods, overridden method can be invoked through the use of the keyword super. It can be also used to refer to a hidden field.

Question-127. Explain garbage collection in Java ?

Answer- It uses garbage collection to free the memory. By cleaning those objects that is no longer reference by any of the program.

Question-128. Define immutable object ?

Answer- An immutable object can’t be changed once it is created.

Question-129. Define the usage of this() with constructors ?

Answer- It is used with variables or methods and used to call constructer of same class.

Question-130. Define TreeSet ?

Answer- It is a Set implemented when we want elements in a sorted order.

Question-131. Explain Set Interface ?

Answer- It is a collection of element which cannot contain duplicate elements. The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited.

Question-132. What is the difference between object oriented programming language and object based programming language ?

Answer- Object based programming languages follow all the features of OOPs except Inheritance. JavaScript is an example of object based programming languages.

Question-133. What is the purpose of default constructor ?

Answer- The java compiler creates a default constructor only if there is no constructor in the class.

Question-134. Define function overloading ?

Answer- If a class has multiple functions by same name but different parameters, it is known as Method Overloading.

Question-135. Define function overriding ?

Answer- If a subclass provides a specific implementation of a method that is already provided by its parent class, it is known as Method Overriding.

Question-136. Why vector class is used ?

Answer- The Vector class provides the capability to implement a growable array of objects. Vector proves to be very useful if you don't know the size of the array in advance, or you just need one that can change sizes over the lifetime of a program.

Question-137. What is the difference between window and frame ?

Answer- The Frame class extends Window to define a main application window that can have a menu bar.

Question-138. What is the difference between paint() and repaint() methods ?

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

Question-139. What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy ?

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

Question-140. What is Serialization and Deserialization ?

Answer- Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects.

Question-141. Explain the use of subclass in a Java Program ?

Answer- Sub class inherits all the public and protected methods and the implementation. It also inherits all the default modifier methods and their implementation.

Question-142. What is the Collections API ?

Answer- The Collections API is a set of classes and interfaces that support operations on collections of objects.

Question-143. The immediate superclass of Applet class ?

Answer- Panel is the immediate superclass. A panel provides space in which an application can attach any other component, including other panels.

Question-144. What is Garbage Collection ?

Answer- Garbage collection is a process of reclaiming the runtime unused objects.It is performed for memory management.

Question-145. What is gc()?

Answer- gc() is a daemon thread.gc() method is defined in System class that is used to send request to JVM to perform garbage collection.

Question-146. What is the purpose of finalize() method ?

Answer- finalize() method is invoked just before the object is garbage collected.It is used to perform cleanup processing.

Question-147. an unrefrenced objects be refrenced again ?

Answer- Yes.

Question-148. What kind of thread is the Garbage collector thread ?

ANswer- Daemon thread.

Question-149. What is difference between final, finally and finalize ?

Answer-
final: final is a keyword, final can be variable, method or class.You, can't change the value of final variable, 
can't override final method, can't inherit final class.

finally: finally block is used in exception handling. finally block is always executed.
finalize():finalize() method is used in garbage collection.finalize() method is invoked just before the object is garbage collected.The finalize() method can be used to perform any cleanup processing.

Question-150. What is the purpose of the Runtime class ?

Answer- The purpose of the Runtime class is to provide access to the Java runtime system.

Question-151. How will you invoke any external process in Java ?

Answer- By Runtime.getRuntime().exec(?) method.

Question-152. What an I/O filter ?

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

Question-153. What is transient keyword ?

Answer- If you define any data member as transient,it will not be serialized.

Question-154. What is Externalizable ?

Answer- Externalizable interface is used to write the state of an object into a byte stream in compressed format.It is not a marker interface.

Question-155. What is the difference between Serializalble and Externalizable interface ?

Answer- Serializable is a marker interface but Externalizable is not a marker interface.When you use Serializable interface, your class is serialized automatically by default. But you can override writeObject() and readObject() two methods to control more complex object serailization process. When you use Externalizable interface, you have a complete control over your class's serialization process.

Question-156. Which containers use a FlowLayout as their default layout ?

Answer- The Panel and Applet classes use the FlowLayout as their default layout.

Question-157. What are peerless components ?

Answer- The peerless components are called light weight components.

Question-158. is the difference between a Scrollbar and a ScrollPane?

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

Question-159. What is a lightweight component ?

Answer- Lightweight components are the one which doesn?t go with the native call to obtain the graphical units. They share their parent component graphical units to render them. For example, Swing components.

Question-160. What is a heavyweight component ?

Answer- For every paint call, there will be a native call to get the graphical units.For Example, AWT.

Question-162. Can you write a Java class that could be used both as an applet as well as an application ?

Answer- Yes. Add a main() method to the applet.

Question-163. What is multithreading ?

Answer- Multithreading is a process of executing multiple threads simultaneously. Its main advantage is:
Threads share the same address space.
Thread is lightweight.
Cost of communication between process is low.
                            

Question-164. What is thread ?

Answer- A thread is a lightweight subprocess.It is a separate path of execution.It is called separate path of execution because each thread runs in a separate stack frame.

Question-165. What is the difference between preemptive scheduling and time slicing ?

Answer- Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

Question-166. What does join() method ?

Answer- The join() method waits for a thread to die. In other words, it causes the currently running threads to stop executing until the thread it joins with completes its task.

Question-167. Is it possible to start a thread twice ?

Answer- No, there is no possibility to start a thread twice. If we does, it throws an exception.

Question-168. Can we call the run() method instead of start() ?

Answer- yes, but it will not work as a thread rather it will work as a normal object so there will not be context-switching between the threads.

Question-169. What about the daemon threads ?

Answer- The daemon threads are basically the low priority threads that provides the background support to the user threads. It provides services to the user threads.

Question-170. Can we make the user thread as daemon thread if thread is started ?

Answer- No, if you do so, it will throw IllegalThreadStateException

Question-171. What is shutdown hook ?

Answer- The shutdown hook is basically a thread i.e. invoked implicitely before JVM shuts down. So we can use it perform clean up resource.

Question-172. When should we interrupt a thread ?

Answer- We should interrupt a thread if we want to break out the sleep or wait state of a thread.

Question-173. What is synchronization ?

Answer- Synchronization is the capabilility of control the access of multiple threads to any shared resource.It is used:
To prevent thread interference.
To prevent consistency problem.
                            

Question-174. What is the purpose of Synchronized block ?

Answer- Synchronized block is used to lock an object for any shared resource. Scope of synchronized block is smaller than the method.

Question-175. Can Java object be locked down for exclusive use by a given thread ?

Answer- Yes. You can lock an object by putting it in a "synchronized" block. The locked object is inaccessible to any thread other than the one that explicitly claimed it.

Question-176. What is static synchronization ?

Answer- If you make any static method as synchronized, the lock will be on the class not on object.

Question-177. What is the difference between notify() and notifyAll() ?

Answer- The notify() is used to unblock one waiting thread whereas notifyAll() method is used to unblock all the threads in waiting state.

Question-178. What is deadlock ?

Answer- Deadlock is a situation when two threads are waiting on each other to release a resource. Each thread waiting for a resource which is held by the other waiting thread.

Question-179. What is the difference between ArrayList and Vector ?

Answer-
ArrayList Vector
1) ArrayList is not synchronized. 1) Vector is synchronized.
2) ArrayList is not a legacy class. 2) Vector is a legacy class.
3) ArrayList increases its size by 50% of the array size. 3) Vector increases its size by doubling the array size.

Question-180. What is the difference between ArrayList and LinkedList ?

Answer-
ArrayList LinkedList
1) ArrayList uses a dynamic array. 1) LinkedList uses doubly linked list.
2) ArrayList is not efficient for manipulation because a lot of shifting is required. 2) LinkedList is efficient for manipulation.
3) ArrayList is better to store and fetch data. 3) LinkedList is better to manipulate data.

Question-181. What is the difference between Iterator and ListIterator ?

Answer- Iterator traverses the elements in forward direction only whereas ListIterator traverses the elements in forward and backward direction.
  
Iterator ListIterator
1) Iterator traverses the elements in forward direction only. 1) ListIterator traverses the elements in backward and forward directions both.
2) Iterator can be used in List, Set and Queue. 2) ListIterator can be used in List only.

Question-182. What is the difference between Iterator and Enumeration ?

Answer-
Iterator Enumeration
1) Iterator can traverse legacy and non-legacy elements. 1) Enumeration can traverse only legacy elements.
2) Iterator is fail-fast. 2) Enumeration is not fail-fast.
3) Iterator is slower than Enumeration. 3) Enumeration is faster than Iterator.

Question-183. What is the difference between List and Set ?

Answer- List can contain duplicate elements whereas Set contains only unique elements.

Question-184. What is the difference between HashSet and TreeSet ?

Answer- HashSet maintains no order whereas TreeSet maintains ascending order.

Question-185. What is the difference between Set and Map ?

Answer- Set contains values only whereas Map contains key and values both.

Question-186. What is the difference between HashSet and HashMap ?

Answer- HashSet contains only values whereas HashMap contains entry(key,value). HashSet can be iterated but HashMap need to convert into Set to be iterated.

Question-187. What is the difference between HashMap and TreeMap ?

Answer- HashMap maintains no order but TreeMap maintains ascending order.

Question-188. What is the difference between HashMap and Hashtable ?

Answer-
  
HashMap Hashtable
1) HashMap is not synchronized. 1) Hashtable is synchronized.
2) HashMap can contain one null key and multiple null values.2) Hashtable cannot contain any null key or null value.

Question-190. What is the difference between Collection and Collections ?

Answer- Collection is an interface whereas Collections is a class. Collection interface provides normal functionality of data structure to List, Set and Queue. But, Collections class is to sort and synchronize collection elements.

Question-191. What is the difference between Comparable and Comparator ?

Answer-
  
Comparable Comparator
1) Comparable provides only one sort of sequence. 1) Comparator provides multiple sort of sequences.
2) It provides one method named compareTo(). 2) It provides one method named compare().
3) It is found in java.lang package. 3) it is found in java.util package.
4) If we implement Comparable interface, actual class is modified.4) Actual class is not modified

Question-192. What is the advantage of Properties file ?

Answer- If you change the value in properties file, you don't need to recompile the java class. So, it makes the application easy to manage.

Question-193. What does the hashCode() method ?

Answer- The hashCode() method returns a hash code value (an integer number). The hashCode() method returns the same integer number, if two keys (by calling equals() method) are same. But, it is possible that two hash code numbers can have different or same keys.

Question-194. Why we override equals() method ?

Answer- The equals method is used to check whether two objects are same or not. It needs to be overridden if we want to check the objects based on property. For example, Employee is a class that has 3 data members: id, name and salary. But, we want to check the equality of employee object on the basis of salary. Then, we need to override the equals() method.

Question-195. How to synchronize List, Set and Map elements ?

Answer- Yes, Collections class provides methods to make List, Set or Map elements as synchronized:
public static List synchronizedList(List l){}
public static Set synchronizedSet(Set s){}
public static SortedSet synchronizedSortedSet(SortedSet s){}
public static Map synchronizedMap(Map m){}
public static SortedMap synchronizedSortedMap(SortedMap m){}

Question-196. What is the advantage of generic collection ?

Answer- If we use generic class, we don't need typecasting. It is typesafe and checked at compile time.

Question-197. What is hash-collision in Hashtable and how it is handled in Java ?

Answer- Two different keys with the same hash value is known as hash-collision. Two different entries will be kept in a single hash bucket to avoid the collision.

Question-198. What is the Dictionary class ?

Answer- The Dictionary class provides the capability to store key-value pairs.

Question-199. What is the default size of load factor in hashing based collection ?

Answer- The default size of load factor is 0.75. The default capacity is computed as initial capacity * load factor. For example, 16 * 0.75 = 12. So, 12 is the default capacity of Map.

Question-200. What is JDBC ?

Answer- JDBC is a Java API that is used to connect and execute query to the database. JDBC API uses jdbc drivers to connects to the database.

Question-201. What is JDBC Driver ?

Answer- JDBC Driver is a software component that enables java application to interact with the database.There are 4 types of JDBC drivers:
JDBC-ODBC bridge driver
Native-API driver (partially java driver)
Network Protocol driver (fully java driver)
Thin driver (fully java driver)
                            

Question-202. What are the steps to connect to the database in java ?

Answer- Registering the driver class Creating connection Creating statement Executing queries Closing connection

Question-203. What are the JDBC API components ?

Answer- The java.sql package contains interfaces and classes for JDBC API.
Interfaces:

Connection
Statement
PreparedStatement
ResultSet
ResultSetMetaData
DatabaseMetaData
CallableStatement etc.
Classes:

DriverManager
Blob
Clob
Types
SQLException etc.
                            

Question-204. What are the JDBC statements ?

Answer- There are 3 JDBC statements. Statement PreparedStatement CallableStatement

Question-205. What is the difference between Statement and PreparedStatement interface ?

Answer- In case of Statement, query is complied each time whereas in case of PreparedStatement, query is complied only once. So performance of PreparedStatement is better than Statement.

Questiok-206. How can we execute stored procedures and functions ?

Answer- By using Callable statement interface, we can execute procedures and functions.

Question-207. What is the role of JDBC DriverManager class ?

Answer- The DriverManager class manages the registered drivers. It can be used to register and unregister drivers. It provides factory method that returns the instance of Connection.

Question-208. What does the JDBC Connection interface ?

Answer- The Connection interface maintains a session with the database. It can be used for transaction management. It provides factory methods that returns the instance of Statement, PreparedStatement, CallableStatement and DatabaseMetaData.

Question-209. What does the JDBC ResultSet interface ?

Answer- The ResultSet object represents a row of a table. It can be used to change the cursor pointer and get the information from the database.

Question-210. What does the JDBC ResultSetMetaData interface ?

Answer- The ResultSetMetaData interface returns the information of table such as total number of columns, column name, column type etc.

Question-211. What does the JDBC DatabaseMetaData interface ?

Answer- The DatabaseMetaData interface returns the information of the database such as username, driver name, driver version, number of tables, number of views etc.

Question-212. Which interface is responsible for transaction management in JDBC ?

Answer- The Connection interface provides methods for transaction management such as commit(), rollback() etc.

Question-213. What is batch processing and how to perform batch processing in JDBC ?

Answer- By using batch processing technique in JDBC, we can execute multiple queries. It makes the performance fast.

Question-214. How can we store and retrieve images from the database ?

Answer- By using PreparedStatement interface, we can store and retrieve images.
Tutors
  • Manjit Singh

  • Umesh Kumar

  • Sandeep Kaur

  • Ramandeep Singh

  • Sunil Sharma

  • Vijay Mahajan

  • Gurpreet Kaur

Our Skills
  • Java 100%
  • Android 95%
  • IOS 85%
  • PHP 95%
  • Design 90%
  • HTML CSS 95%
  • WordPress 95%
  • Magento 95%
  • UI 95%
FOLLOW US ON
facebook link  linkedin link  google plus link  twitter link  website rss link
Placements Done Over 5000
WE ACCEPT ONLINE PAYMENTS
online payment
PAY ONLINE
online payment