1000 Java Interview Questions PDF
1000 Java Interview Questions PDF
Java
Interview Question & Answers
Knowledge Powerhouse
No part of this book can be copied in any form. The publisher and the author have used good
faith efforts to ensure that the information in this book is correct and accurate. The
publisher and the author disclaim all responsibility for errors or omissions. Use of the
information in this book is at your own risk.
www.KnowledgePowerhouse.com
DEDICATION
To our readers!
CONTENTS
Java Basics
1. What is the difference between JDK and JRE?
2. What is Java Virtual Machine (JVM)?
3. What are the different types of memory areas allocated by JVM?
4. What is JIT compiler?
5. How Java platform is different from other platforms?
6. Why people say that Java is 'write once and run anywhere' language?
7. How does ClassLoader work in Java?
8. Do you think ‘main’ used for main method is a keyword in Java?
9. Can we write main method as public void static instead of public static
void?
10. In Java, if we do not specify any value for local variables, then what
will be the default value of the local variables?
11. Let say, we run a java class without passing any arguments. What will
be the value of String array of arguments in Main method?
12. What is the difference between byte and char data types in Java?
OOPS
13. What are the main principles of Object Oriented Programming?
14. What is the difference between Object Oriented Programming
language and Object Based Programming language?
15. In Java what is the default value of an object reference defined as an
instance variable in an Object?
16. Why do we need constructor in Java?
17. Why do we need default constructor in Java classes?
18. What is the value returned by Constructor in Java?
19. Can we inherit a Constructor?
20. Why constructors cannot be final, static, or abstract in Java?
Inheritance
21. What is the purpose of ‘this’ keyword in java?
22. Explain the concept of Inheritance?
23. Which class in Java is superclass of every other class?
24. Why Java does not support multiple inheritance?
25. In OOPS, what is meant by composition?
26. How aggregation and composition are different concepts?
27. Why there are no pointers in Java?
28. If there are no pointers in Java, then why do we get
NullPointerException?
29. What is the purpose of ‘super’ keyword in java?
30. Is it possible to use this() and super() both in same constructor?
31. What is the meaning of object cloning in Java?
Static
32. In Java, why do we use static variable?
33. Why it is not a good practice to create static variables in Java?
34. What is the purpose of static method in Java?
35. Why do we mark main method as static in Java?
36. In what scenario do we use a static block?
37. Is it possible to execute a program without defining a main() method?
38. What happens when static modifier is not mentioned in the signature
of main method?
39. What is the difference between static method and instance method in
Java?
Method Overloading and Overriding
40. What is the other name of Method Overloading?
41. How will you implement method overloading in Java?
42. What kinds of argument variations are allowed in Method
Overloading?
43. Why it is not possible to do method overloading by changing return
type of method in java?
44. Is it allowed to overload main() method in Java?
45. How do we implement method overriding in Java?
46. Are we allowed to override a static method in Java?
47. Why Java does not allow overriding a static method?
48. Is it allowed to override an overloaded method?
49. What is the difference between method overloading and method
overriding in Java?
50. Does Java allow virtual functions?
51. What is meant by covariant return type in Java?
Polymorphism
52. What is Runtime Polymorphism?
53. Is it possible to achieve Runtime Polymorphism by data members in
Java?
54. Explain the difference between static and dynamic binding?
Abstraction
55. What is Abstraction in Object Oriented programming?
56. How is Abstraction different from Encapsulation?
57. What is an abstract class in Java?
58. Is it allowed to mark a method abstract method without marking the
class abstract?
59. Is it allowed to mark a method abstract as well as final?
60. Can we instantiate an abstract class in Java?
61. What is an interface in Java?
62. Is it allowed to mark an interface method as static?
63. Why an Interface cannot be marked as final in Java?
64. What is a marker interface?
65. What can we use instead of Marker interface?
66. How Annotations are better than Marker Interfaces?
67. What is the difference between abstract class and interface in Java?
68. Does Java allow us to use private and protected modifiers for
variables in interfaces?
69. How can we cast to an object reference to an interface reference?
Final
70. How can you change the value of a final variable in Java?
71. Can a class be marked final in Java?
72. How can we create a final method in Java?
73. How can we prohibit inheritance in Java?
74. Why Integer class in final in Java?
75. What is a blank final variable in Java?
76. How can we initialize a blank final variable?
77. Is it allowed to declare main method as final?
Package
78. What is the purpose of package in Java?
79. What is java.lang package?
80. Which is the most important class in Java?
81. Is it mandatory to import java.lang package every time?
82. Can you import same package or class twice in your class?
83. What is a static import in Java?
84. What is the difference between import static com.test.Fooclass and
import com.test.Fooclass?
Internationalization
85. What is Locale in Java?
86. How will you use a specific Locale in Java?
Serialization
87. What is the serialization?
88. What is the purpose of serialization?
89. What is Deserialization?
90. What is Serialization and Deserialization conceptually?
91. Why do we mark a data member transient?
92. Is it allowed to mark a method as transient?
93. How does marking a field as transient makes it possible to serialize an
object?
94. What is Externalizable interface in Java?
95. What is the difference between Serializable and Externalizable
interface?
Reflection
96. What is Reflection in Java?
97. What are the uses of Reflection in Java?
98. How can we access private method of a class from outside the class?
99. How can we create an Object dynamically at Runtime in Java?
Garbage Collection
100.What is Garbage Collection in Java?
101. Why Java provides Garbage Collector?
102.What is the purpose of gc() in Java?
103.How does Garbage Collection work in Java?
104.When does an object become eligible for Garbage Collection in Java?
105.Why do we use finalize() method in Java?
106.What are the different types of References in Java?
107.How can we reference an unreferenced object again?
108.What kind of process is the Garbage collector thread?
109.What is the purpose of the Runtime class?
110. How can we invoke an external process in Java?
111. What are the uses of Runtime class?
Inner Classes
112. What is a Nested class?
113. How many types of Nested classes are in Java?
114. Why do we use Nested Classes?
115. What is the difference between a Nested class and an Inner class in
Java?
116. What is a Nested interface?
117. How can we access the non-final local variable, inside a Local Inner
class?
118. Can an Interface be defined in a Class?
119. Do we have to explicitly mark a Nested Interface public static?
120.Why do we use Static Nested interface in Java?
String
121. What is the meaning of Immutable in the context of String class in
Java?
122.Why a String object is considered immutable in java?
123.How many objects does following code create?
124.How many ways are there in Java to create a String object?
125.How many objects does following code create?
126.What is String interning?
127.Why Java uses String literal concept?
128.What is the basic difference between a String and StringBuffer
object?
129.How will you create an immutable class in Java?
130.What is the use of toString() method in java ?
131. Arrange the three classes String, StringBuffer and StringBuilder in
the order of efficiency for String processing operations?
Exception Handling
132.What is Exception Handling in Java?
133.In Java, what are the differences between a Checked and
Unchecked?
134.What is the base class for Error and Exception classes in Java?
135.What is a finally block in Java?
136.What is the use of finally block in Java?
137.Can we create a finally block without creating a catch block?
138.Do we have to always put a catch block after a try block?
139.In what scenarios, a finally block will not be executed?
140.Can we re-throw an Exception in Java?
141. What is the difference between throw and throws in Java?
142.What is the concept of Exception Propagation?
143.When we override a method in a Child class, can we throw an
additional Exception that is not thrown by the Parent class method?
Multi-threading
144.How Multi-threading works in Java?
145.What are the advantages of Multithreading?
146.What are the disadvantages of Multithreading?
147.What is a Thread in Java?
148.What is a Thread’s priority and how it is used in scheduling?
149.What are the differences between Pre-emptive Scheduling Scheduler
and Time Slicing Scheduler?
150.Is it possible to call run() method instead of start() on a thread in
Java?
151. How will you make a user thread into daemon thread if it has already
started?
152.Can we start a thread two times in Java?
153.In what scenarios can we interrupt a thread?
154.In Java, is it possible to lock an object for exclusive use by a thread?
155.How notify() method is different from notifyAll() method?
Collections
156.What are the differences between the two data structures: a Vector
and an ArrayList?
157.What are the differences between Collection and Collections in Java?
158.In which scenario, LinkedList is better than ArrayList in Java?
159.What are the differences between a List and Set collection in Java?
160.What are the differences between a HashSet and TreeSet collection
in Java?
161. In Java, how will you decide when to use a List, Set or a Map
collection?
162.What are the differences between a HashMap and a Hashtable in
Java?
163.What are the differences between a HashMap and a TreeMap?
164.What are the differences between Comparable and Comparator?
165.In Java, what is the purpose of Properties file?
166.What is the reason for overriding equals() method?
167.How does hashCode() method work in Java?
168.Is it a good idea to use Generics in collections?
Mixed Questions
169.What are Wrapper classes in Java?
170.What is the purpose of native method in Java?
171. What is System class?
172.What is System, out and println in System.out.println method call?
173.What is the other name of Shallow Copy in Java?
174.What is the difference between Shallow Copy and Deep Copy in
Java?
175.What is a Singleton class?
176.What is the difference between Singleton class and Static class?
Java Collection
177.What is the difference between Collection and Collections
Framework in Java?
178.What are the main benefits of Collections Framework in Java?
179.What is the root interface of Collection hierarchy in Java?
180.What are the main differences between Collection and Collections?
181. What are the Thread-safe classes in Java Collections framework?
182.How will you efficiently remove elements while iterating a
Collection?
183.How will you convert a List into an array of integers like- int[]?
184.How will you convert an array of primitive integers int[] to a List
collection?
185.How will you run a filter on a Collection?
186.How will you convert a List to a Set?
187.How will you remove duplicate elements from an ArrayList?
188.How can you maintain a Collection with elements in Sorted order?
189.What is the difference between Collections.emptyList() and creating
new instance of Collection?
190.How will you copy elements from a Source List to another list?
191. What are the Java Collection classes that implement List interface?
192.What are the Java Collection classes that implement Set interface?
193.What is the difference between an Iterator and ListIterator in Java?
194.What is the difference between Iterator and Enumeration?
195.What is the difference between an ArrayList and a LinkedList data
structure?
196.What is the difference between a Set and a Map in Java?
197.What is the use of a Dictionary class?
198.What is the default size of load factor in a HashMap collection in
Java?
199.What is the significance of load factor in a HashMap in Java?
200.What are the major differences between a HashSet and a HashMap?
201.What are the similarities between a HashSet and a HashMap in Java?
202.What is the reason for overriding equals() method?
203.How can we synchronize the elements of a List, a Set or a Map?
204.What is Hash Collision? How Java handles hash-collision in
HashMap?
205.What are the Hash Collision resolution techniques?
206.What is the difference between Queue and Stack data structures?
207.What is an Iterator in Java?
208.What is the difference between Iterator and Enumeration in Java?
209.What is the design pattern used in the implementation of Enumeration
in Java?
210.Which methods do we need to override to use an object as key in a
HashMap?
211. How will you reverse a List in Java?
212.How will you convert an array of String objects into a List?
213.What is the difference between peek(), poll() and remove() methods
of Queue interface in java?
214.What is the difference between Array and ArrayList in Java?
215.How will you insert, delete and retrieve elements from a HashMap
collection in Java?
216.What are the main differences between HashMap and
ConcurrentHashMap in Java?
217.What is the increasing order of performance for following collection
classes in Java?
218.Why does Map interface not extend Collection interface in Java?
219.What are the different ways to iterate elements of a list in Java?
220.What is CopyOnWriteArrayList? How it is different from ArrayList
in Java?
221.How remove() method is implemented in a HashMap?
222.What is BlockingQueue in Java Collections?
223.How is TreeMap class implemented in Java?
224.What is the difference between Fail-fast and Fail-safe iterator in
Java?
225.How does ConcurrentHashMap work in Java?
226.What is the importance of hashCode() and equals() methods?
227.What is the contract of hashCode() and equals() methods in Java?
228.What is an EnumSet in Java?
229.What are the main Concurrent Collection classes in Java?
230.How will you convert a Collection to SynchronizedCollection in Java?
231.How IdentityHashMap is different from a regular Map in Java?
232.What is the main use of IdentityHashMap?
233.How can we improve the performance of IdentityHashMap?
234.Is IdentityHashMap thread-safe?
235.What is a WeakHashMap in Java?
236.How can you make a Collection class read Only in Java?
237.When is UnsupportedOperationException thrown in Java?
238.Let say there is a Customer class. We add objects of Customer class
to an ArrayList. How can we sort the Customer objects in ArrayList by
using customer firstName attribute of Customer class?
239.What is the difference between Synchronized Collection and
Concurrent Collection?
240.What is the scenario to use ConcurrentHashMap in Java?
241.How will you create an empty Map in Java?
242.What is the difference between remove() method of Collection and
remove() method of Iterator?
243.Between an Array and ArrayList, which one is the preferred
collection for storing objects?
244.Is it possible to replace Hashtable with ConcurrentHashMap in Java?
245.How CopyOnWriteArrayList class is different from ArrayList and
Vector classes?
246.Why ListIterator has add() method but Iterator does not have?
247.Why do we sometime get ConcurrentModificationException during
iteration?
248.How will you convert a Map to a List in Java?
249.How can we create a Map with reverse view and lookup in Java?
250.How will you create a shallow copy of a Map?
251.Why we cannot create a generic array in Java?
252.What is a PriorityQueue in Java?
253.What are the important points to remember while using Java
Collections Framework?
254.How can we pass a Collection as an argument to a method and ensure
that method will not be able to modify it?
255.Can you explain how HashMap works in Java?
256.Can you explain how HashSet is implemented in Java?
257.What is a NavigableMap in Java?
258.What is the difference between descendingKeySet() and
descendingMap() methods of NavigableMap?
259.What is the advantage of NavigableMap over Map?
260.What is the difference between headMap(), tailMap() and subMap()
methods of NavigableMap?
261.How will you sort objects by Natural order in a Java List?
262.How can we get a Stream from a List in Java?
263.Can we get a Map from a Stream in Java?
264.What are the popular implementations of Deque in Java?
Advanced Multi-threading
265.What is a Thread in Java?
266.What is the priority of a Thread and how it is used in scheduling?
267.What is the default priority of a thread in Java?
268.What are the three different priorities that can be set on a Thread in
Java?
269.What is the purpose of join() method in Thread class?
270.What is the fundamental difference between wait() and sleep()
methods?
271.Is it possible to call run() method instead of start() on a thread in
Java?
272.What is a daemon thread in Java?
273.How can we make a regular thread Daemon thread in Java?
274.How will you make a user thread into daemon thread if it has already
started?
275.Can we start a thread two times in Java?
276.What is a Shutdown hook in Java?
277.What is synchronization in Java?
278.What is the purpose of Synchronized block in Java?
279.What is static synchronization?
280.What is a Deadlock situation?
281.What is the meaning of concurrency?
282.What is the main difference between process and thread?
283.What is a process and thread in the context of Java?
284.What is a Scheduler?
285.What is the minimum number of Threads in a Java program?
286.What are the properties of a Java thread?
287.What are the different states of a Thread in Java?
288.How will you set the priority of a thread in Java?
289.What is the purpose of Thread Groups in Java?
290.Why we should not stop a thread by calling its stop() method?
291.How will you create a Thread in Java?
292.How can we stop a thread in the middle of execution in Java?
293.How do you access the current thread in a Java program?
294.What is Busy waiting in Multi-threading?
295.How can we prevent busy waiting in Java?
296.Can we use Thread.sleep() method for real-time processing in Java?
297.Can we wake up a thread that has been put to sleep by using
Thread.sleep() method?
298.What are the two ways to check if a Thread has been interrupted?
299.How can we make sure that Parent thread waits for termination of
Child thread?
300.How will you handle InterruptedException in Java?
301.Which intrinsic lock is acquired by a synchronized method in Java?
302.Can we mark a constructor as synchronized in Java?
303.Can we use primitive values for intrinsic locks?
304.Do we have re-entrant property in intrinsic locks?
305.What is an atomic operation?
306.Can we consider the statement i++ as an atomic operation in Java?
307.What are the Atomic operations in Java?
308.Can you check if following code is thread-safe?
309.What are the minimum requirements for a Deadlock situation in a
program?
310.How can we prevent a Deadlock?
311. How can we detect a Deadlock situation?
312.What is a Livelock?
313.What is Thread starvation?
314.How can a synchronized block cause Thread starvation in Java?
315.What is a Race condition?
316.What is a Fair lock in multi-threading?
317.Which two methods of Object class can be used to implement a
Producer Consumer scenario?
318.How JVM determines which thread should wake up on notify()?
319.Check if following code is thread-safe for retrieving an integer value
from a Queue?
320.How can we check if a thread has a monitor lock on a given object?
321.What is the use of yield() method in Thread class?
322.What is an important point to consider while passing an object from
one thread to another thread?
323.What are the rules for creating Immutable Objects?
324.What is the use of ThreadLocal class?
325.What are the scenarios suitable for using ThreadLocal class?
326.How will you improve the performance of an application by multi-
threading?
327.What is scalability in a Software program?
328.How will you calculate the maximum speed up of an application by
using multiple processors?
329.What is Lock contention in multi-threading?
330.What are the techniques to reduce Lock contention?
331.What technique can be used in following code to reduce Lock
contention?
332.What is Lock splitting technique?
333.Which technique is used in ReadWriteLock class for reducing Lock
contention?
334.What is Lock striping?
335.What is a CAS operation?
336.Which Java classes use CAS operation?
337.Is it always possible to improve performance by object pooling in a
multi-threading application?
338.How can techniques used for performance improvement in a single
thread application may degrade the performance in a multi-threading
application?
339.What is the relation between Executor and ExecutorService
interface?
340.What will happen on calling submit() method of an ExecutorService
instance whose queue is already full?
341.What is a ScheduledExecutorService?
ACKNOWLEDGMENTS
We thank our readers who constantly send
feedback and reviews to motivate us in creating
these useful books with the latest information!
INTRODUCTION
Java byte code can run on any supported platform in same way.
Where as other languages require libraries compiled for a specific
platform to run.
6. Why people say that Java is 'write
once and run anywhere' language?
You can write Java code on Windows and compile it in Windows
platform. The class and jar files that you get from Windows
platform can run as it is on Unix environment. So it is a truly
platform independent language.
Behind all this portability is Java byte code. Byte code generated by
Java compiler can be interpreted by any JVM. So it becomes much
easier to write programs in Java and expect those to run on any
platform.
Java compiler javac compiles java code and JVM java runs that
code.
7. How does ClassLoader work in
Java?
In Java, ClassLoader is a class that is used to load files in JVM.
ClassLoader loads files from their physical file locations e.g.
Filesystem, Network location etc.
We can write static public void main() instead of public static void
main().
10. In Java, if we do not specify any
value for local variables, then what
will be the default value of the local
variables?
Java does not initialize local variables with any default value. So
these variables will be just null by default.
11. Let say, we run a java class without
passing any arguments. What will be
the value of String array of
arguments in Main method?
By default, the value of String array of arguments is empty in Java.
It is not null.
12. What is the difference between
byte and char data types in Java?
Both byte and char are numeric data types in Java. They are used to
represent numbers in a specific range.
Major difference between them is that a byte can store raw binary
data where as a char stores characters or text data.
The issue with Multiple Inheritance is that both the parent classes
may have different implementation for the same method. So they
have different ways of doing the same thing. Now which
implementation should the child class choose?
Lets say you have a class TV and another class AtomBomb. Both
have method switchOn() but only TV has switchOff() method. If
your class inherits from both these classes then you have an issue
that you can switchOn() both parents, but switchOff will only
switchOff() TV.
Also a static method can access and modify static data members.
This also helps in keeping the behavior as well as state at the class
level.
35. Why do we mark main method as
static in Java?
The main method in Java is marked as static, so that JVM can call it
to start the program. If main method is not static, then which
constructor will be called by Java process?
Before Java 5, any method that overrides the method of parent class
would have same return type.
E.g.
Person p = new Person();
p.walk(); // Java compiler resolves this binding at compile time.
There are interfaces that do not have any data member or methods.
These interfaces are called Marker interface.
E.g. Serializable, Cloneable, Remote etc.
65. What can we use instead of
Marker interface?
We can use annotations instead of Marker interface.
66. How Annotations are better than
Marker Interfaces?
Annotations serve the purpose of conveying metadata about the
class to its consumers without creating a separate type for it.
Integer class is a wrapper for int. If it is not marked final, then any
other class can extend it and modify the behavior of Integer
operations. To avoid this Integer wrapper class is marked as final.
75. What is a blank final variable in
Java?
When we declare a final variable without giving any initial value,
then it is called blank final variable.
76. How can we initialize a blank final
variable?
A blank final instance variable can be initialized in a constructor.
If you have two classes with same name, then you may get name
collision on importing the class erroneously.
FileName: Foo.java
public class Foo {
private void message(){System.out.println("hello java"); }
}
FileName: FooMethodCall.java
import java.lang.reflect.Method;
public class FooMethodCall{
public static void main(String[] args)throws Exception{
Class c = Class.forName("Foo");
Object o= c.newInstance();
Method m =c.getDeclaredMethod("message", null);
m.setAccessible(true);
m.invoke(o, null);
}
}
99. How can we create an Object
dynamically at Runtime in Java?
We can use Reflection to create an Object dynamically at Runtime
in Java. We can use Class.newInstance() or
Constructor.newInstance() methods for creating such Objects.
Garbage Collection
100. What is Garbage Collection in
Java?
Java has an internal mechanism called Garbage collection to
reclaim the memory of unused projects at run time.
1. Strong Reference
2. Soft Reference
3. Weak Reference
4. Phantom Reference
107. How can we reference an
unreferenced object again?
We can provide implementation in finalize() method to reference
and unreferenced object. For an unreferenced object, finalize()
method is called at the time of Garbage Collection. At this time,
Object can pass its reference ‘this’ to finalize() method and revive
itself.
108. What kind of process is the
Garbage collector thread?
Garbage Collection is a Daemon process in JVM. It is an internal
process that keep checking Memory usage and cleans up the
memory.
109. What is the purpose of the
Runtime class?
The purpose of the Runtime class is to provide access to the Java
Runtime system. This class provides certain important methods like:
// Client Code
Abc.registerCallback(new Abc.Xyz() {
public void callback() {...}
});
Any code that cannot access Abc can not access interface Xyz also.
The above code creates only one object. Since there is only one
String Literal “HelloWorld” created, all the references point to
same object.
124. How many ways are there in
Java to create a String object?
Java provides two ways to create a String object. One is by using
String Literal, the other is by using new operator.
125. How many objects does
following code create?
Code:
String s = new String("HelloWorld");
The above code creates two objects. One object is created in String
constant pool and the other is created on the heap in non-pool area.
126. What is String interning?
Stack
Properties
Vector
Hashtable
BlockingQueue
ConcurrentMap
ConcurrentNavigableMap
149. How will you efficiently
remove elements while iterating a
Collection?
The right way to remove elements from a collection while iterating
is by using ListIterator.remove() method.
E.g.
An iterator is first created to traverse the list. But at the same time
the list is changed by remove() method.
The other option would be to use a for loop and explicitly adding
integers to a List.
int[]intArray = {10,20,30};
List<Integer> intList = new ArrayList<Integer>();
for (int i: intArray) {
intList.add(i);
}
152. How will you run a filter on a
Collection?
We can use CollectionUtils of Apache for this purpose. We will
have to create a Predicate that will define the condition for our
filter. Then we can apply this Predicate in filter() method.
In this example we filter any names that are less than 5 characters
long.
2. Null values: A HashMap allows only one null key and any
number of null values. A Hashtable does not allow null
keys and null values.
Properties files are used for many purposes in all kinds of Java
applications. Some of the uses are to store configuration, initial
data, application options etc.
When we change the value of a key in a properties file, there is no
need to recompile the Java application. So it provides benefit of
changing values at runtime.
166. What is the reason for overriding
equals() method?
The equals() method in Object class is used to check whether two
objects are same or not. If we want a custom implementation we can
override this method.
For example, a Person class has first name, last name and age. If we
want two Person objects to be equal based on name and age, then
we can override equals() method to compare the first name, last
name and age of Person objects.
AbstractList
AbstractSequentialList
ArrayList
AttributeList
CopyOnWriteArrayList
LinkedList
RoleList
RoleUnresolvedList
Stack
Vector
172. What are the Java Collection
classes that implement Set interface?
Java classes that implement Set interface are:
AbstractSet
ConcurrentSkipListSet
CopyOnWriteArraySet
EnumSet
HashSet
JobStateReasons
LinkedHashSet
TreeSet
173. What is the difference between an
Iterator and ListIterator in Java?
Iterator and ListIterator are two interfaces in Java to traverse data
structures. The differences between these two are:
For example, a Person class has first name, last name and age. If we
want two Person objects to be equal based on name and age, then
we can override equals() method to compare the first name, last
name and age of Person objects.
static <K,V>
SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m)
Returns a synchronized (thread-safe) sorted map backed by the
specified sorted map.
Stack is a LIFO data structure. LIFO stands for Last In First Out.
The element that is added last is removed first from the collection.
In a Stack elements are added or removed from the top of stack.
E.g.
Collections.reverse(myList);
192. How will you convert an array of
String objects into a List?
Java provides Arrays class in java.util package. Arrays class has a
method asList() that accepts an Array as input and returns a List as
output.
Hashtable
Collections.SynchronizedMap
ConcurrentHashMap
HashMap
Hashtable has the worst performance and HashMap has the best
performance.
198. Why does Map interface not
extend Collection interface in Java?
A Map is a collection objects. But Map interface is not compatible
with Collection interface in Java.
The problem arises when HashMap treats both outputs same instead
of different. It will overwrite the most recent key-value pair with
the previous key-value pair.
ArrayBlockingQueue
CopyOnWriteArrayList
CopyOnWriteArraySet
ConcurrentHashMap
ConcurrentLinkedDeque
ConcurrentLinkedQueue
LinkedBlockingQueue
LinkedBlockingDeque
PriorityBlockingQueue
210. How will you convert a Collection
to SynchronizedCollection in Java?
Java provides an easy method in java.utils.Collections class to
create a ThreadSafe collection from a regular collection.
The presence of a mapping for a given key does not prevent the key
from being discarded by the garbage collector.
Collections.unmodifiableMap(Map m)
Collections.unmodifiableList(List l)
Collections.unmodifiableSet(Set s)
Collections.unmodifiableCollection(Collection c)
217. When is
UnsupportedOperationException
thrown in Java?
In a Java collection UnsupportedOperationException is thrown
when the requested operation is not supported by the collection.
myMap = Collections.emptyMap();
It is a thread-safe list.
key set
value set
key-value set
PriorityQueue does not allow null values. We cannot add any object
that does not provide natural ordering to PriorityQueue.
This will make sure that any operation to change the collection will
throw UnsupportedOperationException.
235. Can you explain how
HashMap works in Java?
In Java, a HashMap works on the concept of hashing.
Once Key object’s location is found, it may happen that more than
one Key is stored in same location. So now we use equals() method
to find the exact Key object. Once the exact Key object is found we
use it to get Value object.
236. Can you explain how HashSet
is implemented in Java?
Internally, a HashSet uses a HashMap to store the elements and to
maintain the uniqueness of elements.
//this headmap2 will contain elements "1", "2", and "3" because
"inclusive"=true
NavigableMap headmap2 = original.headMap("3", true);
All the three methods return a subset of the original map in a view
form.
241. How will you sort objects by
Natural order in a Java List?
We can use Collections.sort method to sort the elements of a List in
natural order. To use this method, we have to make sure that element
objects implement compareTo() method.
E.g. items.stream()
.map( item -> item.toLowerCase() )
When we start JVM, Java starts one thread. This thread calls the
main method of the class passed in argument to java call.
246. What is the priority of a
Thread and how it is used in
scheduling?
In Java, every Thread has a priority. This priority is specified as a
number between 1 to 10.
When we use join(), the current thread stops executing. It wait for
the thread on which join() is called to finish.
This makes sure that current thread will continue only after the
thread it joined finished running. Consider following example:
A wait() and notify() has to happen within the same block that is
synchronized on the monitor object.
When we call wait() the current thread releases the monitor and
goes to waiting state. Then another thread calls notify() to wake it
up.
In Java, you can create process and then create multiple threads
from that process. Each process can execute in parallel to perform
independent tasks.
By default Java starts one thread when the main method of a class is
called.
256. What is a Thread’s priority
and how it is used in scheduling?
In Java, every Thread has a priority. This priority is specified as an
integer value. The priority value is used in scheduling to pick up the
thread with higher priority for execution. The threads with higher
priority get more preference in execution than the threads with
lower priority.
At times there is a circular wait when more than two threads are
waiting on each other’s resources.
273. What is the meaning of
concurrency?
Concurrency is the ability of a program to execute several programs
simultaneously. This is achieved by distributing computations over
multiple CPU cores of a machine or even over different machines
within the same network.
When we call stop() method, the thread unlocks all monitors that it
has acquired. If any locked object was in an inconsistent state, this
state gets visible to all other threads.
// Busy waiting
while (timeToStop > currentTime) {
currentTime = System.currentTimeMillis();
}
}
});
287. How can we prevent busy
waiting in Java?
There is a simple way to prevent busy-waiting in Java. We can just
put the current thread to sleep for given amount of time.
Thread.sleep(10000);
SOP(“Interrupting myThread");
myThread.interrupt();
}
}
290. What are the two ways to
check if a Thread has been
interrupted?
These are the two ways to check for thread interruption:
myThread.start();
// Join on myThread
myThread.join();
292. How will you handle
InterruptedException in Java?
The run() method of the Runnable interface does not allow that
throwing any exceptions. So we cannot re-throw
InterruptedException.
The reasoning behind this is that, in this case, only the constructing
thread would have access to the object being constructed.
295. Can we use primitive values
for intrinsic locks?
No. Java does not allow primitive values to be used for intrinsic
locks.
296. Do we have re-entrant
property in intrinsic locks?
Yes. An intrinsic lock can be accessed by the same thread multiple
times. So an Intrinsic lock is re-entrant.
If it is not allowed then the code that acquires a lock would have to
avoid acquiring the lock that it has already acquired.
297. What is an atomic operation?
An atomic operation is an operation that completes in a single step
relative to other threads.
Due to this the method getInstance() will return an object that may
not have been initialized properly.
We can use the keyword volatile for instance to make this thread-
safe code.
Now both threads hold two different locks. And both threads want
to have both locks. So they release their lock and try again from the
beginning. This situation keeps repeating multiple times..
305. What is Thread starvation?
In a priority based scheduling, Threads with lower priority get
lesser time for execution than higher priority threads.
Hence these threads with lower priority will not get enough time to
finish their work in time.
307. What is a Race condition?
A race condition is an unwanted situation in which a program
attempts to perform two or more operations at the same time, but
because of the logic of the program, the operations have to be
performed in proper sequence to run the program correctly.
Most of the time race condition occurs in “check then act” scenario.
Both threads check and act on same value. But one of the threads
acts in between check and act. See this example to understand race
condition.
if (x == 3) // Check
{
y = x * 5; // Act
Only one of the two threads will get new value from the queue and
make it empty. The second thread will poll on an empty queue and it
will not get any non-null return value.
312. How can we check if a thread has
a monitor lock on a given object?
In Java, Thread class has a static method holdsLock(Object
objToCheck) to check whether thread has a lock on objToLock
object.
This method will return true if current thread holds the lock on the
objToLock object that was passed as an argument to this method.
313. What is the use of yield() method
in Thread class?
The yield() method of Thread class is used to give a hint to
scheduler that the current thread wants to free the processor.
The scheduler can either use this hint or just ignore this hint. Since
the scheduler behavior is not guaranteed, it may happen that the
current thread again gets the processor time.
When we say a program does not scale, it means that program fails
on increasing the size of task.
320. How will you calculate the
maximum speed up of an application
by using multiple processors?
Amdahl’s law gives the theoretical speedup in latency of the
execution of a task at fixed workload.
The code uses Random() to get a random string and it also used
Integer to convert 42 in an object. Since these lines of code are
specific to this thread, these can be moved out of Synchronization
block.
synchronized (map) {
map.put(key, value);
}
324. What is Lock splitting
technique?
Lock splitting is a technique to reduce Lock contention in multi-
threading. It is applicable in scenario when one lock is used to
synchronize access to different aspects of the same application.
Sometimes we put one lock to protect the whole array. There can be
multiple threads trying to get the lock for same array. This single
lock on array can cause Lock contention among threads. To resolve
this we can give one lock to each element of the array. Or we can
use modulus function to assign different locks to a small group of
array elements. In this way we can reduced the chance of Lock
contention. This is Lock splitting technique.
325. Which technique is used in
ReadWriteLock class for reducing
Lock contention?
ReadWriteLock uses two locks. One lock for read-only operations,
another lock for write operations.
Let say thread T1 can update a value by passing its current value
and the new value to be updated to the CAS operation. In case
another thread T2 has updated the current value of previous thread,
the previous thread T1’s current value is not equal to the current
value of T2. Hence the update operation fails.
In this case, thread T1 will read the current value again and try to
update it.
myService.shutdown();
}
335. What is the main difference
between Runnable and Callable
interface?
Runnable interface defines run() method that does not return any
value.
We can also use it to control how many threads can access the
critical section of a program or a resource concurrently.
Once a thread has finished its work, we can use release() method to
release the permits.
340. What is a CountDownLatch in
Java?
CountDownLatch class helps in implementing synchronization in
Java. It is used to implement the scenarios in which one or more
threads have to wait until other threads have reached the same state
such that all thread can start.
CyclicBarrier resets the internal value to the initial value once the
value reaches zero. CyclicBarrier can be used to implement the
scenarios in which threads have to wait for each other multiple
times.
342. What are the scenarios suitable
for using Fork/Join framework?
ForkJoinPool class is in the center of Fork/Join framework. It is a
thread pool that can execute instances of ForkJoinTask.
To improve performance thread can cache the values from heap into
their stack. This can create problem if the same variable is modified
by more than one thread.
On taking Thread dump, Java writes the state of all threads in log
files or standard error console.
This is the simple one, -Xss parameter is used to control stack size
of Thread in Java. You can see this list of JVM options to learn
more about this parameter.
348. Which parameter can be used
to control stack size of a thread in
Java?
We use –Xss parameter to control the stack size of a thread in Java.
If we set it as 1 MB, then every thread will get 1MB of stack size.
349. There are two threads T1 and
T2? How will you ensure that these
threads run in sequence T1, T2 in
Java?
In Java there are multiple ways to execute threads in a sequence.
We can call join() method to start a thread when another thread has
finished.
We start with the last thread to execute first. And make this thread
join on the next thread.
In this case we start thread T2 first. And then call T1.join() so that
thread T2 waits for thread T1 to finish execution.
1. Lambda Expression
2. Stream API
3. Date and Time API
4. Functional Interface
5. Interface Default and Static Methods
6. Optional
7. Base64 Encoding and Decoding
8. Nashorn JavaScript Engine
9. Collections API Enhancements
10. Concurrency Enhancements
11. Fork/Join Framework Enhancements
12. Spliterator
13. Internal Iteration
14. Type Annotations and Repeatable Annotations
15. Method Parameter Reflection
16. JVM Parameter Changes
351. What are the main benefits of
new features introduced in Java 8?
The main benefits of Java 8 features are:
Parameter list = e
Arrow = ->
Body = System.out.println( e )
354. What is the data type of a
Lambda expression?
A Lambda expression fulfills the purpose of passing code as data.
Type inference algorithm also tries to find the most specific type
that can work with all types of arguments.
369. Does Java 7 support Type
Inference?
Yes, Java 7 supports Type Inference. In Java 8, Oracle has enhanced
the Type Inference concept. Now it can be used to define Lambda
expressions, functions and Method references.
370. How does Internal Iteration
work in Java 8?
In an Iterator, the fundamental question is that which party controls
the iteration. Is it Iterator or the Collection on which iterator runs.
In the above code, class ChildClass gives compile time error. Java
Compiler cannot decide which display method should it invoke in
ChildClass.
public interface A{
default void display() { //code goes here }
}
public interface B extends A{ }
public interface C extends A{ }
public class D implements B,C{
default void display() {
B.super.display();
}
}
public interface BaseInterface{
default void display() { //code goes here }
}
public interface BaseOne extends BaseInterface { }
public interface BaseTwo extends BaseInterface { }
public class ChildClass implements BaseOne, BaseTwo {
default void display(){
BaseOne.super.display();
}
}
It a value is present, we can call get() method to get the value. Else
we will get nothing.
We can also call instant() method on Clock object to get the current
time in a readable format.
397. Is it possible to define a static
method in an Interface?
Yes, from Java 8, an Interface can also has a static method.
398. How can we analyze the
dependencies in Java classes and
packages?
Java 8 comes with a new command line tool jdeps that can help in
analyzing the package-level and class-level dependencies.
E.g.
The String "[One:Two:Three]" may be constructed as follows:
The += operator implicitly casts the result of addition into the type
of variable used to hold the result.
What happens when you put return statement or System.exit () on try
or catch block? Will finally block execute?
You can answer by saying that finally block executes even if we put
a return statement in the try block or catch block. But finally block
does not execute if you call System.exit() from try or catch block.
406. What does the expression 1.0 /
0.0 return? Will there be any
compilation error?
Double class is the source of many tricky interview questions. You
may know about the double primitive type and Double class. But
while doing floating point arithmetic some people don't pay enough
attention to Double.INFINITY, NaN, and -0.0. There are rules that
govern the floating point arithmetic calculations involving Double.
.
407. Can we use multiple main
methods in multiple classes?
Yes. When we start an application in Java, we just mention the class
name to be run to java command. The JVM looks for the main
method only in the class whose name is passed to java command.
Therefore, there is no conflict amongst the multiple classes having
main method.
408. Does Java allow you to
override a private or static method?
The question is tricky but the answer is very simple. You cannot
override a private or static method in Java. If we create a similar
method with same return type and same method arguments in child
class, then it will hide the superclass method. This is known as
method hiding.
If you put the same key again in a HashMap, then it will replace the
old mapping because HashMap doesn't allow duplicate keys. The
same key will have same HashCode as previous key object. Due to
same HashCode, it will be stored at the same position in the bucket.
410. How can you make sure that N
threads can access N resources
without deadlock?
So a thread waiting for same resource can not get into deadlock
while the other thread is trying to get it and holding the resource
required by first thread. If both of them release the resources in right
order, one of them can acquire it to finish the work.
411. How can you determine if JVM is
32-bit or 64-bit from Java Program?
We can find JVM bit size 32 bit or 64 bit by running java command
from the command prompt.
Sun has a Java System property to determine the bit size of the
JVM: 32 or 64:
Since main method is static in Java, and instance variables are non-
static, we cannot access instance variable inside main. The solution
is to create an instance of the object and then access the instance
variables.
416. Let say there is a method that
throws NullPointerException in the
superclass. Can we override it with a
method that throws
RuntimeException?
wait() is meant for conditional wait and it can release a lock that
can be acquired by another thread to change the condition on which
it is waiting.
420. Can you create an Immutable
object that contains a mutable object?
An int is 32 bit in Java. But a byte is just 8 bit in Java. We can cast
an int to byte. But we will lose higher 24 bits of int while casting.
Because a byte can hold only first 8 bits of int. Remaining 24 bits
(32-8 = 24) will be lost.
427. In Java, can we store a double
value in a long variable without
explicit casting?
By using these methods, you can find out how much of the heap is
used and how much heap space still remains.
When Queue is empty, poll() method fails and it returns null, but
remove() method fails and throws Exception.
443. Can you catch an exception
thrown by another thread in Java?
Yes, it can be done by using Thread.UncaughtExceptionHandler.
Due to this cost, there are many situations where static nested
classes are preferred over inner classes. When instances of the
nested class outlive instances of the enclosing class, the nested
class should be static to prevent memory leaks.
When the JVM is started, three types of class loaders are used:
Classes may be loaded from the local file system, a remote file
system, or even the web.
446. What are the situations in
which you choose HashSet or
TreeSet?
HashSet is better than TressSet in almost every way. It gives O(1)
for add(), remove() and contains() operations. Whereas, TressSet
gives O(log(N)) for these operations.
Still, TreeSet is useful when you wish to maintain order over the
inserted elements or query for a range of elements within the set.
You can also attach meta-data to enum values in Java. Also enum
values are typesafe, where as integer constants are not.
Java build tools and IDEs can also produce dependency reports that
tell you which libraries depend on that JAR. Mostly, identifying and
upgrading the library that depends on the older JAR resolve the
issue.
451. How can you check if a String
is a number by using regular
expression?
Regex is a powerful tool for matching patterns and searching
patterns.
On the other hand, Simple API for XML (SAX) parser is an event
based parser. It doesn't load the whole XML into memory. Due to
this reason DOM is faster than SAX but require more memory and
is not suitable to parse large XML files.
458. Between Enumeration and
Iterator, which one has better
performance in Java?
Enumeration interface is a read-only interface. It has better
performance than Iterator. It is almost twice as fast as compared to
an Iterator. It also uses very less memory. Also Enumeration does
not have remove() method.
When you come across situations that are unexpected then use Error
class in Java. Also recovering from Error is not possible in most of
cases. So it is better to terminate the program.
470. What is the advantage of
PreparedStatement over Statement
class in Java?
PreparedStatements are precompiled statements for database
queries. Due to this their performance is much better. Also, we can
reuse PreparedStatement objects with different input values to the
same query.
Also a Session can store any Java object. But the Cookie can only
store small information in a String object.
475. Which protocol does Browser
and Servlet use to communicate with
each other?
HTTP protocol. The Browser and Servlet communicate with each
other by using the HTTP protocol.
476. What is HTTP Tunneling?
There are many network communication protocols on the Internet.
But HTTP is the most popular among them. HTTP Tunneling is a
technique in which HTTP or HTTPS protocol encapsulated the
communication done by any other type of protocol. The masking of
other protocol requests as HTTP requests is known as HTTP
Tunneling.
477. Why do we use JSP instead of
Servlet in Java?
Since JSP pages are dynamically compiled into servlets, the
programmers can easily make updates to the presentation layer
code.
The last servlet in the chain will be responsible for sending final
response to client.
480. Can you instantiate this class?
public class A
{
A a = new A();
}
String is also used as a parameter in many Java classes. Eg. You can
pass hostname, port number as String while opening a network
connection. If any one can modify your copy of the String, it can
change the hostname. Due to this reason, it makes sense to make
String final as soon as it is created.
483. What is the difference between
sendRedirect and forward methods?
When you use sendRedirect method, it creates a new request. When
you use the forward method, it just forwards a request to a new
target.
Let say, when you insert the object, the Hashcode is X, the
HashMap will store it in bucket X. But when you search for it the
Hashcode is Y, then HashMap will look for the object in bucket Y.
So you are not getting what you stored.
You can also use Exchanger class for this purpose. An Exchanger is
a bidirectional form of a SynchronousQueue in Java. You can use it
to swap the objects as well.
503. How can you determine if your
program has a deadlock?
If we suspect that our application is stuck due to a Deadlock, then
we just take a thread dump by using the command specific to
environment in which your application is running. Eg. In Linux you
can use command kill -3.
In case of deadlock, you will see in thread dump the current status
and stack trace of threads in the JVM, and one or more of them will
be stuck with message deadlock.
E.g.
1. Request
2. Response
3. Application
4. Exception
5. Page
6. Config
7. Session
10. How will you extend JSP code?
We can extend JSP code by using Tag libraries and Custom actions.
11. How will you handle runtime
exceptions in JSP?
E.g.
<%@ page attribute="value" %>
E.g.
<%@ taglib uri=“abc.html” prefix=“tag_prefix” >
With this tag, container will try to locate the bean. If bean is not
already loaded then it will create an instance of a bean and load it.
Later this bean can be used in expressions or JSP code.
25. What is difference between
include Directive and include Action
of JSP?
Some of the main differences between include Directive and
include Action are as follows:
E.g.
1. Core tags
2. SQL tags
3. Formatting tags
4. XML tags
5. JSTL Functions
31. How will you pass information
from one JSP to another JSP?
We can pass information from one JSP to another by using implicit
objects. If different JSP are called in same session, we can use
session object to pass information from one JSP to another.
Like- www.abcserver.com?sessionid=1234
36. How do you debug code in JSP?
Now we can use this error page in other JSP where we want to
handle error. In case of an error or exception, these JSP will direct
it to errorPage.
The _jspService() method will create the output that will be sent by
JSP container to client browser.
40. How will you implement Auto
Refresh of page in JSP?
We can use setIntHeader() method to set the refresh frequency with
which we want to auto-refresh a JSP page.
We can send key “Refresh” with the time in seconds for auto refresh
of the JSP page.
E.g. response.setIntHeader(“Refresh”,10)
41. What are the important status
codes in HTTP?
Every HTTP request comes back with a status code from the server.
The important status codes in HTTP are as follows:
First we create a Cookie object. We set the name and value of the
cookie to be created.
We set the expiry time of the Cookie by setting the maximum age.
We can use setMaxAge() method for this.
In this way we can use Cookie to set some information at client side
and retrieve its value.
46. What is the main difference
between a Session and Cookie in JSP?
A Session is always stored at the Server side. In JSP, session is a
built-in object in JSP container.
We can use both the methods for Session tracking. But Cookie
method needs permission from user for storing cookie at the client
location.
47. How will you prevent creation of
session in JSP?
We can simply set the session attribute as false in page directive to
prevent creation of session object.
response.setHeader(“Cache-Control”, “no-store”);
response.setDateHeader(“Expires”,”0”);
50. How will you redirect request to
another page in browser in JSP code?
We can use sendRedirect() method in JSP to redirect the request to
another location or page.
In this case the request will not come back to server. It will redirect
in the browser itself.
JSP Engine loads all the filters in when we start the server.
57. How can you upload a large file in
JSP?
To upload a file by JSP we can use <input type=”file”> in the Form
data being passed from HTML.
For a client, at runtime we can vary the algorithm based on the type
of request we have received.
E.g. In real life, students are waiting for the result of their test. Here
students are the observers and test is the subject. Once the result of
test is known, testing organization notifies all the students about
their result.
Main issue with Observer pattern is that it can cause memory leaks.
The subject holds a strong reference to observers. If observers are
not de-registered in time, it can lead to memory leak.
61. What are the examples of
Observer design pattern in JDK?
In JDK there are many places where Observer design pattern is
used. Some of these are as follows:
1. java.util.Observer, java.util.Observable
2. javax.servlet.http.HttpSessionAttributeListener
3. javax.servlet.http.HttpSessionBindingListener
5. javax.faces.event.PhaseListener
62. How Strategy design pattern is
different from State design pattern in
Java?
State design pattern is a behavioral design pattern that is use for
defining the state machine for an object. Each state of an object is
defined in a child class of State class. When different actions are
taken on an Object, it can change its state.
E.g.
Open a FileInputStream:
Add buffering:
Add Gzip:
Add Serialization:
With Singleton pattern we can be sure that there is only one instance
of a class at any time in the application.
Similarly there is gc() method that can run the Garbage Collector.
With only one copy of gc() method, we can ensure that no other
object can run the Garbage Collector when one instance of GC is
already running.
Due to all these reasons there is only one copy of Runtime in Java.
To ensure single copy of Runtime, it is implemented as a Singleton
in Java.
68. What is the way to implement a
thread-safe Singleton design pattern
in Java?
In Java there are many options to implement a thread-safe Singleton
pattern. Some of these are as follows:
Sample code:
class DoubleCheckSingleton {
private volatile HelloSingleton helloSingleton; // Use Volatile
}
2. Bill Pugh Singleton: We can also use the method by Bill
Pugh for implementing Singleton in Java. In this we use an
Inner Static class to create the Singleton instance.
Sample code:
// Private constructor
private SingletonBillPugh(){}
Sample Code:
INSTANCE;
public static void doImplementation(){
…..
}
}
69. What are the examples of
Singleton design pattern in JDK?
In JDK there are many places where Singleton design pattern is
used. Some of these are as follows:
java.awt.Desktop.getDesktop()
70. What is Template Method design
pattern in Java?
It is a behavioral design pattern. We can use it to create an outline
for an algorithm or a complex operation. We first create the skeleton
of a program. Then we delegate the steps of the operation to
subclasses. The subclasses can redefine the inner implementation of
each step.
We can use same algorithm for Chess game with same set of
abstract methods. The subclass for Chess game can provide the
concrete implementation of methods like initializeGame(),
makeMove(), endGame() etc.
Java.lang.Class.forName()
java.net.URLStreamHandlerFactory.createURLStreamHandler(String)
java.util.Calendar.getInstance()
java.util.ResourceBundle.getBundle()
java.text.NumberFormat.getInstance()
java.nio.charset.Charset.forName()
java.util.EnumSet.of()
javax.xml.bind.JAXBContext.createMarshaller()
73. What is the benefit we get by
using static factory method to create
object?
By using Static Factory Method we encapsulate the creation process
of an object. We can use new() to create an Object from its
constructor. Instead we use static method of a Factory to create the
object. One main advantage of using Factory is that Factory can
choose the correct implementation at runtime and create the right
object. The caller of method can specify the desired behavior.
3. javax.swing.GroupLayout.Group.addComponent(): We can
use addComponent() method to build a UI that can contain
multiple levels of components.
4. java.lang.Appendable
javax.xml.xpath.XPathFactory.newInstance()
javax.xml.parsers.DocumentBuilderFactory.newInstance()
javax.xml.transform.TransformerFactory.newInstance()
76. What are the examples of
Decorator design pattern in JDK?
In JDK there are many places where Decorator design pattern is
used. Some of these are as follows:
In JDK there are many places where Proxy design pattern is used.
Some of these are as follows:
java.lang.reflect.Proxy
java.rmi.*
javax.inject.Inject
javax.ejb.EJB
javax.persistence.PersistenceContext
78. What are the examples of Chain of
Responsibility design pattern in JDK?
In JDK there are many places where Chain of Responsibility design
pattern is used. Some of these are as follows:
java.util.Pattern
java.text.Normalizer
java.util.concurrent.ExecutorService
In JDK there are many places where Visitor design pattern is used.
Some of these are as follows:
javax.lang.model.element.AnnotationValue and
AnnotationValueVisitor
javax.faces.component.visit.VisitContext and
VisitCallback
85. How Decorator design pattern is
different from Proxy pattern?
Main differences between Decorator and Proxy design pattern are:
javax.xml.bind.annotation.adapters.XmlAdapter.marshal()
91. What is the difference between
Factory and Abstract Factory design
pattern?
With Factory design pattern we can create concrete products of a
type that Factory can manufacture. E.g. If it is CarFactory, we can
produce, Ford, Toyota, Honda, Maserati etc.
This will ensure that no one can use clone() method or Cloneable
interface to create more than one instance of Singleton object.
102. What is the use of Interceptor
design pattern?
Interceptor design pattern is used for intercepting a request. Primary
use of this pattern is in Security policy implementation.
Core module
Bean module
Context module
Spring Expression Language module
112. What are the modules in Data
Access/Integration layer of Spring
framework?
Modules in Data Access/Integration Layer of Spring framework are:
There can be more than one bean in a Spring application. But all
these Beans are instantiated and assembled by Spring container.
<set> : This type is used for injecting a set of values. As per set
property, duplicates are not allowed.
no: This is default setting for Autowiring. In this case, we use “ref”
mode to mention the explicit bean that is being referred for wiring.
E.g.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-
2.5.xsd">
<bean
class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanP
</beans>
164. What is @Qualifier annotation
in Spring?
We use @Qualifier annotation to mark a bean as ready for auto
wiring. This annotation is used along with @Autowired annotation
to specify the exact bean for auto wiring by Spring container.
165. How Spring framework makes
JDBC coding easier for developers?
Spring provides a mature JDBC framework to provide support for
JDBC coding. Spring JDBC handled resource management as well
as error handling in a generic way. This reduces the work of
software developers.
They just have to write queries and related statements to fetch the
data or to store the data in database.
166. What is the purpose of
JdbcTemplate?
Spring framework provides JdbcTemplate class that contains many
convenient methods for regular tasks like- converting data into
primitives or objects, executing prepared or callable statements etc.
Hibernate
Java Persistence API (JPA)
TopLink
Java Data Objects (JDO)
Apache Object Relational Bridge (ORB)
170. How will you integrate Spring
and Hibernate by using
HibernateDaoSupport?
We can use following steps for integrating Spring and Hibernate:
This is the place where the code of an Aspect is inserted to add new
behavior in the existing execution flow.
178. What is an Advice in Spring
AOP?
An Advice in Spring AOP, is an object containing the actual action
that an Aspect introduces.
1. BeanNameAutoProxyCreator: This is a
BeanPostProcessor that creates AOP proxies for beans
automatically by matching names.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-
3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
">
188. What is Annotation-based
aspect implementation in Spring
AOP?
This is a declarative style AOP implementation. In this case, we use
annotations like @Aspect, @Pointcut, @Joinpoint etc. to annotate
code with different types of AOP elements.
This can be used Java 5 onwards, when the support for Annotations
was introduced.
189. How does Spring MVC
framework work?
Spring provides its own Model View Controller (MVC) framework
for developing web applications.
E.g. @RequestMapping(
value = "/test/mapping",
method = GET,
headers = "Accept=application/json")
195. What are the main features of
Spring MVC?
Spring MVC has following main features:
In prototype scope bean, the Spring IoC container creates new bean
instance of the object every time a request for that specific bean is
made.
197. How will you decide which scope-
Prototype or Singleton to use for a
bean in Spring?
In general, we use prototype scope for all stateful beans and
singleton scope for stateless beans.
Since a stateless bean does not maintain any state, we can use the
same object instance again and again. Singleton scope bean serves
the same purpose.
E.g. If there are two properties in a class, we can use Setter method
to inject just one property in the class.
For spring beans that are used in multiple contexts in Spring MVC,
we can create them in root context and initialize with listener.
Identity: Relational model has just one criteria for sameness of data.
It is based on primary key. In object model like Java we can have
equals as well as == for sameness of objects.
Data navigation: In Object model, you can move from one object to
another object for getting data. Egg. you can retrieve and Employee
object, then go to its department object and then get the employees
in the department object. In RDBMS, we try to minimize the SQL
calls, so we get all the data by using joins.
214. What are the key
characteristics of Hibernate?
Hibernate has following key characteristics:
Egg.
POJO emphasizes the fact that this class is a simple Java class, not
a heavy class like EJB.
HQL works well with persistent objects and their properties. HQL
does not work on database tables.
<sql-query name="callEmployeeStoreProcedure">
<return alias="employee"
class="com.testHibernate.util.Employee"/>
<![CDATA[CALL GetEmployees(:employeeId)]]>
</sql-query>
</hibernate-mapping>
We can call it with getNamedQuery().
Query query =
session.getNamedQuery("callEmployeeStoreProcedure")
.setParameter("employeeId", “1234”);
List result = query.list();
for(int i=0; i<result.size(); i++){
Employee employee = (Employee)result.get(i);
System.out.println(employee.getEmployeeCode());
}
Native SQL: We can use Native SQL to call a store procedure query
directly. In this example GetEmployees() stored procedure is being
called.
Use annotation:
We can also mark out stored procedure with
@NamedNativeQueries annotation.
//Employee.java
@NamedNativeQueries({
@NamedNativeQuery(
name = "callEmployeeStoreProcedure",
query = "CALL GetEmployees(:employeeId)",
resultClass = Employee.class
)
})
@Entity
@Table(name = "employee")
public class Employee implements java.io.Serializable {
...
Call it with getNamedQuery().
Query query =
session.getNamedQuery("callEmployeeStoreProcedure")
.setParameter("employeeId", “1234”);
List result = query.list();
for(int i=0; i<result.size(); i++){
Employee employee = (Employee)result.get(i);
System.out.println(employee.getEmployeeCode());
}
222. What is Criteria API in
Hibernate?
Criteria is a simplified API in Hibernate to get entities from
database by creating Criterion objects.
<property name=”show_sql”>true</property>
225. What are the different types of
collections supported by Hibernate?
Hibernate supports following two types of collections:
Any reference to this object is still valid. We can even update this
object. Later on we can even attach an object in detached state to a
new session and make it persistent.
Many to one
One to one
One to many
238. What is Unit of Work design
pattern?
Unit of Work is a design pattern to define business transactions.
Class is org.hibernate.criterion.Order.
Egg.
Session s = null;
Transaction trans = null;
try {
s = sessionFactory.openSession();
trans = s.beginTransaction();
doTheAction(s);
trans.commit();
} catch (RuntimeException exc) {
trans.rollback();
} finally {
s.close();
}
243. How can we mark an
entity/collection as immutable in
Hibernate?
In Hibernate, by default an entity or collection is mutable. We can
add, delete or update an entity/collection.
XML file: We can also set the property mutable=false in the XML
file for an entity to make it immutable.
244. What are the different options
to retrieve an object from database in
Hibernate?
In Hibernate, we can use one of the following options to retrieve
objects from database:
Identifier: We can use load() or get() method and pass the identifier
like primary key to fetch an object from database.
HQL: We can create a HQL query and get the object after executing
the query.
Native SQL: We can write native SQL query for a database and just
execute it to get the data we want and convert it into desired object.
245. How can we auto-generate
primary key in Hibernate?
We can use the primary key generation strategy of type
GenerationType.AUTO to auto-generate primary key while
persisting an object in Hibernate.
Egg.
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
We can leave it null/0 while persisting and Hibernate automatically
generates a primary key for us.
Hashtable
EHCache
OSCache
SwarmCache
JBoss Cache 1.x
JBoss Cache 2
249. Which is the default
transaction factory in Hibernate?
In Hibernate, default transaction factory is
JDBCTransactionFactory. But we can change it by setting the
property hibernate.transaction.factory_class.
250. What are the options to disable
second level cache in Hibernate?
This is a trick question. By default Second level cache is already
disabled in Hibernate.
In case, your project is using a second level cache you can use one
of the following options to disable second level cache in Hibernate:
In this strategy, Hibernate does not fetch the whole collection into
memory unless it is essential.
Read only: If an application requires caching only for read but not
for write operations, then we can use this strategy. It is very simple
to use and give very good performance benefit.
A Set in Hibernate can only store unique objects. If we add the same
element to set second time, it just replaces the old one. By default a
Set is unordered collection in Hibernate.
257. How can we monitor the
performance of Hibernate in an
application?
We can use following ways to monitor Hibernate performance:
The inverse side in this mapping is the owner of object. In this case
customer is the owner or order. Since an order cannot exist without
a customer. But a customer can exist without an order.
Also customer has no column to save order data. But an Order table
can store customer id, which is used for mapping.
260. What is ORM metadata?
ORM uses metadata for its internal work. ORM maintains metadata
to generate code used for accessing columns and tables.
On the other hand, get() method returns null value when an object is
not found in the database.
@NamedQueries({
@NamedQuery(
name = "findBookByAuthor”,
query = "from Book s where s.author = :author”
)
})
265. What are the two locking
strategies in Hibernate?
There are two popular locking strategies that can be used in
Hibernate:
Just before the commit, we check if any of the resource has changed
by another transaction, then we throw exception and rollback the
transaction.
The other transaction can proceed with same resource only after the
lock has been released by previous transaction.
266. What is the use of version
number in Hibernate?
Version number is used in optimistic locking in Hibernate. When a
transaction modifies an object, it increments its version. Based on
version number, second transaction can determine if the object it has
read earlier has changed or not.
Table per subclass: In this case we can have separate table for each
kind of book. HardCoverBook table for HardCoverBook book
class. PaperBackBook table for PaperBackBook book class. And
there will be a parent table, Book for Book class.
Table per concrete class: In this case also we have separate table
for each kind of book. But in this case we have even inherited
properties defined inside each table. There is no parent table Book
for Book class, since it is not a concrete class.
Maven
269. What is Maven?
Maven is a software project management tool. It is open source
software from Apache software foundation.
1. Build
2. Testing
3. Release
4. Reporting
5. Software Change Management (SCM)
6. Documentation
7. Distribution
272. What are the main advantages
of Maven?
Maven has a long list of advantages for Software development.
Some of the main advantages are:
It also contains default values for many projects. E.g. target is the
name of build directory for Java Maven project.
285. What is Super POM?
Super POM is Maven’s default POM. All the POM files extend
from Super POM.
286. What are the main required
elements in POM file?
Every POM file should have following required elements:
1. project root
2. modelVersion
3. groupID: the id of the project's group.
4. artifactID: the id of the artifact (project)
5. version: the version of the artifact under the specified
group
287. What are the phases in Build
lifecycle in Maven?
In Maven, each build lifecycle consists of many phases. Default
build lifecycle has following phases:
mvn -package
289. What is the format of fully
qualified artifact name of a Maven
project?
A Maven project has artifact name with following format:
<groupId>:<artifactId>:<version>
Parent pom
groupId: org.Orgname.Projectname
artifactId: org.Orgname.Projectname
version: x.x.x
E.g. org.Orgname.Projectname:org.Orgname.Projectname-1.0.0.pom
Modules
groupId: org.Orgname.Projectname
artifactId: org.Orgname.Projectname.Modulename
version: x.x.x
E.g.
org.Orgname.Projectname:org.Orgname.Projectname.Modulename-
1.0.0.jar
290. What is an Archetype in
Maven?
As per official definition, an Archetype is a Maven project
templating toolkit.
mvn archetype:generate
292. What are the three main build
lifecycles of Maven?
Maven has following three build lifecycles that further contain
multiple phases:
Note: In the above command replace Dplugin with the plugin prefix
as the argument. Do not use the artifact ID of plugin here.
295. What are the different types of
profile in Maven? Where will you
define these profiles?
In Maven, we can have following types of Profile:
Per Project
It is defined in the POM itself (pom.xml).
Per User
We can define it in the Maven-settings
(%USER_HOME%/.m2/settings.xml).
Global
It is defined in the global Maven-settings
(${maven.home}/conf/settings.xml).
Profile descriptor
Descriptor is located in project basedir (profiles.xml) (It is not
supported in Maven 3.0)
296. What are the different setting
files in Maven? Where will you find
these files?
Maven is very simple to use. At the core it has a setting file names
settings.xml. This file contains the setting element that is used to
configure the Maven with different options.
mvn -version
299. How will you verify if Maven is
installed on Windows?
To check this, type mvn –version in cmd prompt of Windows. This
will give you the version of Maven installed on Windows.
300. What is a Maven artifact?
A Maven artifact is a file that gets deployed to a Maven repository.
In most cases it is a JAR file.
test: This scope is used for dependencies that are required for test
compilation and execution phases. This scope is not transitive.
system: This scope is same as provided scope, except that you have
to provide the JAR that contains it explicitly. In this case, he artifact
is always available. There is no need to look it up in a repository.
E.g.
<dependencies>
<dependency>
<groupId>test.ProjectX</groupId>
<artifactId>ProjectX</artifactId>
<version>1.0</version>
<scope>compile</scope>
<exclusions>
<exclusion> <!-- exclusion is mentioned here -->
<groupId>test.ProjectY</groupId>
<artifactId>ProjectY</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
303. How Maven searches for JAR
corresponding to a dependency?
Maven first looks for a JAR related to a dependency in the local
repository. If it finds it there then it stops.
If it does not find it in local repo, it looks for the JAR in the remote
repository and downloads the corresponding version of JAR file.
From remote repository it stores the JAR into local repository.
304. What is a transitive
dependency in Maven?
Let say you have a Project A that depends on dependency B. The
dependency B further depends on dependency C. So your
dependency C is a Transitive Dependency of your project A.
${basedir}/target/classes/
308. What are the default locations
for source, test and build directories
in Maven?
The default locations are as follows:
Source: src/main/java
Test: src/main/test
Build: Target
309. What is the result of jar:jar
goal in Maven?
In Maven, jar:jar goal creates a jar file in the Maven build
directory. Jar file is create with the name format ${project.id}-
${project.currentVersion}.jar.
jar:jar does not recompile sources. It just creates a jar from already
compiled classes.
310. How can we get the debug or
error messages from the execution of
Maven?
At times, project build or compile fails in Maven. At this time it is
very helpful to see the debug or error messages from Maven
execution.
But release version always gives exactly same set files with each
download.
312. How will you run test classes in
Maven?
We need Surefire plugin to run the test classes in Maven.
or
<properties>
<property>
<name>test</name>
<value>some-value</value>
</property>
</properties>
314. How can we skip the running
of tests in Maven?
We can use the parameter -Dmaven.test.skip=true or -
DskipTests=true in the command line for skipping the tests.
Maven is mainly used for Java based systems. Gradle is used for a
variety of languages. It is a Polyglot build tool.
317. What is the difference between
Inheritance and Multi-module in
Maven?
In Maven, we can create a parent project that will pass its values to
its children projects.
Open source projects from Apache Commons are one of the most
portable projects. These build can work just out of the box.
GIT
319. How can we see n most recent
commits in GIT?
We can use git log command to see the latest commits. To see the
three most recent commits we use following command:
git log -3
320. How can we know if a branch
is already merged into master in GIT?
We can use following commands for this purpose:
git branch --merged master : This prints the branches merged into
master
git branch --merged lists : This prints the branches merged into
HEAD (i.e. tip of current branch)
git branch --no-merged : This prints the branches that have not been
merged
At any given time, one head is selected as the ‘current head’ This
head is also known as HEAD (always in uppercase).
323. What is the most popular
branching strategy in GIT?
There are many ways to do branching in GIT. One of the popular
ways is to maintain two branches:
In .git, GIT stores all the metadata for the repository. The contents
of .git directory are of internal use to GIT.
329. What are the main benefits of
GIT?
There are following main benefits of GIT:
5. User Interface: GIT does not have good UI. But SVN has
good user interfaces.
332. How will you start GIT for
your project?
We use git init command in an existing project directory to start
version control for our project.
After this we can use git add and git commit commands to add files
to our GIT repository.
333. What is git clone in GIT?
In GIT, we use git clone command to create a copy of an existing
GIT repository in our local.
We use git pull command to bring our local branch up to date with
its remote version.
338. What does ‘git push’ command
in GIT do internally?
In GIT, git push command does following two commands:
1. fetch: First GIT, copies all the extra commits from server
into local repo and moves origin/master branch pointer to
the end of commit chain.
Later we can use the stash and apply those changes back to our
working directory.
At times we are in the middle of some work and do not want to lose
the unfinished work, we use git stash command.
340. What is the meaning of ‘stage’
in GIT?
In GIT, stage is a step before commit. To stage means that the files
are ready for commit.
Let say, you are working on two features in GIT. One of the features
is finished and the other is not yet ready. You want to commit and
leave for home in the evening. But you can commit since both of
them are not fully ready. In this case you can just stage the feature
that is ready and commit that part. Second feature will remain as
work in progress.
341. What is the purpose of git
config command?
We can set the configuration options for GIT installation by using git
config command.
342. How can we see the
configuration settings of GIT
installation?
We can use ‘git config --list’ command to print all the GIT
configuration settings in GIT installation.
343. How will you write a message
with commit command in GIT?
We call following command for commit with a message:
$/> git commit –m <message>
344. What is stored inside a commit
object in GIT?
GIT commit object contains following information:
E.g.
the business days in this week are
<<<<<<< HEAD
five
=======
six
>>>>>>> branch-feature
To resolve the merge conflict in a file, we edit the file and fix the
conflicting change. In above example we can either keep five or six.
After editing the file we run git add command followed by git
commit command. Since GIT is aware that it was merge conflict, it
links this change to the correct commit.
353. What command will you use to
delete a branch?
GitHub Desktop
GITX-dev
Gitbox
Git-cola
SourceTree
Git Extensions
SmartGit
GitUp
363. What is the use of git diff
command in GIT?
In GIT, git diff command is used to display the differences between
2 versions, or between working directory and an index, or between
index and most recent commit.
It helps in finding the changes that can be used for code review for a
feature or bug fix.
364. What is git rerere?
In GIT, rerere is a hidden feature. The full form of rerere is “reuse
recorded resolution”.
git diff –cached: It displays the differences between the index and
the most recent commit.
1. The paths that have differences between the index file and
the current HEAD commit.
3. The paths in the working tree that are not tracked by GIT.
Among the above three items, first item is the one that we commit by
using git commit command. Item two and three can be committed
only after running git add command.
367. What is the main difference
between git diff and git status?
In GIT, git diff shows the differences between different commits or
between the working directory and index.
Or we can use
git stash apply <stashname>
370. Why do we use git log
command?
We use git log command to search for specific commits in project
history.
We can search git history by author, date or content. It can even list
the commits that were done x days before or after a specific date.
371. Why do we need git add
command in GIT?
GIT gives us a very good feature of staging our changes before
commit. To stage the changes we use git add command. This adds
our changes from working directory to the index.
HASH: The SHA1 hash of the Git tree that refers to the state of
index at commit time.
Commit Author: The name of person/process doing the commit and
date/time.
Comment: Some text messages that contains the reason for the
commit .
374. How can we convert git log
messages to a different format?
We can use pretty option in git log command for this.
This option converts the output format from default to other formats.
There are pre-built formats available for our use.
Often, commit messages contain JIRA ticket, bug id, defect id etc.
for a project.
377. How GIT protects the code in
a repository?
GIT is made very secure since it contains the source code of an
organization. All the objects in a GIT repository are encrypted with
a hashing algorithm called SHA1.
This algorithm is quite strong and fast. It protects source code and
other contents of repository against the possible malicious attacks.
GIT also supports both branching and tagging that promotes multiple
kinds of workflows in version control.
379. How can we change a commit
message in GIT?
If a commit has not been pushed to GitHub, we can use git commit --
ammend command to change the commit message.
The bare repository does not contain any working or checked out
copy of source files. A bare repository stores git revision history in
the root folder of repository instead of in a .git subfolder.
If we use git clean –x, then ignored files are also removed.
389. What is the purpose of git tag
command?
We use git tag command to add, delete, list or verify a tag object in
GIT.
Tag objects created with options –a, -s, -u are also known as
annotated tags.
We can use git diff-tree command to list the name of files that were
changed in a commit.
GIT will automatically run the script on the event of any of these
hooks.
394. What is the difference between
pre-receive, update and post-receive
hooks in GIT?
Pre-receive hook is invoked when a commit is pushed to a
destination repository. Any script attached to this hook is executed
before updating any reference. This is mainly used to enforce
development best practices and policies.
Post-receive hook is invoked after the updates have been done and
accepted by a destination repository. This is mainly used to
configure deployment scripts. It can also invoke Continuous
Integration (CI) systems and send notification emails to relevant
parties of a repository.
395. Do we have to store Scripts for
GIT hooks within same repository?
A Hook is local to a GIT repository. But the script attached to a
hook can be created either inside the hooks directory or it can be
stored in a separate repository. But we have to link the script to a
hook in our local repository.
We first tell a bad commit that contains the bug and a good commit
that was present before the bug was introduced.
Then git bisect picks a commit between those two endpoints and
asks us whether the selected commit is good or bad.
Git also provides support for creating an alias for a commit. This
alias is known as refs. Every tag in GIT is a ref. These refs can also
be used to identify a commit. Some of the special tags in GIT are
HEAD, FETCH_HEAD and MERGE_HEAD.
399. When we run git branch
<branchname>, how does GIT know
the SHA-1 of the last commit?
GIT uses the reference named HEAD for this purpose. The HEAD
file in GIT is a symbolic reference to the current branch we are
working on.
If we run git checkout branchA, Git updates the file to look like this:
$ cat .git/HEAD
ref: refs/heads/branchA
400. What are the different types of
Tags you can create in GIT?
In GIT, we can create two types of Tags.
So the people using git co have made the alias for git checkout in
their own environment.
403. How can we see the last
commit on each of our branch in
GIT?
When we run git branch command, it lists all the branches in our
local repository. To see the latest commit associated with each
branch, we use option –v.
git branch –v
Master is the default name for a starting branch when we run git init
command.
Origin is the default name for a remote when we run git clone
command. If we run git clone -o myOrigin instead, then we will
have myOrigin/master as our default remote branch.
405. How can we configure GIT to
not ask for password every time?
When we use HTTPS URL to push, the GIT server asks for
username and password for authentication. It prompts us on the
terminal for this information.
1. Local
2. HTTP
3. Secure Shell (SSH)
4. Git
407. What is GIT protocol?
Git protocol is a mechanism for transferring data in GIT. It is a
special daemon. It comes pre-packaged with GIT. It listens on a
dedicated port 9418. It provides services similar to SSH protocol.
You can even set you name and email in the commit history by using
filter-branch.
413. What are the three main trees
maintained by GIT?
GIT maintains following three trees:
These options tell the GIT which side to favor in merge conflicts.
As the name suggests, in ours, the changes in our branch are favored
over the other branch during a merge conflict.
416. How can we ignore merge
conflicts due to Whitespace?
GIT provides an option ignore-space-change in git merge command
to ignore the conflicts related to whitespaces.
Following is a sample:
If our application is content rich and used across multiple locations, we can
use Amazon CloudFront to increase its performance. Some of the techniques
used by Amazon CloudFront are as follows:
Caching: Amazon CloudFront caches the copies of our application’s content at
locations closer to our viewers. By this caching our users get our content very
fast. Also due to caching the load on our main server decreases.
Edge / Regional Locations: CloudFront uses a global network of Edge and
Regional edge locations to cache our content. These locations cater to almost
all of the geographical areas across the world.
Persistent Connections: In certain cases, CloudFront keeps persistent
connections with the main server to fetch the content quickly.
Other Optimization: Amazon CloudFront also uses other optimization
techniques like TCP initial congestion window etc to deliver high performance
experience.
434. What is the mechanism behind
Regional Edge Cache in Amazon
CloudFront?
A Regional Edge Cache location lies between the main webserver and the
global edge location. When the popularity of an object/content decreases, the
global edge location may take it out from the cache.
But Regional Edge location maintains a larger cache. Due to this the
object/content can stay for long time in Regional Edge location. Due to this
CloudFront does not have to go back to main webserver. When it does not find
any object in Global Edge location it just looks for in Regional Edge location.
This improves the performance for serving content to our users in Amazon
CloudFront.
435. What are the benefits of
Streaming content?
We can get following benefits by Streaming content:
1. Control: We can provide more control to our users for what they
want to watch. In a video streaming, users can select the locations in
video where they want to start watching from.
2. Content: With streaming our entire content does not stay at a user’s
device. Users gets only the part they are watching. Once the session is
over, content is removed from the user’s device.
In Amazon CloudFront we can detect the country from where end users are
requesting our content. This information can be passed to our Origin server by
Amazon CloudFront. It is sent in a new HTTP header.
Based on different countries we can generate different content for different
versions of the same content. These versions can be cached at different Edge
Locations that are closer to the end users of that country.
In this way we are able to target our end users based on their geographic
locations.
439. What are the main features of
Amazon CloudFront?
Flexibility: The businesses that have fluctuating bandwidth demands need the
flexibility of Cloud Computing. If you need high bandwidth, you can scale up
your cloud capacity. When you do not need high bandwidth, you can just scale
down. There is no need to be tied into an inflexible fixed capacity
infrastructure.
Disaster Recovery: Cloud Computing provides robust backup and recovery
solutions that are hosted in cloud. Due to this there is no need to spend extra
resources on homegrown disaster recovery. It also saves time in setting up
disaster recovery.
Automatic Software Updates: Most of the Cloud providers give automatic
software updates. This reduces the extra task of installing new software
version and always catching up with the latest software installs.
Low Capital Expenditure: In Cloud computing the model is Pay as you Go.
This means there is very less upfront capital expenditure. There is a variable
payment that is based on the usage.
Collaboration: In a cloud environment, applications can be shared between
teams. This increases collaboration and communication among team members.
Remote Work: Cloud solutions provide flexibility of working remotely. There
is no on site work. One can just connect from anywhere and start working.
Security: Cloud computing solutions are more secure than regular onsite work.
Data stored in local servers and computers is prone to security attacks. In
Cloud Computing, there are very few loose ends. Cloud providers give a
secure working environment to its users.
Document Control: Once the documents are stored in a common repository, it
increases the visibility and transparency among companies and their clients.
Since there is one shared copy, there are fewer chances of discrepancies.
Competitive Pricing: In Cloud computing there are multiple players, so they
keep competing among themselves and provide very good pricing. This comes
out much cheaper compared to other options.
Environment Friendly: Cloud computing saves precious environmental
resources also. By not blocking the resources and bandwidth.
442. What is On-demand computing
in Cloud Computing?
There are many concepts like- grid computing, utility computing, autonomic
computing etc. that are similar to on-demand computing.
An IAAS provider can give physical, virtual or both kinds of resources. These
resources are used to build cloud.
IAAS provider also handles security and backup recovery for these services.
The main resources in IAAS are servers, storage, routers, switches and other
related hardware etc.
445. What is the benefit of Platform
as a Service?
Biggest disadvantage of PaaS is that a developer can only use the tools that
PaaS provider makes available. A developer cannot use the full range of
conventional tools.
Some PaaS providers lock in the clients in their platform. This also decreases
the flexibility of clients using PaaS.
448. What are the different
deployment models in Cloud
computing?
Private Cloud: Some companies build their private cloud. A private cloud is a
fully functional platform that is owned, operated and used by only one
organization.
Primary reason for private cloud is security. Many companies feel secure in
private cloud. The other reasons for building private cloud are strategic
decisions or control of operations.
There is also a concept of Virtual Private Cloud (VPC). In VPC, private cloud
is built and operated by a hosting company. But it is exclusively used by one
organization.
Public Cloud: There are cloud platforms by some companies that are open for
general public as well as big companies for use and deployment. E.g. Google
Apps, Amazon Web Services etc.
The public cloud providers focus on layers and application like- cloud
application, infrastructure management etc. In this model resources are shared
among different organizations.
Hybrid Cloud: The combination of public and private cloud is known as
Hybrid cloud. This approach provides benefits of both the approaches- private
and public cloud. So it is very robust platform.
A client gets functionalities and features of both the cloud platforms. By using
Hybrid cloud an organization can create its own cloud as well as they can pass
the control of their cloud to another third party.
449. What is the difference between
Scalability and Elasticity?
Scalability is the ability of a system to handle the increased load on its current
hardware and software resources. In a highly scalable system it is possible to
increase the workload without increasing the resource capacity. Scalability
supports any sudden surge in the demand/traffic with current set of resources.
E.g. If in a system, one server can handle 100 users, 2 servers can handle 200
users and 10 servers can handle 1000 users. But in case for adding every X
users, if you need 2X the amount of servers, then it is not a scalable design.
Let say, you have just one user login every hour on your site. Your one server
can handle this load. But, if suddenly, 1000 users login at once, can your
system quickly start new web servers on the fly to handle this load? Your
design is elastic if it can handle such sudden increase in traffic so quickly.
450. What is Software as a Service?
Many applications like Google docs, Microsoft office etc. provide SaaS model
for their software.
The benefit of SaaS is that a client can add more users on the fly based on its
current needs. And client does not need to install or maintain any software on
its premises to use this software.
451. What are the different types of
Datacenters in Cloud computing?
Containerized Datacenter
Low-Density Datacenters
Simple multi-tenancy: In this setup, each client gets its own resources. These
resources are not shared with other clients. It is more secure option, since
there is no sharing of resources. But it an inefficient option, since for each
client more money is needed to scale it with the rising demands. Also it takes
time to scale up the application in this mode.
Fine grain multi-tenancy: In this mode, the feature provided to each client is
same. The resources are shared among multiple clients. It is an efficient mode
of cloud service, in which data is kept private among different clients but
computing resources are shared. Also it is easier and quicker to scale up the
SaaS implementation for different clients.
453. What are the important things
to care about in Security in a cloud
environment?
Organizations have to keep their Data most secure during the transfer between
two locations. Also they have to keep data secure when it is stored at a
location. Hackers can hack into application or they can get an unauthorized
copy of the data. So it becomes important to encrypt the data during transit as
well as during rest to protect it from unwanted hackers.
454. Why do we use API in cloud
computing environment?
There are different types of clients for cloud computing APIs. It is easier to
serve different needs of multiple clients with APIs in cloud computing
environment.
455. What are the different areas of
Security Management in cloud?
Identity Management: This aspect creates different level of users, roles and
their credentials to access the services in cloud.
Authentication: In this area, we check the credentials of a user and confirm that
it is the correct user. Generally this is done by user password and multi-factor
authentication like-verification by a one-time use code on cell phone.
Authorization: In this aspect, we check for the permissions that are given to a
user or role. If a user is authorized to access a service, they are allowed to use
it in the cloud environment.
456. What are the main cost factors
of cloud based data center?
Costs in a Cloud based data center are different from a traditional data center.
Main cost factors of cloud based data center are as follows:
Labor cost: We need skilled staff that can work with the cloud-based
datacenter that we have selected for our operation. Since cloud is not a very
old technology, it may get difficult to get the right skill people for handling
cloud based datacenter.
Power cost: In some cloud operations, power costs are borne by the client.
Since it is a variable cost, it can increase with the increase in scale and usage.
Computing cost: The biggest cost in Cloud environment is the cost that we pay
to Cloud provider for giving us computing resources. This cost is much higher
compared to the labor or power costs.
457. How can we measure the
cloud-based services?
For computing resource we measure by usage in terms of time and the power
of computing resource.
For a storage resource we measure by usage in terms of bytes (giga bytes) and
bandwidth used in data transfer.
With a traditional datacenter, people cost is very high since we have to hire a
large number of technical operation people for in-house datacenter.
459. How will you optimize
availability of your application in a
Cloud environment?
Cloud Model: We have to select the right cloud model for implementing IaaS
strategy. It can be SaaS, PaaS or CaaS.
DOCKER
461. What is Docker?
If we want to find IDs of all the Docker images in our local system,
we can user docker images command.
% docker images
% docker-compose -f docker-compose.json up
466. Can we run multiple apps on
one server with Docker?
With this we get cleaner environment and it can be used for multiple
uses.
467. What are the common use
cases of Docker?
Some of the common use cases of Docker are as follows:
Docker has wide acceptance due to its usability as well as its open
source approach of integrating with different systems.
UNIX Shell
471. How will you remove all files
in current directory? Including the
files that are two levels down in a sub-
directory.
In Unix we have rm command to remove files and sub-directories.
With rm command we have –r option that stands for recursive. The
–r option can delete all files in a directory recursively.
My_dir
->Level_1_dir
-> Level_1_dir ->Level_2_dir
-> Level_1_dir ->Level_2_dir->a.txt
Command:
rm – r *
The asterisk (*) is a wild card character that stands for all the files
with any name.
472. What is the difference between
the –v and –x options in Bash shell
scripts?
In a BASH Unix shell we can specify the options –v and –x on top
of a script as follows:
#!/bin/bash -x –v
With –x option BASH shell will echo the commands like for, select,
case etc. after substituting the arguments and variables. So it will
be an expanded form of the command that shows all the actions of
the script. It is very useful for debugging a shell script.
In –v option, If we run the script, the shell prints the entire file and
then executes. If we run the script interactively, it shows each
command after pressing enter.
473. What is a Filter in Unix
command?
In Unix there are many Filter commands like- cat, awk, grep, head,
tail cut etc.
Awk and Sed are complex filters that provide fully programmable
features.
Even Data scientists use Unix filters to get the overview of data
stored in the files.
474. What is Kernel in Unix
operating system?
Kernel is the central core component of a Unix operating system
(OS).
But Kernel does not directly interact with a user. For a new task,
Kernel will spawn a shell and user will work in a shell.
A Shell also has a command interpreter that can take our commands
and send these to be executed by Unix operating system.
Some of the popular Shells on Unix are: Korn shell, BASH, C shell
etc.
476. What are the different shells in
Unix that you know about?
Unix has many flavors of Shell. Some of these are as follows:
In this format the first character identifies the entry type. The entry
type can be one of the following:
Each Inode has a number that is used in the index table. Unix kernel
uses Inode number to access the contents of an Inode.
If you enjoyed this book or gained knowledge from it in any way, then I’d like
to ask you for a favor. Would you be kind enough to leave a review for this
book on Amazon.com?
https://aws.amazon.com
https://www.docker.com/
https://www.nagios.com
https://github.com/