CORE JAVA INTERVIEW QUESTIONS AND ANSWER CONT...
Moti Lal Kumar
Associate Staff Engineer | Java | Spring Boot | Microservices | Hibernate | Jpa | Rest API | Angular | SQL | AWS | DSA | Kafka
I'm sharing core java interview questions and answer notes cont....
Please like , comment and share for better approach.
101) What is the difference between String and StringBuffer and String Builder classes?
All are final classes. String class Objects are Immutable and Thread safe
StringBuffer class objects are Mutable and Thread safe
StringBuilder class objects are Mutable and Non Thread safe
102) Explain about toString() method?
The toString() method is implemented in such a way that it will always return the class name followed by @ symbol and then the hexadecimal representation of the objects address. And if we override it, then we will see whatever implementation we provide, whatever we return back from the toString method that will be used instead.
103) What is the use of equals method in java? Equals method is used to compare two objects. This method is present in Object class. It is similar to that of == operator, used to compare references to objects. But if we want to compare contents present in objects then we should override this method in our class, then it compares the content of two objects. It has already overridden in String class, Wrapper classes, and Enum class.
104) What is the use of hashCode() method?
hashCode() method is used to get the unique reference of an object.
105) Can you give examples of different utility methods in String class?
length(), charAt(), contains(), substring(), startsWith(), endsWith(), indexOf() etc..
106) What are differences between String and StringBuffer?
String class is used to create Immutable objects. String class objects will be created by using String literal and new operator. StringBuffer class is used to create Mutable objects. StringBuffer class objects are created by using new operator.
107) What are differences between StringBuilder and StringBuffer?
Both are used to create Mutable objects. But StringBuffer is threadsafe and StringBuilder is non thread safe.
108) Define Assert statements and when it is used?
An assertion allows testing the correctness of any assumptions that have been made in the program. An assertion is achieved using the assert statement in Java. While executing assertion, it is believed to be true. If it fails, JVM throws an error named AssertionError. It is mainly used for testing purposes during development. The assert statement is used with a Boolean expression and can be written in two different ways.
First way: assert expression;
Second way: assert expression1: expression2;
109) What is Coupling? Coupling is a measure of how much a class is dependent on other classes. There should be minimal dependencies between classes. So, We should always aim for low coupling between classes.
110) What is Cohesion?
Cohesion is a measure of how related the responsibilities(methods) of a class are. A class must be highly cohesive that is its responsibilities should be highly related to one another. EXCEPTION HANDLING:
111) How can you handle exceptions in Java?
By using try catch and finally blocks.
112) Why is exception handling important?
By using Exception handling mechanism we can avoid the damage that should be happened for our data. We can provide our own user friendly exception messages.
113) What is the super class for all exceptions and errors in java?
Throwable class which is in java.lang package
114) What is the super class for all exceptions in java?
Exception class
115) What are the keywords used to handle an exception in java?
Try, catch, and finally keywords
116) Name different type of exceptions in java?
Checked and Unchecked exceptions
117) Can we write statements between try block and catch block?
No
118) What design pattern is used to implement exception handling features in most languages?
Chain of responsibility design pattern → a way of passing a request between chain of objects.
119) What is the need for finally block?
Clean up or closing operations will be performed in finally block. Finally block always gets executed where exception is there or not.
120) In what scenarios is code in finally not executed?
If JVM crashes in between like if we use System.exit() and if exception is thrown in finally. 121) Is try without a catch is allowed?
Yes. We can use try and finally blocks without a catch block.
122) What is exception handler in java?
The code that catches the exception thrown by JVM.
123) Can we just use try instead of finally and catch blocks?
No.
124) Can you explain the hierarchy of exception handling classes?
Throwable class is the super class for all exceptions and errors Error class is the super class for all?Error classes
Exception class is the direct super class for all checked exceptions(exceptions which are detected by compiler at compile time)
RuntimeException class is the super class for all unchecked exceptions(exceptions which are detected by JVM at runtime)
125) Difference between 1. System.out.println(1/0); 2. System.out.println(2.0/0);
In first case, Arithmetic Exception raises at run time.
In second case, Infinity is the output.
126) What is the difference between error and exception?
Error is used in situations when there is nothing a programmer can do about an error.
Ex: VirtualMachineError, StackOverFlowError, OutOfMemoryError
Exception is used in situations when a programmer can handle the exception.
127) What is the difference between checked exceptions and unchecked exceptions? Checked exceptions are detected by compiler at compile time. Exception class is super class for all checked exceptions.
Unchecked exceptions are detected by JVM at runtime. RuntimeException class is the super class for all unchecked exceptions. Exception class is super class for RuntimeException class.
128) Which Exception class can you use in the catch block to handle both checked and unchecked exceptions?
Exception class
129) Difference between throw and throws keywords?
Throw is used to throw an exception explicitly by the programmer.
Throws is used when the programmer don’t want to handle the exception.
130) How do you throw an exception from a method?
Using throw keyword
131) What happens when you throw a checked exception from a method?
It raises a compile time error.(unhandled exception type exception)
领英推荐
132) What are the options you have to eliminate compilation errors when handling checked exceptions?
Declaring that a method would throw an exception Handling the checked exception with a try catch blocks
133) How do you create a custom exception?
Create a user defined class which extends Exception class or RuntimeException class.
134) How do you handle multiple exceptions in a single catch block?
Using Pipe operator
135) Can you explain about try with resources?
When the try block ends the resources are automatically released. We don not need to create a separate finally block.
try(BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
// logic
}
catch(Exception e)
{
e.printStackTrace();
}
136) What is the need for threads in Java?
Threads allow java code to run in parallel. We want to do more things in less time
137) How do you create a thread?
By extending Thread class By implementing Runnable interface
138) How do you create a thread by extending thread class?
class UserDefinedThread extends Thread {
public void run( ) {
// logic
}
}?
139) How do you create a thread by implementing runnable interface?
class UserDefinedThread implements Runnable{
public void run()
{
// logic
}
}
140) How do you run a thread in Java?
By using Thread class start() method
141) What are the different states of a thread?
New, Runnable, Running, Blocked / Waiting, Treminated / Dead states
142) What is priority of a thread? How do you change the priority of a thread?
Thread priorities ranges from 1 to 10. Default thread priority is 5.
We can change the thread priority using setPriority() method.
143) What is Executor Service?
Java.util.concurrent.ExecutorService interface is a new way of executing tasks asynchronously in the background. It is similar to that of a Thread pool.
144) Explain different ways of creating executor services
There are 3 ways of creating executor services.
ExecutorService executorService1 = Executors.newSingleThreadExecutor(); ExecutorService executorService2 = Executors.newFixedThreadPool(10);
ExecutorService executorService1 = Executors.newScheduledThreadPool(10);
145) How do you check whether an executionservice task executed successfully?
We can use a Future interface to check the return value. Future interface get method will return null if the task finished successfully.
146) What is callable?How do you execute a callable from executionservice?
Runnable interface run method has a return type void. It cannot return any result from executing a task. A Callable interface class method has a return type. If you have multiple return values possible from a task, we can use the Callable interface.
Future future = executorService1.submit(new Callable(){
public String call() throws Exception{?
return “hello”;
}
});
S.o.pln(future.get());
147) Can you give an example of a synchronized block?
synchronized(this){
// logic
}?
148) Can a static method be synchronized?
Yes
149) What is the use of join method in threads?
We can maintain the order of execution of threads.
150) Describe a few other important methods in threads?
isDaemon(), setDaemon(),setName(), getName(), getId(), yield(), sleep(), interrupted() etc..
151) What is a deadlock?
Lets consider a situation where thread1 is waiting for thread2 and thread2 is waiting for thread1. This situation is called a Deadlock. In this situation, both threads would wait for one another for ever.
152) What are the important methods in Java for inter-thread communication? wait(), notify(), notifyAll() methods.
153) What is the use of wait method?
This method is present in Object class. This causes the thread to wait until it is notified.
154) What is the use of notify method? This method is present in Object class. This causes the object to notify other waiting threads.
155) What is the use of notifyAll method?
If more than one thread is waiting for an object, we can notify all the threads by using notifyAll methods.