500 Question Asked in Core Java Interview
500 Question Asked in Core Java Interview
500 Question Asked in Core Java Interview
show Answer
Ans. A cookie is a small piece of text stored on a user's computer by the browser for a specific domain.
Commonly used for authentication, storing site preferences, and server session identification.
Q2. Can we reduce the visibility of the overridden method ?show Answer
Ans. No
Q3. What are different types of inner classes ?show Answer
Ans. Simple Inner Class, Local Inner Class, Anonymous Inner Class , Static Nested Inner Class.
Q4. Difference between TreeMap and HashMap ?show Answer
Ans. They are different the way they are stored in memory. TreeMap stores the Keys in order whereas
HashMap stores the key value pairs randomly.
Q5. What is the difference between List, Set and Map ?show Answer
Ans. List - Members are stored in sequence in memory and can be accessed through index.
Set - There is no relevance of sequence and index. Sets doesn't contain duplicates whereas multiset can
have duplicates. Map - Contains Key , Value pairs.
Q6. Difference between Public, Private, Default and Protected ?
Answer
Ans. Private - Not accessible outside object scope.
Public - Accessible from anywhere.
Default - Accessible from anywhere within same package.
Protected - Accessible from object and the sub class objects.
Q7. What is servlet Chaining ?show Answer
Ans. Multiple servlets serving the request in chain.
Q8. What are the Wrapper classes available for primitive types ?show Answer
Ans. boolean - java.lang.Boolean
byte - java.lang.Byte
char - java.lang.Character
double - java.lang.Double
float - java.lang.Float
int - java.lang.Integer
long - java.lang.Long
short - java.lang.Short
void - java.lang.Void
Q9. What are concepts introduced with Java 5 ?show Answer
Ans. Generics , Enums , Autoboxing , Annotations and Static Import.
Q10. Does Constructor creates the object ?show Answer
Ans. New operator in Java creates objects. Constructor is the later step in object creation. Constructor's
job is to initialize the members after the object has reserved memory for itself.
Q11. Can static method access instance variables ?show Answer
Ans. Though Static methods cannot access the instance variables directly, They can access them using
instance handler.
Q12. Does Java support Multiple Inheritance ?show Answer
Ans. Interfaces does't facilitate inheritance and hence implementation of multiple interfaces doesn't make
multiple inheritance. Java doesn't support multiple inheritance.
Q13. Difference between == and .equals() ?show Answer
Ans. "equals" is the member of object class which returns true if the content of objects are same whereas
"==" evaluate to see if the object handlers on the left and right are pointing to the same object in memory.
HashMap allows null values whereas Hashtable doesnt allow null values.
if(a == b) {
System.out.println ("TRUE");
} else {
System.out.println ("FALSE");
}show Answer
Ans. FALSE.
== operator compares object references, a and b are references to two different objects, hence the
FALSE. .equals method is used to compare string object content.
Q26. There are two objects a and b with same hashcode. I am inserting these two objects inside a
hashmap.
hMap.put(a,a);
hMap.put(b,b);
where a.hashCode()==b.hashCode()
Now tell me how many objects will be there inside the hashmap?show Answer
Ans. There can be two different elements with the same hashcode. When two elements have the same
hashcode then Java uses the equals to further differentation. So there can be one or two objects
depending on the content of the objects.
Q27. Difference between long.Class and Long.TYPE ?show Answer
Ans. They both represent the long primitive type. They are exactly the same.
Q28. Does Java provides default copy constructor ?show Answer
Ans. No
Q29. What are the common uses of "this" keyword in java ?show Answer
Ans. "this" keyword is a reference to the current object and can be used for following -
2). A thread is a path of code execution in the program, which has its own local variables, program
counter(pointer to current execution being executed) and lifetime.
3. When the JavaVirtual Machine (JavaVM, or just VM) is started by the operating system, a new process
is created. Within that process, many threads can be created.
4. Consider an example : when you open Microsoft word in your OS and you check your task manger
then you can see this running program as a process. now when you write something in opened word
document, then it performs more than one work at same time like it checks for the correct spelling, it
formats the word you enter , so within that process ( word) , due to different path execution(thread) all
different works are done at same time.
5. Within a process , every thread has independent path of execution but there may be situation where
two threads can interfere with each other then concurrency and deadlock come is picture.
6. like two process can communicate ( ex:u open an word document and file explorer and on word
document you drag and drop another another file from file explorer), same way two threads can also
communicate with each other and communication with two threads is relatively low.
7. Every thread in java is created and controlled by unique object of java.lang.Thread class.
8. prior to jdk 1.5, there were lack in support of asynchronous programming in java, so in that case it was
considered that thread makes the runtime environment asynchronous and allow different task to perform
concurrently.
Q31. How can we run a java program without making any object?show Answer
Ans. By putting code within either static method or static block.
Q32. Explain multithreading in Java ?show Answer
Ans. 1. Multithreading provides better interaction with the user by distribution of task
2. Threads in Java appear to run concurrently, so it provides simulation for simultaneous activities.
The processor runs each thread for a short time and switches among the threads to simulate simultaneous execution (context-switching) and it make appears that each thread has its own processor.By
using this feature, users can make it appear as if multiple tasks are occurring simultaneously when, in
fact, each is
running for only a brief time before the context is switched to the next thread.
class B {
void test() {
System.out.println("test() method");
}
}
class C extends A, B {
}
So which test() method C class will take? As A & B class test() methods are different , So here we would
Facing Ambiguity.
Q41. What is the difference between time slicing and preemptive scheduling ?show Answer
Ans. In preemptive scheduling, highest priority task continues execution till it enters a not running state or
a higher priority task comes into existence. In time slicing, the task continues its execution for a
predefined period of time and reenters the pool of ready tasks.
Q42. What is the initial state of a thread when it is created and started?show Answer
Ans. Ready state.
Q43. What one should take care of, while serializing the object?
show Answer
Ans. One should make sure that all the included objects are also serializable. If any of the objects is not
serializable then it throws a NotSerializable Exception.
Q44. What is a String Pool ?show Answer
Ans. String pool (String intern pool) is a special storage area in Java heap. When a string is created and if
the string already exists in the pool, the reference of the existing string will be returned, instead of
creating a new object and returning its reference.
Q45. Why is String immutable in Java ?show Answer
Ans. 1. String Pool
When a string is created and if the string already exists in the pool, the reference of the existing string will
be returned, instead of creating a new object. If string is not immutable, changing the string with one
reference will lead to the wrong value for the other references.
If string is not immutable, One can change its hashcode and hence not fit to be cached.
3. Security
String is widely used as parameter for many java classes, e.g. network connection, opening files, etc.
Making it mutable might possess threats due to interception by the other code segment.
Q46. what is the use of cookie and session ? and What is the difference between them ?show
Answer
Ans. Cookie and Session are used to store the user information. Cookie stores user information on client
side and Session does it on server side. Primarily, Cookies and Session are used for authentication, user
preferences, and carrying information across multiple requests. Session is meant for the same purpose
as the cookie does. Session does it on server side and Cookie does it on client side. One more thing that
quite differentiates between Cookie and Session. Cookie is used only for storing the textual information.
Session can be used to store both textual information and objects.
Q47. Which are the different segments of memory ?
show Answer
Ans. 1. Stack Segment - contains local variables and Reference variables(variables that hold the address
of an object in the heap)
2. Heap Segment - contains all created objects in runtime, objects only plus their object attributes
(instance variables)
3. Code Segment - The segment where the actual compiled Java bytecodes resides when loaded
Q48. Which memory segment loads the java code ?show Answer
Ans. Code segment.
Q49. which containers use a border Layout as their default layout ?show Answer
Ans. The window, Frame and Dialog classes use a border layout as their default layout.
Q50. Can a lock be acquired on a class ?show Answer
Ans. Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object.
Q51. What state does a thread enter when it terminates its processing?show Answer
Ans. When a thread terminates its processing, it enters the dead state.
Q52. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?show
Answer
Ans. Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits,
it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16
uses 16-bit and larger bit patterns.
Q53. Does garbage collection guarantee that a program will not run out of memory?show Answer
Ans. Garbage collection does not guarantee that a program will not run out of memory. It is possible for
programs to use up memory resources faster than they are garbage collected. It is also possible for
programs to create objects that are not subject to garbage collection
Q54. What is an object's lock and which object's have locks?show Answer
Ans. An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to
the object. A thread may execute a synchronized method of an object only after it has acquired the
object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object.
Q55. What is casting?show Answer
Ans. There are two types of casting, casting between primitive numeric types and casting between object
references. Casting between numeric types is used to convert larger values, such as double values, to
smaller values, such as byte values. Casting between object references is used to refer to an object by a
compatible class, interface, or array type reference
Q56. What restrictions are placed on method overriding?show Answer
Ans. Overridden methods must have the same name, argument list, and return type. The overriding
method may not limit the access of the method it overrides. The overriding method may not throw any
exceptions that may not be thrown by the overridden method.
Q57. How does a try statement determine which catch clause should be used to handle an
exception?show Answer
Ans. When an exception is thrown within the body of a try statement, the catch clauses of the try
statement are examined in the order in which they appear. The first catch clause that is capable of
handling the exception is executed. The remaining catch clauses are ignored.
Q58. Describe what happens when an object is created in Java ?show Answer
Ans. 1. Memory is allocated from heap to hold all instance variables and implementation-specific data of
the object and its superclasses. Implemenation-specific data includes pointers to class and method data.
2. The instance variables of the objects are initialized to their default values.
3. The constructor for the most derived class is invoked. The first thing a constructor does is call the
constructor for its superclasses. This process continues until the constructor for java.lang.Object is called,
as java.lang.Object is the base class for all objects in java.
4. Before the body of the constructor is executed, all instance variable initializers and initialization blocks
are executed. Then the body of the constructor is executed. Thus, the constructor for the base class
completes first and constructor for the most derived class completes last.
Q59. What is the difference between StringBuffer and String class ?show Answer
Ans. A string buffer implements a mutable sequence of characters. A string buffer is like a String, but can
be modified. At any point in time it contains some particular sequence of characters, but the length and
content of the sequence can be changed through certain method calls. The String class represents
character strings. All string literals in Java programs, such as "abc" are constant and implemented as
instances of this class; their values cannot be changed after they are created.
Q60. Describe, in general, how java's garbage collector works ?show Answer
Ans. The Java runtime environment deletes objects when it determines that they are no longer being
used. This process is known as garbage collection. The Java runtime environment supports a garbage
collector that periodically frees the memory used by
objects that are no longer needed. The Java garbage collector is a mark-sweep garbage collector that
scans Java's dynamic memory areas for objects, marking those that are referenced. After all possible
paths to objects are investigated, those objects that are not marked (i.e. are not referenced) are known to
be garbage and are collected.
Q61. What is RMI ?show Answer
Ans. RMI stands for Remote Method Invocation. Traditional approaches to executing code on other
machines across a network have been confusing as well as tedious and error-prone to implement. The
nicest way to think about this problem is that some object happens to live on another machine, and that
you can send a message to the remote object and get a result as if the object lived on your local machine.
This simplification is exactly what Java Remote Method Invocation (RMI) allows you to do.
Q62. What is JDBC? Describe the steps needed to execute a SQL query using JDBC.show Answer
Ans. The JDBC is a pure Java API used to execute SQL statements. It provides a set of classes and
interfaces that can be used by developers to write database applications.
override the superclasses constructor, which would be possible if they were inherited. By giving the
developer the ability to override a superclasses constructor you would erode the encapsulation abilities of
the language.
Q64. What is JSON ?show Answer
Ans. JSON is "JavaScript Object Notation", primarily used for client-server or server-server
communication. Its a much lighter and readable alternative to XML. JSON is language independent and is
easily parse-able in all programming languages.
Q65. What is the role of JSON.stringify ?show Answer
Ans. JSON.stringify() turns an object into a JSON text and stores that JSON text in a string.
{"name":"xyz","gender":"male";"age":30}
Q66. When were Enums introduced in Java ?show Answer
Ans. Enums were introduced with java 5.
Q67. Which function is used to convert a JSON text into an object ?show Answer
Ans. eval
Q68. Which data types are supported by JSON ?show Answer
Ans. Number
String
Boolean
Array
Object
null
Q69. What are the benefits of JSON over XML ?show Answer
Ans. Lighter and faster than XML as on-the-wire data format
Object Representation - Information is presented in object notations and hence better understandable.
Easy to parse and conversion to objects for information consumption.
Support multiple data types - JSON supports string, number, array, boolean whereas XML data are all
string.
Ans. MVC2
Q74. What is an API ( Application Programming Interface ) ?show Answer
Ans. An API is a kind of technical contract which defines functionality that two parties must provide: a
service provider (often called an implementation) and an application. an API simply defines services that
a service provider (i.e., the implementation) makes available to applications.
Q75. What is URL?
show Answer
Ans. URL is Uniform Resource Locator which is representation of HTTP address.
Q76. Explain features of struts2 ?show Answer
Ans. 1) It is an Action based MVC based framework which has adopt mvc2.
2) Struts2 is a pull-MVC (or MVC2) framework where action takes the role of the model rather than the
controller. The pull concepts means views ability to pull data from an action, rather than having a
separate model object available.
3) The Model View-Controller pattern in Struts2 is implemented with five core components actions,
interceptors, value stack / OGNL, result types and results / view technologies.
7) Theme based tag libraries integrated with struts tag as well as support of Ajax tag.
8) Can have various view options like jsp, velocity, freemarker etc.
9) We can embed plugin through which we can modify and extend framework features.
Q77. What is HTTP ?show Answer
Ans. HTTP or Hypertext Transfer Protocol is internet protocol for tranmission of hypertext ( text with meta
data ) over internet.
Q78. what is content negotiation?show Answer
Ans. Suppose we want to visit a site for any information, information can be represented in different
languages like English,German or may be other and their format for presentation can also differ from
HTML to PDF or may be Plain text. In this case when an client makes an HTTP request to a server, client
can also specify the media types here. Client can specify what it can accept back from host and on the
basis of availability the host will return to the client. This is called content negotiation because client and
server negotiated on the language and format of the content to be shared.
Q79. Is tomcat an application or Web server ?show Answer
Ans. Application server.
Q80. Is Apache an application or Web server ?show Answer
Ans. Web server.
Q81. What are the default or implicitly assigned values for data types in java ?show Answer
Ans. boolean ---> false
byte ----> 0
short ----> 0
int -----> 0
long ------> 0l
char -----> /u0000
float ------> 0.0f
2.Abstraction is used for hiding the unwanted data and giving relevant data. while Encapsulation means
hiding the code and data into a single unit to protect the data from outside world.
3. Abstraction lets you focus on what the object does instead of how it does it while Encapsulation means
hiding the internal details or mechanics of how an object does something.
4.For example: Outer Look of a Television, like it has a display screen and channel buttons to change
channel it explains Abstraction but Inner Implementation detail of a Television how CRT and Display
Screen are connect with each other using different circuits , it explains Encapsulation.
Q83. Can I import same package/class twice? Will the JVM load the package twice at
runtime?show Answer
Ans. One can import the same package or same class multiple times. Neither compiler nor JVM
complains wil complain about it. And the JVM will internally load the class only once no matter how many
times you import the same class.
Q84. Explain static blocks in Java ?show Answer
Ans. A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the
static keyword. Here is an example:
static {
// whatever code is needed for initialization goes here
}
A class can have any number of static initialization blocks, and they can appear anywhere in the class
body. The runtime system guarantees that static initialization blocks are called in the order that they
appear in the source code.
Q85. Which access specifier can be used with Class ?show Answer
Ans. For top level class we can only use "public" and "default". We can use private with inner class.
Q86. Explain Annotations ?show Answer
Ans. Annotations, a form of metadata, provide data about a program that is not part of the program itself.
Annotations have no direct effect on the operation of the code they annotate. Annotations have a number
of uses, among them:
Information for the compiler Annotations can be used by the compiler to detect errors or suppress
warnings.
Compile-time and deployment-time processing Software tools can process annotation information to
generate code, XML files, and so forth.
Runtime processing Some annotations are available to be examined at runtime.
}
To add this same metadata with an annotation, you must first define the annotation type. The syntax for
doing this is:
@interface ClassPreamble {
String author();
String date();
int currentRevision() default 1;
String lastModified() default "N/A";
String lastModifiedBy() default "N/A";
// Note use of array
String[] reviewers();
}
The annotation type definition looks similar to an interface definition where the keyword interface is
preceded by the at sign (@) (@ = AT, as in annotation type). Annotation types are a form of interface,
which will be covered in a later lesson. For the moment, you do not need to understand interfaces.
The body of the previous annotation definition contains annotation type element declarations, which look
a lot like methods. Note that they can define optional default values.
After the annotation type is defined, you can use annotations of that type, with the values filled in, like
this:
@ClassPreamble (
author = "John Doe",
date = "3/17/2002",
currentRevision = 6,
lastModified = "4/12/2004",
lastModifiedBy = "Jane Doe",
// Note array notation
reviewers = {"Alice", "Bob", "Cindy"}
)
public class Generation3List extends Generation2List {
Q88. What are few of the Annotations pre defined by Java?show Answer
Ans. @Deprecated annotation indicates that the marked element is deprecated and should no longer be
used. The compiler generates a warning whenever a program uses a method, class, or field with the
@Deprecated annotation.
@Override annotation informs the compiler that the element is meant to override an element declared in
a superclass.
@SuppressWarnings annotation tells the compiler to suppress specific warnings that it would otherwise
generate.
@SafeVarargs annotation, when applied to a method or constructor, asserts that the code does not
perform potentially unsafe operations on its varargsparameter. When this annotation type is used,
unchecked warnings relating to varargs usage are suppressed.
@FunctionalInterface annotation, introduced in Java SE 8, indicates that the type declaration is intended
to be a functional interface, as defined by the Java Language Specification.
@Documented annotation indicates that whenever the specified annotation is used those elements
should be documented using the Javadoc tool. (By default, annotations are not included in Javadoc.)
@Target annotation marks another annotation to restrict what kind of Java elements the annotation can
be applied to.
@Inherited annotation indicates that the annotation type can be inherited from the super class. (This is
not true by default.) When the user queries the annotation type and the class has no annotation for this
type, the class' superclass is queried for the annotation type. This annotation applies only to class
declarations.
@Repeatable annotation, introduced in Java SE 8, indicates that the marked annotation can be applied
more than once to the same declaration or type use. For more information, see Repeating Annotations.
Q91. How to display and set the Class path in Unix ?show Answer
Ans. To display the current CLASSPATH variable, use these commands in UNIX (Bourne shell):
% echo $CLASSPATH
Now all members being private , you can't change the state of the object.
Object Creation is the process to create the object in memory and returning its handler. Java provides
New keyword for object creation.
Initialization is the process of setting the initial / default values to the members. Constructor is used for
this purpose. If we don't provide any constructor, Java provides one default implementation to set the
default values according to the member data types.
Static methods belong to the class and not the objects. They belong to the class and hence doesn't fit
properly for the polymorphic behavior.
A static method is not associated with any instance of a class so the concept of overriding for runtime
polymorphism using static methods is not applicable.
Q108. Can we access instance variables within static methods ?show Answer
Ans. Yes.
we cannot access them directly but we can access them using object reference.
Static methods belong to a class and not objects whereas non static members are tied to an instance.
Accessing instance variables without the instance handler would mean an ambiguity regarding which
instance the method is referring to and hence its prohibited.
Q109. Can we reduce the visibility of the inherited or overridden method ?show Answer
Ans. No.
Q110. Give an Example of checked and unchecked exception ?show Answer
Ans. ClassNotFoundException is checked exception whereas NoClassDefFoundError is a unchecked
exception.
Q111. Name few Java Exceptions ?show Answer
Ans. IndexOutofBound , NoClassDefFound , OutOfMemory , IllegalArgument.
Q112. Which of the following is tightly bound ? Inheritance or Composition ?show Answer
Ans. Inheritence.
Q113. How can we make sure that a code segment gets executed even in case of uncatched
exceptions ?show Answer
Ans. By putting it within finally.
Q114. Explain the use of "Native" keyword ?show Answer
Ans. Used in method declarations to specify that the method is not implemented in the same Java source
file, but rather in another language
show Answer
Ans. Autoboxing is the automatic conversion that the Java compiler makes between the primitive types
and their corresponding object wrapper classes
Q125. What is an Enum type ?
show Answer
Ans. An enum type is a special data type that enables for a variable to be a set of predefined constants
Q126. What are Wrapper Classes ? What are Primitive Wrapper Classes ?
show Answer
Ans. A wrapper class is any class which "wraps" or "encapsulates" the functionality of another class or
component. A Wrapper Class that wraps or encapsulates the primitive data type is called Primitive
Wrapper Class.
Q127. What Design pattern Wrapper Classes implement ?show Answer
Ans. Adapter.
Q128. What is "Import" used for ?
show Answer
Ans. Enables the programmer to abbreviate the names of classes defined in a package.
Q129. Different types of memory used by JVM ?show Answer
Bootstrap , Extension and System are the class loaders used by JVM.
Q131. Can we declare interface methods as private ?show Answer
Ans. No.
Q132. What is a Static import ?show Answer
Ans. By static import , we can access the static members of a class directly without prefixing it with the
class name.
Q133. Difference between StringBuffer and StringBuilder ?show Answer
Ans. StringBuffer is synchronized whereas StringBuilder is not.
Q134. Difference between Map and HashMap ?
show Answer
Ans. Map is an interface where HashMap is the concrete class.
Q135. What is a Property class ?show Answer
Ans. The properties class is a subclass of Hashtable that can be read from or written to a stream.
Q136. Explain the scenerios to choose between String , StringBuilder and StringBuffer ?show
Answer
Ans. If the Object value will not change in a scenario use String Class because a String object is
immutable.
If the Object value can change and will only be modified from a single thread, use a StringBuilder
If the Object value may change, and can be modified by multiple threads, use a StringBuffer because
StringBuffer is thread safe(synchronized).
Q137. Explain java.lang.OutOfMemoryError ?
show Answer
Ans. This Error is thrown when the Java Virtual Machine cannot allocate an object because it is out of
memory, and no more memory could be made available by the garbage collector.
Q138. Can we have multiple servlets in a web application and How can we do that ?show Answer
Ans. Yes by making entries in web.xml
Q139. How can we manage Error Messages in the web application ?show Answer
Ans. Within message.properties file.
Q140. Is JVM, a compiler or interpretor ?
show Answer
Ans. Its an interpretor.
Q141. Difference between implicit and explicit type casting ?
show Answer
Ans. An explicit conversion is where you use some syntax to tell the program to do a conversion whereas
in case of implicit type casting you need not provide the data type.
Q142. Difference between loadClass and Class.forName ?show Answer
Ans. loadClass only loads the class but doesn't initialize the object whereas Class.forName initialize the
object after loading it.
Ans. Builder is a creational Design Pattern whereas Composite is a structural design pattern. Composite
creates Parent - Child relations between your objects while Builder is used to create group of objects of
predefined types.
Q150. Example of Chain of Responsibility Design Pattern ?
show Answer
Ans. Exception Handling Throw mechanism.
Q151. Example of Observer Design Pattern ?
show Answer
Ans. Listeners.
Q152. Difference between Factory and Strategy Design Pattern ?show Answer
Ans. Factory is a creational design pattern whereas Strategy is behavioral design pattern. Factory
revolves around the creation of object at runtime whereas Strategy or Policy revolves around the decision
at runtime.
Q153. Shall we use abstract classes or Interfaces in Policy / Strategy Design Pattern ?show
Answer
Ans. Strategy deals only with decision making at runtime so Interfaces should be used.
Q154. Which kind of memory is used for storing object member variables and function local
variables ?show Answer
Ans. Local variables are stored in stack whereas object variables are stored in heap.
Q155. Why do member variables have default values whereas local variables don't have any
default value ?
show Answer
Ans. member variable are loaded into heap, so they are initialized with default values when an instance of
a class is created. In case of local variables, they are stored in stack until they are being used.
Q173. Can we instantiate the object of derived class if parent constructor is protected ?
show Answer
Ans. No
Q174. Can we declare an abstract method private ?
show Answer
Ans. No Abstract methods can only be declared protected or public.
Q175. What are the design considerations while making a choice between using interface and
abstract class ?show Answer
Ans. Keep it as a Abstract Class if its a "Is a" Relationsship and should do subset/all of the functionality.
Keep it as Interface if its a "Should Do" relationship.
Q176. What is a config Object? show Answer
Ans. The config object is an instantiation of javax.servlet.ServletConfig and is a direct wrapper around the
ServletConfig object for the generated servlet. This object allows the JSP programmer access to the
Servlet or JSP engine initialization parameters such as the paths or file location.
Q177. What is a pageContext Object? show Answer
Ans. The pageContext object is an instance of a javax.servlet.jsp.PageContext object. The pageContext
object is used to represent the entire JSP page. This object stores references to the request and
response objects for each request. The application, config, session, and out objects are derived by
accessing attributes of this object.The pageContext object also contains information about the directives
issued to the JSP page, including the buffering information, the errorPageURL, and page scope.
Q178. What is suspend() method used for ?show Answer
Ans. suspend() method is used to suspend the execution of a thread for a period of time. We can then
restart the thread by using resume() method.
Q179. Difference between suspend() and stop() ?show Answer
Ans. Suspend method is used to suspend thread which can be restarted by using resume() method.
stop() is used to stop the thread, it cannot be restarted again.
Q180. What are the benefits of using Spring Framework ?show Answer
Ans. Spring enables developers to develop enterprise-class applications using POJOs. The benefit of
using only POJOs is that you do not need an EJB container product.
Spring is organized in a modular fashion. Even though the number of packages and classes are
substantial, you have to worry only about ones you need and ignore the rest.
Spring does not reinvent the wheel instead, it truly makes use of some of the existing technologies like
several ORM frameworks, logging frameworks, JEE, Quartz and JDK timers, other view technologies.
Testing an application written with Spring is simple because environment-dependent code is moved into
this framework. Furthermore, by using JavaBean-style POJOs, it becomes easier to use dependency
injection for injecting test data.
Springs web framework is a well-designed web MVC framework, which provides a great alternative to
web frameworks such as Struts or other over engineered or less popular web frameworks.
Lightweight IoC containers tend to be lightweight, especially when compared to EJB containers, for
example. This is beneficial for developing and deploying applications on computers with limited memory
and CPU resources.
Spring provides a consistent transaction management interface that can scale down to a local
transaction
Q181. what is the difference between collections class vs collections interface ?show Answer
Ans. Collections class is a utility class having static methods for doing operations on objects of classes
which implement the Collection interface. For example, Collections has methods for finding the max
element in a Collection.
Q182. Will this code give error if i try to add two heterogeneous elements in the arraylist. ? and
Why ?
int 1 is auto boxed to Integer and "1" is String and hence both are objects.
Q183. Difference between Java beans and Spring Beans ?show Answer
Ans. Java Beans managed by Spring IoC are called Spring Beans.
Q184. What is the difference between System.console.write and System.out.println ?show Answer
Ans. System.console() returns null if your application is not run in a terminal (though you can handle this
in your application)
System.out and System.err use the default platform encoding, while the Console class output methods
use the console encoding
Q185. What are various types of Class loaders used by JVM ?show Answer
Ans. Bootstrap - Loads JDK internal classes, java.* packages.
Extensions - Loads jar files from JDK extensions directory - usually lib/ext directory of the JRE
Java does not support destructors but rather adds a finalize() method. Finalize methods are invoked by
the garbage collector prior to reclaiming the memory occupied by the object, which has the finalize()
method.
Java does not include structures or unions because the traditional data structures are implemented as an
object oriented framework.
In C++ the programmer needs to worry about freeing the allocated memory , where in Java the Garbage
Collector takes care of the the unneeded / unused variables.
Java is platform independent language but c++ is depends upon operating system.
Java uses compiler and interpreter both and in c++ their is only compiler.
Internet support is built-in Java but not in C++. However c++ has support for socket programming which
can be used.
Java does not support header file, include library files just like C++ .Java use import to include different
Classes and methods.
There is no scope resolution operator :: in Java. It has . using which we can qualify classes with the
namespace they came from.
Java is pass by value whereas C++ is both pass by value and pass by reference.
C++ programs runs as native executable machine code for the target and hence more near to hardware
whereas Java program runs in a virtual machine.
C++ was designed mainly for systems programming, extending the C programming language whereas
Java was created initially to support network computing.
C++ allows low-level addressing of data. You can manipulate machine addresses to look at anything you
want. Java access is controlled.
C++ has several addressing operators . * & -> where Java has only one: the .
We can create our own package in Java(set of classes) but not in c and c++.
dynamic class loading - Dynamic loading is a technique for programmatically invoking the functions of a
class loader at run time.
Flush() is used to clear all the data characters stored in the buffer and clear the buffer.
Struts 2 actions are not singleton and a new action object copy is created each time a new action request
is made and hence its thread safe.
Q192. What are some Java related technologies used for distributed computing ?show Answer
finally - handles exception. The finally block is optional and provides a mechanism to clean up regardless
of what happens within the try block. Use the finally block to close files or to release
other system resources like database connections, statements etc.
finalize() - method helps in garbage collection. A method that is invoked before an object is discarded by
the garbage collector, allowing it to clean up its state.
Q195. When do you get ClassCastException?show Answer
Ans. As we only downcast class in the hierarchy, The ClassCastException is thrown to indicate that code
has attempted to cast an object to a subclass of which it is not an instance.
Q196. Explain Thread States ?show Answer
Ans. Runnable - waiting for its turn to be picked for execution by the thread schedular based on thread
priorities.
Running - The processor is actively executing the thread code. It runs until it becomes blocked, or
voluntarily gives up its turn.
Waiting: A thread is in a blocked state while it waits for some external processing such as file I/O to finish.
Sleeping - Java threads are forcibly put to sleep (suspended) with Thread.sleep. they can resume using
Thread.resume method.
Blocked on I/O - Will move to runnable after I/O condition like reading bytes of data etc changes.
A weak reference will get removed on the next garbage collection cycle.
A phantom reference will be finalized but the memory will not be reclaimed. Can be useful when you want
to be notified that an object is about to be collected.
Q198. Difference between yield() and sleeping()? show Answer
Ans. When a task invokes yield(), it changes from running state to runnable state. When a task invokes
sleep(), it changes from running state to waiting/sleeping state.
Q199. What is a daemon thread? Give an Example ?show Answer
Ans. These are threads that normally run at a low priority and provide a basic service to a program or
programs when activity on a machine is reduced. garbage collector thread is daemon thread.
Q200. What is the difference between AWT and Swing?show Answer
Ans. Swing provides both additional components like JTable, JTree etc and added functionality to AWTreplacement components.
Swing components can change their appearance based on the current look and feel library thats being
used.
Swing components follow the MVC paradigm, and thus can provide a much more flexible UI.
Swing provides extras for components, such as icons on many components, decorative borders for
components, tool tips for components etc.
Swing provides built-in double buffering ,which means an off-screen buffer is used during drawing and
then the resulting bits are copied onto the screen.
Swing provides paint debugging support for when you build your own component.
Q201. What is the order of method invocation in an applet?show Answer
Ans. public void init()
public void start()
public void stop()
public void destroy()
Q202. Name few tools for probing Java Memory Leaks ?show Answer
Ans. JProbe, OptimizeIt
Q203. Which memory areas does instance and static variables use ?show Answer
Ans. instance variables are stored on stack whereas static variables are stored on heap.
Q204. What is J2EE? What are J2EE components and services?show Answer
Ans. J2EE or Java 2 Enterprise Edition is an environment for developing and deploying enterprise
applications. The J2EE platform consists of J2EE components, services, Application Programming
Interfaces (APIs) and protocols that provide the functionality for developing multi-tiered and distributed
Web based applications.
Q205. What are the components of J2EE ?show Answer
Ans. applets
Client component like Client side Java codes.
Web component like JSP, Servlet WAR
Enterprise JavaBeans like Session beans, Entity beans, Message driven beans
Enterprise application like WAR, JAR, EAR
A SAX parser serves the client application always only with pieces of the document at any given time
whereas A DOM parser always serves the client application with the entire document no matter how
much is actually needed by the client.
A SAX parser, however, is much more space efficient in case of a big input document whereas DOM
parser is rich in functionality.
Use a DOM Parser if you need to refer to different document areas before giving back the information.
Use SAX is you just need unrelated nuclear information from different areas.
Xerces, Crimson are SAX Parsers whereas XercesDOM, SunDOM, OracleDOM are DOM parsers.
Q208. What is DTD ?show Answer
Ans. DTD or Document Type Definition is a standard agreed upon way of communication between two
parties. Your application can use a standard DTD to verify that data that you receive
from the outside world is valid and can be parsed by your parser.
Q209. What is XSD ?show Answer
Ans. XSD or Xml Schema Definition is an extension of DTD. XSD is more powerful and extensible than
DTD
Q210. What is JAXP ?show Answer
Ans. Stands for Java API for XML Processing. This provides a common interface for creating and using
SAX, DOM, and XSLT APIs in Java regardless of which vendors implementation is actually being used.
Q211. What is JAXB ?show Answer
Ans. Stands for Java API for XML Binding. This standard defines a mechanism for writing out Java
objects as XML and for creating Java objects from XML structures.
Q212. What is marshalling ?show Answer
Ans. Its the process of creating XML structures out of Java Objects.
Q213. What is unmarshalling ?show Answer
Ans. Its the process of creating Java Objects out of XML structures.
Q214. Which load testing tools have you used ?show Answer
Ans. Rational Robot, JMeter, LoadRunner.
Q215. What are LDAP servers used for ?show Answer
Ans. LDAP servers are typically used in J2EE applications to authenticate and authorise users. LDAP
servers are hierarchical and are optimized for read access, so likely to be faster than database in
providing read access.
Q216. What is the difference between comparable and comparator in java.util pkg?show Answer
Ans. Comparable interface is used for single sequence sorting i.e.sorting the objects based on single data
member where as comparator interface is used to sort the object based on multiple data members.
Q217. What are different modules of spring ?show Answer
Ans. There are seven core modules in spring
Spring MVC
The Core container
O/R mapping
DAO
Application context
Aspect Oriented Programming or AOP
Web module
The DispatcherServlet finds the appropriate Controller with the help of HandlerMapping and then invokes
associated Controller.
Then the Controller executes the logic business logic and then returns ModeAndView object to the
DispatcherServlet.
The View is rendered and the Dispatcher Servlet sends the output to the Servlet container. Finally Servlet
Container sends the result back to the user.
Q219. What is Spring configuration file?
show Answer
Ans. Spring configuration file is an XML file. This file contains the classes information and describes how
these classes are configured and introduced to each other.
Q220. Q: What is default scope of bean in Spring framework?show Answer
Ans. The default scope of bean is Sing leton for Spring framework.
Q221. What bean scopes does Spring support? Explain them.
show Answer
Ans. The Spring Framework supports following five scopes -
Singleton
prototype
request
session
global-session
Ans. servlet is a small, server-resident program that typically runs automatically in response to user input.
A network socket is an endpoint of an inter-process communication flow across a computer network.
We can think of it as a difference between door and gate. They are similar as they both are entry points
but they are different as they are put up at different areas.
Sockets are for low-level network communication whereas Servlets are for implementing websites and
web services
Q224. Difference Between this() and super() ?
show Answer
Ans. 1.this is a reference to the current object in which this keyword is used whereas super is a reference
used to access members specific to the parent Class.
2.this is primarily used for accessing member variables if local variables have same name, for constructor
chaining and for passing itself to some method whereas super is primarily used to initialize base class
members within derived class constructor.
Q225. What are the phases of the JSP life cycle ?show Answer
Ans. Translation of JSP Page
The declaration of scriptlet tag is placed inside the _jspService() method whereas The declaration of jsp
declaration tag is placed outside the _jspService() method.
Q227. What are JSP directives ? What are different types of directives ?show Answer
Ans. The jsp directives are messages that tells the web container how to translate a JSP page into the
corresponding servlet.
page directive
include directive
taglib directive
Ans. In GUI programming, an object that can be registered to be notified when events of
some given type occur. The object is said to listen for the events.
Q230. What is MVC ? show Answer
Ans. The Model/View/Controller pattern, a strategy for dividing responsibility in a GUI component. The
model is the data for the component. The view is the visual presentation of the component on the screen.
The controller is responsible for reacting to events by changing the model. According to the MVC pattern,
these responsibilities should be handled by different objects.
Q231. What is race condition ?show Answer
Ans. A source of possible errors in parallel programming, where one thread can cause an error in another
thread by changing some aspect of the state of the program that the second thread is depending on (such
as the value of variable).
Q232. What is unicode ?show Answer
Ans. A way of encoding characters as binary numbers. The Unicode character set includes
characters used in many languages, not just English. Unicode is the character set that is
used internally by Java.
Q233. What is ThreadFactory ?show Answer
Ans. ThreadFactory is an interface that is meant for creating threads instead of explicitly creating threads
by calling new Thread(). Its an object that creates new threads on demand. Using thread factories
removes hardwiring of calls to new Thread, enabling applications to use special thread subclasses,
priorities, etc.
Q234. What is PermGen or Permanent Generation ?show Answer
Ans. The memory pool containing all the reflective data of the java virtual machine itself, such as class
and method objects. With Java VMs that use class data sharing, this generation is divided into read-only
and read-write areas. The Permanent generation contains metadata required by the JVM to describe the
classes and methods used in the application. The permanent generation is populated by the JVM at
runtime based on classes in use by the application. In addition, Java SE library classes and methods may
be stored here.
Q235. What is metaspace ?show Answer
Ans. The Permanent Generation (PermGen) space has completely been removed and is kind of replaced
by a new space called Metaspace. The consequences of the PermGen removal is that obviously the
PermSize and MaxPermSize JVM arguments are ignored and you will never get a
java.lang.OutOfMemoryError: PermGen error.
Q236. What is the benefit of inner / nested classes ?show Answer
Ans. You can put related classes together as a single logical group.
Nested classes can access all class members of the enclosing class, which might be useful in certain
cases.
Nested classes are sometimes useful for specific purposes. For example, anonymous inner classes are
useful for writing simpler event-handling code with AWT/Swing.
Q237. Explain Static nested Classes ?show Answer
Ans. The accessibility (public, protected, etc.) of the static nested class is defined by the outer class.
A static nested class is not an inner class, it's a top-level nested class.
The name of the static nested class is expressed with OuterClassName.NestedClassName syntax.
When you define an inner nested class (or interface) inside an interface, the nested class is declared
implicitly public and static.
Static nested classes can extend another class or it can be used as a base class.
Static nested classes can access the members of the outer class (only static members, obviously).
The outer class can also access the members (even private members) of the nested class through an
object of nested class. If you dont declare an instance of the nested class, the outer class cannot access
nested class elements directly.
Q238. Explain Inner Classes ?show Answer
Ans. The accessibility (public, protected, etc.) of the inner class is defined by the outer class.
Just like top-level classes, an inner class can extend a class or can implement interfaces. Similarly, an
inner class can be extended by other classes, and an inner interface can be implemented or extended by
other classes or interfaces.
Inner classes can have inner classes, but youll have a hard time reading or understanding such complex
nesting of classes.
Q239. Explain Method Local Inner Classes ?show Answer
Ans. You can create a non-static local class inside a body of code. Interfaces cannot have local classes,
and you cannot create local interfaces.
Local classes are accessible only from the body of the code in which the class is defined. The local
classes are completely inaccessible outside the body of the code in which the class is defined.
You can extend a class or implement interfaces while defining a local class.
A local class can access all the variables available in the body of the code in which it is defined. You can
pass only final variables to a local inner class.
Q240. Explain about anonymous inner classes ?show Answer
Ans. Anonymous classes are defined in the new expression itself, so you cannot create multiple objects
of an anonymous class.
You cannot explicitly extend a class or explicitly implement interfaces when defining an anonymous class.
An anonymous inner class is always created as part of a statement; don't forget to close the statement
after the class definition with a curly brace. This is a rare case in Java, a curly brace followed by a
semicolon.
Anonymous inner classes have no name, and their type must be either a subclass of the named type or
an implementer of the named interface
Q241. What will happen if class implement two interface having common method?show Answer
Ans. That would not be a problem as both are specifying the contract that implement class has to follow.
If class C implement interface A & interface B then Class C thing I need to implement print() because of
interface A then again Class think I need to implement print() again because of interface B, it sees that
there is already a method called test() implemented so it's satisfied.
Q242. What is the advantage of using arrays over variables ?show Answer
Ans. Arrays provide a structure wherein multiple values can be accessed using single reference and
index. This helps in iterating over the values using loops.
Q243. What are the disadvantages of using arrays ?show Answer
Ans. Arrays are of fixed size and have to reserve memory prior to use. Hence if we don't know size in
advance arrays are not recommended to use.
Arrays store its values in contentious memory location. Not suitable if the content is too large and needs
to be distributed in memory.
There is no underlying data structure for arrays and no ready made method support for arrays, for every
requriment we need to code explicitly
Q244. Difference between Class#getInstance() and new operator ?show Answer
Ans. Class.getInstance doesn't call the constructor whereas if we create an object using new operator ,
we need to have a matching constructor or copiler should provide a default constructor.
Q245. Can we create an object if a Class doesn't have any constructor ( not even the default
provided by constructor ) ?show Answer
Ans. Yes , using Class.getInstance.
Q246. What is a cloneable interface and what all methods does it contain?show Answer
Ans. It is not having any method because it is a MARKER interface.
Q247. When you will synchronize a piece of your code?show Answer
Ans. When you expect your code will be accessed by different threads and these threads may change a
particular data causing data corruption.
Q248. Are there any global variables in Java, which can be accessed by other part of your
program?show Answer
Ans. No. Global variables are not allowed as it wont fit good with the concept of encapsulation.
Q249. What is an applet? What is the lifecycle of an applet?show Answer
Ans. Applet is a dynamic and interactive program that runs inside a web page displayed by a java
capable browser.
Labels, Push Buttons, Check Boxes, Choice Lists, Lists, Scrollbars, Text Components.
Byte Streams: Provide a convenient means for handling input and output of bytes.
Character Streams: Provide a convenient means for handling input & output of characters.
Byte Streams classes: Are defined by using two abstract classes, namely InputStream and OutputStream.
Character Streams classes: Are defined by using two abstract classes, namely Reader and Writer.
Q252. What is session tracking and how do you track a user session in servlets?show Answer
Ans. Session tracking is a mechanism that servlets use to maintain state about a series requests from the
same user across some period of time. The methods used for session tracking are:
User Authentication - occurs when a web server restricts access to some of its resources to only those
clients that log in using a recognized username and password
Hidden form fields - fields are added to an HTML form that are not displayed in the client's browser. When
the form containing the fields is submitted, the fields are sent back to the server
URL rewriting - every URL that the user clicks on is dynamically modified or rewritten to include extra
information. The extra information can be in the form of extra path information, added parameters or
some custom, server-specific URL change.
Cookies - a bit of information that is sent by a web server to a browser and which can later be read back
from that browser.
HttpSession- places a limit on the number of sessions that can exist in memory.
Q253. What is connection pooling?show Answer
Ans. It's a technique to allow multiple clients to make use of a cached set of shared and reusable
connection objects providing access to a database or other resource.
Q254. Advantage of Collection classes over Arrays ?show Answer
Ans. Collections are re-sizable in nature. We can increase or decrease the size as per recruitment.
Collections can hold both homogeneous and heterogeneous data's.
Collections have performance overheads as they deal with objects and offer dynamic memory expansion.
This dynamic expansion could be a bigger overhead if the collection class needs consecutive memory
location like Vectors.
Ans. System.out and System.err both represent the monitor by default and hence can be used to send
data or results to the monitor. But System.out is used to display normal messages and results whereas
System.err is used to display error messages and System.in represents InputStream object, which by
default represents standard input device, i.e., keyboard.
Q261. Is it possible to compile and run a Java program without writing main( ) method?show
Answer
Ans. Yes, it is possible by using a static block in the Java program.
Q262. What are different ways of object creation in Java ?show Answer
Ans. Using new operator - new xyzClass()
Using factory methods - xyzFactory.getInstance( )
Using newInstance( ) method - (Class.forName(xyzClass))emp.newInstance( )
By cloning an already available object - (xyzClass)obj1.clone( )
Ans. Volatile is an instruction that the variables can be accessed by multiple threads and hence shouldn't
be cached. As volatile variables are never cached and hence their retrieval cannot be optimized.
Q266. Do you think that Java should have had pointers ?show Answer
Ans. Open ended Questions.
Q267. How would you go about debugging a NullPointerException?show Answer
Ans. Open ended Questions.
Q268. How does Java differ from other programming languages you've worked with?show Answer
Ans. Open ended Questions.
Q269. Should good code be self-documenting, or is it the responsibility of the developer to
document it?show Answer
Ans. Open ended Questions.
Q270. What are points to consider in terms of access modifier when we are overriding any
method?show Answer
Ans. 1. Overriding method can not be more restrictive than the overridden method.
reason : in case of polymorphism , at object creation jvm look for actual runtime object. jvm does not look
for reference type and while calling methods it look for overridden method.
If by means subclass were allowed to change the access modifier on the overriding method, then
suddenly at runtimewhen the JVM invokes the true object's version of the method rather than the
reference type's version then it will be problematic
2. In case of subclass and superclass define in different package, we can override only those method
which have public or protected access.
3. We can not override any private method because private methods can not be inherited and if method
can not be inherited then method can not be overridden.
Q271. what is covariant return type? show Answer
Ans. co-variant return type states that return type of overriding method can be subtype of the return type
declared in method of superclass. it has been introduced since jdk 1.5
Q272. How compiler handles the exceptions in overriding ?show Answer
Ans. 1)The overriding methods can throw any runtime Exception , here in the case of runtime exception
overriding method (subclass method) should not worry about exception being thrown by superclass
method.
2)If superclass method does not throw any exception then while overriding, the subclass method can not
throw any new checked exception but it can throw any runtime exception
3) Different exceptions in java follow some hierarchy tree(inheritance). In this case , if superclass method
throws any checked exception , then while overriding the method in subclass we can not throw any new
checked exception or any checked exception which are higher in hierarchy than the exception thrown in
superclass method
Q273. Why is Java considered Portable Language ?show Answer
Ans. Java is a portable-language because without any modification we can use Java byte-code in any
platform(which supports Java). So this byte-code is portable and we can use in any other major
platforms.
Q274. Tell something about history of Java ?show Answer
Ans. Java was initially found in 1991 by James Gosling, Sun Micro Systems. At first it was called as
"Oak". In 1995 then it was later renamed to "Java". java is a originally a platform independent language.
Currently Oracle, America owns Java.
Q275. How to find if JVM is 32 or 64 bit from Java program. ?show Answer
Ans. You can find JVM - 32 bit or 64 bit by using System.getProperty() from Java program.
Q276. Does every class needs to have one non parameterized constructor ?show Answer
Ans. No. Every Class only needs to have one constructor - With parameters or without parameters.
Compiler provides a default non parameterized constructor if no constructors is defined.
Q277. Difference between throw and throws ?show Answer
Ans. throw is used to explicitly throw an exception especially custom exceptions, whereas throws is used
to declare that the method can throw an exception.
We cannot throw multiple exceptions using throw statement but we can declare that a method can throw
multiple exceptions using throws and comma separator.
Q278. Can we use "this" within static method ? Why ?show Answer
Ans. No. Even though "this" would mean a reference to current object id the method gets called using
object reference but "this" would mean an ambiguity if the same static method gets called using Class
name.
Q279. Similarity and Difference between static block and static method ?show Answer
Ans. Both belong to the class as a whole and not to the individual objects. Static methods are explicitly
called for execution whereas Static block gets executed when the Class gets loaded by the JVM.
Q280. What are the platforms supported by Java Programming Language?show Answer
Ans. Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of
UNIX/Linux like HP-Unix, Sun Solaris, Redhat Linux, Ubuntu, CentOS, etc
Ans. Java uses Just-In-Time compiler to enable high performance. Just-In-Time compiler is a program
that turns Java bytecode into instructions that can be sent directly to the processor.
Q282. What is IDE ? List few Java IDE ?show Answer
Ans. IDE stands of Integrated Development Environment. Few Java IDE's are WSAD ( Websphhere
Application Developer ) , RAD ( Rational Application Developer ) , Eclipse and Netbeans.
Q283. What is an Object ?show Answer
Ans. Object is a run time entity whose state is stored in fields and behavior is shown via methods.
Methods operate on an object's internal state and serve as the primary mechanism for object-to-object
communication.
Q284. What is a Class ?show Answer
Ans. A class is a blue print or Mold using which individual objects are created. A class can contain fields
and methods to describe the behavior of an object.
Q285. According to Java Operator precedence, which operator is considered to be with highest
precedence?show Answer
Ans. Postfix operators i.e () [] . is at the highest precedence.
Q286. What data type Variable can be used in a switch statement ?show Answer
Ans. Variables used in a switch statement can only be a byte, short, int, or char.
Ans. 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.
Q289. What things should be kept in mind while creating your own exceptions in Java?show
Answer
Ans. All exceptions must be a child of Throwable.
If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule,
you need to extend the Exception class.
You want to write a runtime exception, you need to extend the RuntimeException class.
Q292. What is the difference between the Reader/Writer class hierarchy and the
InputStream/OutputStream class hierarchy?show Answer
Ans. The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class
hierarchy is byte-oriented
Q295. What is the difference between a break statement and a continue statement?show Answer
Ans. 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 the loop
statement.
Q299. What will happen if static modifier is removed from the signature of the main method?show
Answer
Q302. What are the advantages and Disadvantages of Sockets ?show Answer
Ans. Sockets are flexible and sufficient. Efficient socket based programming can be easily implemented
for general communications. It cause low network traffic.
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.
Q303. What environment variables do I need to set on my machine in order to be able to run Java
programs?show Answer
Ans. CLASSPATH and PATH are the two variables.
Q305. What is the difference between the size and capacity of a Vector?show Answer
Ans. The size is the number of elements actually stored in the vector, while capacity is the maximum
number of elements it can store at a given instance of time.
Q311. How can I change the default location of the generated jar when I command "mvn
package"?show Answer
Ans. By default, the location of the generated jar is in ${project.build.directory} or in your target directory.
We can change this by configuring the outputDirectory of maven-jar-plugin.
Q312. What is Maven's order of inheritance?show Answer
Ans. 1. parent pom
2. project pom
3. settings
4. CLI parameters
Ans. Combine the data of our application and its manipulation at one place.
Encapsulation Allow the state of an object to be accessed and modified through behaviors.
Reduce the coupling of modules and increase the cohesion inside them.
When we create a String using double quotes, JVM looks in the String pool to find if any other String is
stored with same value. If found, it just returns the reference to that String object else it creates a new
String object with given value and stores it in the String pool.
When we use new operator, JVM creates the String object but dont store it into the String Pool. We can
use intern() method to store the String object into String pool or return the reference if there is already a
String with equal value present in the pool.
show Answer
Ans. private static boolean isPalindrome(String str) {
if (str == null)
return false;
StringBuilder strBuilder = new StringBuilder(str);
strBuilder.reverse();
return strBuilder.toString().equals(str);
}
Q321. Write a method that will remove given character from the String?show Answer
Ans. private static String removeChar(String str, char c) {
if (str == null)
return null;
return str.replaceAll(Character.toString(c), "");
}
Q322. Which String class methods are used to make string upper case or lower case?show
Answer
Ans. toUpperCase and toLowerCase
Q323. How to convert String to byte array and vice versa?show Answer
Ans. We can use String getBytes() method to convert String to byte array and we can use String
constructor new String(byte[] arr) to convert byte array to String.
Q324. Why Char array is preferred over String for storing password?
show Answer
Ans. String is immutable in java and stored in String pool. Once its created it stays in the pool until unless
garbage collected, so even though we are done with password its available in memory for longer duration
and there is no way to avoid it. Its a security risk because anyone having access to memory dump can
find the password as clear text.
Q325. Why String is popular HashMap key in Java?show Answer
Ans. Since String is immutable, its hashcode is cached at the time of creation and it doesnt need to be
calculated again. This makes it a great candidate for key in a Map and its processing is fast than other
HashMap key objects. This is why String is mostly used Object as HashMap keys.
Q326. What ate the getter and setter methods ?show Answer
Ans. getters and setters methods are used to store and manipulate the private variables in java beans. A
getters as it has name, suggest retrieves the attribute of the same name. A setters are allows you to set
the values of the attributes.
Q327. public class a {
public static void main(String args[]){
final String s1="job";
final String s2="seeker";
String s3=s1.concat(s2);
String s4="jobseeker";
System.out.println(s3==s4); // Output 1
System.out.println(s3.hashCode()==s4.hashCode()); Output 2
}
}
Hash code is generated to be used as hash key in some of the collections in Java and is calculated using
string characters and its length. As they both are same string literals, and hence their hashcode is
same.Output 2 will be true.
Q328. What is the use of HashCode in objects ?show Answer
Ans. Hashcode is used for bucketing in Hash implementations like HashMap, HashTable, HashSet etc.
In Inheritance there is only one object in memory ( derived object ) whereas in Composition , parent
object holds references of all composed objects.
From Design perspective - Inheritance is "is a" relationship among objects whereas Composition is "has
a" relationship among objects.
Q330. Will finally be called always if all code has been kept in try block ?show Answer
Ans. The only time finally won't be called is if you call System.exit() or if the JVM crashes first.
Q331. Will the static block be executed in the following code ? Why ?
class Test
{
static
{
System.out.println("Why I am not executing ");
}
public static final int param=20;
}
}
}show Answer
Ans. No the static block won't get executed as the referenced variable in the Test class is final. Compiler
replaces the content of the final variable within Demo.main method and hence actually no reference to
Test class is made.
Q332. Will static block for Test Class execute in the following code ?
class Test
{
static
{
System.out.println("Executing Static Block.");
}
public final int param=20;
class Test{
static void display(){
System.out.println("Buggy Bread");
}
}
class Demo{
public static void main(String... args){
Test t = null;
t.display();
}
}show Answer
Ans. Yes. static method is not accessed by the instance of class. Either you call it by the class name or
the reference.
Q335. How substring() method of String class create memory leaks?show Answer
Ans. substring method would build a new String object keeping a reference to the whole char array, to
avoid copying it. Hence you can inadvertently keep a reference to a very big character array with just a
one character string.
Q336. Write a program to reverse a string iteratively and recursively ?show Answer
Ans. Using String method -
new StringBuffer(str).reverse().toString();
Iterative -
Recursive -
getRandom7() {
String binaryStr = String.valuesOf(random(2))+String.valuesOf(random(2))+String.valuesOf(random(2));
binaryInt = Integer.valueOf(binaryStr);
int sumValue=0;
int multiple = 1;
while(binaryInt > 0){
binaryDigit = binaryInt%10;
if(n1 == n2)
System.out.println("equal 2"); show Answer
Ans. equal 1
Q340. Difference between new operator and Class.forName().newInstance() ?show Answer
Ans. new operator is used to statically create an instance of object. newInstance() is used to create an
object dynamically ( like if the class name needs to be picked from configuration file ). If you know what
class needs to be initialized , new is the optimized way of instantiating Class.
Q341. What is Java bytecode ?show Answer
Ans. Java bytecode is the instruction set of the Java virtual machine. Each bytecode is composed by one,
or two bytes that represent the instruction, along with zero or more bytes for passing parameters.
Q342. How to find whether a given integer is odd or even without use of modules operator in
java?show Answer
Ans. public static void main(String ar[])
{
int n=5;
if((n/2)*2==n)
{
System.out.println("Even Number ");
}
else
{
System.out.println("Odd Number ");
}
}
}
Q343. Is JVM a overhead ? show Answer
Ans. Yes and No. JVM is an extra layer that translates Byte Code into Machine Code. So Comparing to
languages like C, Java provides an additional layer of translating the Source Code.
Though it looks like an overhead but this additional translation allows Java to run Apps on all platforms as
JVM provides the translation to the Machine code as per the underlying Operating System.
Q344. Can we use Ordered Set for performing Binary Search ?show Answer
Ans. We need to access values on the basis of an index in Binary search which is not possible with Sets.
Q345. What is Byte Code ? Why Java's intermediary Code is called Byte Code ?show Answer
Ans. Bytecode is a highly optimized set of instructions designed to be executed by the Java run-time
system. Its called Byte Code because each instruction is of 1-2 bytes.
1: istore_1
2: iload_1
3: sipush 1000
6: if_icmpge 44
9: iconst_2
10: istore_2
Q346. Difference between ArrayList and LinkedList ?show Answer
Ans. LinkedList and ArrayList are two different implementations of the List interface. LinkedList
implements it with a doubly-linked list. ArrayList implements it with a dynamically resizing array.
Q347. If you are given a choice to use either ArrayList and LinkedList, Which one would you use
and Why ?show Answer
Ans. ArrayList are implemented in memory as arrays and hence allows fast retrieval through indices but
are costly if new elements are to be inserted in between other elements.
LinkedList allows for constant-time insertions or removals using iterators, but only sequential access of
elements
Q348. What are the pre-requisite for the collection to perform Binary Search ?show Answer
Ans. 1. Collection should have an index for random access.
2. Collection should have ordered elements.
Q349. Can you provide some implementation of a Dictionary having large number of words ? show
Answer
Ans. Simplest implementation we can have is a List wherein we can place ordered words and hence can
perform Binary Search.
Other implementation with better search performance is to use HashMap with key as first character of the
hashmap {
a ( key ) -> hashmap (key-aa , value (hashmap(key-aaa,value)
b ( key ) -> hashmap (key-ba , value (hashmap(key-baa,value)
....................................................................................
z( key ) -> hashmap (key-za , value (hashmap(key-zaa,value)
}
or
class BuggyBread {
System.out.println(s2 == s5);
}
}show Answer
Ans. true, due to String Pool, both will point to a same String object.
Q357. What will be the output of following code ?
class BuggyBread2 {
void BuggyBread2() {
counter = 5;
}
BuggyBread2(int x){
counter = x;
}
Ans. Compile time error as it won't find the constructor matching BuggyBread2(). Compiler won't provide
default no argument constructor as programmer has already defined one constructor. Compiler will treat
user defined BuggyBread2() as a method, as return type ( void ) has been specified for that.
Q358. What will be the output of following code ?
class BuggyBread1 {
public String method() {
return "Base Class - BuggyBread1";
}
}
Though Base Class handler is having the object of Derived Class but its not overriding as now with a
definition having an argument ,derived class will have both method () and method (int) and hence its
overloading.
Q360. Which markup languages can be used in restful web services ? show Answer
Ans. XML and JSON ( Javascript Object Notation ).
Q361. Difference between Inner and Outer Join ?show Answer
Ans. Inner join is the intersection of two tables on a particular columns whereas Outer Join is the Union of
two tables.
Can make a queue wherein we can verify and order the request to DB.
Less use of cursors as they lock the tables for long time.
For example - we may like to pull some info from a table and then do some operations on that data and
then store the output in final output table. We can store the intermediary values in a temp table and once
we have final output with us, we can just delete it.
Q365. Why Web services use HTTP as the communication protocol ?show Answer
Ans. With the advent of Internet, HTTP is the most preferred way of communication. Most of the clients (
web thin client , web thick clients , mobile apps ) are designed to communicate using http only. Web
Services using http makes them accessible from vast variety of client applications.
Q366. what will be the output of this code ?
test(s1);
System.out.println(s1);
test(s1);
System.out.println(s1);
test(s1);
System.out.println(s1);
class Animal {
public void eat() throws Exception {
}
}
Q370. What are advantages of using Servlets over CGI ?show Answer
Ans. Better Performance as Servlets doesn't require a separate process for a single request.
Ans. Session cookies , which are deleted once the session is over.
1. C:\directory\..\directory\file.txt
2. C:\directory\subDirectory1\directory\file.txt
3. \directory\file.txtshow Answer
Ans. 2nd
Q381. What will the following code print when executed on Windows ?
}
}show Answer
Ans. It will create the file myfile.txt in the current directory.
Q384. What will be the output of following code ?
a.
b.
c.
d.
class BuggyBread1 {
}
}show Answer
Ans. Though we are trying to serialize BuggyBread1 object but we haven't declared the class to
implement Serializable.
}
}show Answer
Ans. No, It will throw java.io.NotSerializableException.
Q396. Will this code work fine if BuggyBread2 doesn't implement Serializable ?
private int x = 5;
}
}show Answer
Ans. Yes.
Q397. Can we compose the Parent Class object like this ?
java.util.Calendar c = java.util.Calendar.getInstance();
c.add(Calendar.MONTH, 5);
System.out.println(c.getTime());show Answer
Ans. Date and Time after 5 months from now.
Q401. Which of the following code is correct ?
a. DateFormat df = DateFormat.getInstance();
b. DateFormat df = DateFormat.getDateInstance();
c. DateFormat df = DateFormat.getInstance(DateFormat.FULL);
d. DateFormat df = DateFormat.getDateInstance(DateFormat.FULL);show Answer
Ans. All except c are correct.
Q402. What is the use of parse method in DateFormat ?show Answer
Ans. It is used to parse String to get the Date Object with initialized date.
Q403. Which of the following is not a valid java.util.Locale initialization ?
a. new Locale ()
a. NumberFormat.getInstance()
b. NumberFormat.getDateInstance()
c. NumberFormat.getCurrencyInstance()
d. NumberFormat.getNumberInstance()show Answer
Ans. b i.e NumberFormat.getDateInstance()
Q405. What will the following code print ?
Ans. Keys
Q419. How TreeMap orders the elements if the Key is a String ?show Answer
Ans. As String implements Comparable, It refers to the String compareTo method to identify the order
relationship among those elements.
Q420. Can we add heterogeneous elements into TreeMap ?show Answer
Ans. No, Sorted collections don't allow addition of heterogeneous elements as they are not comparable.
Q421. Will it create any problem if We add elements with key as user defined object into the
TreeMap ?show Answer
Ans. It won't create any problem if the objects are comparable i.e we have that class implementing
Comparable interface.
Q422. Can we null keys in TreeMap ?show Answer
Ans. No, results in exception.
Q423. Can value be null in TreeMap ?show Answer
Ans. Yes.
Q424. Which interface TreeMap implements ?show Answer
Ans. TreeMap implements NavigableMap, SortedMap, Serializable and Clonable.
Q425. Do we have form beans in Struts 2 ?show Answer
Ans. No, because they are not longer required. As action classes are no more singleton in Struts 2, user
inputs can be captured in action itself.
Q426. What is a ConcurrentHashMap ?show Answer
Ans. ConcurrentHashMap is a hashMap that allows concurrent modifications from multiple threads as
there can be multiple locks on the same hashmap.
Q427. What is the use of double checked locking in createInstance() of Singleton class?
What advantage does the first code offer compared to the second ?show Answer
Ans. In First Case , Lock for the synchronized block will be received only if
singleton == null whereas in second case every thread will acquire the lock before executing the code.
The problem of synchronization with singleton will only happen when the object has not be instantiated.
Once instantiated , the check singleton == null will always generate true and the same object will be
returned and hence no problem. First condition will make sure that synchronized access ( acquiring locks
) will only take place if the object has not been created so far.
Q428. Why are Getter and Setter better than directly changing and retrieving fields ?show Answer
Ans. 1. Methods can participate in runtime polymorphism whereas member variables cannot.
3. If the input format changes , that can be absorbed by making change ( wrapping ) in the setter and
getter.
Q429. Can we overload main method in Java ?show Answer
Ans. Yes, but the overloaded main methods without single String[] argument doesn't get any special
status by the JVM. They are just another methods that needs to be called explicitly.
Q430. What the Bean scopes provided by Spring ?show Answer
Ans. Singleton , Prototype , Request , Session , global-session
Q431. What are the various Auto Wiring types in Spring ?show Answer
Ans. By Name , By Type and Constructor.
Q432. Difference between first level and second level cache in hibernate ?show Answer
Ans. 1. First level cache is enabled by default whereas Second level cache needs to be enabled explicitly.
2. First level Cache came with Hibernate 1.0 whereas Second level cache came with Hibernate 3.0.
3. First level Cache is Session specific whereas Second level cache is shared by sessions that is why
First level cache is considered local and second level cache is considered global.
Q433. What are the the methods to clear cache in Hibernate ?show Answer
Ans. Evict() and clear(). Evist is used to clear a particular object from the cache whereas clear clears the
complete local cache.
Q434. What are different types of second level cache ?show Answer
Ans. 1. EHCache ( Easy Hibernate )
2. OSCache ( Open Symphony )
3. Swarm Cache ( JBoss )
4. Tree Cache ( JBoss )
Q435. Can we disable first level cache ? What should one do if we don't want an object to be
cached ?show Answer
Ans. No.We can either call evict after the object retrieval or can use separate sessions.
Q436. How to configure second level cache in Hibernate ?show Answer
Ans. 1. Configure Provider class in Hibernate configuration file.
3. Create an XML file called ehcache.xml and place in classpath which contains time settings and update
settings, behavior of cache , lifetime and idletime of Pojos, how many objects are allowed.
Q437. What is Hibernate ?show Answer
Ans. Hibernate is a Java ORM Framework.
Q438. What are the advantages of Hibernate ?show Answer
Q439. What are the different types of inheritance in Hibernate ?show Answer
Ans. Table Per Class , Table per Sub Class , Table per Concrete Class
Q440. What is the purpose of dialect configured in Hibernate configuration file ?show Answer
Ans. It tells the framework which SQL varient to generate.
Q441. Please specify in what sequence the objects of following classes will be created ?
One to One
One to Many
Many to One
Many to Many
Q444. What are the contents of Hibernate configuration file ( hibernate.cfg.xml ) ?show Answer
Ans. HBM Files ( Mapping )
DB Connection ( DB Connection String , User Name , Password , Pool Size )
SQL Dialect ( SQL variant to be generated )
Show SQL ( Show / No show SQL on Console )
Auto Commit ( True / False )
Q445. What are the Core Interfaces of Hibernate Framework ? show Answer
Ans. Configuration
SessionFactory
Session
Transaction
Query and Citeria
get makes the call to DB immediately whereas load makes the call to proxy.
Q448. What is lazy fetching in Hibernate ?show Answer
Ans. Lazy fetching is the technique of not loading the child objects when parent objects are loaded. By
default Hibernate does not load child objects. One can specify whether to load them or not while doing
the association.
Q449. Different types of Hibernate Instance States ?show Answer
Ans. Transient - In this state, an instance is not associated with any persistence context
Persistent - In this state, an instance is associated with a persistence context
Detached - This is a state for an instance which was previously associated with a persistence context an
has been currently closed dissociated
Q450. Is It Good to use Reflection in an application ? Why ?show Answer
Ans. no, It's like challenging the design of application.
Q451. Why is Reflection slower ?show Answer
Ans. Because it has to inspect the metadata in the bytecode instead of just using precompiled addresses
and constants.
Q452. When should we use prototype scope and singleton scope for beans ?show Answer
Ans. We should use singleton scope for beans when they are stateless and prototype when they are
stateful.
Q453. Difference between Assert and Verify ?show Answer
Ans. Assert works only if assertions ( -ea ) are enabled which is not required for Verify.
Assert throws an exception and hence doesn't continue with the test if assert evaluates to false whereas
it's not so with Verify.
Q454. What is the difference between ArrayList and LinkedList ?show Answer
Ans. Underlying data structure for ArrayList is Array whereas LinkedList is the linked list and hence have
following differences -
1. ArrayList needs continuous memory locations and hence need to be moved to a bigger space if new
elements are to be added to a filled array which is not required for LinkedList.
2. Removal and Insertion at specific place in ArrayList requires moving all elements and hence leads to
O(n) insertions and removal whereas its constant O(1) for LinkedList.
3. Random access using index in ArrayList is faster than LinkedList which requires traversing the
complete list through references.
4. Though Linear Search takes Similar Time for both, Binary Search using LinkedList requires creating
new Model called Binary Search Tree which is slower but offers constant time insertion and deletion.
5. For a set of integers you want to sort using quicksort, it's probably faster to use an array; for a set of
large structures you want to sort using selection sort, a linked list will be faster.
Q455. Which class elements are not persisted ?show Answer
Ans. Static and Transient.
Q456. Which annotations are used in Hibernate ?show Answer
Ans. @Entity
@Table
@Id
@Column
@Temporal
@Basic
@Enumerated
@Access
@Embeddable
@Lob
@AttributeOverride
@Embedded
@GeneratedValue
@ElementCollection
@JoinTable
@JoinColumn
@CollectionId
@GenericGenerator
@OneToOne
@OneToMany
@ManyToOne
@ManyToMany
@NotFound
Q457. What entries we make in the hibernate config file if we are not using hbm files but
Annotations ?show Answer
Ans. We configure Entity classes having annotated mappings.
Q458. How many SessionFactory and Session objects are created ?show Answer
Ans. Single SessionFactory object and multiple session objects for opening different session. Hibernate
creates new Session object per thread.
Q459. What is the way to rollback transaction if something goes wrong using hibernate API ? show
Answer
Ans. We can have the code calling Hibernate API within try block and can have transaction.rollback within
Catch.
Q460. What is the use of hbm2ddl Configuration in Hibernate ?show Answer
Ans. This configuration specifies if hibernate should creates the Schema / Table on its own if the
respective table is not found.
"update" doesn't create the table if it's not found whereas configuration set as "create" creates the
schema automatically.
@Entity
@Entity
@Table ( name=""EMPLOYEES"" )
@Entity ( name="EMP")
@Table ( name="EMPLPYEES" )
show Answer
Ans. First Annotation will set the Entity name as EMPLOYEES and hence will try to map with the same
Table name.
The second annotation will make the Entity mapped to table EMPLOYEES irrespective of the Entity
Name ( which is class name in this case ).
Third Annotations will set the different names for Enitity and Table and will explicitly map them.
Q463. What are the different ID generating strategies using @GeneratedValue annotation ?show
Answer
Ans. Auto , Identity , Sequence and Table.
or
3. Make sure that we are accessing the dependent objects before closing the session.
Q469. Which type of associated Entities are Eagerly loaded by Default ?show Answer
Ans. OneToOne
Q470. After which Hibernate version , related Entities are initialized lazily ?show Answer
Ans. After Hibernate 3.0
Q471. Can we declare Entity class as final ?show Answer
Ans. Yes but as Hibernate creates the Proxy Classes inherited from the Entity Classes to communicate
with Database for lazy initialization. Declaring entity classes as final will prohibit communication with
database lazily and hence will be a performance hit.
Q472. What are the restrictions for the entity classes ?show Answer
Ans. 1. Entity classes should have default constructor.
3. All elements to be persisted should be declared private and should have public getters and setters in
the Java Bean style.
4. All classes should have an ID that maps to Primary Key for the table.
Q473. What is the difference between int[] x; and int x[]; ?show Answer
Ans. No Difference. Both are the acceptable ways to declare an array.
Q474. What are the annotations used in Junit with Junit4 ?show Answer
Ans. @Test
The Test annotation indicates that the public void method to which it is attached can be run as a test
case.
@Before
The Before annotation indicates that this method must be executed before each test in the class, so as to
execute some preconditions necessary for the test.
@BeforeClass
The BeforeClass annotation indicates that the static method to which is attached must be executed once
and before all tests in the class.
@After
The After annotation indicates that this method gets executed after execution of each test.
@AfterClass
The AfterClass annotation can be used when a method needs to be executed after executing all the tests
in a JUnit Test Case class so as to clean-up the set-up.
@Ignores
The Ignore annotation can be used when you want temporarily disable the execution of a specific test.
Q475. What is asynchronous I/O ?show Answer
Ans. It is a form of Input Output processing that permits other processing to continue before the I/O
transmission has finished.
Q476. If there is a conflict between Base Class Method definition and Interface Default method
definition, Which definition is Picked ?show Answer
System.out.println("HelloJava8");
}
}show Answer
Ans. There won't be any error and upon execution the overriding class method will be executed.
Q485. What will happen if there is a default method conflict as mentioned above and we have
specified the same signature method in the base class instead of overriding in the existing class ?
show Answer
Ans. There won't be any problem as the Base class method will have precedence over the Interface
Default methods.
Q486. If a method definition has been specified in Class , its Base Class , and the interface which
the class is implementing, Which definition will be picked if we try to access it using Interface
Reference and Class object ? show Answer
Ans. Class method definition is overriding both the definitions and hence will be picked.
Q487. If a method definition has been specified in the Base Class and the interface which the
class is implementing, Which definition will be picked if we try to access it using Interface
Reference and Class object ? show Answer
Ans. Base Class Definition will have precedence over the Interface Default method definition.
Q488. Can we use static method definitions in Interfaces ?show Answer
Ans. Yes, Effective Java 8.
Q489. Can we access Interface static method using Interface references ?show Answer
Ans. No, only using Interface Name.
Q490. Can we have default method with same name and signature in the derived Interface as the
static method in base Interface and vice versa ?show Answer
Ans. Yes , we can do that as static methods are not accessible using references and hence cannot lead
to conflict. We cannot do inverse as Default methods cannot be overridden with the static methods in
derived interface.
Q491. What is a Lambda Expression ? What's its use ?show Answer
Ans. Its an anonymous method without any declaration. Lambda Expression are useful to write shorthand
Code and hence saves the effort of writing lengthy Code. It promotes Developer productivity, Better
Readable and Reliable code.
Q492. Difference between Predicate, Supplier and Consumer ? show Answer
Ans. Predicate represents an anonymous function that accepts one argument and produces a result.
Supplier represents an anonymous function that accepts no argument and produces a result.
Consumer represents an anonymous function that accepts an argument and produces no result.
Q493. What does the following lambda expression means ?
Ans. We can't get the address of a reference like a pointer. Moreover we cannot perform pointer
arithmetic with references.
Q497. Difference between TCP and UDP ?show Answer
Ans. http://www.cyberciti.biz/faq/key-differences-between-tcp-and-udp-protocols/
Q498. What things you would care about to improve the performance of Application if its identified
that its DB communication that needs to be improved ?show Answer
Ans. 1. Query Optimization ( Query Rewriting , Prepared Statements )
2. Restructuring Indexes.
3. DB Caching Tuning ( if using ORM )
4. Identifying the problems ( if any ) with the ORM Strategy ( If using ORM )