Prepare Interview

Mock Exams

Make Homepage

Bookmark this page

Subscribe Email Address

Core Java Interview Questions and Answers

Test your skills through the online practice test: Core Java Quiz Online Practice Test

Ques 291. What is polymorphism in Java? Method overloading or overriding?

What is polymorphism in Java

Polymorphism is an Oops concept which advice use of common interface instead of concrete implementation while writing code. When we program for interface our code is capable of handling any new requirement or enhancement arise in near future due to new implementation of our common interface. If we don't use common interface and rely on concrete implementation, we always need to change and duplicate most of our code to support new implementation. Its not only java but other object oriented language like C++ also supports polymorphism and it comes as fundamental along with encapsulation , abstraction and inheritance.

Method overloading and method overriding in Java
Method is overloading and method overriding uses concept of polymorphism in java where method name remains same in two classes but actual method called by JVM depends upon object. Java supports both overloading and overriding of methods. In case of overloading method signature changes while in case of overriding method signature remains same and binding and invocation of method is decided on runtime based on actual object. This facility allows java programmer to write very flexibly and maintainable code using interfaces without worrying about concrete implementation. One disadvantage of using polymorphism in code is that while reading code you don't know the actual type which annoys while you are looking to find bugs or trying to debug program. But if you do java debugging in IDE you will definitely be able to see the actual object and the method call and variable associated with it.

Is it helpful? Add Comment View Comments
 

Ques 292. What is Encapsulation in Java and OOPS with Example?

Encapsulation is nothing but protecting anything which is prone to change. rational behind encapsulation is that if any functionality which is well encapsulated in code i.e maintained in just one place and not scattered around code is easy to change. this can be better explained with a simple example of encapsulation in Java. we all know that constructor is used to create object in Java and constructor can accept argument.

Advantage of Encapsulation in Java and OOPS
Here are few advantages of using Encapsulation while writing code in Java or any Object oriented programming language:

1. Encapsulated Code is more flexible and easy to change with new requirements.
2. Encapsulation in Java makes unit testing easy.
3. Encapsulation in Java allows you to control who can access what.
4. Encapsulation also helps to write immutable class in Java which are a good choice in multi-threading
environment.
5. Encapsulation reduce coupling of modules and increase cohesion inside a module because all piece of one thing
are encapsulated in one place.
6. Encapsulation allows you to change one part of code without affecting other part of code.

What should you encapsulate in code
Anythign which can be change and more likely to change in near future is candidate of Encapsulation. This also helps to write more specific and cohesive code. Example of this is object creation code, code which can be improved in future like sorting and searching logic.

Design Pattern based on Encapsulation in Java
Many design pattern in Java uses encapsulation concept, one of them is Factory pattern which is used to create objects. Factory pattern is better choice than new operator for creating object of those classes whose creation logic can vary and also for creating different implementation of same interface. BorderFactory class of JDK is a good example of encapsulation in Java which creates different types of Border and encapsulate creation logic of Border. Singleton pattern in Java also encpasulate how you create instance by providing getInstance() method. since object
is created inside one class and not from any other place in code you can easily change how you create object without
affect other part of code.

Is it helpful? Add Comment View Comments
 

Ques 293. Difference between Thread and Runnable interface in Java?

Here are some of my thoughts on whether I should use Thread or Runnable for implementing task in Java, though you have another choice as "Callable" for implementing thread which we will discuss later.

1) Java doesn't support multiple inheritance, which means you can only extend one class in Java so once you extended Thread class you lost your chance and can not extend or inherit another class in Java.

2) In Object oriented programming extending a class generally means adding new functionality, modifying or improving behaviors. If we are not making any modification on Thread than use Runnable interface instead.

3) Runnable interface represent a Task which can be executed by either plain Thread or Executors or any other means. so logical separation of Task as Runnable than Thread is good design decision.

4) Separating task as Runnable means we can reuse the task and also has liberty to execute it from different means. since you can not restart a Thread once it completes. again Runnable vs Thread for task, Runnable is winner.

5) Java designer recognizes this and that's why Executors accept Runnable as Task and they have worker thread which executes those task.

6) Inheriting all Thread methods are additional overhead just for representing a Task which can can be done easily with Runnable.

Is it helpful? Add Comment View Comments
 

Ques 294. Difference between Wait and Sleep , Yield in Java

Difference between Wait and Sleep in Java
Main difference between wait and sleep is that wait() method release the acquired monitor when thread is waiting while Thread.sleep() method keeps the lock or monitor even if thread is waiting. Also wait method in java should be called from synchronized method or block while there is no such requirement for sleep() method. Another difference is Thread.sleep() method is a static method and applies on current thread, while wait() is an instance specific method and only got wake up if some other thread calls notify method on same object. also in case of sleep, sleeping thread immediately goes to Runnable state after waking up while in case of wait, waiting thread first acquires the lock and then goes into Runnable state. So based upon your need if you require a specified second of pause use sleep() method or if you want to implement inter-thread communication use wait method.

here is list of difference between wait and sleep in Java :

1) wait is called from synchronized context only while sleep can be called without synchronized block. see Why wait and notify needs to call from synchronized method for more detail.

2) wait is called on Object while sleep is called on Thread. see Why wait and notify are defined in object class instead of Thread.

3) waiting thread can be awake by calling notify and notifyAll while sleeping thread can not be awaken by calling notify method.

4) wait is normally done on condition, Thread wait until a condition is true while sleep is just to put your thread on sleep.

5) wait release lock on object while waiting while sleep doesn’t release lock while waiting.

Difference between yield and sleep in java
Major difference between yield and sleep in Java is that yield() method pauses the currently executing thread temporarily for giving a chance to the remaining waiting threads of the same priority to execute. If there is no waiting thread or all the waiting threads have a lower priority then the same thread will continue its execution. The yielded thread when it will get the chance for execution is decided by the thread scheduler whose behavior is vendor dependent. Yield method doesn’t guarantee that current thread will pause or stop but it guarantee that CPU will be relinquish by current Thread as a result of call to Thread.yield() method in java.

Sleep method in Java has two variants one which takes millisecond as sleeping time while other which takes both mill and nano second for sleeping duration.

sleep(long millis)
or
sleep(long millis,int nanos)

Cause the currently executing thread to sleep for the specified number of milliseconds plus the specified number of nanoseconds.

10 points about Thread sleep() method in Java
I have listed down some important and worth to remember points about Sleep() method of Thread Class in Java:

1) Thread.sleep() method is used to pause the execution, relinquish the CPU and return it to thread scheduler.

2) Thread.sleep() method is a static method and always puts current thread on sleep.

3) Java has two variants of sleep method in Thread class one with one argument which takes milliseconds as duration for sleep and other method with two arguments one is millisecond and other is nanosecond.

4) Unlike wait() method in Java, sleep() method of Thread class doesn't relinquish the lock it has acquired.

5) sleep() method throws Interrupted Exception if another thread interrupt a sleeping thread in java.

6) With sleep() in Java its not guaranteed that when sleeping thread woke up it will definitely get CPU, instead it will go to Runnable state and fight for CPU with other thread.

7) There is a misconception about sleep method in Java that calling t.sleep() will put Thread "t" into sleeping state, that's not true because Thread.sleep method is a static method it always put current thread into Sleeping state and not thread "t".

That’s all on Sleep method in Java. We have seen difference between sleep and wait along with sleep and yield in Java. In Summary just keep in mind that both sleep() and yield() operate on current thread.

Is it helpful? Add Comment View Comments
 

Ques 295. Difference between Vector and ArrayList in Java

1) Vector and ArrayList are index based and backed up by an array internally.
2) Both ArrayList and Vector maintains the insertion order of element. Means you can assume that you will get the object in the order you have inserted if you iterate over ArrayList or Vector.
3) Both iterator and ListIterator returned by ArrayList and Vector are fail-fast.

Key Differences between Vector and ArrayList in Java
1) First and foremost difference is Vector is synchronized and ArrayList is not, what it means is that all the method which structurally modifies Vector e.g. add () or remove () are synchronized which makes it thread-safe and allows it to be used safely in a multi-threaded environment. On the other hand ArrayList methods are not synchronized thus not suitable for use in multi-threaded environment.

2) ArrayList is faster than Vector. Since Vector is synchronized it pays price of synchronization which makes it little slow. On the other hand ArrayList is not synchronized and fast which makes it obvious choice in a single-threaded access environment. You can also use ArrayList in a multi-threaded environment if multiple threads are only reading values from ArrayList.

3) Whenever Vector crossed the threshold specified it increases itself by value specified in capacityIncrement field while you can increase size of arrayList by calling ensureCapacity () method.

4) Vector can return enumeration of items it hold by calling elements () method which is not fail-fast as opposed to iterator and ListIterator returned by ArrayList.

5) Another point worth to remember is Vector is one of those classes which comes with JDK 1.0 and initially not part of Collection framework but in later version it's been re-factored to implement List interface so that it could become part of collection framework



Conclusion is use ArrayList wherever possible and avoids use of Vector until you have no choice.

Is it helpful? Add Comment View Comments
 

Most helpful rated by users:

©2024 WithoutBook