1. What do you mean Run time Polymorphism?
Answer: Polymorphism –
one can do multiple operations. Method Overloading and Method Overriding are
two different polymorphism available in Java. Overloaded method invocation
decided during compile time. As the same the overridden method’s invocation is decided
only during runtime.
2. Can we have try - followed by finally without catch block?
Answer:
1.
try – block must be followed by either catch or finally
2.
Before returning value either from try or catch finally
block code will be executed.
3.
To overcome running finally block we can call
System.exit(0) from try or catch block. It will stop the JVM thread.
3. How will you create thread?
Answer:
1.
By extending Thread class and overriding run() method.
2.
By implementing Runnable interface and overriding run()
method. It is the mostly preferred way because a) It allow us to extend another
classes b) The class and resources can be shared to other threads by passing
the instance like new Thread(ir), but in otherwise thread instance are unique.
4. Why implementing Runnable is better than extending thread?
Answer:
1.
When you implement Runnable, it allows you to extend
another Class.
2.
When your Class extend Thread, the class has only one
object of it, but if you implement Runnable interface you can declare multiple
Thread objects belongs to that class. Please see below code.
MyRunnable mr=new Runnable();
Thread t1= new Thread(mr);
Thread
t2 = new Thread(mr);
5. Please list out the features of OOPS?
Answer:
1.
Encapsulation: Wrapping up data and behavior into single unit
called Class and protecting them from outside access.
2.
Abstraction: Showing essential features without showing background
details.
3.
Polymorphism: One entity can take many forms.
4.
Inheritance: One object allowed to acquire properties of
another object.
6. What is the Use of Synchronized?
Answer:
1.
Synchronized Instance Method: Only one thread can utilize
this method by using the instance’s synchronized method. Another instance’s
method can be accessed by another thread without considering it.
2.
Synchronized Static Method: Only one thread can access thru
class name at any time.
3.
Synchronized Block:
a.
Inside Method – Same as instance synchronized method but
another thread can enter into method and not into the block, so they will wait.
b.
Static Block – Only one thread can use using Class name.
7. What is the difference between HashTable and HashMap?
Answer:
HashMap:
a) Not Synchronized
b) Allow Null Key
c) Fail fast Iterator
(if we try to add/remove during iteration so will throw
ConcurrencyModiicationException)
d) Fast in
multithreads 5. No Thread Safe
HashTable:
a) Implements HashMap
internally
b).No null key
c) Fail-safe between
multiple threads (but not guaranteed)
d) Slow in
multithreaded systems 5. Thread Safe
8. What will happen if I insert duplicate key-pair value inserted in to HashTable?
Answer: New Value will
be overridden in the place bucket.
9. Differentiate ArrayList from Vector?
Answer:
Similarities: Both
implements index based Array, maintains insertion order, null values and
duplicates allowed.
Vector: synchronized,
Thread safe, Slower, Increase size by 100%, Legacy from Java 1.0
ArrayList: Not
synchronized, No thread safe, Faster, Increase 50%
10. How do you sort out items in ArrayList in forward and reverse directions?
Answer: Using
Collections.sort(arrList); Also we can create our own comparator.
Collections.sort(fruits,
new Comparator() {
public int compare(Fruit fruite1, Fruit fruite2){
return
fruite1.fruitName.compareTo(fruite2.fruitName);
}
});
11. What is Thread? Why we go for multi-threading?
Answer: Thread is a
single sequential flow of program in JVM. To do multiple sequence of programs
at same time, we go for multithreading.
12. Tell me about join() and wait() methods?
Answer: join () – t1.join
(); is a method of Thread class, will make the current thread to wait until the
“t1” completes its job.
wait() – Method of Object, we write inside
a synchronized block, stops the execution of currently running thread and lets
the other waiting threads to take the monitor.
Sleep () vs wait () –
sleep-ed threads cannot be woken up by notify calls, but wait-ed methods can be
woken up by other threads.
Thread is a single
sequential flow of program in JVM. To do multiple sequence of programs at same
time, we go for multithreading.
13. Could you tell in what scenario you go for Abstract Class rather than Interface?
Answer: When I want to
have declare behaviors common to subclasses and define a common behaviors then
I will go for abstract class.
But I want just to
declare the behaviors and let the subclasses have their own definition by
creating interface.
14. Difference between AWT and Swings?
Answer: AWT libraries
are to native with System OS UI, thus UI differs across OS and Heavy weight
Swing is Java UI
libraries run upon System OS, thus UI will not differ when we run in different
OS and Light in weight as runs on top of JVM.
15. I have a method add() throws XXXException, If I have this same method with some other Exception throw in Child Class, will that compile and run? Is it overridden or overloaded?
Answer:
·
If the superclass
method does not declare an exception -Ã If the superclass
method was not declared with an exception, then subclass overridden method
cannot declare the checked exception but it can declare unchecked exception.
·
If the superclass
method declares an exception -Ã If the superclass
method declares an exception, subclass overridden method can declare same,
subclass exception or no exception but cannot declare parent exception.
16. Is substring () method creates new
object in String pool?
Answer: Yes. Will
create new object in string pool but we need to assign them to reference.
String s1= new
String(“Balaji”); Ã s1=”Balaji”;
s1.substring(0,3) Ã s1=”Balaji”;
s1=s1.substrign(0.3); s1=”Bal”;
17. What are two uses of the equals() and
hashCode() method?
Answer:
The general contract
of hashCode is:
a)
Whenever it is invoked on the same object more than once
during an execution of a Java application, the hashCode method must consistently
return the same integer.This integer need not remain consistent from one
execution of an application to another execution of the same application.
b)
If two objects are equal according to the equals(Object)
method, then calling the hashCode method on each of the two objects must produce
the same integer result.
c)
It is not required that if two objects are unequal
according to the equals(java.lang.Object) method, then calling the hashCode
method on each of the two objects must produce distinct integer results.
However, the programmer should be aware that producing distinct integer results
for unequal objects may improve the performance of hash tables.
18. If I don't have explicit constructor in
parent class and having in child class, while calling the child's constructor
JVM automatically calls Implicit Constructor of parent class? Yes OR No
Answer: Yes. Compiler will create and it will be
called during runtime. Also Child class can have default constructor and/or
explicit constructor even without in Parent class.
19. What is the different methods available
in MouseMotionListener and MouseActionListener?
Answer:
MouseMotionListener
MouseListener
mousePressed(MouseEvent e)
mouseReleased(MouseEvent e)
mouseEntered(MouseEvent e)
mouseExited(MouseEvent e)
mouseClicked(MouseEvent e)
20. Differentiate Package and interface.
Answer:
Package: Collection of Classes
Interface:
It has just Class signature without actual definition. Pure abstract class.
22. What is
the JPanel's default Layout?
Answer: FlowLayout
23. How will you set layout to a component?
Answer:
JPanel
panel = new JPanel(new BorderLayout());
Container
contentPane = frame.getContentPane();contentPane.setLayout(new FlowLayout());
24. Do you know how to set NULL layout?
Answer: contentPane.setLayout(null);
25. How will you add JScrollPane to a
component?
Answer:
scrollPane
= new JScrollPane();
scrollPane.getViewport().add( label );
topPanel.add(
scrollPane, BorderLayout.CENTER);
26. In JTable, I want to make a CELL Editable?
How this can be done? Write me Code.
Answer: table.setDefaultEditor(Object.class,new
MyEditor());
Please refer here:
http://stackoverflow.com/questions/10077632/implements-a-custom-celleditor-for-a-jtable-with-2-columns-string-integer-and
27. While Closing JFrame, I want to show prompt Alert Dialog? In which method of JFrame, I will write to make prompt?
frame.addWindowListener(new
java.awt.event.WindowAdapter() {
@Override
public void
windowClosing(java.awt.event.WindowEvent windowEvent) {
if (JOptionPane.showConfirmDialog(frame,
"Are you sure to close this window?", "Really Closing?",
JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE)==
JOptionPane.YES_OPTION)
{System.exit(0); }
}});
28. What are the different types of JDBC Driver?
Answer: We have 4
types of interface API to interact with Database Servers.
JDBC-ODBC Bridge Driver:
|
JDBC (Java) will connect with ODBC (Open) drivers like DSN
installed in OS.
|
DSN and Java
|
JDBC-Native API:
|
All JDBC calls will be converted into Native C/C++ calls using
OCI
|
Oracle Call Interface(OCI)
|
JDBC-Net Pure Java:
|
A middleware software will be installed and Java will connect
with that server.
|
Application Server JDBC Resource
|
100% Pure Java:
|
Pure Java Driver API directly connect with Database Server
|
ConnectorJ
|
29. What is abstraction in JAVA?
Answer: Creating a class with declaration of
behaviors without actual implementation/definition of the behavior is called
abstraction in java. This is accomplished though abstract classes and
interfaces in java.
30. What is inheritance in JAVA?
30. What is inheritance in JAVA?
Answer: One class’s object can acquire the
properties of other objects/behaviors.
31. How Encapsulation concept implemented in JAVA?
31. How Encapsulation concept implemented in JAVA?
Answer: Class. It has behavior i.e. methods and
data i.e. variables and can be protected using access specifier.
32. What do you mean checked and unchecked
Exceptions? List some example for both?
Answer:
1.
Unchecked Exception in Java is those Exceptions whose
handling is not verified during Compile time
2.
Checked Exception in Java is those Exceptions were verified
during Compile time
33. Why we go for Collections Framework?
Answer: It provides an interfaces and classes to
handle/manipulate collection of objects.
34. I want to have ordered collection which
allows duplicates? Which collection is used for this?
Answer: List allows duplicate values and maintains
the insertion order.
35. I want to have class which have the behavior of Hash-map? How this can be done?
35. I want to have class which have the behavior of Hash-map? How this can be done?
Answer:
Please refer this page: http://www.vogella.com/tutorials/JavaDatastructures/article.html
Stack
Implementation: http://www.vogella.com/tutorials/JavaDatastructures/article.html
36. What hashCode() and equals() does in
HashMap?
Answer: HashMap works on
mechanism Hashing. Hashing in its simplest form,
is a way to assigning a unique code for any variable/object after applying any
formula/algorithm on its properties. A true Hashing function must follow this
rule:
Hash function should
return the same hash code each and every time, when function is applied on same
or equal objects. In other words, two equal objects must produce same hash code
consistently
On inserting new
(Key,Value) pair, the key is validated with all keys using equals method and
same time their hashCode also validated. If both are same the values will be
replaced, but if differs it will be added as new entry.
37. Do you know Generics? What is it? Why
we need that? How u have used in your coding?
Answer:
Generics means the types (classes and interfaces) are parameterized into
classes, interfaces and methods.
Need:
1.
Algorithms (methods/classes) can be generalized to use any
type (class/interface)
2.
We can avoid runtime type casting issues by forcing compile
time type checking
3.
Type casting can be eliminated during coding.
Sample
Class Box{}
Box b =
new Box();
Java SE7: Box b = new Box<>();
Bounded Type
Parameters: class Box {}
So you can do only Box<>
38. Why we prefer implements Runnable to create THREAD?
Answer:
1. MyThread class implements Runnable has option to
extend other classes
2. Thread instances created and passed to the
MyThread can share the resources of MyThread.
39. Difference between String and
StringBuilder and StringBuffer?
Answer:
1. String class’s all methods returns newly created
String instances. So every operation creates and returns new object.
2.
But StringBuilder and StringBuffer methods are working on same object so there
is no new object created for every operation. StringBuffer is synchronized so
multiple threads can work safely.
Choice:
StringBuilder is preferred over String because of less memory occupied.
StringBuffer
preferred if you go for multiple threads environment.
40. What is the use of default Constructor?
40. What is the use of default Constructor?
Answer: It initializes the objects
during upon creation. The instance variables are set to null/default values
like below.
public Module()
{
super();
this.name = null;
this.credits = 0;
this.hours = 0;
}
This
is exactly the same as
public Module()
{}
41. What is the use of static block?
Answer:
It runs during the class loading by JVM, and used to initialize static variables.
42. What class is on top of all classes, what are the methods that class have?
42. What class is on top of all classes, what are the methods that class have?
Answer:
Object and has 11 methods. http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html?_sm_au_=iZMH0sGMDL4LPsD5
43. Explain about String-pool?
43. Explain about String-pool?
Answer:
Part of Heap Memory storing pool of string objects and maintains unique string
literals.
Immutable
class: final class, with final instance variable and no setter methods.
44. What are the Class-loaders you have used?
44. What are the Class-loaders you have used?
Answer:
There are 8 different types of class loaders in JVM.
Bootstrap Class Loader à Bootstrap class
loader loads java’s core classes like java.lang, java.util etc. These are
classes that are part of java runtime environment. Bootstrap class loader is
native implementation and so they may differ across different JVMs.
Extensions Class Loader à JAVA_HOME/jre/lib/ext contains jar packages that are extensions of standard core java classes. Extensions class loader loads classes from this ext folder. Using the system environment propery java.ext.dirs you can add ‘ext’ folders and jar files to be loaded using extensions class loader.
System Class Loader à Java classes that are available in the java classpath are loaded using System class loader
Extensions Class Loader à JAVA_HOME/jre/lib/ext contains jar packages that are extensions of standard core java classes. Extensions class loader loads classes from this ext folder. Using the system environment propery java.ext.dirs you can add ‘ext’ folders and jar files to be loaded using extensions class loader.
System Class Loader à Java classes that are available in the java classpath are loaded using System class loader
ClassLoader.loadClass() & Class.forName() used to load class
objects.
45. Write code with Iterator()?
45. Write code with Iterator()?
Answer: Map map = new HashMap();
Iterator entries =
map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
Integer key = (Integer)entry.getKey();
Integer value = (Integer)entry.getValue();
System.out.println("Key = " + key + ", Value = " +
value);
}
46. What do you mean Serialization? Tell me about Volatile and transient variables?
Answer:
Objects can be represented as a sequence of bytes including its information
about it and its variables. Transient variables cannot be serialized so their
values will be either null or 0. Volatile variables can be
serialized/deserialized. But volatile values will maintain same value across
many threads because it is created and shared from main memory and not in
Thread’s cache memory.
47. In String differentiate == and equals ()?
47. In String differentiate == and equals ()?
Answer:
== compares the instances, equals checks character sequence.
48. What is mean by Immutable Classes? How could you create?
48. What is mean by Immutable Classes? How could you create?
Answer:
A class where its objects state cannot be changes once created. Final class
with final variables and with no setter methods is an immutable class.
49. What do you mean by Wrapper Classes? Can we extend Wrapper Classes?
49. What do you mean by Wrapper Classes? Can we extend Wrapper Classes?
Answer:
The primitive types are need to be processed in collections so they need to be
interpreted in reference instead of primitive values, so Wrapper classes for
primitive types are intoroduced.
50. What is the use of Thread-Local?
50. What is the use of Thread-Local?
Answer:
To maintain the instances unique per thread we use ThreadLocal like private
static fields.
51. If we have 5 abstract-methods in abstract class, does we need to implement all methods?
51. If we have 5 abstract-methods in abstract class, does we need to implement all methods?
Answer:
Yes the extending class should implement all of them.
52. If I call wait() what will be the current threads state ? i.e., from which state to which state?
52. If I call wait() what will be the current threads state ? i.e., from which state to which state?
Answer:
The currently running thread goes to paused state and will resume again by
notify() of another thread. From running state to paused state.
53. All classes extends Object, if Class A extends Class B, it becomes like multiple inheritance isn’t? But Java won't support it? How this is resolved?
53. All classes extends Object, if Class A extends Class B, it becomes like multiple inheritance isn’t? But Java won't support it? How this is resolved?
Answer:
On compilation Object becomes A’s super class and A becomes B’s super class.
54. I have different types of objects (Employee, Salary, Item, Delivery etc) in Hash-Set as its items, I want to sort them, How to do that?
54. I have different types of objects (Employee, Salary, Item, Delivery etc) in Hash-Set as its items, I want to sort them, How to do that?
Answer:
We want to override equals and hashCode method so unique objects only will be
maintained and duplicates will be overridden.
55. What is the difference between static and instance methods and variables? And about their memory sharing? Answer: We want to override equals and hashCode method so unique objects only will be maintained and duplicates will be overridden.
56. I want to store transient variable, How can I do that?
55. What is the difference between static and instance methods and variables? And about their memory sharing? Answer: We want to override equals and hashCode method so unique objects only will be maintained and duplicates will be overridden.
56. I want to store transient variable, How can I do that?
Answer:
We need to override writeObject and readObject to make the transient variables
to get serialized and de-serialized.
57. Tell me the different Layouts available?
57. Tell me the different Layouts available?
Answer:
FlowLayout, NullLayout, GridLayout, GridBagLayout and BorderLayout.
58. Why we have wait(), notify() and notify all() methods in Object class ?
58. Why we have wait(), notify() and notify all() methods in Object class ?
Answer:
On thread execution on object for example, myObject if we call myObject.wait()
then the currently running will be paused. Notify and notifyAll() will call
other threads to take monitor and run.
59. How will you create Immutable Class Object?
59. How will you create Immutable Class Object?
Answer:
final Class, private and final variables and there is no setter methods.
60. Tell me about How JVM works?
60. Tell me about How JVM works?
Answer:
final Class, private and final variables and there is no setter methods.
61. A class implementing two interfaces
with add they have same method declaration? Is ti possible and how the method overriding
will work?
Answer:
Will work without any issues, because we simply implement the blueprint and not
the implementation. Actual implementation is at the class only.
62. Cloning – shallow copy and deep copy?
Answer:
Shallow
copy means – the reference only copied remaining internal
objects/values/elements will remain same. If value is changed it reflects at
all references.
Deep
Copy means – Copying everything to new object. So new full structure is
created. If values is changes it reflects at only the particular reference.
63. Why Java does not supported Multiple
Inheritance of Classes?
Answer:
On Java design, the creators thought that Multiple Inheritance will create many
problems and so not allowed class level multiple inheritance and allowed multiple
inheritance through interfaces.
63. What do u mean static import why it is
introduced?
Answer:
To avoid the static class names repeatedly at all places, just do static import
and use the methods and variables without the name of the class.
import
java.lang.Math.PI;
double r =
Math.cos(Math.PI * theta); can be
converted into
import static java.lang.Math.PI;
double r = cos(PI *
theta);
64. What are the Java 5 version features?
Java 6 features and Java 7 features?
Java 5
|
1.
Generics
2.
Enhanced For Loop
3.
Auto boxing and Unboxing of primitive
type wrappers
4.
Static import
5.
Annotations or Metadata
6.
Type safe ENUM ex: enum fruits{APPLE,
ORANGE, GRAPE, PAPAYA}
7.
Varagrs – arguments as sequence
add(int…args) – so u can send any number of args either as array or sequence
of int
|
Java 6
|
Few Collections re-engineering for performance
|
Java 7
|
1.
String in switch statements
2.
Byte, int,short, long can be expressed as
binary line 01011010
3.
Try-with resources
4.
Catch – multiple exceptions
5.
Throw – multiple exceptions
6. Underscore
in numeric literals
7. Type
inference in Generics ie no need of right hand side type Map
|
65. Observable – How to use it?
Answer:
class Observable – If u want to make
an object observable extend this class, add Observers.
Interface Observer – To make an observer
for an observable class implement this interface.