You are on page 1of 40

Java Interview questions with answers

Hi Friends,

Here I collect 100 basic java questions from various sites. Then also i prepare the answer
from complete reference book and different sites. But I am not cover all topic in java . I hope its useful
for fresher. Totally I took 10 to 15 days for this preparation.
By
R. Eswara Moorthy, MCA(2006-09)
mailto: eswaramoorthy1985@gmail.com

1. What is JDK?
Java Development Kit contains all the software and tools needed to compile, debug, and run applets
and applications written using Java language. The JDK includes the Java compiler and interpreter and
many Java libraries. It includes the JVM, compiler, debugger and other tools for developing Java applets and
applications.

2. What is JRE?
Java Runtime Environment provides the minimum requirements for executing a Java application; it
consists of the Java Virtual Machine (JVM), core classes, and supporting files. It is part of the (JDK), a set of
programming tools for developing Java applications.

3. What is JVM?
Javac is used to compile this code and to generate .class file. Class file is also known as byte
code. Java byte code is an input to Java Virtual Machine. JVM read this code and interpret it and executes
the program. Java Virtual Machine like its real counter part executes the program and generates output.
4. What is byte code?
Java bytecode is produced by the Java compiler and executed by the JVM (Java Virtual Machine).
Each byte code opcode is one byte in length, although some require parameters, resulting in some multi-byte
instructions. Not all of the possible 256 opcodes are used.

5. What is machine code?


Programming code written in a machine language that can be executed directly by a machine
(computer) without any conversion or translation.

6. What is a oops concepts?


OOP is the technique to create programs based on the real world. It is a method of programming
based on a hierarchy of classes, and well-defined and cooperating objects.

7. What are oops concepts?


Object, Class, Inheritance, Interface, Package, Polymorphism, Encapsulations.

8. What is class?
A class is a structure that defines the data and the methods to work on that data. The class definition
describes all the properties, behavior, and identity of objects present within that class. It contains variable
declaration and method definitions.

9. What is object?
An instance of the class is called object. It is possible to create multiple objects for single class. i.e
It is possible to have multiple objects created from one class.
Real time example: Real world object share two characteristics. They all have state behavior. Dogs have state
(Name, Color, Breath, Hungry) behaviors (Barking, Fetching, Wagging tail)
10. What is encapsulation?
It means binding together code and data it manipulates, and keeps both safe from outside
interference and misuse. If a field is declared private, it cannot be accessed by anyone outside class there by
hiding the fields with in class.

11. What is Inheritance?


It is the process of by which one class acquires the properties of another class. One object acquired
the properties of another object. A class that is derived from another class is called a subclass (also a derived
class, extended class, or child class). The class from which the subclass is derived is called a superclass (also
a base class or a parent class).

12. What is Polymorphism?


It have many forms. This principle can also be applied to object-oriented programming and
languages like the Java language. Subclasses of a class can define their own unique behaviors and yet share
some of the same functionality of the parent class. Method Overriding Runtime Polymorphism. Method
Overloading Compile time polymorphism.

13. What is Interface?


Interfaces are declared using the interface keyword, and may only contain method
signatures and constant declarations (variable declarations which are declared to be both static and final). An
interface may never contain method definitions.

14. What is Package?


A package is a namespace that organizes a set of related classes and interfaces. A package provides
a unique namespace for the types it contains. Classes in the same package can access each other's package-
access members.

15. What is Type conversion or type casting?


Common to assign a value of one type to variable of another type. If the two types are compatible,
then java will perform the conversion automatically.

16. What is truncation?


Integer doesnt have fractional components. When a floating-point value is assigned to an integer
type, the fractional component is lost.

17. Switch ,Break


The switch statement is javas multi-way branch statement. By using break we can force
immediate termination of a loop.

18. What is call-By-Value?


When a simple type is passed to a method, it is done by use of call-by-value.
19. What is Call-By- Reference?
Objects are passed by use of call-by-reference.
20. Purpose on new operator?
The new operator dynamically allocates memory (i.e. Allocates at run time) for an objects and
returns a reference to it.

21. What is Constructor?


A constructor initializes an object immediately upon creation. It has the same name as the class in
which it resides and is syntactically similar to a method. Except that they use the name of the class and have
no return type.

22. Types of constructor?


Default constructor : There is no parameter.
Parameterized constructor: they have single or more then one parameterized constructor.

23. Purpose of this keyword?


this is a reference to the current object the object whose method or constructor is being called.
You can refer to any member of the current object from within an instance method or a constructor by using
this. To resolve the ambiguity between instance variables and parameters. To pass the current object as a
parameter to another method.

24. Garbage collection?


The name "garbage collection" implies that objects no longer needed by the program are "garbage"
and can be thrown away. GC is a form of automatic memory management. Just collector, attempts to reclaim
garbage, or memory occupied by objects that are no longer in use by the program.

25. Purpose of finalize () method?


Sometimes an object will need to perform some action when it is destroyed. For example, if an object
is holding some non-Java resource such as a file handle or window character font, then you might want to
make sure these resources are freed before an object is destroyed. To handle such situations, Java provides a
mechanism called finalization. By using finalization, you can define specific actions that will occur when an
object is just about to be reclaimed by the garbage collector.
protected void finalize()
{
// finalization code here
s.close(); //close the socket
in.close(); out.close(); // close IO streams
}

26. Define Recursion


Simply put, recursion is when a function calls itself. That is, in the course of the function definition
there is a call to that very same function. At first this may seem like a never ending loop, or like a dog chasing
its tail. It can never catch it.

27. What is static?


A static method cant access instance variable. It can access static variable. Static method can access
static method only. Non static method can access both static and non-static method.
28. What is innerclass?
Inner Classes cannot have static members. Only static final variables. Interfaces are never inner.
Static classes are not inner classes. Inner classes may inherit static members that are not compile-time
constants even though they may not declare them. The Java programming language allows you to define a
class within another class. Such a class is called a nested class and is.

29. What is local and Anonymous class?


There are two additional types of inner classes. You can declare an inner class within the body of a
method. Such a class is known as a local inner class. You can also declare an inner class within the body of a
method without naming it. These classes are known as anonymous inner classes. You will encounter such
classes in advanced Java programming.

30. Inheritance?
Refer the 11th question
Class Base
{
Public void baseMethod () { }
}
Class Derived extends base
{ //We can able access base class methods and variables
}
Public static void main (String args []) throws Exception
{
Derived d = new Derived();
d. baseMethod();
}
31. Types of Inheritance?
1.Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Hybrid Inheritance
5. Support for multiple inheritance also but with the help of Interface.

32. Use of super keyword?


The super keyword in java programming language refers to the superclass of the class where the
super keyword is currently being used. The super keyword as a standalone statement is used to call the
constructor of the superclass in the base class.

33. Define method overloading?


In same class, if name of the method remains common but the number and type of parameters are
different, then it is called method overloading in Java. Method names are equal but different number and type
of argument and different return type.

34. Define method overriding?


Method names are equal and argument, type and return type are same. In a class hierarchy, when a
method in a subclass has the same name and type signature as a method in its superclass, then the method in
the subclass is said to override the method in the superclass.
35. How to call or access base class (override) method? example (This question expect after ask What
is overriding? So try to understand the following program)
Class A
{
void show ()
{
System.out.println (This is Base Class Show method);
}
}
Class B extends A
{
Public B () //Constructor
{
super.show(); //This method called during object initialization
}
void show ()
{
super.show();
System.out.println (This is derived class show method output);
}
}
public static void main(String args[]) throws Exception
{
B b = new B(); // b is a base class object
b.show();
}

Output:
This is Base Class Show method output -- this line execute during create object for class B.
This is Base Class Show method output -- this line execute during call b.show
This is derived class show method output.
36. What is Abstract Class?
An abstract class is a class that is declared abstractit may or may not include abstract methods.
Abstract classes cannot be instantiated, but they can be subclassed. but they can be extended into sub-
classes.An abstract method is a method that is declared without an implementation (without braces, and
followed by a semicolon), like this:
abstract void moveTo (double deltaX, double deltaY);

37. What is Interface?


An interface in the Java programming language is an abstract type that is used to specify an
interface (in the generic sense of the term) that classes must implement. Interfaces are declared using the
interface keyword, and may only contain method signatures and constant declarations (variable declarations
which are declared to be both static and final). An interface may never contain method definitions.

38. Purpose of final keyword?


A final class cannot be subclassed. This is done for reasons of security and efficiency. A final
method cannot be overridden by subclasses. Using final to Prevent Inheritance. A final variable can only be
assigned once. This assignment does not grant the variable immutable status. If the variable is a field of a
class, it must be assigned in the constructor of its class.

39. What is Package?


A package is a grouping of related types providing access protection and name space management.
Note that types refers to classes, interfaces, enumerations, and annotation types. Enumerations and annotation
types are special kinds of classes and interfaces, respectively, so types are often referred to in this lesson
simply as classes and interfaces.

40. What is an Exception?


An exception is an event that occurs during the execution of a program that disrupts the normal flow
of instructions. The use of exceptions to manage errors has some advantages over traditional error-
management techniques.
41. What is an error?
An Error is a subclass of Throwable that indicates serious problems that a reasonable application
should not try to catch. Most such errors are abnormal conditions.

42. Types of Exception?


There are many types of exceptions in java: Some exceptions are: 1)Arithmetic Exception -very
common exception which occurs when there is any error in the arithmetic operation u specify.
2) NullPointer Exception - happens if u specify a wrong or unavailable destination
3) ArrayIndexOutOfBounds Exception - happens if u point the unavailable index of the array
4) NegativeArraySizeException -happens when u specify negative size for array
5) NumberFormat Exception -happens in the case of wrong number format

43. What is Runtime Exception?


RuntimeException is the superclass of those exceptions that can be throws during the normal
operation of the JVM. A method is not required to declare in its throws clause any subclasses of
RuntimeException that might be thrown during the execution of the method but not caught.

44. What is compile time exception?

45. Purpose of try block?


Program statements that you want to monitor for exceptions are contained within a try block. If an
exception occurs within the try block, it is thrown. The first step in constructing an exception handler is to
enclose the statements that might throw an exception within a try block.

46. Purpose of catch block?


Our code can catch this exception (using catch) and handle it in some rational manner. System-
generated exceptions are automatically thrown by the Java run-time system.
47. Purpose of throw block?
To manually throw an exception, use the keyword throw. Before catching an exception it is must to
be thrown first. This means that there should be a code somewhere in the program that could catch the exception.
We use throw statement to throw an exception or simply use the throw keyword with an object reference to throw
an exception. A single argument is required by the throw statement i.e. a throwable object. As mentioned earlier
Throwable objects are instances of any subclass of the Throwable class.
throw new VeryFastException();

48. Purpose of throws?


Any exception that is thrown out of a method must be specified as such by a throws clause.

49. Purpose of finally block?


Any code that absolutely must be executed before a method returns is put in a finally block. i.e) If any
exception raise with in try block , directly goes to exception block. And exit the program. Suppose if want
write ant code before terminating, that part of code write into finally block.
try{
}
finally{ //Write necessary executing code here before exit the program.
}
catch{
}
50. Some time dont need finally block code. But finally block code must be execute all time. How to avoid
finally block code at certain time?
System.exit(0); Whereever use this code, automatically terminate the program.

51. Which is possible to single try and multiple catch block?

Yes. It is possible. try with single catch block will catch what ever the exception thrown by the code
inside the try block but it will not be clear..some time a code in a try block can throw different type of
exception.To catch the different type of exception what our code throws we can use difference type of catch
for the single try block it will be more clear and help full.
52. What is Chained Exception?
An application often responds to an exception by throwing another exception. In effect, the first
exception causes the second exception. It can be very helpful to know when one exception causes another.

53. What is thread?


thread is a program's path of execution.
54. Life cycle of Thread?
There are number of stages for executing the Thread.
1.ready to run
2.run
3.suspend(wait,sleep)
4.resume(notify,notify all)
5.kill.

55. What is synchronization?


Synchronization is a process of controlling the access of shared resources by the multiple threads in
such a manner that only one thread can access one resource at a time. In non synchronized multithreaded
application, it is possible for one thread to modify a shared object while another thread is in the process of
using or updating the object's value. Synchronization prevents such type of data corruption.
public synchronized void method1(){
// Appropriate method-related code.
}

56. How to create a thread?


There are two main ways of creating a thread.
The first is to extend the Thread class and
The second is to implement the Runnable interface.

57. Define extend thread


The first way to create a thread is to create a new class that extends Thread, and then to
create an instance of that class. The extending class must override the run( ) method, which is the entry point
for the new thread. It must also call start( ) to begin execution of the new thread.

58. Define implement tunnable interface


The easiest way to create a thread is to create a class that implements the Runnable interface.
Runnable abstracts a unit of executable code. You can construct a thread on any object that implements
Runnable. To implement Runnable, a class need only implement a single method called run( ), which is
declared like this:
public void run( )
Inside run( ), you will define the code that constitutes the new thread. It is important to understand that run( )
can call other methods, use other classes, and declare variables, just like the main thread can. The only
difference is that run( ) establishes the entry point for another, concurrent thread of execution within your
program.

59. Which is better? Extend the thread and Implement Runnable


Extending the Thread class will make your class unable to extend other classes, because of the
single inheritence feature in JAVA. However, this will give you a simpler code structure. If you implement
runnable, you can gain better object-oriented design and consistency and also avoid the single inheritance
problems.
A better way to create a thread in Java is to implement Runnable interface.
if the thread class you are creating is to be subclass of some other class, it cant extend from the Thread class.
This is because Java does not allow a class to inherit from more than one class. In such a case one can use
Runnable interface to implement threads.

60. Purpoe of isAlive()?


The isAlive( ) method returns true if the thread upon which it is called is still running. It returns false
otherwise.
final boolean isAlive( )

61. Purpose of join()?


The method that you will more commonly use to wait for a thread to finish is called join( ), shown here:
final void join( ) throws InterruptedException
This method waits until the thread on which it is called terminates. Its name comes from the concept of the
calling thread waiting until the specified thread joins it. Additional forms of join( ) allow you to specify a
maximum amount of time that you want to wait for the specified thread to terminate.
62. Which method cant synchronized?

63. What is deadlock in java?


A special type of error that you need to avoid that relates specifically to multitasking is deadlock,
which occurs when two threads have a circular dependency on a pair of synchronized objects. For example,
suppose one thread enters the monitor on object X and another thread enters the monitor on object Y. If the
thread in X tries to call any synchronized method on Y, it will block as expected. However, if the thread in Y,
in turn, tries to call any synchronized method on X, the thread waits forever, because to access X, it would
have to release its own lock on Y so that the first thread could complete.

64. Define String


The String class represents character strings . Strings are constant; their values cannot be changed
after they are created. String objects are immutable they can be shared. For example:
String str = "abc";

is equivalent to:

char data[] = {'a', 'b', 'c'};


String str = new String(data);

65. What are the method available in String Class?


Length - Measure the String length int len = str.length();
Concat Concatenation of two Strings String str3 = str1.concat(str2);
charAt - Returns the character at the specified index. Char c = str1.charAt(2);
replace - Returns a new string resulting from
replacing all occurrences of String str3 = str1.replace(char old,char new);

oldChar in this string with newChar.


And so on.

66. Purpose of equals() and ==?


equals() is used to compare the content of the object. if(str1.equals(str3)) i.e compare each and every
char of the astring.
== is used to compare object only if(str1==str2)

67. Defne String Buffer


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.
String buffers are safe for use by multiple threads. The methods are synchronized where necessary so that all
the operations on any particular instance behave as if they occur in some serial order that is consistent with the
order of the method calls made by each of the individual threads involved.

68. What is Collection?


The Collections Framework provides a well-designed set of interfaces and classes for storing and
manipulating groups of data as a single unit, a collection. The framework provides a convenient API to many
of the abstract data types familiar from computer science data structure curriculum: maps, sets, lists, trees,
arrays, hashtables and other collections. The following diagrams shows the framework interface hierarchy.

Interface Implementation Historical


Set HashSet TreeSet
Vector
List ArrayList LinkedList
Stack
Hashtable
Map HashMap TreeMap
Properties

69. Defne List Interface


The List interface extends Collection and declares the behavior of a collection that stores a sequence
of elements. Elements can be inserted or accessed by their position in the list, using a zero-based index. A list
may contain duplicate elements.
To obtain the object stored at a specific location, call get( ) with the index of the object.
To assign a value to an element in the list, call set( ), specifying the index of the object to be changed.
To find the index of an object, use indexOf( ) or lastIndexOf( ).

70. Define Set Interface


The Set interface defines a set. It extends Collection and declares the behavior of a collection that
does not allow duplicate elements. Therefore, the add( ) method returns false if an attempt is made to add
duplicate elements to a set. It does not define any additional methods of its own.

71. Define SortedSet Interface


The SortedSet interface extends Set and declares the behavior of a set sorted in ascending
order.Several methods throw a NoSuchElementException when no items are contained in the invoking set. A
ClassCastException is thrown when an object is incompatible with the elements in a set.
To obtain the first object in the set, call first( ).
To get the last element, use last( ).
To obtain a subset of a sorted set by calling subSet( ), specifying the first and last object in the set.
To obtain the subset that starts with the first element in the set, use headSet( ).
To obtain the subset that ends the set, use tailSet( ).

72. Define Map interface


The Map interface maps unique keys to values. A key is an object that you use to retrieve a value at a
later date. Given a key and a value, you can store the value in a Map object. After the value is stored, you can
retrieve it by using its key.
Maps revolve around two basic operations: get( ) and put( ). To put a value into a map, use put(
), specifying the key and the value. To obtain a value, call get( ), passing the key as an argument. The value is
returned.

73. Define SortedMap Interface


The SortedMap interface extends Map. It ensures that the entries are maintained in ascending key order
Sorted maps allow very efficient manipulations of submaps (in other words, a subset of a map).
To obtain a submap, use headMap( ), tailMap( ), or subMap( ).
To get the first key in the set, call firstKey( ).
To get the last key, use lastKey( ).

74. What is ArrayList class?


The ArrayList class extends AbstractList and implements the List interface. ArrayList supports
dynamic arrays that can grow as needed. In Java, standard arrays are of a fixed length. After arrays are
created, they cannot grow or shrink. an ArrayList can dynamically increase or decrease in size
Public static void main(String args[])throws Exception {
ArrayList al = new ArrayList();
System.out.println("Initial size of al: " + al.size());
al.add("C"); al.add("A");
al.add("E"); al.add("B");
a1.add("5"); al.add(1,"X");
System.out.println("Size of al after additions: " +al.size());
System.out.println("Contents of al: " + al);
// Remove elements from the array list
al.remove("E");
al.remove(2);
System.out.println("Size of al after deletions: " +al.size());
System.out.println("Contents of al: " + al);
}
Output :
Initialsizeofal:0
Sizeofalafteradditions:6
Contentsofal:[C,X,A,E,B,5]
Sizeofalafterdeletions:4
Contentsofal:[C,X,B,D]

75. How to get element fromArrayList?


get(int index)

Returns the element at the specified position in this list.


Public static void main(String args[])throws Exception {
ArrayList al = new ArrayList();
al.add("C"); al.add("A");
al.add("E"); al.add("B");
for(int i=0; i<al.size(); i++)
{
String s = (String)al.get(i); //Convert object to string
System.out.println(i+st value : +s);
}
}
Output:
0 st value : C
1 st value : A
2 st value : E
3 st value : B

76. Define LinkedList class


The LinkedList class extends AbstractSequentialList and implements the List interface.It provides
a linked-list data structure. It contains some additional methods such as :
void addFirst(Object obj) - To add elements to the start of the list,
void addLast(Object obj) - To add elements to the end,
Object getFirst( ) - To obtain the first element,
Object getLast( ) - To retrieve the last element,,
Object removeFirst( ) - To remove the first element
Object removeLast( ) - To remove the last element,

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


{
LinkedList link = new LinkedList();
link.add("C"); link.add("A");
link.add("E"); link .add("B");
System.out.println(Intial content : +link);
link.addLast("Z");
link.addFirst("A1");
link.add(1, "A2");THE JAVA LIBRARY
System.out.println("After adding : " + link);
// remove elements from the linked list
link.remove("E");
link.remove(2);
System.out.println("After Deletion : "+ link);
// remove first and last elements
link.removeFirst();
link.removeLast();
System.out.println(After deletion : +link();
String value = (String)link.get(2); System.out.print( 2nd value ;+value);
}

Output:
IntialContent:[C,A,E,B]
AfterAdding:[A1,A2,C,A,E,B,Z]
AfterDeletion:[A1,A2,A,B,Z]
AfterDeletion:[A2,A,B]
2ndvalue:B

77. Define HashSet class


HashSet extends AbstractSet and implements the Set interface. It creates a collection that uses a
hash table for storage.Note that a hash set does not guarantee the order of its elements, because the process of
hashing doesnt usually lend itself to the creation of sorted sets. If you need sorted storage, then another
collection, such as TreeSet, is a better choice.
publicstaticvoidmain(Stringargs[]){

HashSeths=newHashSet();
hs.add("B"); hs.add("A");
hs.add("D"); hs.add("E");
hs.add("C"); hs.add("F");
System.out.println(Hashsetcontents:+hs);
}
Output:
Hashsetcontents:[A,F,E,D,C,B]

78. Define LinkedHashSet class


This class extends HashSet, but adds no members of its own. LinkedHashSet maintains a linked list
of the entries in the set, in the order in which they were inserted. This allows insertion-order iteration over the
set. That is, when cycling through a LinkedHashSet using an iterator, the elements will be returned in the
order in which they were inserted. This is also the order in which they are contained in the string returned by
toString( ) when called on a LinkedHashSet object.
To see the effect of LinkedHashSet, try substituting LinkedHashSet For HashSet in the preceding program
Output:
LinkedHashSetcontents:[B,A,D,E,C,F]

79. Define TreeSet class


TreeSet provides an implementation of the Set interface that uses a tree for storage. Objects are
stored in sorted, ascending order. Access and retrieval times are quite fast, which makes TreeSet an excellent
choice when storing large amounts of sorted information that must be found quickly.
publicstaticvoidmain(Stringargs[]){
//Createatreeset
TreeSetts=newTreeSet();
//Addelementstothetreeset
ts.add("C"); ts.add("A"); output:
ts.add("B"); ts.add("E");[A,B,C,D,E,F]
ts.add("F"); ts.add("D");
System.out.println(ts);}

80. Hoe to reterive the elements from ArrayList, TreeSet, LinkedList, HashSet, and LinkedHashSet using
Iterator?
public static void main(String args[])throws Exception{
ArrayListal=newArrayList();
//AddelementstothearrayList
al.add("A"); al.add("B");
al.add("C"); al.add("D");
al.add("E"); al.add("F");
System.out.println(ArrayListContent);
Iteratoritr=al.iterator();
While(itr.hashNext()){
Stringcontent=(String)itr.next();
System.out.print(,\t+content);
}
}
Output:
ArrayListContent:A,B,C,D,E,F

The above program applicable for TreeSet, LinkedList, HashSet and LinkedHashSet.

81. Define Random Access Interface


This interface contains no members.However, by implementing this interface, a collection signals that
it supports efficient random access to its elements

82. Concept of Maps:


A map is an object that stores associations between keys and values, or key/value pairs. Given a key,
you can find its value. Both keys and values are objects. The keys must be unique, but the values may be
duplicated. Some maps can accept a null key and null values, others cannot.

83. Define SortedMap Interface


The SortedMap interface extends Map. It ensures that the entries are maintained in ascending key order.
Sorted maps allow very efficient manipulations of submaps (in other words, a subset of a map).
To obtain a submap, use headMap( ), tailMap( ), or subMap( ).
To get the first key in the set, call firstKey( ).
To get the last key, use lastKey( ).

84. Define HashMap class


The HashMap class uses a hash table to implement the Map interface. This allows the execution time of
basic operations, such as get( ) and put( ), to remain constant even for large sets. You should note that a hash
map does not guarantee the order of its elements. the order in which elements are added to a hash map is not
ecessarily the order in which they are read by an iterator.
public static void main(String args[])throws Exception{
// Create a hash map
HashMap hm = new HashMap();
// Put elements to the map
hm.put("John Doe", new Double(3434.34));
hm.put("Tom Smith", new Double(123.22));
hm.put("Jane Baker", new Double(1378.00));
hm.put("Todd Hall", new Double(99.22));
hm.put("Ralph Smith", new Double(-19.08));
//Getasetoftheentries
Set set = hm.entrySet();
//Getaniterator
Iterator i = set.iterator();
//Displayelements
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());

double balance = ((Double)hm.get("John Doe")).doubleValue();


hm.put("John Doe", new Double(balance + 1000));
System.out.println("John Doe's new balance: " + hm.get("John Doe"));
}

Output:
ToddHall:99.22
RalphSmith:19.08
JohnDoe:3434.34
JaneBaker:1378.0
TomSmith:123.22
JohnDoescurrentbalance:4434.34

85. Define TreeMap Class


The TreeMap class implements the Map interface by using a tree. A TreeMap provides an
efficient means of storing key/value pairs in sorted order, and allows rapid retrieval. You should note that,
unlike a hash map, a tree map guarantees that its elements will be sorted in ascending key order. It does not
define any additional methods and put and get method procedure is same as HashMap class.
86. Define LinkedHashMap class
LinkedHashMap maintains a linked list of the entries in the map, in the order in which they were
inserted. This allows insertion-order iteration over the map. That is, when iterating a LinkedHashMap, the
elements will be returned in the order in which they were inserted. You can also create a LinkedHashMap
that returns its elements in the order in which they were last accessed.

87. Define Vector class


Vector implements a dynamic array. It is similar to ArrayList, but with two differences: Vector is
synchronized, and it contains many legacy methods that are not part of the collections framework.
Public static void main(String args[])throws Exception{
Vector v = new Vector();
v.add(A); v.add(B);
v.addElement(C);
v.add(1,X);
System.out.println( Vector Content : +v+ and its size is : +v.size());
//Step 1. How to Reterive the contents from vector . This ordinary way
for(int i=0; i<v.size(); i++)
{
String s = (String)v.get(i);
System.out.println(i+ value+s);
}
//Step 2 : The another way to reterive element from
Emumeration e = v.elements();
While(e.hasMoreElements())
{
String val = (String)e.nextElement();
System.out.println(Val :+val);
}
}
Output :
Vector Content v[A,X,B,C]
0 value :A 1 value X
2 value :B 3 value C and its size is : 4
Val : A Val :X Val : B Val :C

88. Define Hashtable


Like HashMap, Hashtable stores key/value pairs in a hash table. When using a Hashtable, you
specify an object that is used as a key, and the value that you want linked to that key. The key is then hashed,
and the resulting hash code is used as the index at which the value is stored within the table.
public static void main(String args[])throws Exception
{
Hashtable ht = new Hashtable();
ht.put("John Doe", new Double(3434.34));
ht.put("Tom Smith", new Double(123.22));
ht.put("Jane Baker", new Double(1378.00));
ht.put("Todd Hall", new Double(99.22));
ht.put("Ralph Smith", new Double(-19.08));

Enumeration e = ht.keys();
while(e.hasMoreElements()) {
String key = (String) e.nextElement();
System.out.println(Key + ": " +ht.get(key));
}
}
Output:
ToddHall:99.22
RalphSmith:19.08
JohnDoe:3434.34
JaneBaker:1378.0
TomSmith:123.22

89. Define Properties Class


Properties is a subclass of Hashtable. It is used to maintain lists of values in which the key is a
String and the value is also a String. The Properties class is used by many other Java classes. For example, it
is the type of object returned by System.getProperties( ) when obtaining environmental values.
public static void main(String args[])throws Exception
{
Propertiescapitals=newProperties();
Setstates;
Stringstr;
capitals.put("Illinois","Springfield");
capitals.put("Missouri","JeffersonCity");
capitals.put("Washington","Olympia");
capitals.put("California","Sacramento");
capitals.put("Indiana","Indianapolis");
//Showallstatesandcapitalsinhashtable.
states=capitals.keySet();//getsetviewofkeys
Iteratoritr=states.iterator();
while(itr.hasNext()){
str=(String)itr.next();
System.out.println("Thecapitalof"+str+"is"
+capitals.getProperty(str)+".");
}
System.out.println();
}
Output :
ThecapitalofMissouriisJeffersonCity.
ThecapitalofIllinoisisSpringfield.
ThecapitalofIndianaisIndianapolis.
ThecapitalofCaliforniaisSacramento.
ThecapitalofWashingtonisOlympia.

90. Features of properties class?


One of the most useful aspects of Properties is that the information contained in a Properties
object can be easily stored to or loaded from disk with the store( ) and load( ) methods. At any time, you can
write a Properties object to a stream or read it back. This makes property lists especially convenient for
implementing simple databases.

91. What is StringTokenizer class?


The StringTokenizer class provides the first step in this parsing process, often called the lexer (lexical
analyzer) or scanner. StringTokenizer implements the Enumeration interface. Therefore, given an input string,
you can enumerate the individual tokens contained in it using StringTokenizer.
To use StringTokenizer, you specify an input string and a string that contains delimiters. Delimiters
are characters that separate tokens. Each character in the delimiters string is considered a valid delimiter
public static void main(String args[]) {
Stringdate=15122009;
StringTokenizerst=newStringTokenizer(date,"-");
while(st.hasMoreTokens()){
Stringtok=st.nextToken();
System.out.println(tok);
}
}
Output :
15
12
2009

92. What is Locale class?


Locale object represents a specific geographical, political, or cultural region. An operation that
requires a Locale to perform its task is called locale-sensitive and uses the Locale to tailor information for
the user. For example, displaying a number is a locale-sensitive operation--the number should be formatted
according to the customs/conventions of the user's native country, region, or culture.

93. How to Create a New File?


File f = new File(D:/Eswar/sample.txt);
f.createNewFile()
This two lines are used to create empty file .

94. Define Serialization and Deserialization?


Serialization is the process of writing the state of an object to a byte stream. This is useful when
you want to save the state of your program to a persistent storage area, such as a file.
At a later time, you may restore these objects by using the process of deserialization.

publicstaticvoidmain(Stringargs[]){
//Objectserialization
try{
MyClassobject1=newMyClass("Hello",7,2.7e10);
System.out.println("object1:"+object1);
FileOutputStreamfos=newFileOutputStream("serial");
ObjectOutputStreamoos=newObjectOutputStream(fos);
oos.writeObject(object1);
oos.flush();
oos.close();
}
catch(Exceptione){
System.out.println("Exceptionduringserialization:"+e);
System.exit(0);
}

//Objectdeserialization
try{
MyClassobject2;
FileInputStreamfis=newFileInputStream("serial");
ObjectInputStreamois=newObjectInputStream(fis);
object2=(MyClass)ois.readObject();
ois.close();
System.out.println("object2:"+object2);
}
catch(Exceptione){
System.out.println("Exceptionduringdeserialization:"+e);
System.exit(0);
}
}
}
classMyClassimplementsSerializable{
Strings;
inti;
doubled;
publicMyClass(Strings,inti,doubled){
this.s=s;
this.i=i;
this.d=d;
}
publicStringtoString(){
return"s="+s+";i="+i+";d="+d;
}
}

This program demonstrates that the instance variables of object1 and object2 are
identical. The output is shown here:
object1:s=Hello;i=7;d=2.7E10
object2:s=Hello;i=7;d=2.7E10

95. What is Statement?


Statement is a Interface . The object used for executing a static SQL statement and returning the
results it produces.

96. What is PreparedStatement?


public interface PreparedStatement extends Statement
An object that represents a precompiled SQL statement. A SQL statement is precompiled and
stored in a PreparedStatement object. This object can then be used to efficiently execute this statement
multiple times.

97. What is CallableStatement?


public interface CallableStatement extends PreparedStatement

The interface used to execute SQL stored procedures. JDBC provides a stored procedure SQL escape syntax
that allows stored procedures to be called in a standard way for all RDBMSs. This escape syntax has one form
that includes a result parameter and one that does not. If used, the result parameter must be registered as an
OUT parameter. The other parameters can be used for input, output or both. Parameters are referred to
sequentially, by number, with the first parameter being 1.

98. Define call by reference and call by value?


When a simple type is passed to a method, it is done by use of call-by-value
Objects are passed by use of call-by-reference.

99. Define AccessModifier in java


public - When a member of a class is modified by the public specifier, then that member can
be accessed by any other code. .
private - Declared as private, cant be seen outside of its class
protected - Declared as protected can be access by classe in the same packages and subclassed in
other package.
default - When no access specifier is used, then by default the member of a class is public
within its own package, but cannot be accessed outside of its package.

100. Purpose of new operatior?


The new operator dynamically allocates memory (i.e, allocates at run time) for an object and
returns a reference to it.

101. How to sort collection?


List myList; List myList;
myList = getUnsortedList( .. ); (OR) myList = getUnsortedList()
Set Items; Collections.sort(myList);
Items = new TreeSet(myList);

102. What is Marker interface?


An interface with no methods Egs: Serializable, Remote and Cloneable.

Differences :

1. Diff. between overloading and overridding?

S.I No Overloading Overriding


1. same method name with different same method names with same arguments and same
arguments may or may not be same return return types associated in a class and its subclass.
type written in the same class itself.
2. Method overriding is when a child class Method overloading is defining several methods in the
redefines the same method as a parent same class, that accept different numbers and types of
class, with the same parameters. parameters.
3. It is an example of CompileTime It is an example of Runtime Polymorphism
Polynorphism

2. Diff. between Interface and Abstract?

S.I No Interface Abstract


1. An interface contain only decleration but It contains abstract and non-abstract methods
no
Implementation
2. It cannot inherit from another class or It can inherit from another non-abstract class.
interface. Abstract class AbsTest2 extends Test1{ // method
decleration and definition }
where Test1 is non Abstract class. AbsTest2 inherit all
properties from Test1 class.
3. It Support Multiple Inheritance It does not support Multiple Inheritance.

3. Diff. between throw and throws?


S.I No throw throws
1. exception is thrown manually used in the case of checked exceptions to reintimate
the compiler that we have handled the exception. so
throws is to be used at the time of defining a method
and also at the time of calling that function which rises
an checked exception.
2. try public static void main(String args[])throws Excep{
{
}
throw
and
}catch(Exception e){
} void add(int a,int b)throws Exception{......}

4. Diff. between sleep() and wait()?


S.I No sleep() wait()
1.

2.
3.

5. Diff. between compile time and runtime excepion


S.I No CompileTime Exception RunTime Exception
1. A compile-time error is a problem found at A runtime error is anything that goes wrong at
compile time. runtime
2. Compile time errors are nothing but the where as Runtime errors are nothing but the logicall
syntax errors in the program i.e., the errors
program should follow the structure of java
3. Compile time errors are taken care by Run time errors are taken care by programers.
compiler
6. Diff. between process and thread?

S.I No Process thread


1. Process has its own memory space, runtime Thread runs inside a process and share its resources
environment and process Id with other threads.
2. Process is a program inder execution Thread is a part of program
3. Process may have multiple threads. Proces
is an executing program.

7. Diff between String and StringBuffer?


S.I No String StringBuffer
1. the String class is used to manipulate The StringBuffer class is used to represent characters
character strings that cannot be changed. that can be modified.
Simply stated, objects of type String are
read only
2. It is immutable. once you declare it you are It is mutable. You can change the content of
not able to modify it StringBuffer variable.
3. StringBuffer is faster than String when performing
simple concatenations.
4. It is constant It is dynamic and growable.

8. Diff. between List and Set?


S.I No List Set
1. List allows duplicate values set doesnt allow duplicates
2. List maintains the order in which you Set doesnt maintain order
inserted elements in to the list
3.

9. Diff between Map and Set?


S.I No Map Set
1. Map have key, object with key you can get It is just the object
the object.
2. Map allow duplicate values Set not allow duplicate.
3.

10. Diff between List and Map?


S.I No List Map
1. Elements are stored in particular order. Elements are stored in key, value pairs.
2. Repetitions of elements are allowed. Repetitions of values are allowed but not keys.
3.

11. Diff between LinkedList and ArrayList?


S.I No ArrayList LinkedList
1. Inserting an element in the middle of the But fast on LinkedList.
list is relatively slow on ArrayList.
2. A List implemented with an array. Allows Relatively slow for random access
rapid random access to elements
3.

12. Diff between Vector and ArrayList?


S.I No ArrayList Vector
1. Arraylist is not synchronized It is synchronized.
2. It has no default size It has a default size of 10.
3. The ArrayList increases its array size by A Vector defaults to doubling the size of its array
50 percent

13. Diff between Vector and Map?


S.I No
1.
2.
3.

14. Diff between Hashtable and Hashmap?


S.I No Hashtable Hashmap
1. It support synchronization It is not synchronized
2. It can not allow null values It allow null values
3. It is thread safe. That means when It is thread safe
multiple thread accessing a hashtable and
one of these thread try to update that
hashtable then locking takes data integrity.
4. It is faster than hashtable.
5. Retrieves the elements using Enumerator Retrieves the elements using Iterator

15.Diff between Treemap and Treeset?


S.I No Treemap Treeset
1. It has cotainsKey, get, put and remove It has add and remove methods.
methods.
2.

16. Diff between Hashmap and Hashset?


S.I No Hashmap Hashset
1. It implements Map interface. It implements Set interface
2. It prints the elements ordered It has no order.
3. It allow null values It does not all duplicate values.

17. Diff between Collection and Collections?


S.I No Collection Collections
1. It is a interface implemented by all other It is a class.
interface like list and set.
2. It is an object that groups multiple It is used to store, retrieve and manipulate data and to
elements into a single unit. retransmit data from one method to another.

18. Diff between Enumeration and Iterator?


S.I No Enumeration Iterator
1. It is an interface It is an interface.
2. It has two methods It has 3 methods.
hasMoreElements() hashNext(),
nextElement() next() and remove()
3. By using enumerator we can reterive more By using iterator we can reterive the values one by
than one value. one.
19. Diff between Iterator and ListIterator
S.I No Iterator ListIterator
1. An iterator forward traversing only List Iterator both type of traversing is possible.
possible
2. Modify the list during iteration and obtain the
iterators current position in the list.
3. ListIterator extends Iterator and support modification

20. Diff between methods and constructor


S.I No Constructor Methods
1. A constructor is a member function of a A method is an ordinary member function of a class
class that is used to create objects of that
class.
2. It has the same name as the class itself, It has its own name, a return type (which may be
has no return type, and is invoked using void), and is invoked using the dot operator.
the new operator.
3. Constructor does not have a return
statement in its body.

21. Diff between notify and notifyAll?


S.I No Notify notifyAll
1. 'notify' method wakes up a single thread NotifyAll' it says that its will wake up all the threads
waiting on the object and passes the waiting on the object and will select a thread to pass
control of the monitor to it control to it
2.
3.

22. Diff between StringBuilder and StringBuffer?


S.I No StringBuilder StringBuffer
1. StringBuilder is unsynchronized StringBuffer is synchronized.
2. When the application needs to be run only
in a single thread then it is better to use It.
It is more efficient than StringBuffer.
3. If your text can change and will only be .If your text can changes, and will be accessed from
accessed from a single thread, use a multiple threads, use a StringBuffer because
StringBuilder because StringBuilder is StringBuffer is synchronous.
unsynchronized.

23. Diff between J1.4 and J1.5?


S.I No
1.
2.
3.

DataBase Connection code (MySql) in java


Public static void main(String args[])throws Exception {
try{
String driver = "com.mysql.jdbc.Driver";
Class.forName(driver).newInstance(); // load mysql driver
String url = "jdbc:mysql://localhost:3306/studentdb";
String username = "root";
String password = "admin";

Connection conn = DriverManager.getConnection(url, username, password);


stmt=conn.createStatement();
String query = "";
ResultSet rs = st.executeQuery();
}catch(Exception e){
System.out.println(Exeption :+e);
}
}

Relationship between JDK, JRE and JVM?


JRE is Java runtime environments. It is used to help in doing work with the combination of hardware
and software. It makes the Java easy to transfer data language. The programmers can create the software without
think that how and where the software run.

JVM is a Java virtual machine which facilitates the programmer to execute the Java code easily. It gives a
platform to run the different abstracts of language between central processing unit (CPU) and operating system.
JVM is program which has JRE and it converts the source code into byte code. This code is easy to understand for
the machine and some time called machine code.

JDK is Java development kit. It is used with the combination of Java software to develop the new software. JDK
contains more then one JRE and developmental sub program like debugger, libraries etc. In the libraries you may
use the JVM which is embedded in library code. It is used for compilation of byte code and library software. JDK
works with the help of JVM and JRE.
JSP

1. What is JSP?
avaServer Pages (JSP) is a server side Java technology that allows software developers to create
dynamically generated web pages, with HTML, XML, or other document types, in response to a Web client
request to a Java Web Application container (server). JSP pages are loaded in the server and operated from a
structured special installed Java server packet called a J2EE Web Application often packaged as a .war or .ear
file archive.

JSP pages are efficient, it loads into the web servers memory on receiving the request very first time and the
subsequent calls are served within a very short period of time.

In today's environment most web sites servers dynamic pages based on user request. Database is very
convenient way to store the data of users and other things. JDBC provide excellent database connectivity in
heterogeneous database environment. Using JSP and JDBC its very easy to develop database driven web
application.

Java is known for its characteristic of "write once, run anywhere." JSP pages are platform independent. Your
port your .jsp pages to any platform.

2. Diff between jsp and servlet?


S.I No JSP Servlet
1.
2. .
3. .

3. What is Implicit object?


There are nine implicit objects. Here is the list of all the implicit objects:

Object Class
application javax.servlet.ServletContext
config javax.servlet.ServletConfig
exception java.lang.Throwable
out javax.servlet.jsp.JspWriter
page java.lang.Object
PageContext javax.servlet.jsp.PageContext
request javax.servlet.ServletRequest
response javax.servlet.ServletResponse
session javax.servlet.http.HttpSession

4. What is Application ?

These objects has an application scope. These objects are available at the widest context level, that allows to
share the same information between the JSP page's servlet and any Web components with in the same
application.

5. What is Config:
These object has a page scope and is an instance of javax.servlet.ServletConfig class. Config object allows to
pass the initialization data to a JSP page's servlet. Parameters of this objects can be set in the deployment
descriptor (web.xml) inside the element <jsp-file>. The method getInitParameter() is used to access the
initialization parameters.

6. What is Exception:

This object has a page scope and is an instance of java.lang.Throwable class. This object allows the exception
data to be accessed only by designated JSP "error pages."

7. What is Out:

This object allows us to access the servlet's output stream and has a page scope. Out object is an instance of
javax.servlet.jsp.JspWriter class. It provides the output stream that enable access to the servlet's output stream.

8. What is Page:

This object has a page scope and is an instance of the JSP page's servlet class that processes the current
request. Page object represents the current page that is used to call the methods defined by the translated
servlet class. First type cast the servlet before accessing any method of the servlet through the page.

9. What is Pagecontext:

PageContext has a page scope. Pagecontext is the context for the JSP page itself that provides a single API to
manage the various scoped attributes. This API is extensively used if we are implementing JSP custom tag
handlers. PageContext also provides access to several page attributes like including some static or dynamic
resource.

10. What is Request:

Request object has a request scope that is used to access the HTTP request data, and also provides a context to
associate the request-specific data. Request object implements javax.servlet.ServletRequest interface. It uses
the getParameter() method to access the request parameter. The container passes this object to the
_jspService() method.
11. What is Response:

This object has a page scope that allows direct access to the HTTPServletResponse class object. Response
object is an instance of the classes that implements the javax.servlet.ServletResponse class. Container
generates to this object and passes to the _jspService() method as a parameter.

12. What is Session:

Session object has a session scope that is an instance of javax.servlet.http.HttpSession class. Perhaps it is the
most commonly used object to manage the state contexts. This object persist information across multiple user
connection.

13. What is Cookie?


A cookie is information that a Web site puts on your hard disk so that it can remember something about
you at a later time.

14. Web server?


A web server is a computer program that delivers (serves) content, such as this web page, using the
Hypertext Transfer Protocol. The term web server can also refer to the computer or virtual machine running the
program.
A computer that delivers (serves up) Web pages. Every Web server has an IP address and possibly a domain name.
For example, if you enter the URL http://www.pcwebopedia.com/index.html in your browser, this sends a request
to the server whose domain name is pcwebopedia.com. The server then fetches the page named index.html and
sends it to your browser

1) Difference between get and post method?


2) How will you pass the values to post methods?
3) Static and Dynamic
4) Difference between getParameter and getParameterValues?
5) What is Forward Action?
6) Difference between sendredirect and forward?

sendRedirect() sends a redirect response back to the client's browser. The browser will normally interpret
this response by initiating a new request to the redirect URL given in the response.
forward() does not involve the client's browser. It just takes browser's current request, and hands it off to
another servlet/jsp to handle. The client doesn't know that they're request is being handled by a different
servlet/jsp than they originally called.

There are different situations where you want to use one or the other. For example, if you want to hide the
fact that you're handling the browser request with multiple servlets/jsp, and all of the servlets/jsp are in the
same web application, use forward() or include(). If you want the browser to initiate a new request to a
different servlet/jsp, or if the servlet/jsp you want to forward to is not in the same web application, use
sendRedirect().

When you invoke a forward request, the request is sent to another resource on the server, without
the client being informed that a different resource is going to process the request. This process
occurs completely with in the web container. When a sendRedirtect method is invoked, it causes the
web container to return to the browser indicating that a new URL should be requested. Because the
browser issues a completely new request any object that are stored as request attributes before the
redirect occurs will be lost. This extra round trip a redirect is slower than forward.

7) Difference between global forward and forward?


8) Difference between Action & Dynaaction?

1.What is MVC architecture?

You might also like