Java Interview Questions and Answers covered in this post:
What are the access modifiers and their scope?
- There are four access modifiers which are as follows.
1. Default
2. Private
3. Protected
4. Public
- Scope:
Access Modifier |
Within Class |
Within Package |
Subclass in another package |
Outside package |
Default |
Y |
Y |
N |
N |
Private |
Y |
N |
N |
N |
Protected |
Y |
Y |
Y |
N |
Public |
Y |
Y |
Y |
Y |
Can you explain the public static void main(String[] args)
Method?
- Main method is a starting point of java program
execution.
- Main method components:
1. public: Access modifier of main() is public so the
method can be invoked from outside. This method must be public so the java
runtime can invoke it. If you make the main method private or protected then
you won’t get a compile-time error but a runtime exception.
2. static: We are aware of the use of static. Without
creating an object we can invoke the method of the class. So java runtime
can invoke the main method without instantiating the class.
3. void: return type of the main method is void cause the
main method doesn’t return anything.
4. main: This is the fixed name of the main method. You
cannot change the name of the main method otherwise you will get a runtime
exception.
5. (String args[]) : These are the command line argument.
We can pass these arguments to the java program.
What is the ternary operator in java?
-
Ternary operator lets you write if statement in one line.
-
Ternary operator evaluates either true or false.
- There are three parts of the ternary operator. The first part is expression
end with a question mark and two options separated with a colon.
- Variable = condition ? expression1: expression2.
package simplifiedjava.crackedInterview; public class TernaryOperatorDemo {
public
static
void
main(String[] args) {
int
num=20;
String typeNum
= (num
> 0) ? "Positive"
: "Negative";
System.out.println(typeNum);
}
}
Output : Positive |
Can you specify the scenario where you can implement String,
StringBuffer and StringBuilder?
- String: When content is fixed and never change throughout life then
String is a good option.
- StringBuffer: When content is not fixed and the requirement is
thread-safety then go for StringBuffer.
- StringBuilder: When content is not fixed and content would be
changing multiple times and no need for thread safety then go for
StringBuilder.
How to achieve Thread safety in java?
- Thread safety means multiple threads sharing the same resource without
producing an unpredictable result.
- We can achieve thread-safety in multiple ways. Please refer to the below 8 options.
1. Synchronized Methods.
2. Synchronized Blocks.
3. Synchronized Collection. (Using Collections Utility
Class).
4. Concurrent Collection.
5. Immutable Implementation.
6. Thread-Local Field.
7. Volatile Field.
8. Stateless Implementation.
Explanation in details.
1.
Synchronized Methods:
Ø The method can be declared with a
synchronized
keyword.
Ø Once you declared the method with a
synchronized
keyword then only one thread can execute shared resources at a time. Other
threads will be blocked until the first thread finishes its execution.
Ø synchronized
method depends on either “Intrinsic Lock” or “Monitor Lock”.
Ø When the thread calls the
synchronized
method, it acquires the intrinsic lock.
Ø The Monitor is just a reference to the role that the lock
performs on the associated objects.
Ø Please refer to the below example.
package simplifiedjava.crackedInterview; public class SynchronizedMethodDemo {
int counter
= 0;
public synchronized void
getCounter() {
counter
=+ 1; // Similar to counter = counter +1;
System.out.println("Counter is "+ counter); }
public static void
main(String[] args) {
new
SynchronizedMethodDemo().getCounter();
}
} |
2.
Synchronized Block:
Ø A
synchronized
block can be called a statement block.
Ø Method synchronization is highly expensive so to avoid this
situation we can perform synchronization at the statement level which is
less expensive from a performance perspective.
Ø A
synchronized
block generally declares inside a method.
Ø Please refer to the below example.
package simplifiedjava.crackedInterview;
import
java.util.ArrayList;
import
java.util.Arrays;
import
java.util.Collection; import java.util.Collections; public class SynchronizedBlockDemo {
int counter
= 0;
public void
getCounter() {
synchronized(this) {
counter
=+ 1; // Similar to counter = counter +1;
}
System.out.println("Counter is "+ counter); }
public static void
main(String[] args) {
new
SynchronizedMethodDemo().getCounter();
}
} |
3.
Synchronized Collection:
Ø We can create a thread-safe collection by using utility
methods of the Collections utility class.
Ø Once you create the thread-safe collection object then only
one thread can execute at a time. While other threads will be blocked until
the collection object is unblocked by the first thread.
Ø Please refer to the below example.
package simplifiedjava.crackedInterview;
import
java.util.Arrays;
import
java.util.Collections; import java.util.List; public class SynchronizedCollectionDemo {
public static void
main(String[] args) {
Thread t1 = new
Thread(new
MyClass1());
Thread t2 = new
Thread(new
MyClass2());
t1.start();
t2.start();
} } class MyClass1 implements Runnable{
@Override
public void
run() {
List<Integer> list1
= Arrays.asList(10,20,30,40,50);
List<Integer> synchronizedList1
= Collections.synchronizedList(list1);
for(Integer i : list1) {
System.out.println(i);
}
} } class MyClass2 implements Runnable{
@Override
public void
run() {
List<Integer> list2
= Arrays.asList(60,70,80,90,100);
List<Integer> synchronizedList2
= Collections.synchronizedList(list2);
for(Integer i : list2) {
System.out.println(i);
}
}
} |
4.
Concurrent Collection:
Ø Java provides java.util.concurrent package for thread
safety.
Ø Java.util.concurrent package has some thread safe classes
like ConcurrentHashMap, CopyOnWriteArrayList, CopyOnWriteArraySet.
Ø Please refer to the below example.
package simplifiedjava.crackedInterview;
import
java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class ConcurrentCollectionDemo {
public static void
main(String[] args) {
Map<String,Integer> concurrentMap = new
ConcurrentHashMap<>();
concurrentMap.put("one", 1);
concurrentMap.put("two", 2);
concurrentMap.put("three", 3);
}
} |
5.
Immutable Implementation:
Ø Immutable means its internal states can’t be changed once it
is created.
Ø If we need to share the state between different threads, we
can create thread-safe classes by making them immutable classes.
Ø If the state will be fixed forever then immutable objects can
be used thread-safely.
Ø Please refer to the below example.
package simplifiedjava.crackedInterview; public final class ImmutableClassDemo { private final String empCode="E001";
public
String getEmpCode() {
return empCode;
}
} |
6.
Thread-Local Field:
Ø We can easily create classes whose fields are thread-local by
simply defining private fields in the Thread class.
Ø We can create thread-safe classes that don’t share states
between threads by making their fields thread-local.
Ø Please refer to the below example.
package simplifiedjava.crackedInterview;
import
java.util.Arrays; import java.util.List; public class ThreadLocalDemo1 extends Thread { private final List<Integer> numList = Arrays.asList(10,20,30,40,50);
@Override
public void
run() {
for(int n : numList) {
System.out.println(n);
}
} } package simplifiedjava.crackedInterview;
import
java.util.Arrays; import java.util.List; public class ThreadLocalDemo2 extends Thread{ private final List<String> wordList = Arrays.asList("Hi","Hello","GM","GA","GN");
@Override
public void
run() {
for(String str : wordList) {
System.out.println(str);
}
}
} |
7.
Volatile Field:
Ø If you declare a variable as volatile, JVM will store those
variables on main memory.
Ø We can make sure every time JVM reads the value from the main
memory.
Ø Every time JVM writes the value it will write on the main
memory.
Ø Volatile keyword ensures that variable will be visible to all
thread and thread can read the value from main memory.
Ø Please refer to the below example.
package simplifiedjava.crackedInterview; public class ThreadLocalVariableDemo {
private volatile int empId; private String name; public static void main(String[] args) {
}
} |
8.
Stateless Implementation:
Ø Stateless implementation is the simplest way to achieve
thread safety.
Ø Stateless implementation is nothing but function
implementation which produces the same result every time. There is no change
to change the state by any thread.
Ø Please refer to the below example.
package simplifiedjava.crackedInterview; public class StateLessImplementationDemo { public static void main(String[] args) {
int i
= 10;
int square = i * i ;
System.out.println(square);
}
} |
What is deadlock? How to avoid a situation of dead lock?
- Deadlocks are a set of blocked processes, each holding a resource and
waiting to acquire a resource held by another process.
- We can avoid the deadlock: Do not grant a resource request if this
allocation has the potential to lead to deadlock.
What is NotSerializableException? When it can be thrown?
- The NotSerializableException is thrown when attempting to serialize or
deserialize an object that does not implement the java. io.Serializable
interface.
- Please refer to the below example.
package simplifiedjava.crackedInterview; import java.io.Serializable; public class Parent{ 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));
} } 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);
} }
Output:
Values Before Serialization : 10 and 20
Exception in thread "main" java.io.NotSerializableException: simplifiedjava.crackedInterview.Child
at
java.io.ObjectOutputStream.writeObject0(Unknown Source)
at
java.io.ObjectOutputStream.writeObject(Unknown Source)
at
simplifiedjava.crackedInterview.SerializationInHeritanceDemo.main(SerializationInHeritanceDemo.java:19) |
What is HashSet? Can you explain internal working of Hashset?
- HashSet of Collection framework represents the group of unique objects.
- HashSet internally uses hashing technique to store the elements. It's not
guaranteed in which sequence the elements will be stored or retrieved.
- Whenever you insert an element into HashSet using add() method, it creates
an entry in the HashMap object with the element you have specified as its
key and constant called “PRESENT” as its value. This “PRESENT” is defined in
the HashSet class as below.
-
private static final Object PRESENT = new Object();
-
Please refer the add method.
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
-
Please refer to the below example.
package
simplifiedjava.crackedInterview; import java.util.HashSet; public class HashSetDemo {
public static void
main(String[] args) {
HashSet<String> dayList = new
HashSet<String>();
dayList.add("Sat");
dayList.add("Sun");
dayList.add("Mon");
dayList.add("Tue");
dayList.add("Sun");
System.out.println(dayList);
}
}
Output: [Tue, Sat, Sun, Mon] |
- Graphical Representation of Internal working of HashSet
What is rehashing?
- Hashmap re-size itself by creating a new bucket array of size twice the previous size of hashmap and then start putting all old elements into the new bucket array this process is called rehashing.
What will happen if I declared multiple abstract methods in one
interface?
- If you declare multiple abstract methods inside interface and interface is
annotated with
@FunctionalInterface
then it will give a compile-time error.
- 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:
1. Can I declare final and abstract method in class.
2. What is static binding and dynamic binding.
3. What is the use of trim() method in String.
4. What are the multiple ways to create a thread. which one is recommendable.
5. What is the purpose of Inner classes.
6. What is the difference between static inner class and non static inner class.
7. What is load factor in collection API. What is the default size of load factor.
8. Can you explain internal working of ArrayList.
9. Explain the defined method in Stack.
10.What is entrySet?
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