Java Made So Easyxcxc
Java Made So Easyxcxc
Q2. Is there any difference between creating string with and without new
operator?
When String is created without new operator, it will be created in string pool.
When String is created using new operator, it will force JVM to create new
string in heap (not in string pool).
String s1 = "abc";
No string with “abc” is there in pool, so JVM will create string in string pool and s1
will be a reference variable which will refer to it.
String s2 = new String("abc");
String is created using new operator, it will force JVM to create new string in heap
(not in string pool).
String s3 = "abc";
string with “abc” is there in pool, so s3 will be a reference variable which will refer to
“abc” in string pool.
Q4. Can we use custom object as key in HashMap? If yes then how?
For using object as Key in HashMap, we must implements equals and hashcode
method.
Q5. How do we override equals and hashcode method, write a code to use
Employee(i.e. custom object) as key in HashMap? (Important)
After answering above question, immediately it will be followed up by this questions
We will override equals() and hashCode() like this -
By overriding equals() and hashCode() method we could use custom object as key in
HashMap.
1) Check whether obj is null or not.
@Override
if(obj==null)
if(this.getClass()!=obj.getClass())
}
@Override
}
Let’s say in an organisation there exists a employee with id=1 and name=’sam’ and
some data is stored corresponding to him, but if modifications have to be made in
data, previous data must be overridden.
import java.util.HashMap;
import java.util.Map;
System.out.println(hm.get(1));
}
/*OUTPUT
data OVERRIDDEN
*/
If, we note above program, what we will see is we didn’t override equals() and
hashCode() method, but still we were able to store data in HashMap, override data
and retrieve data using get method.
>Let’s check in Integer’s API, how Integer class has overridden equals() and
hashCode() method :
return value;
}
return false;
2) private member variable -> Making member variables private ensures that fields
cannot be accessed outside class.
3) final member variable -> Make member variables final so that once assigned their
values cannot be changed
Integer
Double
Long
Short
Byte
And all other Wrapper classes.
ArrayList
LinkedList
vector
HashSet
Iterator returned by few Collection framework Classes are fail-safe, means any
structural modification made to these classes during iteration won’t throw any
Exception.
CopyOnWriteArrayList
CopyOnWriteArraySet
ConcurrentSkipListSet
Please read : Differences between Exception and Error in java, Exception and Error
inheritance.
implement Cloneable than calling clone method on its object will throw
CloneNotSupportedException.
4) shallow copy- If we implement Cloneable interface, we must override clone
method and call super.clone() from it, invoking super.clone() will do shallow copy.
5) Deep copy - We need to provide custom implementation of clone method for deep
copying. When the copied object contains some other object its references are copied
it's one of the favourite question of interviewers. Intention is to test few basic core
java concepts.
Static method cannot be overridden in java, any attempt to do this will not cause
compilation error, but the results won’t be same when we would have overridden
non-static methods.
But why?
Overriding in Java means that the method would be called on the run time based on
type of the object and not on the compile time type of it.
But static methods are class methods access to them is always resolved during
compile time only using the compile time type information.
Accessing static method using object references is a bad practice (we must access
static variable using Class Name) and just an extra liberty given by the java designers.
EXAMPLE :
Assign any sub type object to reference of superclass [obj=new SubClass()] won’t
have any impact on call to static method at runtime.
Accessing static method using object references is bad practice (discussed above)
and just an extra liberty given by the java designers.
}
obj.method();
}
/*OUTPUT
superClass method
*/
If non-static methods would have been used in above program, output would have been
subClass method
Important points you must know about overriding static methods in java
Static method cannot be overridden, any attempt to do this will
not cause compilation error. (Discussed above)
Static method cannot be overridden with non-static method, any
attempt to do this will cause compilation error.
class A {
System.out.println(1);
}
class B extends A {
void m(){
System.out.println(2);
}
Q42. What is difference between equals method and == operator in java? And
what will be output of following code snippets?
Code snippet 1
String s1 = new String("abc");
System.out.println(s1.equals(s2))
;
Code snippet 2
StringBuffer sb1 = new
StringBuffer("abc");
System.out.println(sb1.equals(sb2));
== operator
The == operator checks for referential equality of object, it checks whether two
references are referring to same object or not.
equals method
By default equals method checks for referential equality (Class may override the
method and provide different functionality)
By default if x == y returns true then equals method also returns true.
Example -
StringBuffer class doesn’t overrides equals method of Object class. The result
is true if both references are referring to same StringBuffer object.
String class overrides equals method of Object class and compares one string
object to the other string object. The result is true if characters in both String
object appears in same order.
class SuperClass{
class SuperClass{
SuperClass(){ //no-arg
constructor
super();
}
}
SubClass(){
super();
}
}
Q45. What are Differences between JDK, JRE and JVM, OpenJDK, JIT
Compiler?
byte
short
Q47. Explain Implicit casting/promotion of primitive Data type in
java?
char
long
float
boolea
n
Threads consumes CPU in best possible manner, hence enables multi processing.
Multi threading reduces idle time of CPU which improves performance of application.
MyRunnable runnable=new
MyRunnable();
2) And then create Thread object by calling constructor and passing
reference of Runnable interface i.e. runnable object :
Thread thread=new
Thread(runnable);
Well the answer is you must extend Thread only when you are looking to modify
run() and other methods as well. If you are simply looking to modify only the run()
method implementing Runnable is the best option (Runnable interface has only one
abstract method i.e. run() ).
Q51. How can you ensure all threads that started from main must end in order in
which they started and also main should end in last? (Important)
Interviewers tend to know interviewees knowledge about Thread methods. So this is
time to prove your point by answering correctly. We can use join() method to ensure
all threads that started from main must end in order in which they started and also
main should end in last.
Q52. What is difference between starting thread with run() and start()
method? (Important)
This is quite interesting question, it might confuse you a bit and at time may make
you think is there really any difference between starting thread with run() and start()
method.
When you call start() method, main thread internally calls run() method to start newly
created thread. So run() method is ultimately called by newly created thread.
When you call run() method main thread rather than starting run() method with
newly thread it start run() method by itself.
Volatile does not acquire any lock on variable or object, but Synchronization
acquires lock on method or block in which it is used.
Volatile variables are not cached, but variables used inside synchronized
method or block are cached.
When volatile is used will never create deadlock in program, as volatile never
obtains any kind of lock . But in case if synchronization is not done properly,
we might end up creating dedlock in program.
Q58. Why wait(), notify() and notifyAll() are in Object class and not in Thread
class? (Important)
Every Object has a monitor, acquiring that monitors allow thread to hold lock
on object. But Thread class does not have any monitors.
wait(), notify() and notifyAll() are called on objects only > When wait() method
is called on object by thread it waits for another thread on that object to
release object monitor by calling notify() or notifyAll() method on that object.
When notify() method is called on object by thread it notifies all the threads
which are waiting for that object monitor that object monitor is available now.
So, this shows that wait(), notify() and notifyAll() are called on objects only.
Now, Straight forward question that comes to mind is how thread acquires
object lock by acquiring object monitor? Let’s try to understand this basic
concept in detail?
Wait(), notify() and notifyAll() method being in Object class allows all the
threads created on that object to communicate with other. [As multiple
threads may exist on same object].
As multiple threads exists on same object. Only one thread can hold object
monitor at a time. As a result thread can notify other threads of same object
that lock is available now. But, thread having these methods does not make
any sense because multiple threads exists on object it's not other way around
(i.e. multiple objects exists on thread).
Now let’s discuss one hypothetical scenario, what will happen if Thread class
contains wait(), notify() and notifyAll() methods?
Having wait(), notify() and notifyAll() methods means Thread class also must
have their monitor.
Q59. Is it important to acquire object lock before calling wait(), notify() and
notifyAll()?
Yes, it’s mandatory to acquire object lock before calling these methods on
object. As discussed above wait(), notify() and notifyAll() methods are always
called from Synchronized block only, and as soon as thread enters
synchronized block it acquires object lock (by holding object monitor). If we
call these methods without acquiring object lock i.e. from outside synchronize
block then java.lang. IllegalMonitorStateException is thrown at runtime.
Wait() method needs to enclosed in try-catch block, because it throws compile
time exception i.e. InterruptedException.
Q60. How can you solve consumer producer problem by using wait() and
notify() method? (Important)
Here come the time to answer very very important question from interview
perspective. Interviewers tends to check how sound you are in threads inter
communication. Because for solving this problem we got to use
synchronization blocks, wait() and notify() method very cautiously. If you
misplace synchronization block or any of the method, that may cause your
program to go horribly wrong. So, before going into this question first i’ll
recommend you to understand how to use synchronized blocks, wait() and
notify() methods.
Q61. How can you solve consumer producer pattern by using BlockingQueue?
(Important)
Now it’s time to gear up to face question which is most probably going to be
followed up by previous question i.e. after how to solve consumer producer
problem using wait() and notify() method. Generally you might wonder why
interviewer's are so much interested in asking about solving consumer
producer problem using BlockingQueue, answer is they want to know how
strong knowledge you have about java concurrent Api’s, this Api use
consumer producer pattern in very optimized manner, BlockingQueue is
designed is such a manner that it offer us the best performance.
Q63. What is reflection in java? Have you ever used reflection directly or
directly?
Reflection is used to load java classes at runtime. This is very interesting question,
though you may not have used reflection directly in java, but definitely you must
have used it indirectly, but you must be thinking how. answer is quite simple -
Frameworks like struts, spring and hibernate uses reflection for loading classes at
runtime.
Static variable
static variables are also known as class variables.
Static class
static class are also known as static nested class.
Top level class can never be static in java.
Static block
static blocks are also known as static initialization blocks in java.
They are called as soon as class is loaded even before instance of class is created (i.e.
before constructor is called).
But why?
Overriding in Java means that the method would be called on the run time based on
type of the object and not on the compile time type of it .
But static methods are class methods access to them is always resolved during
compile time only using the compile time type information.
Q67. Which method is called for garbage collection in java? What algorithm
does garbage collector follow?
For detailed explanation must read : Inner class/ nested class, static nested
class, local and anonymous inner class in java
Q71. What is Differences between Instance
initialization block and Static initialization block?
Please read : Differences between Instance initialization block and Static
initialization block in java - Features in detail with programs
Please read :
Please read :
Please read : Difference between notify() and notifyAll() methods, with program
When we call start() method on thread, it internally calls run() method with newly
created thread. So, if we don’t override run() method newly created thread won’t be
called and nothing will happen.
For more Please read : What will happen if we don’t override run method of thread?
When we call start() method on thread, it internally calls run() method with newly created
thread. So, if we override start() method, run() method will not be called until we write
code for calling run() method.
For more Please read : What will happen if we override start method of thread?
Or,
2. by entering static synchronized methods.
Performance point of view - Busy spin is very bad from performance point of view, because
one thread keeps on looping continuously ( and consumes CPU) waiting for another thread
to signal.
while(productionInProcess){
System.out.println("BUSY SPIN - Consumer waiting for production to get
over");
}
For more Please read : Differences between execute() and submit() method of
executor framework
Future<Double> futureDouble=executor.submit(new
SquareDoubleCallable(2.2));
Q95.What is CyclicBarrier?
There might be situation where we might have to trigger event only when one or more
threads completes certain operation.
2 or more threads wait for each other to reach a common barrier point. When all
threads have reached common barrier point (i.e. when all threads have called await()
method) >
All waiting threads are released, and
Event can be triggered as well.
Now, when all threads have reached common barrier point (i.e. all friends have reached
place A) >
All waiting threads are released (All friends can play game), and
Event can be triggered (they will start playing game).
For more Please read :Similarity and Difference between CyclicBarrier and
CountDownLatch in Java
return INSTANCE;
}