Part 9
Core java interview questions and answers for 3-5 years experience covered in this post:
What will happen if I am trying to run
a thread which is already in running the state?
- Yes, we can't start already running thread. It will throw
IllegalThreadStateException at runtime - if the thread was already
started.
- For your reference please refer to the below example.
package simplifiedjava.crackedInterview; public class RestartedThreadDemo extends Thread{
@Override
public
void
run() {
}
public
static
void
main(String[] args) {
Thread t
= new
Thread();
t.start();
t.start();
} }
Output: Exception in thread "main" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Unknown Source)
at simplifiedjava.crackedInterview.RestartedThreadDemo.main(RestartedThreadDemo.java:14)
|
How will you prevent to be serialized
child class when its parent class is Serializable?
- There is no direct way to prevent child class from serialization. You can
override writeObject() and readObject() methods in your child class and then
explicitly throw NotSerializableException. It will prevent child class from
serialization.
- Please refer to the below example.
package simplifiedjava.crackedInterview; import java.io.Serializable; public class Parent implements Serializable{ public int i;
public
Parent() {
System.out.println("Parent Class no-arg constructor called."); }
public
Parent(int i) {
this.i = i; }
public void
check(){
System.out.println("Parent Class check() method");
}
} package simplifiedjava.crackedInterview;
import
java.io.NotSerializableException;
import
java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class Child extends Parent{
int j; public Child() {
}
public
Child(int i,int j) {
super(i);
this.j = j; }
public void
check(){
System.out.println("Addition in Child Class "+ (i + j)); }
private void
writeObject(ObjectOutputStream oos)throws
NotSerializableException {
throw new
NotSerializableException(); }
private void
readObject(ObjectInputStream ois) throws
NotSerializableException {
throw new
NotSerializableException();
} } package simplifiedjava.crackedInterview;
import
java.io.File;
import
java.io.FileInputStream;
import
java.io.FileOutputStream;
import
java.io.IOException;
import
java.io.ObjectInputStream; import java.io.ObjectOutputStream;
public class
SerializationInHeritanceDemo { public static void main(String[] args) throws IOException, ClassNotFoundException {
Child c1 = new
Child(10,20); System.out.println("Values Before Serialization : " + c1.i +" and "+ c1.j);
FileOutputStream fos = new
FileOutputStream(new
File("abc.ser"));
ObjectOutputStream oos = new
ObjectOutputStream(fos);
oos.writeObject(c1);
FileInputStream fis = new
FileInputStream("abc.ser");
ObjectInputStream ois = new
ObjectInputStream(fis);
Child c2
=(Child) ois.readObject();
System.out.println("Values After Deserialization : "+ c2.i +" and "+ c2.j); }
Values Before Serialization : 10 and 20
Exception in thread "main" java.io.NotSerializableException
at
simplifiedjava.crackedInterview.Child.writeObject(Child.java:26)
at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown
Source)
at
java.lang.reflect.Method.invoke(Unknown Source)
at
java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
at
java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at
java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at
java.io.ObjectOutputStream.writeObject0(Unknown Source)
at
java.io.ObjectOutputStream.writeObject(Unknown Source) at simplifiedjava.crackedInterview.SerializationInHeritanceDemo.main(SerializationInHeritanceDemo.java:19) |
Can you declare class inside
class?
- Without existing one type of object if there is no chance of existing
another type of object then we can declare a class inside a class.
- E.g. University can have several departments, without existing university
there is no chance of an existing departments. Hence, we have to declare
department class inside university class.
- Please refer to the below example.
package simplifiedjava.crackedInterview;
public class
University { public class Department{
}
} |
Can you declare interface inside
interface?
- Yes, we can declare interface inside interface.
- We can take the example of Map. A map is a group of key/value
pairs.
- Each key/value pair is called Entry.
- Without an existing map object, there is no chance to exist an Entry
object. Hence, interface Entry is defined inside Map.
- Please refer to the below example.
public interface Map <K,V> { public interface Entry<K,V>{
}
} |
Can you declare interface inside
class?
- Inside a class, if we require multiple implementations of an interface and
all these implementations are related to the class then we can define an
interface inside a class.
- Please refer to the below Example.
package simplifiedjava.crackedInterview; public class InterfaceDefinedInsideClassDemo {
interface
Vehicle{
public void
getNoOfWheels(); }
class
Bus implements
Vehicle{
public void
getNoOfWheels() {
System.out.println("Six Wheels");
} }
class
Pulsor implements
Vehicle{
public void
getNoOfWheels() {
System.out.println("Two Wheeler");
} }
public static void
main(String[] args) {
InterfaceDefinedInsideClassDemo demo = new
InterfaceDefinedInsideClassDemo();
Vehicle v = demo.new
Bus(); v.getNoOfWheels();
v = demo.new
Pulsor();
v.getNoOfWheels();
}
}
Output:
Six Wheels
Two Wheeler |
Can you declare class inside
interface?
- If the functionality of the class is closely associated with the interface
then it is highly recommended to declare a class inside the interface.
- Please refer to the below example.
package simplifiedjava.crackedInterview; public interface EmailService { public void sendEmail(EmailDetails e);
class
EmailDetails{
String toList;
String ccList;
String subject;
String body;
}
} |
Which data structure is implemented for
HashSet?
- Internally HashMap has been implemented for HashSet.
What is TreeMap? Can you explain how
the objects will be stored in TreeMap?
- TreeMap is a data structure where elements are stored in some
natural sorting order.
- Underlying data structure is the RED-BLACK tree.
- Insertion order never maintains. Maintain some natural
sorting order.
- Duplicates keys are not allowed but duplicate values are
allowed.
- If we are depending on natural sorting order then keys should be
homogeneous and comparable otherwise it will through ClassCastException.
- If we are defining our comparator then keys need not be
homogeneous or comparable.
- We can insert homogeneous as well as Heterogeneous (Different
types of Object) objects in the Treemap.
- Null is strictly now allowed after java 7.
- Till java 6, For non-empty Treemap if we are trying to insert an entry with
the null key then we will get NullPointerException. For empty tree map at
first entry with null key is allowed but after inserting new key you will
get NullPointerException.
- Please refer to the below example.
package simplifiedjava.crackedInterview; import java.util.TreeMap; public class TreeMapDemo { public static void main(String[] args) {
TreeMap<Integer, String> tMap = new
TreeMap<Integer, String>();
tMap.put(100, "Hundred");
tMap.put(1, "One");
tMap.put(1000, "Thousand");
tMap.put(10, "Ten");
System.out.println(tMap);
}
}
Output:
{1=One, 10=Ten, 100=Hundred, 1000=Thousand} |
What is the difference between Iterator
and ListIterator?
|
Iterator |
ListIterator |
1. |
Iterator is universal iterator. |
ListIterator is not universal iterator. |
2. |
Iterator can iterate all collection objects. |
ListIterator can iterate only the list. |
3. |
Iterator moves only forwards direction. |
ListIterator can move bidirectionally. |
4. |
Iterator can perform only read and remove operations. |
ListIterator can perform read, write, update and remove
operations. |
5. |
Iterator has 3 methods for iteration.
1. hasNext();
2. next();
3. remove(); |
ListIterator has 9 methods.
1. hasNext();
2. next();
3. nextIndex();
4. hasPrevious();
5. previous();
6. previousIndex();
7. remove();
8. add();
9. set(); |
What is CopyOnWriteArrayList? How does
it work internally?
- CopyOnWriteArrayList is Concurrent implementation of List interface.
- CopyOnWriteArrayList implements List interface so, all basic functionality
of List is applicable to CopyOnWriteArrayList.
- It is a very costly object because every update operation creates a clone
copy of the same object.
- When one thread is iterating CopyOnWriteArrayList same time another thread
is allowed to perform writes operation still we won’t get
ConcurrentModificationException.
- Iterator of ArrayList performs remove operation. Iterator of
CopyOnWriteArrayList can not perform the remove operation. If we try to
remove then it will throw UnSupportedOperationException.
- Iterator of CopyOnWriteArrayList is Fail-Safe.
- Please refer to the below example.
package
simplifiedjava.crackedInterview; import java.util.concurrent.CopyOnWriteArrayList; public class CopyOnWriteArrayListDemo {
public static void
main(String[] args) {
CopyOnWriteArrayList<Integer> list = new
CopyOnWriteArrayList<Integer>();
list.add(10);
list.add(20);
list.add(30);
list.add(40);
list.add(50);
System.out.println(list);
}
}
Output: [10, 20, 30, 40, 50] |
- Java interview questions and answers all MNC - Click here
- Basic core java interview questions and answers for freshers - Click here
- Core java interview questions for 3 years experience - Click here
- Core java interview questions and answers for 3-5 years exp - Click here
- Core java interview questions and Answers for 5 - 7 Years exp - Click here
- Basic Java Interview Questions and Answers - Click here
- Java interview questions and answers on oops - Click here
- Java interview questions and answers on Strings - Click here
- Java interview questions on exception handling - Click here
- Interview questions on multithreading in java for experienced - Click here
- Interview questions on serialization in java for experienced - Click here
- Interview questions on inner class in java for experienced - Click here
- Interview questions on Collections in java for experienced - Click here
Upcoming questions in next post:
Thank you techies for visiting this blog. I hope you enjoyed this blog and got more technical knowledge. I have tried to cover all types of questions and provided examples tested on eclipse as much as I can. Guys, please don’t just mug up the questions and answers. Try to clear your concepts with examples. Try to write a code on eclipse once you read the concepts. It will help you to memorize the concepts for a very long time. Simultaneously you will be prepared for interview programs as well. It will help you to survive in the IT sector for a long time. It may be easy to crack an interview but it's really tough to survive in the IT industry with inadequate knowledge and skills. I have collected all the questions from actual interviews attended by my friends, colleagues, college mate and classmate. I have covered frequently asked questions as well as challenging questions. I have included many programs to understand the concept thoroughly. I will try to explain the concept with the help of a real-time program in eclipse. You can share more questions which are not covered in this blog or post. Always welcome your suggestions and queries. I will definitely try to resolve it. Please comment your queries and new set of questions under the comment sections. I will create a new post for those questions.
My total experience is 10. Initially I had worked on some
support projects and then I moved to java projects. I had worked
with many multi-national companies like R-Systems, Tata
Consultancy Services, Cybage Softwares. Fortunately,
TCS and Cybage has given me an opportunity to take interviews
for experienced candidates. I have conducted more than 1000
interviews by now. Mock sessions will be conducted for minimal charges. I will guide you personally on how to crack interviews. All sessions will be online sessions only. My interview book will be provided free of cost if you enroll for personal training. Once you have done practice then I assured you will definitely crack almost all java interviews. I have published my book named with "All MNC Java Interview" which is available on amazon. You can go through it or you can directly contact to me if you are interested to read the book. I will give you special discount. I have covered near about 550 questions and answers with program tested on eclipse and necessary diagram. I have covered interview questions asked in all reputed MNC like TCS, Infosys, Capgemini, Tech Mahindra, Cognizant, City Bank, Barclays, Amdocs, Mindtree etc. My purpose behind this book is, help you to get a job in your dream company. I can understand this is a struggling period for job seekers and freshers. Everybody must have gone from this phase. so never give up. Keep upgrading yourself. I am sure you will get a job in your dream company. All the best!!! Please reach out to me for personal training for interview preparation.
You can reach out to me at mncjavainterview@gmail.com.
|
0 Comments