Está en la página 1de 36

 Abstraction: Showing the essential and hiding the non-

Essential is known as Abstraction.

 Encapsulation: The Wrapping up of data and functions

into a single unit is known as Encapsulation.
The ability to make changes in your implementation code
without breaking the code of others who use your code is a key
benefit of encapsulation.

 Inheritance: is the Process by which the Obj of one class

acquires the properties of Obj’s another Class.

 Polymorphism: The ability to take more than one form, it

supports Method Overloading & Method Overriding.

 Method overloading: When a method in a class having the

same method name with different arguments (diff Parameters
or Signatures) is said to be Method Overloading. This is Compile
time Polymorphism.

 Method Overriding: When a method in a Class having same

method name with same arguments is said to be Method
overriding. This is Run time Polymorphism.

 Dynamic dispatch: is a mechanism by which a call to

Overridden function is resolved at runtime rather than at
Compile time, and this is how Java implements Run time

 Dynamic Binding: Means the code associated with the

given procedure call is not known until the time of call at run

 Bite code: Is an optimized set of instructions

designed to be executed by Java-run time.

 JIT- is a compiler for Byte code, it complies byte code into

executable code in real time.

 Identifiers: are the Variables that are declared under

particular Data type.(Int a,b)
 Literals: are the values assigned to the Identifiers.(Int

 Variable: A data item named by an identifier.

 Class variable: A data item associated with a particular

class as a whole not with particular instances of the class. Class
variables are defined in class definitions. Also called a static

 Instance variable: Any data item that is associated with

a particular object. Also called a field.

 Local variable: A data item known within a block, but

inaccessible to code outside the block.

 Class method: A method that is invoked without

reference to a particular object. Also called a method. Also
instance method.

 Instance method: Any method that is invoked with

respect to an instance of a class. Also called simply a method.

 Interface: Interface defines a set of methods but does not

implement them. A class that implements the interface agrees to
implement all of the methods defined in the interface. Interface
can be used to implement the inheritance relationship between
the non related classes.

 Abstract Class: Which has more than one abstract method

which doesn’t have method body but at least one of its methods
need to be implemented in derived Class.? Abstract classes can
be used to implement the inheritance relationship between the
classes that belongs same hierarchy.

 Difference between Interfaces and Abstract class?

Interfaces Abstract class
All the methods declared in Whereas abstract class must
the Interface are Abstract have at least one abstract
method and others may be
In Interface we need not use In abstract class keyword
the keyword for methods abstract must be used for
Interface can extend more An abstract class can extend
than one interface only one class

 What are access specifiers and access modifiers?

Accesss specifiers Access modifiers
Public -Accessed Public
anywhere Abstract
Protected -Accessed C,SC& Final - can’t be changed.
P Static - can be accessed
Private -Accessed C without reference to any
Default -Accessed C & P object.
Volatile - Volatile is used in
multi-processor environments
Synchronized - Synchronize
keyword is used to control the
access to critical code in multi-
threaded programming.
Transient- During serialization,
Object’s transient variables are
not serialized.

Specif cla Subcl pack wor

ier ss ass age ld
Privat Y
Prote Y Y Y
Public Y Y Y Y
(none Y Y

If a variable is declared protected, then the class itself can

access it, its subclass can access it, and any class in the same
package can also access it, but otherwise a class cannot access

• Public : The Variables and methods can be access any

where and any package.
• Protected : The Variables and methods can be access
same Class, same Package & sub class.
• Private : The variable and methods can be access in
same class only.

Same class -
Public, Protected, and Private
Same-package & subclass - Public,
Same Package & non-sub classes - Public,
Different package & Sub classes - Public,
Different package & non- sub classes - Public

 Static : access modifier. When a member is declared as

Static, it can be accessed without reference to any

 Final : access modifier. If a Variable is declared as final,

the value contained in the Variable can’t be changed.

 Transient : access modifier. During serialization,

Object’s transient variables are not serialized.

 Volatile: access modifier. Volatile is used in multi-

processor environments. When multiple threads using the
same variable, each thread will have its own copy of the
local cache for that variable. So, when it's updating the
value, it is actually updated in the local cache not in the
main variable memory. The other thread which is using
the same variable doesn't know anything about the values
changed by the another thread. To avoid this problem, if
you declare a variable as volatile, then it will not be
stored in the local cache. Whenever threads are updating
the values, it is updated to the main memory. So, other
threads can access the updated value.
 Native: access modifier. Native method is like an abstract
method. Native is a Java keyword that is used in method
declarations to specify that the method will be
implemented in another language, but not in Java. This
keyword signals to the Java compiler that the function is a
native language function. Its implementation for is written
in another programming language because of the native
keyword. For example you can write machine-dependent C
code and invoke it from Java. The usual means of write
such methods is JNI (Java Native Interface).
 Synchronized: access modifier. Synchronize keyword is
used to control the access to critical code in multi-
threaded programming.

Declaration of access specifier and access modifiers:

Class Public, Abstract, Final

Inner Final, Static (PPP)
Anonymou Static (PPP)
Variable Final, Static, Transient, Volatile,
Method Final, Static, Abstract, Native,
Constructo (PPP)
Free floating code block Static, Synchronized

 Finalize( ) method: Finalize() is used just before an object

is destroyed and can be called prior to garbage collection. The
signature finalize() : protected void finalize() throws
Throwable {}

 Constructor( ) :A constructor method is special kind of

method that determines how an object is initialized when
created. Constructor has the same name as class name.
Constructor does not have return type.

 Package : A Package is a collection of Classes Interfaces

that provides a high-level layer of access protection and name
space management.

 Object : Object is a Super class for all the classes.

 String: String is Immutable and String Is a final class.

 String Buffer : Is Mutable, The StringBuffer class

provides for strings that will be modified; you use string buffers
when you know that the value of the character data will change.
 Wraper Classes : are the classes that allow primitive
types to be accessed as Objects.
These classes are similar to primitive data types but starting
with capital letter.

Number Byte
Double Short
Float Integer

 primitive Datatypes in Java :

According to Java in a Nutshell, 5th Ed Boolean, byte, char,
short, long float, double, int.

 String Tokenizer: The string tokenizer class allows an

application to break a string into tokens. In the parsing process
it identifies the delimiters provided by the user.

 Instanceof( ) :is used to check to see if an object can be

cast into a specified type with out throwing a cast class

 IsInstanceof( ): determines if the specified Object is

assignment-compatible with the object represented by this
class. Tests whether the value is an instance of a class.

 Garbage Collection: When an object is no longer

referred to by any variable, java automatically reclaims memory
used by that object. This is known as garbage collection.
System.gc() method may be used to call it explicitly and does
not force the garbage collection

 this() : can be used to invoke a constructor of the same


 super(): can be used to invoke a super class constructor.

 Inner class: A classes defined in other classes is called inner

class. The inner can access all the members of the outer class
as if it likes a part of an outer class. Whereas the Outer class
can access the inner by creating an instance of the class.
public static void main(String[] args) {
MyOuter mo = new MyOuter(); // gotta get an instance!
MyOuter.MyInner inner = MyInner();
From inside the outer class instance code, use the inner
class name in the normal way:
MyInner mi = new MyInner();

From outside the outer class instance code (including static

method code within the outer class), the inner class name
must now include the outer class's name:
 Anonymous class: Anonymous class is a class defined inside a
method without a name and is instantiated and declared in the
same place and cannot have explicit constructors.
Inner classes declared without any class name at all. You can
define these classes not just within a method, but even within
an argument to a method.

 Method-Local inner Classes

A class declared inside a method is called as MLIC. So if you
want to actually use the inner class then you must make an
instance of it somewhere within the method but below the
inner class definition.
A method-local inner class can be instantiated only within the
method where the inner class is defined. In other words, no
other code running in any other method inside or outside the
outer class cans ever instantiate the method-local inner class.

main( ) : is the method where Java application

String args[ ] : receives any command line
argument during runtime.System : is a
predefined Class that provides access to the
Out : is output stream connected to console.
Println :displays the output.

Exception: An exception is an abnormal condition that occurs

during the execution of the program. Exceptions are those
which can be handled at the run time Examples for exceptions:
Array out of bonds, attempt to divide by zero etc.
Error: error that does not occur under normal conditions and
cannot be handled at the run time
Eg: Run out of memory, Stack overflow error. Virtual mechine
error – class not found, out of memory, no such method, illegal
access to private field, etc.

Two types of exceptions:

1. Checked Exceptions: must be declaring in the method

declaration or caught in a catch block. Checked
exception must be handled at Compile Time.
2. Un-checked Exceptions: Run-time Exceptions and
Error, doesn’t have to be declare. (But can be caught).

Java Exception handling can be managed by five


 Try: The try block statements that are enclosed

within it and defines the scope of exception handler
associated with it. Try block follows catch or finally
or both.
 Catch: This is a default exception handler. Since the
exception class is the base class for all the
exception class, this handler id capable of catching
any type of exception.
 Finally : when an exception is raised, the statement
in the try block is ignored, sometimes it is
necessary to process certain statements
irrespective of whether an exception is raised or
not, the finally block is used for this purpose.
 Throw: keyword throw is used to through User
Defined Exception
 Throws: keyword throws is used when we want that
exception is to be handled by calling function.

 Thread: can be defined as single sequential flow of

control within a program.
 Single Thread: Application can perform only one task at a
 Multithreaded: A process having more than one thread is said
to be multithreaded.
 Multiprogramming: A multithreaded program contains two or
more parts that can run concurrently.
 Process: A process is an instance of a program that is
There are two distinct types of multitasking.
 Process-based: Is heavy weight- allows you run two or more
programs concurrently.
 Thread-based: Is Light weight- A Program can perform two or
more tasks simultaneously.
 Daemon Thread: Is a low priority thread which runs
immediately on the back ground doing the Garbage Collection
operation for the Java Run time System.

 Creating a Thread :
1. By implementing the Runnable Interface.
2. By extending the thread class.

 Thread Class: To crate threads, create a new class that

extends the Thread class, and instantiate that class. The
extending class must override the run() method and call start()
method to begin execution of the thread. Inside run(), you will
define the code that constitutes a new thread.
Syntax: Public Class <class name> extends Thread { }
The Thread class defines several methods.
- getname() – obtain a thread name.
- getPriority() – obtain thread priority.
- Start ( ) - start a thread by calling a Run().
- Run( ) - Entry point for the thread.
- Sleep( ) - suspend a thread for a period of time.
- IsAlive ( ) - Determine if a thread is still running.
- Join ( ) - wait for a thread to terminate.

 Runable Interface : The Runnable interface consist of a

Single method Run( ), which is executed when the thread is
activated. When a program need it inherit from another class
besides the thread Class, you need to implement the Runnable
Syntax: public void <Class-name> extends <SuperClass-
name> implements Runnable

Eg: public Class myapplet extends Japplet implements

// Implement the Class
Runnable interface is the most advantageous method to create
threads because we need not extend thread Class here.

Difference-If you just want to achieve basic functionality of a

thread you can simply implement runnable interface and
overload run().Whereas yeild(), join() , setPriority() these are
also threads method not present in runnable interface.

 Life Cycle of Thread :

1. New state - After the creations of Thread instance the

thread is in this state but before the start() method
invocation. At this point, the thread is considered not
2. Runnable (Ready-to-run) state - A thread start its life
from Runnable state. A thread first enters runnable
state after the invoking of start() method but a
thread can return to this state after either running,
waiting, sleeping or coming back from blocked state also.
3. Running state - A thread is in running state that means
the thread is currently executing.
4. Dead state - A thread can be considered dead when its
run() method completes.
5. Blocked - A thread can enter in this state because of
waiting the resources

New Thread Runnable -- ---- Not


Dead The Run( ) terminates .

 New Thread : When an instance of a thread class is

created, a thread enters the new thread state. Thread
newThread = new Thread(this); You have to invoke the
Start( ) to start the thread. ie, newThread.Start( );

 Runnable : when the Start( ) of the thread is invoked the

thread enters into the Runnable State.

 Not Runnable : A thread is said to be not runnable state

if it
Is Slleping
Is Waiting
Is being blocked by another thread.
Sleep (long t); where t= no: of milliseconds for which the
thread is inactive.
The sleep( ) is a static method because it operates on the
current thread.

 Dead : A thread can either die naturally or be killed.

A thread dies a natural death when the loop in the Run( ) is
Assigning null to the thread Object kills the thread.
If th loop in the Run( ) has a hundred iterations , the life of the
thread is a hundread iterators of the loop.

 IsAlive( ) : of the thread class is used to determine

wheather a thread has been started or stopped. If
isAlive( ) returns true the thread is still running otherwise
running completed.
 Thread Priorities: are used by the thread scheduler to
decide when each thread should be allowed to run. To set
a thread priority, use to setpriority( ), which is a member
of a void setpriority(int level)- here level
specifies the new priority seting for the calling thread.
The value level must be with in the range:-
You can obtain the current priority setting by calling getpriority(
) of thread.
final int getpriority()

 Synchronization :Two or more threads trying to access

the same method at the same point of time leads to
synchronization. If that method is declared as Synchronized ,
only one thread can access it at a time. Another thread can
access that method only if the first thread’s task is completed.

 Inter Thread Communication :

To Avoid pooling, Java includes an elegant interprocess
communication mechanisim.

Wait( ) - wait() will move the thread to sleep state

allowing for the other thread to execute.
notify( ) - wake up the first thread that called wait( ) on
the same Object.
notifyall( ) – wake up all the threads that called wait ( )
on the same Object. The highest priority thread all run

 Serialization: The process of writing the state of

Object to a byte stream to transfer over the network is known
as Serialization.

 Deserialization : and restored these Objects by


 Externalizable: is an interface that extends Serializable

interface and sends data into streams in compressed format. It
has two methods
WriteExternal(Objectoutput out)
ReadExternal(objectInput in)
Why are there separate wait and sleep methods?
sleep() method maintains control of thread execution but delays
the next action until the sleep time expires.
wait () method gives up control over thread execution indefinitely so
that other threads can run.

What's the difference between a thread's start() and run()

start() is a method on Thread that tells it to start.
run() is a method in the object that the thread executes.

Can I implement my own start() method?

The Thread start() method is not marked final, but should not be
overridden. This method contains the code that creates a new
executable thread and is very specialized.

Collections : A collection allows a group of objects to be
treated as a single unit.
Set List Map
In the set we In list we can store Elements are
can store only duplicate values stored in key ,
unique values it value pairs
can’t store any .Repetitions of
duplicate values values are allowed
but not keys

A Set is an A List is an ordered

unordered grouping of items
grouping of
items with no
Cannot be Can be accessed by It can be accessed
accessed by index using the key/pair
index value

HashSet LinkedHashSet TreeSet

order undefined insertion order Ascending
betterthan has fast adding to Slow
LinkedHashSet the start of the list,
and fast deletion
from the interior
via iteration

assures no assures no assures no

duplicates duplicates duplicates
HashMap TreeMap LinkedHash HashTable
Hashmap Does not Does not But Hashtable
can contain allow null allow null does not allow
null values values as keys values as keys null values as
as the keys and values. and values. keys and
and as well Runtime Runtime values.
as values. exception exception Runtime
Hashmap is Not Not Hashtable is
not syncroniged. syncroniged. syncroniged.
Undefined Ascending Inserted Order Descending
order. Order order

ArrayList Vector LinkedList

Arraylist is not Is synchronized Not synchronized
Elements can Elements can only New Method like
only be added be added using the addFirst,last,
using the index index positions removeFirst,last &
positions only only getFirst , Last

Iterator ListIterator
It Can traverse through the It Can traverse through the
collection with the help of collection with the help of
iterator in forward direction previous () & next () both
only. direction.

 Collection Interface :
 The CI is the root of collection hierarchy and is used for
common functionality across all collections.

 Set Interface: extends Collection Interface. The Class

Hash set implements Set Interface.
 Is used to represent the group of unique elements.
 Set stores elements in an unordered way but does not contain
duplicate elements.
 Sorted set : extends Set Interface. The class Tree Set
implements Sorted set Interface.
 It provides the extra functionality of keeping the elements
 It represents the collection consisting of Unique, sorted
elements in ascending order.

 Map Interface: basic Interface. The classes Hash Map &

Hash Table implements Map interface.
 Used to represent the mapping of unique keys to values.
 By using the key value we can retrieve the values. Two basic
operations are get( ) & put().

 Sorted Map: extends Map Interface. The Class Tree Map

implements Sorted Map Interface.
 Maintain the values of key order.
 The entries are maintained in ascending order.

1. What is List interface?

A List is an ordered collection of objects.

2. What is a Vector?
A Vector is a grow able array of objects.

3. What is the difference between yield() and sleep()?

When a object invokes yield() it returns to ready state. But
when an object invokes sleep() method enters to not
ready state.

4. Can we declare an anonymous class as both

extending a class and implementing an interface?
No. An anonymous class can extend a class or implement
an interface, but it cannot be declared to do both

5. What are the differences between Boolean &

operator and & operator
When an expression containing the & operator is
evaluated, both operands are evaluated. And the &
operator is applied to the operand. When an expression
containing && operator is evaluated, the first operand is
evaluated. If the first operand returns a value of true then
only the second operand is evaluated otherwise the
second part will not get executed. && is also called short
cut and.

6. What is the use of the finally block?

Finally is the block of code that executes always. The code
in finally block will execute even if an exception is
occurred. Finally will not execute when the user calls

7. What is an abstract method?

An abstract method is a method that don't have a body. It
is declared with modifier abstract.

8. what is a the difference between System.err and

We can redirect System.out to another file but we cannot
redirect System.err stream

9. How can you call a constructor from another

constructor ?
By using this() reference.

10. How can you call the constructor of super class?

By using super() syntax.

11. What’s the difference between normal methods and

Constructors must have the same name of the class and
cannot have a return type. They are called only
once, while regular methods can be called whenever
required. We cannot explicitly call a constructor.

12. What is the use of packages in java?

Packages are a way to organize files in java when a
project consists of more than one module. It helps in
resolving name conflicts when different modules have
classes with the same names.

13. What must be the order of catch blocks when

catching more than one exception?
The sub classes must come first. Otherwise it will give a
compile time error.

14. How can we call a method or variable of the

super class from child class ?
We can use super.method() or super.variable syntax for
this purpose.

15. If you are overriding equals() method of a

class, what other methods you might need to
override ?

16. How can you create your own exception ?

Our class must extend either Exception or its sub class

17. What is serialization ?

Serialization is the process of saving the state of an

18. What is de-serialization?

De-serialization is the process of restoring the state of an

19. What is externalizable ?

It is an interface that extends Serializable. It is having two
different methods writeExternal() and readExternal. This
interface allows us to customize the output.

20. What is a native method?

A native method is a method that is implemented in a
language other than Java.

21. How many times may an object's finalize()

method be invoked by the garbage collector?
Only once.

22. What is the difference between a continue

statement and a break statement?
Break statement results in the immediate termination of
the statement to which it applies (switch, for, do, or while).
A continue statement is used to end the current loop
iteration and return control to the loop statement.
23. What is the difference between static and non
static inner class ?
A non-static inner class can have an object instances that
are associated with instances of the class's outer class. A
static inner class can not have any object instances.

24. What is the difference between String and

StringBuffer class ?
Strings are immutable (constant), their values cannot be
changed after they are created. StringBuffer supports
mutable objects.
By immutable, we mean that the value stored in the String object cannot be changed.
Then the next question that comes to our mind is “If String is immutable then how am
I able to change the contents of the object whenever I wish to?” . Well, to be precise
it’s not the same String object that reflects the changes you do.

25. What is the difference between readers and

Readers are character oriented where streams are byte
oriented. The readers are having full support for Unicode

26. What is constructor chaining?

When a constructor of a class is executed it will
automatically call the default constructor of the super
class (if no explicit call to any of the super class
constructor) till the root of the hierarchy.

27. What are the different primitive data type in java ?

There are 8 primitive types in java. boolean , char, byte,
short, int long, float, double.

28. Why we cannot override static methods?

Static means they are associated with a class. In static
methods, the binding mechanism is static binding. So it
must be available at the compile time.

29. What is the difference between static and non

static variables ?
A static variable is associated with the class as a whole
rather than with specific instances of a class. There will be
only one value for static variable for all instances of that
class. Non-static variables take on unique values with
each object instance.
30. What are the restrictions placed on
overloading a method?
Overloading methods must differ in their parameter list, or
number of parameters.

31. What is casting?

Casting means converting one type to another. There are
mainly two types of casting. Casting between primitive
types and casting between object references.

32. What the difference is between == and

equals ?
The equals method can be considered to perform a deep
comparison of the value of an object, whereas the ==
operator performs a shallow comparison. If we are not
overriding the equals method both will give the same
result. == Will is used to compare the object references. It
is used to check whether two objects are points to the
same reference.

33. What is a ResourceBundle class?

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

34. What is the difference between the prefix and

postfix forms of the ++ operator?
The prefix form first performs the increment operation and
then returns the value of the increment operation. The
postfix form first returns the current value of the
expression and then performs the increment operation on
that value.

35. What is hashCode?

Object's hashcode is a signed number(32-bit signed int)
that identifies the object, but it is unique for every object.
Hash code is an unique id number allocated to an object by

36. What is an I/O filter?

An I/O filter is an object that reads from one stream and
writes to another.
37. What is the difference between
RandomAccessFile and File?
The File class contains information the files and
directories of the local file system. The
RandomAccessFile class contains the methods needed
to directly access data contained in any part of a

38. What is the difference between Vector and

ArrayList ?
Vector is synchronized, ArrayList is not. Vector is having a
constructor to specify the incremental capacity. But
ArrayList don't have. By default Vector grows by 100% but
ArrayList grows by 50% only.

39. What do you mean by immutable? How to create an

immutable object?
Immutability means an object cannot be modified after it
has been initialized. There will not be any setter methods
in an immutable class. And normally these classes will be

40. What is class loader in java ?

class loader is a class that is responsible for loading the

41. What is garbage collection?

Garbage collection is the process of releasing memory
used by unreferenced objects. It relieves the programmer
from the process of manually releasing the memory used
by objects .

42. What is a marker interface ?

An interface that contains no methods. Eg: Serializable,
Cloneable, SingleThreadModel etc. It is used to just mark
java classes that support certain capability.

43. What are tag interfaces?

A Tag interface is an alternate name for marker interface.

44. What are the restrictions placed on static

method ?
We cannot override static methods. We cannot access any
object variables inside static method. Also the this
reference also not available in static methods.

45. What is the difference between Iterator and


46. Strings are immutable. But String s="Hello";

String s1=s+"World" returns HelloWorld how ?
Here actually a new object is created with the value of

47. What is static initializer block? What is its use?

Static initializer block is a block of code that declares with

the static keyword. It normally contains the block of code
that must execute at the time of class loading. The static
initializer block will execute only once at the time of
loading the class only.

48. What is the difference between creating a

thread by extending Thread class and by
implementing Runnable interface? Which one should
When creating a thread by extending the Thread class, it
is not mandatory to override the run method (If we are not
overriding the run method , it is useless), because Thread
class have already given a default implementation for run
method. But if we are implementing Runnable , it is
mandatory to override the run method. The preferred way
to create a thread is by implementing Runnable interface,
because it give loose coupling.

49. What is coupling?

A Coupling is the dependency between different

components of a system

50. Why java does not support multiple

Because the multiple inheritance causes the redundancy.
Also we cannot solve diamond problem.

51. How many JVM's we can run in a system?

Any number of JVMs can run in a system. Whenever we

issue the command 'java' a new JVM will start.

52. Why Java is not 100% pure object oriented

Because java uses primitives.

53. Why ArrayList is faster than Vector?

Because Vector is synchronized. Synchronization reduces
the performance.

54. What is the security mechnaism used in java?

Java uses sand box security model.

55. What is sandbox?

Sandbox is a security mechanism for safely running
programs. The sandbox typically provides a tightly-
controlled set of resources for guest programs to run in,
such as scratch space on disk and memory.

56. What is the difference between throw and

throws clause?
Throw is used to throw an exception manually, where as
throws is used in the case of checked exceptions, to tell
the compiler that we haven't handled the exception, so
that the exception will be handled by the calling function.

57. What is composition?

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

58. What is aggregation?

It is a special type of composition. If you expose all the
methods of a composite class and route the method call to
the composite method through its reference, then it is
called aggregation
59. What are the methods in Object?
A clone, equals, wait, finalize, getClass, hashCode, notify,
notifyAll, toString

60. What is adapter class?

An adapter class provides a default implementation of all
methods in an event listener interface.

61. Difference between a Class and an Object?

A class is a definition or prototype whereas an object is an
instance or living representation of the prototype.

62. What if the main method is declared as

The program compiles properly but at runtime it will give
"Main method not public." message.

63. What if the static modifier is removed from the

signature of the main method?
Program compiles. But at runtime throws an error

64. What if I write static public void instead of

public static void?
Program compiles and runs properly.

65. What if I do not provide the String array as the

argument to the method?
Program compiles but throws a runtime error

66. What is the first argument of the String array

in main method?
The String array is empty. It does not have any element.
This is unlike C/C++ where the first element by default is
the program name.
If I do not provide any arguments on the command
line, then the String array of Main method will be
empty of null?
It is empty. But not null.
67. How can one prove that the array is not null
but empty?
Print args.length. It will print 0. That means it is empty.
But if it would have been null then it would have thrown a
NullPointerException on attempting to print args.length.

68. What environment variables do I need to set on

my machine in order to be able to run Java
CLASSPATH and PATH are the two variables.

69. Can an application have multiple classes

having main method?
Yes it is possible. While starting the application we
mention the class name to be run. The JVM will look for the
Main method only in the class whose name you have
mentioned. Hence there is not conflict amongst the
multiple classes having main method.

70. Can I have multiple main methods in the same

No the program fails to compile. The compiler says that
the main method is already defined in the class.

71. Do I need to import java.lang package any

time? Why ?
No. It is by default loaded internally by the JVM.

72. Can I import same package/class twice? Will

the JVM load the package twice at runtime?
One can import the same package or same class multiple
times. Neither compiler nor JVM complains abt it. And the
JVM will internally load the class only once no matter how
many times you import the same class.

73. What is the difference between final, finally

and finalize() in Java?
final - constant declaration.
finally - handles exception.
finalize() - method helps in garbage collection.

74. What is JDBC Driver?

This driver is used to connect to the database.
75. What does Class.forName return?
Returns the Object for the classname specified in argument
passed to Method. Class.forNameused to load drivers.
automatically creates an instance of a
EmbeddedDriver and registers it with the

76. What is the fastest type of JDBC driver?

Type 4 (JDBC Net pure Java Driver) is the fastest JDBC
driver. Type 1 and Type 3 drivers will be slower than Type 2
drivers (the database calls are make at least three
translations versus two), and Type 4 drivers are the
fastest (only one translation).

77. What are the new features added to JDBC 4.0?

• Auto-loading of JDBC driver class

78. Explain Basic Steps in writing a Java program

using JDBC?
• Load the specific JDBC driver
• Open the connection to database
• Create JDBC Statement object. This object contains
SQL query.
• Execute statement which returns resultset(s).
• Process the result set.
• Close the connection.

79. What is a DataSource?

A DataSource class brings another level of abstraction than

directly using a connection object. Data source can be
referenced by JNDI. A DataSource is a facility for storing data.

80. Explain the JDBC Architecture.

The JDBC Architecture consists of two layers:

• The JDBC API, which provides the application-to-JDBC
Manager connection.
• The JDBC Driver API, which supports the JDBC Manager-
to-Driver Connection.

JDBC API uses a driver manager and database-specific

drivers to provide connectivity to databases.

JDBC driver manager ensures that the correct driver is

used to access each data source.

JDBC Architecture

81. What are the main components of JDBC?

• DriverManager: Manages a list of database drivers.

• Driver: The database communications link
• Connection: Interface with all methods for contacting a
database. All communication with database is through
connection object only.
• Statement: Encapsulates an SQL statement which is
passed to the database to be parsed, compiled, planned
and executed.
• ResultSet: The ResultSet represents set of rows retrieved
due to query execution.

82. How the JDBC application works?

A JDBC application can be logically divided into two layers:
1. Driver layer

2. Application layer

• Driver layer consists of DriverManager class and the

available JDBC drivers.
• The application begins with requesting the DriverManager
for the connection.
• An appropriate driver is choosen and is used for
establishing the connection. This connection is given to
the application which falls under the application layer.
• The application uses this connection to create Statement
kind of objects, through which SQL commands are sent to
backend and obtain the results.

Figure 2: JDBC Application

83. How do I load a database driver with JDBC 4.0 / Java

Provided the JAR file containing the driver is properly
configured, just place the JAR file in the classpath. Java
developers NO longer need to explicitly load JDBC drivers using
code like Class.forName() to register a JDBC driver. The
DriverManager class takes care of this by automatically locating
a suitable driver when the DriverManager.getConnection()
method is called.

84. What does the connection object represents?

The connection object represents communication context, i.e.,
all communication with database is through connection
object only.

85. What is Statement?

Statement acts like a vehicle through which SQL commands
can be sent. Through the connection object we create
statement kind of objects.
Statement stmt = conn.createStatement();

This method returns object which implements statement


86.What is PreparedStatement?
A prepared statement is an SQL statement that is precompiled
by the database. prepared statements improve the
performance of SQL commands that are executed multiple
PreparedStatement pstmt = conn.prepareStatement("UPDATE
pstmt.setBigDecimal(1, 153833.00);
pstmt.setInt(2, 110592);

87.What is the difference between a Statement and a


Statement PreparedStatement
Statement has to verify its While a prepared statement
metadata against the has to verify its metadata
database every time. against the database only
If you want to execute the SQL If you want to execute a single
statement once go for SQL statement multiple
STATEMENT number of times, then go for
PreparedStatement objects
can be reused with passing
different values to the queries

88. What are callable statements?

Callable statements are used from JDBC application to invoke
stored procedures and functions.

89. How to call a stored procedure from JDBC ?

CallableStatement stproc_stmt =
conn.prepareCall("{call procname(?,?,?)}");

90. What are types of JDBC drivers?

There are four types of drivers defined by JDBC as follows:

• Type 1: JDBC/ODBC—these require an ODBC (Open

Database Connectivity) driver for the database to be
installed. This type of driver works by translating the
submitted queries into equivalent ODBC queries and
forwards them via native API calls directly to the ODBC
driver. It provides no host redirection capability.

• Type2: Native API (partly-Java driver)—this type of

driver uses a vendor-specific driver or database API to
interact with the database.

• Type 3: Open Protocol-Net—This is not vendor specific

and works by forwarding database requests to a remote
database source using a net server component.

Type 4: Proprietary Protocol-Net(pure Java driver)—


• Again this is all transparent to the client.

91. Which type of JDBC driver is the fastest one?

JDBC Net pure Java driver(Type IV) is the fastest driver because
it converts the JDBC calls into vendor specific protocol calls and
it directly interacts with the database.

92. Does the JDBC-ODBC Bridge support multiple

concurrent open statements per connection? No. You can
open only one Statement object per connection when you are
using the JDBC-ODBC Bridge.

93. Which is the right type of driver to use and when?

• Type I driver is handy for prototyping

• Type III driver adds security, caching, and connection
• Type III and Type IV drivers need no pre-installation

94. What is resultset?

The ResultSet represents set of rows retrieved due to query
ResultSet rs = stmt.executeQuery(sqlQuery);

95. What is connection pooling? what is the main

advantage of using connection pooling?
A connection pool is a mechanism to reuse connections
created. Connection pooling can increase performance
dramatically by reusing connections

96. What are the types of resultsets?

The values are defined in the class java.sql.Connection and are:

• TYPE_FORWARD_ONLY specifies that a resultset is not

scrollable, that is, rows within it can be advanced only in
the forward direction.
• TYPE_SCROLL_INSENSITIVE specifies that a resultset is
scrollable in either direction but is insensitive to changes
committed by other transactions or other statements in
the same transaction.
• TYPE_SCROLL_SENSITIVE specifies that a resultset is
scrollable in either direction and is affected by changes
committed by other transactions or statements within the
same transaction.

Note: A TYPE_FORWARD_ONLY resultset is always insensitive.

97. What’s the difference between

After we get the resultset After we obtain the resultset if
the changes made to data the data is modified then such
are not visible through the modifications are visible
resultset, and hence they through resultset.
are known as insensitive.
Performance not effected Since a trip is made for every
with insensitive. ‘get’ operation, the
performance drastically get

98. What is rowset?

A RowSet object contains a set of rows from a result set.

A ResultSet maintains a connection to a database and because of that it can’t be serialized

and also we cant pass the Resultset object from one class to other class across the network.

RowSet is a disconnected, serializable version of a JDBC ResultSet and also the RowSet
extends the ResultSet interface so it has all the methods of ResultSet. The RowSet can be
serialized because it doesn’t have a connection to any database and also it can be sent from
one class to another across the network.

99. What are the different types of RowSet?

There are two types of RowSet are there. They are:

• Connected - A connected RowSet object connects to the

database once and remains connected until the
application terminates.
• Disconnected - A disconnected RowSet object connects
to the database, executes a query to retrieve the data
from the database and then closes the connection.

100. What is the need of BatchUpdates?

The BatchUpdates feature allows us to group SQL statements

together and send to database server in one single trip.

101. What is difference between comparator &



A comparable object is capable of comparing itself with another

object. The class itself must implements the
java.lang.Comparable interface in order to be able to compare
its instances.


A comparator object is capable of comparing two different

objects. The class is not comparing its instances, but some
other class’s instances. This comparator class must implement
the java.lang.Comparator interface.
What is Dynamic binding with example?

How to check two object in class are equal?

What is static class loading & Dynamic class loading

Static class loading occurs when the name of the class to be loaded is
known to the Java compiler, and the full name can be placed in the class
file. The JVM will use the name in the class file to load the class
any time prior to the first use.

For example, if I have code like this:

import java.util.*;
public class StaticLoadTest {
public static void main(String [] args) {
ArrayList mylist;
mylist = new ArrayList(6);

then the JVM will probably choose to load the java.util.ArrayList class
when it begins to execute line 5. The Java compiler was able to tell
that I wanted java.util.ArrayList because I imported java.util and
I explicitly put ArrayList into my code.

Dynamic class loading is when code requests the JVM to load a class
by using the class name as a String, during execution. The most common
way of doing this is to use the Class.forName() method.

Can a method have same method name with same

aruguments but different return types

No it shows an compile time error.

Java Reflectiion?

Reflection is infrastructure enabling a program can see and

manipulate itself

Finally, what’s the difference between StringBuffer and StringBuilder?

StringBuffer and StringBuilder have the same methods with one difference and that’s of
synchronization. StringBuffer is synchronized( which means it is thread safe and hence you
can use it when you implement threads for your methods) whereas StringBuilder is not
synchronized( which implies it isn’t thread safe).
So, if you aren’t going to use threading then use the StringBuilder class as it’ll be more
efficient than StringBuffer due to the absence of synchronization.

Difference between static and final

Static variable can change their values final variables cannot be changed they are constants .
Static variable it attached to their class not with the object only one copy of static variable is
exists and they can be called with reference of their class only final classed cannot be
extended and their are not static classes.

When we go for Abstract and Interface

In real time how the abstraction and interface uses when we go for those concept in real

Both abstract classes and interfaces are used when there is a difference in behaviour among
the sub-types extending the abstract class or implementing the interface.

When the sub-types behaviour is totally different then you use an interface, when the sub-
types behaviour is partially common and different with respect to the supertype an abstract
class is used. In an abstract class the partially common behaviour is given a concrete
implementation. Since there is no common behaviour between an interface and a sub-type an
interface does not have an implementation for any of its behaviour.

Lets assume you are developing a framework for a 'killer' competition where the people who
participate have to demonstrate their killing skills. Members participating in the competetion
have their own ways of killing.

It could be as different as 'using a gun to kill', 'throwing the victim up in the air and kicking
his balls when he victim comes down, 'slitting his throat or behaeding the victim'

The expected behaviour here is to 'KILL', though all the members do have that behaviour
'KILL" each member manifests the behaviour in a different way. Since the behaviour
manifestation varies from member to member this scenario calls for an interface.

Interface KilingCompetition{
Corpse kill();

Each member will implement this interface and give an implementation in his/her own way.

Now, lets consider a karate competition(is it called sparring?). Here each member has to
follow certain things as laid out by the organizers or the karate protocol. It may include things
like bowing to the opponent before and after the fight starts, taking a stand etc. Now these
behaviours are common and has to manifested in the same way by every paticipating
member. But the behaviour 'fight' will differ from member to member. So now we have a set
of common behaviour and also a behaviour which manifests differently from member to
member. this calls for an abstract class where you give implementation to the common
behaviour and make the differeing behaviour abstract and hence the class abstract.
public abstract class KarateFight{
public void bowOpponent(){
//implementation for bowing which is common
// for every participant

public void takeStand(){

//implementation which is common
// for every participant

public abstract boolean fight(Opponent op);

//this is abstract because it differs from
// person to person


What is the difference between interface and abstract

* interface contains methods that must be abstract; abstract class may contain concrete
* interface contains variables that must be static and final; abstract class may contain non-
final and final variables.
* members in an interface are public by default, abstract class may contain non-public
* interface is used to "implements"; whereas abstract class is used to "extends".
* interface can be used to achieve multiple inheritance; abstract class can be used as a single
* interface can "extends" another interface, abstract class can "extends" another class and
"implements" multiple interfaces.
* interface is absolutely abstract; abstract class can be invoked if a main() exists.
* interface is more flexible than abstract class because one class can only "extends" one super
class, but "implements" multiple interfaces.
* If given a choice, use interface instead of abstract class.

One advantage of using interfaces is that classes in Java can implement multiple interfaces -
classes can only extend one class. If you are writing an API, if you provide an interface
instead of an abstract class, you are not forcing your users into a specific class hierarchy.

• use an abstract class, if you want to provide common implementation to subclasses,

• use an abstract class, if you want to declare non-public members,
• use an abstract class, if you want to be free to add new public methods in the future,
• use an interface if you're sure the API is stable for the long run
• use an interface if you want to provide the implementing classes the opportunity to
inherit from other sources at the same time.

In general, prefer interfaces if you don't need to use an abstract class, because they provide
more design flexibility.