Professional Documents
Culture Documents
Ans. They are loaded at runtime when the respective Class is loaded.
Q24. Can we serialize static variables ?
Ans. No. Only Object and its members are serialized. Static variables
are shared variables and doesn't correspond to a specific object.
Q25. What will this code print ?
String a = new String ("TEST"); String b = new String ("TEST");
if(a == b) {
System.out.println ("TRUE"); } else {
System.out.println ("FALSE"); }
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?
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 ?
Ans. They both represent the long primitive type. They are exactly the
same.
Q28. Does Java provides default copy constructor ?
Ans. No
Q29. What are the common uses of "this" keyword in java ?
Ans. "this" keyword is a reference to the current object and can be used
for following 1. Passing itself to another method.
2. Referring to the instance variable when local variable has the same
name. 3. Calling another constructor in constructor chaining.
Q30. What are the difference between Threads and Processes ?
Ans. 1. when an OS wants to start running program it creates new
process means a process is a program that is currently executing and
every process has at least one thread running within it.
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.
primitives as objects.
Q41. What is the difference between time slicing and preemptive
scheduling ?
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?
Ans. Ready state.
Q43. What one should take care of, while serializing the object?
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 ?
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 ? 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.
2. To Cache its Hashcode
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 ?
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.
{"name":"xyz","gender":"male";"age":30}
Q66. When were Enums introduced in Java ?
Ans. Enums were introduced with java 5.
Q67. Which function is used to convert a JSON text into an object ?
Ans. eval
Q68. Which data types are supported by JSON ?
Ans. Number String Boolean Array
Object null
Q69. What are the benefits of JSON over XML ?
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.
Q70. What are the methods of Object Class ?
Ans. clone() - Creates and returns a copy of this object.
equals() - Indicates whether some other object is "equal to" this one.
finalize() - Called by the garbage collector on an object when garbage
collection determines that there are no more references to the object
getClass() - Returns the runtime class of an object.
hashCode() - Returns a hash code value for the object.
toString() - Returns a string representation of the object.
notify(), notifyAll(), and wait() - Play a part in synchronizing the activities
of independently running threads in a program.
Q71. Explain JMS ( Java Messaging Services ) ?
Ans. JMS Provides high-performance asynchronous messaging. It
enables Java EE applications to communicate with non-Java systems
on top of various transports.
Q72. Explain EJB (Enterprise Java Beans) ?
Ans. EJB Provides a mechanism that make easy for Java developers to
use advanced features in their components, such as remote method
invocation (RMI), object/ relational mapping (that is, saving Java objects
to a relational database), and distributed transactions across multiple
data sources.
Q73. Which MVC is struts2 based on ?
Ans. MVC2
Q74. What is an API ( Application Programming Interface ) ?
Ans. An API is a kind of technical contract which defines functionality
that two parties must provide: a service provider (often called an
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 ?
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 ?
Ans. No.
Q110. Give an Example of checked and unchecked exception ?
Ans. ClassNotFoundException is checked exception whereas
NoClassDefFoundError is a unchecked exception. Q111. Name few
Java Exceptions ?
Ans. IndexOutofBound , NoClassDefFound , OutOfMemory ,
IllegalArgument.
Q112. Which of the following is tightly bound ? Inheritance or
Composition ?
Ans. Inheritence.
Q113. How can we make sure that a code segment gets executed even
in case of uncatched exceptions ? Ans. By putting it within finally.
Q114. Explain the use of "Native" keyword ?
Ans. Used in method declarations to specify that the method is not
implemented in the same Java source file, but rather in another
language Q115. What is "super" used for ?
Ans. Used to access members of the base class. Q116. What is "this"
keyword used for ?
Ans. Used to represent an instance of the class in which it appears.
Q117. Difference between boolean and Boolean ?
Ans. boolean is a primitive type whereas Boolean is a class.
Q118. What is a finalize method ?
Ans. finalize() method is called just before an object is destroyed.
Q119. What are Marker Interfaces ? Name few Java marker interfaces ?
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.
Q156. What is a Default Constructor ?
Ans. The no argument constructor provided by Java Compiler if no
constructor is specified.
Q157. Will Compiler creates a default no argument constructor if we
specify only multi argument constructor ?
Ans. No, Compiler will create default constructor only if we don't specify
any constructor. Q158. Can we overload constructors ?
Ans. Yes.
Q159. What will happen if we make the constructor private ?
Ans. We can't create the objects directly by invoking new operator.
Q160. How can we create objects if we make the constructor private ?
Ans. We can do so through a static public member method or static
block. Q161. What will happen if we remove the static keyword from
main method ?
Ans. Program will compile but will give a "NoSuchMethodError" during
runtime. Q162. Why Java don't use pointers ?
Ans. Pointers are vulnerable and slight carelessness in their use may
result in memory problems and hence Java intrinsically manage their
use. Q163. Can we use both "this" and "super" in a constructor ?
Ans. No, because both this and super should be the first statement.
Q164. Do we need to import java.lang.package ?
Ans. No, It is loaded by default by the JVM.
Q165. Is it necessary that each try block to be followed by catch block ?
Ans. It should be followed by either catch or finally block.
Q166. Can finally block be used without catch ?
Ans. Yes but should follow "try" block then.
Q167. What is exception propogation ?
Ans. Passing the exception object to the calling method.
Q168. Difference between nested and inner classes ?
Ans. Inner classes are non static nested classes.
Q169. What is a nested interface ?
Ans. Any interface declared inside a class or an interface. It is static by
default.
Q170. What is an Externalizable interface ?
Ans. Externalizable interface is used to write the state of an object into a
byte stream in compressed format.
echoing characters
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 ?
Ans. Bootstrap - Loads JDK internal classes, java.* packages.
Extensions - Loads jar files from JDK extensions directory - usually lib/
ext directory of the JRE
System - Loads classes from system classpath.
Q186. How are classes loaded by JVM ?
Ans. Class loaders are hierarchical. The very first class is specially
loaded with the help of static main() method declared in your class. All
the subsequently loaded classes are loaded by the classes, which are
already loaded and running.
Q187. Difference between C++ and Java ?
Ans. Java does not support pointers.
Java does not support multiple inheritances.
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.
C++ compiles to machine language , when Java compiles to byte code .
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.
C++ supports operator overloading whereas Java doesn't.
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 goto statement in Java.
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.
Java Enums are objects instead of int values in C++
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++.
Q188. Difference between static vs. dynamic class loading?
Ans. static loading - Classes are statically loaded with Javas new
operator.
dynamic class loading - Dynamic loading is a technique for
programmatically invoking the functions of a class loader at run time.
Class.forName (Test className);
Q189. Tell something about BufferedWriter ? What are flush() and
close() used for ?
Ans. A Buffer is a temporary storage area for data. The BufferedWriter
class is an output stream.It is an abstract class that creates a buffered
character-output stream. Flush() is used to clear all the data characters
stored in the buffer and clear the buffer.
Close() is used to closes the character output stream.
Q190. What is Scanner class used for ? when was it introduced in
Java ?
Ans. Scanner class introduced in Java 1.5 for reading Data Stream from
the imput device. Previously we used to write code to read a input using
DataInputStream. After
reading the stream , we can convert into respective data type using
in.next() as String ,in.nextInt() as integer, in.nextDouble() as Double etc
Q191. Why Struts 1 Classes are not Thread Safe whereas Struts 2
classes are thread safe ?
Ans. Struts 1 actions are singleton. So all threads operates on the single
action object and hence makes it thread unsafe.
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 ?
page directive
include directive taglib directive
Q228. What is Java bytecode ?
Ans. Java bytecode is the usual name for the machine language of the
Java Virtual Machine. Java programs are compiled into Java bytecode,
which can then be executed by the JVM.
Q229. What is a Listener ?
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 ?
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 ?
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 ?
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 ?
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 ?
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
use.
Arrays can store only homogeneous elements.
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 ?
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 ) ? Ans. Yes , using
Class.getInstance.
Q246. What is a cloneable interface and what all methods does it
contain?
Ans. It is not having any method because it is a MARKER interface.
Q247. When you will synchronize a piece of your code?
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?
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?
Ans. Applet is a dynamic and interactive program that runs inside a web
page displayed by a java capable browser.
Lifecycle methods of Applet init( ) method - Can be called when an applet is first loaded
start( ) method - Can be called each time an applet is started
paint( ) method - Can be called when the applet is minimized or
maximized stop( ) method - Can be used when the browser moves off
the applet's page destroy( ) method - Can be called when the browser is
finished with the applet
Q250. What is meant by controls and what are different types of controls
in AWT / SWT?
Ans. Controls are components that allow a user to interact with your
application and SWT / AWT supports the following types of controls:
Labels, Push Buttons, Check Boxes, Choice Lists, Lists, Scrollbars, Text
Components.
Ans. A child object constructor always first needs to construct its parent.
In Java it is done via an implicit call to the no-args constructor as the first
statement Q308. What is the best practice configuration usage for files pom.xml or settings.xml ?
Ans. The best practice guideline between settings.xml and pom.xml is
that configurations in settings.xml must be specific to the current user
and that pom.xml configurations are specific to the project.
Q309. Why Java provides default constructor ?
Ans. At the beginning of an object's life, the Java virtual machine (JVM)
allocates memory on the heap to accommodate the object's instance
variables. When that memory is first allocated, however, the data it
contains is unpredictable. If the memory were used as is, the behavior of
the object would also be unpredictable. To guard against such a
scenario, Java makes certain that memory is initialized, at least to
predictable default values before it is used by any code.
Q310. In a case where there are no instance variables what does the
default constructor initialize?
Ans. Java expects the superclass ( Object Class ) constructor to be
called while creation of any object. So super constructor is called in case
there are no instance variables to initialize.
Q311. How can I change the default location of the generated jar when I
command "mvn package"?
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?
Ans. 1. parent pom 2. project pom
3. settings
4. CLI parameters
Q313. What is a Mojo?
Ans. A mojo is a Maven plain Old Java Object. Each mojo is an
executable goal in Maven, and a plugin is a distribution of one or more
related mojos. Q314. How do I determine which POM contains missing
transitive dependency?
Ans. run mvn -X
Q315. Difference between Encapsulation and Data Hiding ?
Ans. Data Hiding is a broader concept. Encapsulation is a OOP's centri
concept which is a way of data hiding in OOP's.
Q316. Difference between Abstraction and Implementation hiding ?
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?
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 ?
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 }
}
What will be the Output 1 and Output 2 ?
Ans. S3 and S4 are pointing to different memory location and hence
Output 1 will be false.
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 ?
Ans. Hashcode is used for bucketing in Hash implementations like
HashMap, HashTable, HashSet etc.
Q329. Difference between Compositions and Inheritance ?
Ans. Inheritance means a object inheriting reusable properties of the
base class. Compositions means that an abject holds other objects.
In Inheritance there is only one object in memory ( derived object )
whereas in Composition , parent object holds references of all
Ans. Yes.
Q333. What does String intern() method do?
Ans. intern() method keeps the string in an internal cache that is usually
not garbage collected. Q334. Will the following program display "Buggy
Bread" ?
class Test{
static void display(){ System.out.println("Buggy Bread"); }
}
class Demo{
public static void main(String... args){ Test t = null;
t.display();
}
}
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?
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 ?
Ans. Using String method -
new StringBuffer(str).reverse().toString();
Iterative public static String getReverseString(String str){ StringBuffer strBuffer =
new StringBuffer(str.length); for(int counter=str.length -1 ;
counter>=0;counter--){ strBuffer.append(str.charAt(counter));
}
return strBuffer; }
Recursive public static String getReverseString(String str){ if(str.length <= 1){
return str;
}
return (getReverseString(str.subString(1)) + str.charAt(0); }
Q337. If you have access to a function that returns a random integer
from one to five, write another function which returns a random integer
from one to seven. Ans. We can do that by pulling binary representation
using 3 bits ( random(2) ).
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;
binaryInt = binaryInt /10;
sumValue = sumValue + (binaryDigit * multiple);
multiple = multiple * 2;
}
}
Q338. Write a method to convert binary to a number ?
Ans. convert(int binaryInt) {
int sumValue=0;
int multiple = 1;
while(binaryInt > 0){
binaryDigit = binaryInt%10;
binaryInt = binaryInt /10;
sumValue = sumValue + (binaryDigit * multiple); multiple = multiple * 2;
}
return sumValue; }
Q339. What will the following code print ?
String s1 = "Buggy Bread"; String s2 = "Buggy Bread"; if(s1 == s2)
System.out.println("equal 1");
String n1 = new String("Buggy Bread"); String n2 = new String("Buggy
Bread"); if(n1 == n2)
System.out.println("equal 2");
Ans. equal 1
Q340. Difference between new operator and
Class.forName().newInstance() ?
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 ?
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?
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 ?
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.
C++ Compiler - Source Code --> Machine Code
Java Compiler - Source Code --> Byte Code , JVM - Byte Code -->
Machine 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 ?
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 ?
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.
Sample instructions in Byte Code 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 ?
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 ?
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
1. Retrieval - If Elements are to be retrieved sequentially only, Linked
List is preferred.
2. Insertion - If new Elements are to be inserted in between other
elements , Array List is preferred.
3. Search - Binary Search and other optimized way of searching is not
possible on Linked List.
4. Sorting - Initial sorting could be pain but lateral addition of elements in
a sorted list is good with linked list.
5. Adding Elements - If sufficiently large elements needs to be added
very frequently ,Linked List is preferable as elements don't need
consecutive memory location.
Q348. What are the pre-requisite for the collection to perform Binary
Search ?
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 ?
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 word and value as a
LinkedList. Further level up, we can have linked Hashmaps like ,
hashmap {
a ( key ) -> hashmap (key-aa , value (hashmap(key-aaa,value) b ( key )
-> hashmap (key-ba , value (hashmap(keybaa,value) ....................................................................................
z( key ) -> hashmap (key-za , value (hashmap(key-zaa,value) }
upto n levels ( where n is the average size of the word in dictionary.
Q350. Difference between PATH and CLASSPATH ?
Ans. PATH is the variable that holds the directories for the OS to look for
executables. CLASSPATH is the variable that holds the directories for
JVM to look for .class files ( Byte Code ).
and runs into cyclic wait, it may makes the DB unresponsive. Deadlock
can be avoided using variety of measures, Few listed below -
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. Keeping the
transaction smaller.
Q364. What are temp tables ?
Ans. These are the tables that are created temporarily and are deleted
once the Stored Procedure is complete.
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 ?
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 ?
public static void main(String[] args)
{
StringBuffer s1=new StringBuffer("Buggy");
test(s1); System.out.println(s1); }
private static void test(StringBuffer s){ s.append("Bread");
}
Ans. BuggyBread
Q367. what will be the output of this code ?
public static void main(String[] args) {
String s1=new String("Buggy");
test(s1); System.out.println(s1); }
private static void test(StringBuffer s){ s.append("Bread");
}
Ans. Buggy
Q368. what will be the output of this code ?
public static void main(String[] args)
{
StringBuffer s1=new StringBuffer("Buggy");
test(s1); System.out.println(s1); }
private static void test(StringBuffer s){ s=new StringBuffer("Bread");
}
Ans. Buggy
Q369. what will be the output ?
class Animal {
public void eat() throws Exception { }
}
class Dog2 extends Animal { public void eat(){}
public static void main(){ Animal an = new Dog2(); an.eat();
}
}
Ans. Compile Time Error: Unhandled exception type Exception
Q370. What are advantages of using Servlets over CGI ?
Ans. Better Performance as Servlets doesn't require a separate process
for a single request.
Servlets are platform independent as they are written in Java.
Q371. gfddddddddddddddddddddddddshow Answer
Ans. gfhhhhhhhhhhhhhhhhhhhhf
Q372. Does SQL allow null values ? Can we use it within Where
clause ?
Ans. Yes , we can have null values for columns in SQL. Null value
represent that the columns value is unknown or haven't been filled. Yes,
We can use it within where clause to get the rows with null values.
Q373. Can we add duplicate keys in a HashMap ? What will happen if
we attempt to add duplicate values ?
Ans. No, We cannot have duplicate keys in HashMap. If we attempt to
do so , the previous value for the key is overwritten.
Q374. What is the use of HTTPSession in relation to http protocol ?
Ans. http protocol on its own is stateless. So it helps in identifying the
relationship between multiple stateless request as they come from a
single source.
Q375. Why using cookie to store session info is a better idea than just
using session info in the request ?
Ans. Session info in the request can be intercepted and hence a
vulnerability. Cookie can be read and write by respective domain only
and make sure that right session information is being passed by the
client.
Q376. What are different types of cookies ?
Ans. Session cookies , which are deleted once the session is over.
Permanent cookies , which stays at client PC even if the session is
disconnected. Q377. http protocol is by default ... ?
Ans. stateless
}
}
Ans. NullPointerException at line:
File file = new File("/folder", child);
Q385. What will be the output of following code, assuming that currently
we are in c:\Project ?
public static void main(String[] args){
String child = null;
File file = new File("../file.txt"); System.out.println(file.getPath());
System.out.println(file.getAbsolutePath()); try
{ System.out.println(file.getCanonicalPath()); } catch (IOException e) {
// TODO Auto-generated catch block e.printStackTrace();
}
}
Ans. ..\file.txt C:\Workspace\Project\..\file.txt C:\Workspace\file.txt
Q386. Which is the abstract parent class of FileWriter ?
Ans. OutputStreamWriter
Q387. Which class is used to read streams of characters from a file?
Ans. FileReader
Q388. Which class is used to read streams of raw bytes from a file? Ans.
FileInputStream
Q389. Which is the Parent class of FileInputStream ?
Ans. InputStream
Q390. Which of the following code is correct ?
a.
FileWriter fileWriter = new FileWriter("../file.txt"); File file = new
File(fileWriter );
BufferedWriter bufferedOutputWriter = new BufferedWriter(fileWriter); b.
BufferedWriter bufferedOutputWriter = new BufferedWriter("../file.txt");
File file = new File(bufferedOutputWriter );
FileWriter fileWriter = new FileWriter(file);
c.
File file = new File("../file.txt");
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bufferedOutputWriter = new BufferedWriter(fileWriter);
d.
File file = new File("../file.txt");
BufferedWriter bufferedOutputWriter = new BufferedWriter(file);
FileWriter fileWriter = new FileWriter(bufferedOutputWriter );
Ans. c.
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 ?
Ans. 1. Methods can participate in runtime polymorphism whereas
member variables cannot. 2. Validations can be performed before
setting the variables.
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 ?
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 ?
Ans. Singleton , Prototype , Request , Session , global-session
Q431. What are the various Auto Wiring types in Spring ?
Ans. By Name , By Type and Constructor.
Q432. Difference between first level and second level cache in hibernate
?
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 ?
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 ?
these 2 annotations ?
@Entity
@Entity ( name="EMPLOYEES" )
Ans. The first annotation will try to map the Class with the Table as of
same name as Class whereas the second annotation will specify the
Entity name as "EMPLOYEES" and hence will try to map with Table
Name "EMPLOYEES".
Q462. "What is the difference between these 2 annotations ? @Entity
( name ="EMPLOYEES")
@Entity
@Table ( name=""EMPLOYEES"" )
@Entity ( name="EMP")
@Table ( name="EMPLPYEES" )
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 ?
Ans. Auto , Identity , Sequence and Table.
Q464. How to do Eager loading in Hibernate ?
Ans. Using
lazy = false in hibernate config file
or
@Basic(fetch=FetchType.EAGER) at the mapping Q465. What is Lazy
Initialization in Hibernate ?
Ans. It's a feature to lazily initialize dependencies , relationship and
associations from the Database. Any related references marked as
@OneToMany or @ManyToMany are loaded lazily i.e when they are
accessed and not when the parent is loaded.
Q466. What are the ways to avoid LazyInitializationException ?
Ans. 1. Set lazy=false in the hibernate config file.
2. Set @Basic(fetch=FetchType.EAGER) at the mapping.
3. Make sure that we are accessing the dependent objects before
closing the session. 4. Using Fetch Join in HQL.
Q467. What is cascade ?
The Ignore annotation can be used when you want temporarily disable
the execution of a specific test.
Q475. What is asynchronous I/O ?
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 ?
Ans. Base Class Definition.
Q477. What are new features introduced with Java 8 ?
Ans. Lambda Expressions , Interface Default and Static Methods ,
Method Reference , Parameters Name , Optional , Streams,
Concurrency.
Q478. Can we have a default method without a Body ?
Ans. No. Compiler will give error.
Q479. Does java allow implementation of multiple interfaces having
Default methods with Same name and Signature ?
Ans. No. Compilation error.
Q480. What are Default Methods ?
Ans. With Java 8, We can provide method definitions in the Interfaces
that gets carried down the classes implementing that interface in case
they are not overridden by the Class. Keyword "default" is used to mark
the default method.
Q481. Can we have a default method definition in the interface without
specifying the keyword "default" ? Ans. No. Compiler complains that its
an abstract method and hence shouldn't have the body.
Q482. Can a class implement two Interfaces having default method with
same name and signature ?
public interface DefaultMethodInterface { default public void
defaultMethod(){ System.out.println("DefaultMethodInterface"); }
}
public interface DefaultMethodInterface2 { default public void
defaultMethod(){ System.out.println("DefaultMethodInterface2"); }
}
public class HelloJava8 implements
DefaultMethodInterface,DefaultMethodInterface2 { public static void
main(String[] args){
DefaultMethodInterface defMethIn = new HelloJava8();
defMethIn.defaultMethod();
}}
Ans. No. Compiler gives error saying "Duplicate Default Methods"
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 ?
Ans. Base Class Definition will have precedence over the Interface
Default method definition. Q488. Can we use static method definitions in
Interfaces ?
Ans. Yes, Effective Java 8.
Q489. Can we access Interface static method using Interface references
?
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 ?
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 ?
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 ?
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 ?
helloJava8 ( x-> x%2 )
Ans. helloJava8 receives an Integer as argument and then returns the
modulus of that Integer.
Q494. What is the difference between namenode and datanode in
Hadoop?
Ans. NameNode stores MetaData (No of Blocks, On Which Rack which
DataNode is stored etc) whereas the DataNode stores the actual Data.