Grokking The Java Developer Interview - More Than 200 Questions To Crack The Java, Spring
Grokking The Java Developer Interview - More Than 200 Questions To Crack The Java, Spring
JATIN ARORA
GROKKING THE JAVA DEVELOPER INTERVIEW
COPYRIGHT © 2020 BY JATIN ARORA.
All rights reserved. No part of this book may be reproduced,
distributed, or transmi ed in any form or by any means, including
photocopying, recording or other electronic or mechanical
methods, without the prior wri en permission of the author,
except in the case of brief quota ons embodied in cri cal reviews
and certain other non-commercial uses permi ed by copyright
law.
For permission or any other informa on, contact me at:
ja [email protected]
Preface
Grokking The Java Developer Interview helps you to crack a Java, Spring
& Hibernate interview.
This book covers enough details of a Java/Spring topic that will surely
help the absolute beginners and if you are already familiar with Java &
Spring, then this book will help you to brush-up on the concepts.
The book has more than 200 ques ons that are frequently asked during
an interview for Java, Spring, SpringBoot & Hibernate profile. Some of
the important topics like Mul -threading, Collec on framework,
Singleton Pa ern, SpringBoot Annota ons and many more are covered
in detail. Most of these topics are explained with code examples that
will help you to quickly grasp the concept.
This book contains a lot of code examples, most of the code snippets
are displayed in image format that you can zoom-in and out of.
However, if some image is not clearly visible on your device, you can also
refer to the GitHub repository for this book. The GitHub repo contains
all of the snippets shown in this book and it can be found at:
h ps://github.com/reachja n/Grokking-The-Java-Developer-
Interview
Contact Informa on
I would love to hear from you.
For feedback or queries, you can contact me at
ja [email protected]
Your valuable sugges ons to improve the book are always welcomed.
I wish you all the best and I am confident that this book will help you in
making that job switch that you are looking for.
Happy Learning, Cheers :)
-Ja n Arora
Acknowledgements
I thank my brother, Sumit Kumar, for encouraging me to take up this
project. From reading early dra s to advising me on the structure of the
book to making sure that it was wri en in a manner that was coherent,
organized and engaging at the same me, his role has been pivotal in
the making of this book.
To elaborate a li le on his background, Sumit is an UChicago Alum, and
presently working for Amazon, Sea le as a Research Scien st at Alexa AI.
He has also worked with Samsung, India as a Lead Engineer. He is an
ac ve blogger and regularly post ar cles on Data structures and
Algorithms, System Design, NLP and many more interes ng topics. You
can find those at:
h ps://medium.com/@sumit.arora
h ps://blog.reachsumit.com
-Ja n Arora
Table of Content s
Preface
Acknowledgements
Ques on 1: What are the 4 pillars of OOPS?
Ques on 2: What is an abstract class?
Ques on 3: Does Abstract class have constructor?
Ques on 4: What is an Interface?
Ques on 5: Difference between abstract class and interface
Ques on 6: What to choose – interface or abstract class
Ques on 7: Why Java 8 has introduced default methods?
Ques on 8: Why Java 8 has introduced sta c methods?
Ques on 9: Why Java does not allow mul ple inheritance?
Ques on 10: What are the rules for Method Overloading and Method
Overriding?
Ques on 11: Can we override final methods?
Ques on 12: Can constructors and private methods be overridden?
Ques on 13: What is final keyword and where it can be used?
Ques on 14: What is excep on and excep on handling?
Ques on 15: Difference between error and excep on
Ques on 16: What are the different types of excep ons?
Ques on 17: How excep on handling is done in java?
Ques on 18: Can we write a try block without catch block?
Ques on 19: How to handle mul ple excep ons together?
Ques on 20: When finally block will not get executed
Ques on 21: Difference between throw and throws keyword. And
discuss Excep on Propaga on
Ques on 22: Excep on handling w.r.t. method overriding
Ques on 23: Programs related to Excep on handling and return keyword
Ques on 24: How to make your own custom excep on class?
Ques on 25: How to make custom checked / unchecked excep on?
Ques on 26: What happens when you throw an excep on from finally
block?
Ques on 27: What will be Output of below program related to try-catch-
finally?
Ques on 28: Explain try-with-resources
Ques on 29: Why String is Immutable?
Ques on 30: What does the equals() method of String class do?
Ques on 31: Explain StringBuffer and StringBuilder
Ques on 32: Explain the output of below program related to equals()
method of StringBuilder
Ques on 33: When to use String/StringBuffer/StringBuilder
Ques on 34: Explain equals and hashcode contract
Ques on 35: What is Marker Interface?
Ques on 36: Can you write your own custom Marker interface?
Ques on 37: What is Comparable and Comparator?
Ques on 38: How to compare a list of Employees based on name and
age such that if name of the employee is same then sor ng should be
based on age
Ques on 39: Difference between Comparable and Comparator
Ques on 40: Different methods of Object class
Ques on 41: What type of arguments are allowed in System.out.println()
method?
Ques on 42: Explain System.out.println() statement
Ques on 43: Explain Auto-boxing and Un-boxing
Ques on 44: Find the output of below program
Ques on 45: Can you pass primi ve long value in switch statement?
Ques on 46: Explain sta c keyword in Java
Ques on 47: What is an Inner Class in Java, how it can be instan ated
and what are the types of Inner Classes?
Ques on 48: What is Constructor Chaining in java?
Ques on 49: What is init block?
Ques on 50: What is called first, constructor or init block?
Ques on 51: What is Variable shadowing and Variable hiding in Java?
Ques on 52: What is a constant and how we create constants in Java?
Ques on 53: Explain enum
Ques on 54: What is Cloneable?
Ques on 55: What is Shallow Copy and Deep Copy?
Ques on 56: What is Serializa on and De-serializa on?
Ques on 57: What is SerialVersionUID?
Ques on 58: Serializa on scenarios with Inheritance
Ques on 59: Stopping Serializa on and De-serializa on
Ques on 60: What is Externalizable Interface?
Ques on 61: Externalizable with Inheritance
Ques on 62: Difference between Serializable and Externalizable
Ques on 63: How to make a class Immutable?
Ques on 64: Explain Class loaders in Java
Ques on 65: What is Singleton Design Pa ern and how it can be
implemented?
Ques on 66: What are the different ways in which a Singleton Design
pa ern can break and how to prevent that from happening?
Ques on 67: What are the different design pa erns you have used in
your projects?
Ques on 68: Explain Vola le keyword in java
Ques on 69: What is Garbage Collec on in Java, how it works and what
are the different types of Garbage Collectors?
Ques on 70: Explain Generics in Java
Ques on 71: What is Mul -threading?
Ques on 72: How to create a thread in Java?
Ques on 73: Which way of crea ng threads is be er: Thread class or
Runnable interface
Ques on 74: What will happen if I directly call the run() method and
not the start() method to execute a thread
Ques on 75: Once a thread has been started can it be started again
Ques on 76: Why wait, no fy and no fyAll methods are defined in the
Object class instead of Thread class
Ques on 77: Why wait(), no fy(), no fyAll() methods must be called
from synchronized block
Ques on 78: difference between wait() and sleep() method
Ques on 79: join() method
Ques on 80: yield() method
Ques on 81: Tell something about synchronized keyword
Ques on 82: What is sta c synchroniza on?
Ques on 83: What will be output of below program where one
synchronized method is calling another synchronized method?
Ques on 84: Programs related to synchronized and sta c synchronized
methods
Ques on 85: What is Callable Interface?
Ques on 86: How to convert a Runnable to Callable
Ques on 87: Difference between Runnable and Callable
Ques on 88: What is Executor Framework in Java, its different types and
how to create these executors?
Ques on 89: Tell something about awaitTermina on() method in
executor
Ques on 90: Difference between shutdown() and shutdownNow()
methods of executor
Ques on 91: What is Count down latch in Java?
Ques on 92: What is Cyclic Barrier?
Ques on 93: Atomic classes
Ques on 94: What is Collec on Framework?
Ques on 95: What is Collec ons?
Ques on 96: What is ArrayList?
Ques on 97: What is default size of ArrayList?
Ques on 98: Which data structure is used internally in an ArrayList?
Ques on 99: How add() method works internally or How the ArrayList
grows at run me
Ques on 100: How to make an ArrayList as Immutable
Ques on 101: What is LinkedList?
Ques on 102: When to use ArrayList / LinkedList
Ques on 103: What is HashMap?
Ques on 104: Explain the internal working of put() and get() methods of
HashMap class and discuss HashMap collisions
Ques on 105: equals and hashCode method scenarios in HashMap when
the key is a custom class
Ques on 106: How to make a HashMap synchronized?
Ques on 107: What is Concurrent HashMap?
Ques on 108: What is HashSet class and how it works internally?
Ques on 109: Explain Java’s TreeMap
Ques on 110: Explain Java’s TreeSet
Ques on 111: Difference between fail-safe and fail-fast iterators
Ques on 112: Difference between Iterator and ListIterator
Ques on 113: Difference between Iterator.remove and
Collec on.remove()
Ques on 114: What is the difference between a Monolith and Micro-
service architecture?
Ques on 115: What is Dependency Injec on in Spring?
Ques on 116: What are the different types of Dependency Injec on?
Ques on 117: Difference between Constructor and Se er injec on
Ques on 118: What is @Autowired annota on?
Ques on 119: What is the difference between BeanFactory and
Applica onContext?
Ques on 120: Explain the life-cycle of a Spring Bean
Ques on 121: What are the different scopes of a Bean?
Ques on 122: What is the Default scope of a bean?
Ques on 123: What happens when we inject a prototype scope bean in
a singleton scope bean?
Ques on 124: How to inject a prototype scope bean in a singleton scope
bean?
Ques on 125: Explain Spring MVC flow
Ques on 126: What is the difference between <context:annota on-
config> and <context:component-scan>?
Ques on 127: What is the difference between Spring and SpringBoot?
Ques on 128: What is auto-configura on in SpringBoot?
Ques on 129: What are SpringBoot starters?
Ques on 130: What is @SpringBootApplica on Annota on?
Ques on 131: Where does a Spring Boot applica on start from?
Ques on 132: How to remove certain classes from ge ng auto-
configured in SpringBoot?
Ques on 133: How to autowire a class which is in a package other than
SpringBoot applica on class’s package or any of its sub-packages
Ques on 134: What is applica on.proper es file in a SpringBoot
applica on?
Ques on 135: How to configure the port number of a SpringBoot
applica on?
Ques on 136: Which jar builds our springboot applica on automa cally
whenever we change some code just like a node.js applica on?
Ques on 137: What default embedded server is given in spring boot
web starter and how we can change the default embedded server to the
one of our choice
Ques on 138: Where should we put our html and javascript files in a
spring boot applica on?
Ques on 139: What are the different stereotype annota ons?
Ques on 140: Difference between @Component, @Controller, @Service,
@Repository annota ons?
Ques on 141: Difference between @Controller and @RestController
annota on
Ques on 142: What is @RequestMapping and @RequestParam
annota on?
Ques on 143: How to define a Get or Post endpoint?
Ques on 144: Which annota on is used for binding the incoming json
request to the defined pojo class?
Ques on 145: What is @Qualifier annota on?
Ques on 146: What is @Transac onal annota on?
Ques on 147: What is @ControllerAdvice annota on?
Ques on 148: What is @Bean annota on?
Ques on 149: Difference between @Component and @Bean
Ques on 150: How to do profiling in a SpringBoot applica on
Ques on 151: What is RestTemplate?
Ques on 152: What is Spring Data JPA?
Ques on 153: What is the difference between JPARepository,
CRUDRepository, PagingAndSor ngRepository and which one you have
used in your applica ons?
Ques on 154: What is Spring AOP?
Ques on 155: Have you used Spring Security in your applica on
Ques on 156: What do you know about Spring Batch framework?
Ques on 157: Difference between SOAP and REST
Ques on 158: What is Res ul api?
Ques on 159: What is a stateless object?
Ques on 160: What is the difference between Web Server and
Applica on Server?
Ques on 161: What do you know about CommandLineRunner and
Applica onRunner?
Ques on 162: What do you know about Eureka Naming Server?
Ques on 163: What do you know about Zuul?
Ques on 164: What do you know about Zipkin?
Ques on 165: What do you know about Hysterix?
Ques on 166: What is JPA?
Ques on 167: What is Hibernate?
Ques on 168: Difference between JPA and Hibernate
Ques on 169: What is @En ty?
Ques on 170: How to give a name to a table in JPA?
Ques on 171: What is @Id, @GeneratedValue?
Ques on 172: How to use a custom database sequence in Hibernate to
generate primary key values?
Ques on 173: How to give names to the columns of a JPA En ty
Ques on 174: How to define a @OneToMany rela onship between
en es
Ques on 175: Why annota ons should be imported from JPA and not
from Hibernate?
Ques on 176: What is the difference between get() and load() method
of Hibernate Session?
Ques on 177: What is the difference between save(), saveOrUpdate()
and persist() method of Hibernate Session?
Ques on 178: What is Session and SessionFactory in Hibernate?
Ques on 179: What is First Level and Second Level Cache in Hibernate?
Ques on 180: What is session.flush() method in Hibernate?
Ques on 181: How can we see the SQL query that gets generated by
Hibernate?
Ques on 182: What is Hibernate Dialect and why we need to configure
it?
Ques on 183: What do you know about hibernate.hbm2ddl.auto
property in Hibernate?
Ques on 184: What is Maven?
Ques on 185: What is pom.xml?
Ques on 186: What is local repo and central repo?
Ques on 187: Where we define our local repo path?
Ques on 188: Where do we define proxies so that maven can download
jars from the internet in a corporate environment?
Ques on 189: Explain Maven build life-cycle
Ques on 190: What do you know about SQL Joins?
Ques on 191: Difference between TRUNCATE & DELETE statements
Ques on 192: Difference between Func on and Stored Procedure
Ques on 193: What is DDL, DML statements?
Ques on 194: How to find the nth highest salary from Employee table
Ques on 195: Difference between UNION and UNION ALL commands in
SQL
Ques on 196: Difference between Unique Key and Primary Key in SQL
Ques on 197: What is the difference between Primary and Foreign key in
SQL?
Ques on 198: What is the difference between clustered and non-
clustered index?
Ques on 199: What is the difference between WHERE and HAVING
clause in SQL
Ques on 200: How to change the gender column value from Male to
Female and Female to Male using single Update statement
Ques on 201: Find first 3 largest numbers in an array
Ques on 202: Move all nega ve numbers at the beginning of an array
and all posi ve numbers at the end
About the Author
Question 1: What are the 4 pillars of OOPS?
Answer: 4 pillars of OOPS are:
1. Abstrac on
2. Encapsula on
3. Inheritance
4. Polymorphism
Let’s take a look at them:
Example:
Java Bean, where all data members are made private and you
define certain public methods to the outside world to access
them.
3. Inheritance : Using inheritance means defining a parent-child
rela onship between classes, by doing so, you can reuse the
code that is already defined in the parent class. Code
reusability is the biggest advantage of Inheritance.
Java does not allow mul ple inheritance through classes but it
allows it through interfaces.
4. Polymorphism : Poly means many and Morph means forms.
Polymorphism is the process in which an object or func on
takes different forms. There are 2 types of Polymorphism :
Output:
Example 2:
Output:
Question 4: What is an Interface?
Answer:
Output:
Question 8: Why Java 8 has introduced static methods?
Answer: Consider an example where you want to define a u lity class,
what you usually do is you define a class which contains sta c methods
and then you call these methods using class name. Now, Java 8 onwards
you can do the same thing using an Interface by giving only sta c
methods inside your interface. This way of using Interface for defining
u lity classes is be er as it helps in performance also, because using a
class is more expensive opera on than using an interface.
Output:
Output:
Question 15: Difference between error and exception
Answer: Error : Errors in a program are irrecoverable, they indicate that
something severe has gone wrong in the applica on and the program
gets terminated in case of error occurrence e.g. running out of memory:
OutOfMemoryError , making too many recursive calls: StackOverflowError
etc.
Excep on : Excep ons on the other hand are something that we can
recover from by handling them properly e.g.: trying to access a
property/method from a null object: NullPointerExcep on , dividing an
integer by zero: Arithme cExcep on etc.
Suppose, your method is throwing more than one excep on and you
want to perform some specific ac on based on the excep on thrown,
you should use mul ple catch blocks in this case.
Example using mul ple catch blocks:
When using pipe (|) symbol:
Example: unchecked excep on is thrown and it can be seen from the call
stack that it is propagated
Output:
Output:
Example: checked excep ons are not propagated down the call chain
by default ,
You have to use throws keyword if you want to propagate the checked
excep on, like
Output:
Output:
Example when parent class method does not declare an excep on and
child class declares unchecked excep on :
Output:
One thing you should remember is, if you write anything a er return
statement / throw excep on statement, then that will give Compile me
error as ‘Unreachable code’.
Program 1:
Program 5 :
Output:
Output:
Output:
Answer: This is another very famous interview ques on. If you were
expec ng ‘Equal’ as output, then you were wrong. The output is not
‘Equal’ because StringBuffer and StringBuilder does not override equals
and hashcode methods. In the above program, Object’s class equals()
method is ge ng used and as it compares the reference of two objects,
the output of above program is ‘Not Equal’.
Since hashcode is used in data structures that use hashing algorithm to
store the objects. Examples are HashMap, HashSet, HashTable,
ConcurrentHashMap etc. and all these data structures requires their
keys not to be changed so that stored values can be found by using
hashcode method but StringBuffer/StringBuilder are mutable objects.
This makes them a very poor choice for this role.
You must have heard about the equals and hashcode contract in Java,
which states that if two objects are equals according to equals() method
then their hashcode must be same, vice-versa is not true. Now, had the
equals method for StringBuilder/StringBuffer be overridden, their
corresponding hashcode method would also need to be overridden to
follow that rule. But as explained earlier, these classes don’t need to
have their own hashcode implementa on and hence same is with their
equals method.
Output:
Output:
ComparatorDemo.java :
Output:
ComparatorDemo.java :
Output:
Question 39: Difference between Comparable and
Comparator
Answer:
Output:
- Variable
- Method
- Block
- Nested
class
Sta c Variable : if any variable is declared as sta c, then it is known as
‘sta c variable’. Only single copy of the variable gets created and all
instances of the class share same sta c variable. The sta c variable gets
memory only once in the class area at the me of class loading.
When to use sta c variable : sta c variables should be used to declare
common property of all objects as only single copy is created and shared
among all class objects, for example, the company name of employees
etc.
Sta c Method : When a method is declared with sta c keyword then it is
known as sta c method. These methods belong to the class rather than
the object of the class. As a result, a sta c method can be directly
accessed using class name without the need of crea ng an object.
One of the basic rules of working with sta c methods is that you can’t
access a non-sta c method or field from a sta c method because the
sta c method doesn’t have an instance of the class to use to reference
instance methods or fields. Another restric on is, ‘this’ and ‘super’
cannot be used in sta c context.
For example: main() method is sta c, Java Run me uses this method to
start an applica on without crea ng an object.
Sta c Block : Sta c block gets executed exactly once when the class is
first loaded, use sta c block to ini alize the sta c variables.
Output:
If you have sta c members in your Sta c Inner class then there is no
need to create the inner class object:
Output:
Example:
Output:
Compile me error when sta c variable and sta c method is present in
Inner class:
Remember, you can only access the block level variables, and cannot
change them. You will get compile me error if you try to change them:
A variable whose value is not changed once ini alized is called as
effec vely final variable .
Program:
Employee.java :
AnonymousInnerDemo.java :
Output:
Example 3 : You can use anonymous inner class in situa ons where you
want to override the parent class method without crea ng a separate
child class:
Output:
Example 2:
Output:
Example 3:
Output:
Order of execu on :
- sta c blocks of super classes
- sta c blocks of the class
- init blocks of super classes
- constructors of super classes
- init blocks of the class
- constructors of the class
1. The code in sta c ini aliza on block will be executed
at class load me (and yes, that means only once per
class load), before any instances of the class are
constructed and before any sta c methods are called.
2. The instance ini aliza on block is actually copied by
the Java compiler into every constructor the class has.
So, the code in instance ini aliza on block is
executed exactly before the code in constructor.
If you want to access instance variables then you can do so using ‘this’
keyword like below:
Example 2:
Output:
Variable Hiding : When the child and parent classes both have a variable
with the same name, the child class variable hides the parent class
variable.
Example 1:
Output:
If you want to access parent’s class variable then you can do this using
super keyword:
Example 2:
Output:
Example 2:
Output:
Output:
Here, we have created Employee object e1 with new keyword but then
we created another object Employee e2 which has the same reference as
of e1. So, any change in e2 object will reflect in e1 object and vice-versa.
Now, let’s implement Cloneable interface in our Employee class and
invoke the clone() method on e1 object to make its clone:
Program 2:
Output:
Can you guess the output of the last 2 sysout? Here is the output:
If you are surprised with the above output, then let me make it clear by
saying that, by default Object’s clone() method provide Shallow copy.
This brings us to the next interview ques on: What is shallow copy and
deep copy
Question 55: What is Shallow Copy and Deep Copy?
Answer: Shallow Copy : When we use the default implementa on of
clone() method, a shallow copy of object is returned, meaning if the
object that we are trying to clone contains both primi ve variables and
non-primi ve or reference type variable, then only the object’s
reference is copied not the en re object itself.
Consider this with the example:
Employee object is having Company object as a reference, now when we
perform cloning on Employee object, then for primi ve type variables,
cloning will be done i.e. new instances will be created and copied to the
cloned object but for non-primi ve i.e. Company object, only the
object’s reference will be copied to the cloned object. It simply means
Company object will be same in both original and cloned object,
changing the value in one will change the value in other and vice-versa.
Now, if you want to clone the Company object also, so that your original
and cloned Employee object will be independent of each other, then you
have to perform Deep Copy.
Deep Copy : in Deep copy, the non-primi ve types are also cloned to
make the original and cloned object fully independent of each other.
Program 1:
Output:
In above example, we have overridden the clone method in our
employee class and we called the clone method on mutable company
object.
We can also use Copy constructor to perform deep copy:
Program 2:
Output:
There are 2 other methods by which you can perform deep copy:
- By using Serializa on, where you serialize the original
object and returns the deserialized object as a clone
- By using external library of Apache Commons Lang. Apache
Common Lang comes with Serializa onU ls.clone() method
for performing deep copy on an object. It expects all classes
in the hierarchy to implement Serializable interfaces else
SerializableExcep on is thrown by the system
Serializa onDemo.java:
Output:
Output:
java.io.InvalidClassException : com.serialization.demo.Employee; local class
incompatible: stream classdesc serialVersionUID = -3697389390179909057,
local class serialVersionUID = -3759917827722067163
at java.io.ObjectStreamClass.initNonProxy(Unknown Source)
at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
at java.io.ObjectInputStream.readClassDesc(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at com.serialization.demo.DeserializationTest.main(
DeserializationTest.java:13 )
Serializa onDemo.java:
Output:
Now, let’s add one more field ‘company’ and remove the transient
keyword from our Employee class. Here, as we are changing the class
structure, let’s see if we get the error of InvalidClassExcep on again:
Program 3:
Deserializa onTest.java:
Output:
Output:
Now, one thing to remember here is that the public no-arg constructor
gets called before readExternal() method, so we have to provide this no-
arg constructor or else we will get an excep on during run- me.
Comment the public no-arg constructor from Employee.java:
Program 2:
So, if interviewer asks a ques on that you have a class which has 1000
variables and you want to serialize only 10 specific variables, your
answer should be using an Externalizable interface.
Some points to remember:
- Using Externalizable interface, we can implement custom
logic for serializa on and deserializa on of object
- When using Externalizable, we have to explicitly men on
what fields or variables we want to serialize
- When using Externalizable, a public no-arg constructor is
required
- Using Externalizable, we can also serialize transient and
sta c variables
- readExternal() method must read the values in the same
sequence and with the same types as were wri en by
writeExternal() method
ExternalizableDemo.java:
Output:
The capacity and age variable values are 0 because we did not serialize
these two variables.
Student.java:
Here, we are using ge ers and se ers of parent class, Department, to
serialize and de-serialize its fields.
ExternalizableDemo.java:
Output:
TestImmutable.java:
Here, a er crea ng Employee object, the first change is done in local
address object and then we used the employee’s ge er method to
access the address object and tried to change the value in it.
Output:
As, you can see that the value remained the same.
If we don’t follow the rule about mutable object reference present in
the class, let’s see what will happen in that case.
Let’s change the Employee class constructor and ge er method:
Employee.java:
Now, if we run our TestImmutable.java class, below is the output:
Suppose, you have created a class Employee.java and compiled this class
and Emloyee.class file is created. Now, you want to use this class, the
first request to load this class will come to System/Applica on
ClassLoader, which will delegate the request to its parent, Extension
ClassLoader which further delegates to Primordial or Bootstrap class
loader
Now, Bootstrap ClassLoader will look for this class in rt.jar, since this
class is not there, the request will come to Extension ClassLoader which
looks in jre/lib/ext directory and tries to locate this class there, if this
class is found there then Extension ClassLoader will load this class and
Applica on ClassLoader will not load this class, this has been done to
maintain the Uniqueness principle. But if the class is not loaded by
Extension ClassLoader, then this Employee.class will be loaded by
Applica on ClassLoader from the CLASSPATH.
Employee.java:
Output:
If you are thinking why null is printed when we tried to know which
classloader is loading the java.lang.System class then take a look at the
Javadoc :
We can also create our own custom class loader by extending the
ClassLoader class.
Question 65: What is Singleton Design Pattern and how it
can be implemented?
Answer: This is a famous interview ques on, as it involves many follow-
up ques ons as well. I will cover all of them here:
What is Singleton Design Pa ern?
Singleton design pa ern comes under Crea onal Design Pa erns
category and this pa ern ensures that only one instance of class exists
in the JVM.
Singleton pa ern is used in:
- logging, caching, thread pool etc.
- other design pa erns like Builder, Prototype, Abstract
Factory etc.
- core java classes like java.lang.Run me etc.
How to implement Singleton Pa ern
To implement a Singleton pa ern, we have different approaches but all
of them have the below common concepts:
Output:
We can also access the instance by using the classname like A.instance
because of sta c keyword but we will have to change its access modifier
to ‘public’, so that it is visible outside the singleton class.
Let’s suppose you are crea ng a large object by using a lot of resources,
there may be a chance that object crea on may throw an excep on but
the above way of crea ng a singleton class does not provide any op on
for excep on handling as you can write try-catch only inside a block of
code. There is a solu on to tackle this par cular problem where you can
create the class instance inside a sta c block.
Both the above approaches create the object even before it is used
(ini alized at the me of class loading because of sta c variable and
sta c block), but there are other approaches where we can create a
Singleton class instance in a lazy ini aliza on way i.e. only when
someone asks for it. These approaches are discussed below.
Lazy Ini aliza on: using this way of crea ng Singleton class, the object
will not get created unless someone asks for it. Here we will create the
class instance inside the global access method.
This approach is suitable for only single-threaded applica on, suppose
there are 2 threads and both have checked that the instance is null and
now they are inside the “if(…)” condi on, it will destroy our singleton
pa ern and both threads will have different instances. So, we must
overcome this problem so that our singleton pa ern doesn’t break in
case of mul -threaded environment.
Thread Safe Singleton implementa on: here the easiest way to prevent
mul ple threads from crea ng more than one instance is to make the
global access method ‘synchronized’, this way threads will acquire a lock
first before entering the getInstance() method.
Synchronizing the en re method comes with performance degrada on,
also acquiring the lock and releasing the lock on every call to
getInstance() method seems un-necessary, because only first few calls to
getInstance() method needs to be synchronized, what I mean to say by
this statement is: let’s suppose there are 10 threads that are trying to
call getInstance() method, now you need to apply synchroniza on to
only these 10 threads at this me and the thread which first acquires
the lock will create the object. A er that, every thread will get the same
object because of null check in if condi on, so we can op mize the
above code by using double-checked locking principle , where we will
use a synchronized block inside the if condi on, like shown below:
The reason of second if condi on inside the synchronized block :
suppose there are 2 threads and both called the getInstance() method
at the same me, now they will both be inside the first if condi on as
instance is null at this me, and the first thread which acquires the lock
will create the object and as soon as it exits the synchronized block,
other thread which was wai ng, will acquire the lock and it will also
create another object thus breaking the singleton pa ern. This is why it
is called “double-checked locking”.
Now, some people have faced issues with the above approach in java 1.4
and earlier versions, which was solved in later versions by using ‘vola le’
keyword with the above approach like below:
localRef variable is there for the cases where instance is already
ini alized (discussed above), the vola le field is only accessed once
because we have wri en return localRef not return instance .
There is another approach where an inner sta c class is used to create
the Singleton class instance and it is returned from the global access
method. This approach is called Bill Pugh Singleton Implementa on .
Bill Pugh Singleton Implementa on Program:
The inner class does not get loaded at the me of class A loading, only
when someone calls getInstance() method, it gets loaded and creates
the Singleton instance.
Test.java:
Output:
As we can see from the output, the 2 instances have different hashcode,
thus destroying Singleton.
Now to prevent Singleton from Reflec on, one simple solu on is to
throw an excep on from the private constructor, so when Reflec on
tries to invoke private constructor, there will be an error.
TestSingletonEnum.java:
Output:
Output:
To prevent our Singleton class from Serializa on, there is a method
called readResolve() which is called when ObjectInputStream has read
an object from the stream and is preparing to return it to the caller, so
we can return the only instance of this class from this method, and this
way the only instance of singleton will be assigned to instance2, see
below:
A.java:
Test.java:
Output:
You can also throw an excep on from the readResolve() method, but
returning the only instance approach is be er as your program
execu on will not stop.
One last way which can break Singleton property of a class is:
Cloning : As we know, Cloning is used to create duplicate objects (copy
of the original object). If we create a clone of the instance of our
Singleton class then a new instance will be created thus breaking our
Singleton pa ern.
See the program below:
TestSingleton.java:
Output:
As you can see, both instances have different hashcodes indica ng our
Singleton pa ern is broken, so to prevent this we can override clone
method in our Singleton class and either return the same instance or
throw CloneNotSupportedExcep on from it.
See the program changes below:
Output:
clone() returning the same instance, see the program changes below:
Output:
Now, let’s suppose 2 threads are working on this class and both threads
are running on different processors having their own local copy of
variable x. if any thread modifies its value, the change will not be
reflected back in the original variable x in the main memory leading to
data inconsistency because the other thread is not aware of the
modifica on.
So, to prevent data inconsistency, we can make variable x as vola le:
Now, all the threads will read and write the variable x from/to the main
memory. Using vola le, also prevents compiler from doing any
reordering or any op miza on to the code.
Classes may get collected (unloaded) if the JVM finds they are no longer
needed and space may be needed for other classes. The permanent
genera on is included in a full garbage collec on. And Perm Gen was
available ll Java 7, it is removed from Java 8 onwards and JVM uses
na ve memory for the representa on of class metadata which is called
MetaSpace.
There is a flag MaxMetaspaceSize, to limit the amount of memory used
for class metadata. If we do not specify the value for this, the Metaspace
re-sizes at run me as per the demand of the running applica on.
Parallel/Throughput GC:
Parallel garbage collector uses mul ple threads to perform the garbage
collec on. By default, on a host with N CPUs, this collector uses N
garbage collector threads for collec on. The number of collector threads
can be controlled with the command line op on: -
XX:ParallelGCThreads=<N>
It is called Throughput collector as it uses mul ple CPUs to speed up the
applica on throughput. A drawback of this collector is that it pauses the
applica on threads while performing minor or full GC, so it is best
suited for applica ons where long pauses are acceptable. It is the
default collector in JDK 8.
It can be turned on by using below 2 op ons:
-XX:+UseParallelGC
With this command line op on, you get a mul -thread young genera on
collector with a single-threaded old genera on collector. The op on also
does single-threaded compac on of old genera on.
java -Xmx12m -Xms3m -Xmn1m -XX:PermSize=20m -
XX:MaxPermSize=20m -XX:+UseParallelGC -jar C:\temp\test.jar
-XX:+UseParallelOldGC
With this op on, the GC is both a mul threaded young genera on
collector and mul threaded old genera on collector. It is also a
mul threaded compac ng collector.
Compac ng describes the act of moving objects in a way that there are
no holes between objects. A er a garbage collec on sweep, there may
be holes le between live objects. Compac ng moves objects so that
there are no remaining holes. This compac ng of memory makes it faster
to allocate new chunks of memory to the heap.
java -Xmx12m -Xms3m -Xmn1m -XX:PermSize=20m -
XX:MaxPermSize=20m -XX:+UseParallelOldGC -jar C:\temp\test.jar
G1 Garbage Collector:
The Garbage First or G1 collector is a parallel, concurrent and
incrementally compac ng low-pause garbage collector
G1 collector par ons the heap into a set of equal-sized heap regions.
When G1 performs garbage collec on then a concurrent global marking
phase is performed to determine the liveliness of objects throughout
the heap. A er this mark phase is complete, G1 knows which regions are
mostly empty. It collects unreachable objects from these regions first,
which usually yields a large amount of free space, also called Sweeping.
So G1 collects these regions (containing garbage) first, and hence the
name Garbage-First.
It can be turned on by passing -XX:+UseG1GC in the command line
op ons
java –Xmx25g –Xms5g -XX:+UseG1GC -jar C:\temp\test.jar
Java 8 has introduced one JVM parameter for reducing the unnecessary
use of memory by crea ng too many instances of the same String. This
op mizes the heap memory by removing duplicate String values to a
global single char[] array. We can use the -XX:+UseStringDeduplica on
JVM argument to enable this op miza on.
G1 is the default garbage collector in JDK 9.
Question 70: Explain Generics in Java
Answer: Java Generics provides a way to reuse the same code with
different inputs.
Advantages:
-
Generics provide compile- me type safety that allows
programmers to catch invalid types at compile me.
Before Generics:
A er Generics:
-
When using Generics, there is no need of type-cas ng.
Before Generics:
A er Generics:
-
By using generics, programmers can implement generic
algorithms that work on collec ons of different types, can be
customized and are type safe and easier to read.
Output:
Mul -threading: you will be asked many ques ons on mul -threading,
so, read as much as you can and whatever you can. Here, I am including
some of the important ques ons that are mostly asked in every
interview.
Output:
Here a Task class extends Thread class and overrides the run() method
which contains the business logic, then we make an object of this Task
and call the start() method, which starts the thread execu on. start()
method internally calls run() method .
By implemen ng Runnable interface:
ThreadTest.java:
Output:
If you see the outputs of this and previous program, you will see that
they are different, because any thread can get a chance to execute its
run() method, when the CPU resources are available.
Question 73: Which way of creating threads is better:
Thread class or Runnable interface
Answer: Implemen ng Runnable is always the preferred choice, see the
reasons below:
- As you know, Java does not allow mul ple inheritance
through classes (because of Diamond problem discussed in
Ques on 9), so if you are crea ng threads by extending
Thread class then you will not be able to extend any other
class.
- When we are working with mul -threading, we are not
looking to overwrite any exis ng func onality of Thread
class, we just want to execute the code with mul ple
threads, so in that way also, Runnable is a good choice.
- One more reason to choose Runnable is that, most people
don’t work with just Raw Threads, they use the Executor
framework that is provided from Java 5, that separates the
task from its execu on and we can execute Runnables using
execute(Runnable Task) method of Executor interface .
if these methods were in Thread class, then thread T1 must know that
another thread T2 is wai ng for this par cular resource, so T2 can be
no fied by something like T2.no fy()
But in java, the object itself is shared among all the threads, so one
thread acquires the lock on this object’s monitor, runs the code and
while releasing the lock, it calls the no fy or no fyAll method on the
object itself, so that any other thread which was wai ng on the same
object’s monitor will be no fied that now the shared resource is
available. That is why these methods are defined in the Object class.
Threads have no specific knowledge of each other. They can run
asynchronously and are independent. They do not need to know about
the status of other threads. They just need to call no fy method on an
object, so whichever thread is wai ng on that resource will be no fied.
Let’s consider this with a real-life example:
Suppose there is a petrol pump and it has a single washroom, the key of
which is kept at the service desk. This washroom is a shared resource for
all. To use this shared resource, the user must acquire the key to the
washroom lock. So, the user goes to service desk, acquires the key,
opens the door, locks it from the inside and use the facility.
Meanwhile if another user arrives at the petrol pump and wants to use
the washroom, he goes to the washroom and found that it is locked. He
goes to the service desk and the key is not there because it is with the
current user. When the current user finishes, he unlocks the door and
returns the key to the service desk. He does not bother about the
wai ng users. The service desk gives the key to wai ng user. If there are
more than one user wai ng to use the facility, then they must form a
queue.
Now, apply this analogy to Java, one user is one thread and the
washroom is the shared resource which the threads wish to execute. The
key will be synchronized keyword provided by Java, through which
thread acquires a lock for the code it wants to execute and making other
threads wait un l the current thread finishes. Java will not be as fair as
the service sta on, because any of the wai ng threads may get a chance
to acquire the lock, regardless of the order in which the threads came.
The only guarantee is that all the wai ng threads will get to use the
shared resource sooner or later.
In this example, the lock can be acquired on the key object or the service
desk and none of them is a thread. These are the objects that decide
whether the washroom is locked or not.
Output:
In the code, if you don’t write t2.join(), then current thread will not wait
from the t2 thread to die, see the output below when t2.join()
statement is commented from the code :
There are overloaded versions of join() method also,
We have 2 objects of our Hello class, one object is shared among First
and Second thread, and one object is shared among Third and Fourth
thread, and we are star ng these threads.
Output:
As you can see from the output, the First and Second thread are not
having any thread interference. Same way, Third and Fourth thread does
not have any thread interference but First and Third thread are entering
the synchronized method at the same me with their own object locks
(Hello obj1 and obj2).
Lock which is hold by First thread will only stop the Second thread from
entering the synchronized block, because they are working on the same
instance i.e. obj1, but it cannot stop Third or Fourth thread as they are
working on another instance i.e. obj2.
Output:
Let’s pass a nega ve number, so that excep on will be thrown:
Output:
FixedThreadPoolExecutor :
As its name suggests, this is an executor with a fixed number of threads.
The tasks submi ed to this executor are executed by the specified
number of threads and if there are more tasks than the number of
threads, then those tasks will be added in a queue (e.g.
LinkedBlockingQueue).
How to create a FixedThreadPoolExecutor:
ExecutorService executor = Executors.newFixedThreadPool
(5);
Here, we have created a thread pool executor of 5 threads, that means
at any given me, 5 tasks can be managed by this executor. If there are
more ac ve tasks, they will be added to a queue un l one of the 5
threads becomes free.
An important advantage of the fixed thread pool is that applica ons
using it degrade gracefully. To understand this, consider a web server
applica on where each HTTP request is handled by a separate thread. If
the applica on simply creates a new thread for every new HTTP request,
and the system receives more requests than it can handle immediately,
the applica on will suddenly stop responding to all requests when the
overhead of all those threads exceed the capacity of the system. With a
limit on the number of the threads that can be created, the applica on
will not be servicing HTTP requests as quickly as they come in, but it will
be servicing them as quickly as the system can sustain.
CachedThreadPoolExecutor :
This executor is mainly used when there are many short-lived tasks to be
executed. If you compare this with the fixed thread pool, here the
number of threads of this executor pool is not bounded. If all the
threads are busy execu ng the assigned tasks and if there is a new task,
then a new thread will be created and added to the pool. If a thread
remains idle for close to sixty seconds, it is terminated and removed
from the cache.
Use this one, if you are sure that the tasks will be short-lived, otherwise
there will be a lot of threads in the pool which will lead to performance
issues.
How to create a CachedThreadPoolExecutor:
ExecutorService executor =
Executors.newCachedThreadPool ();
ScheduledExecutor :
Use this executor, when you want to schedule your tasks, like run them
at regular intervals or run them a er a given delay. There are 2 methods
which are used for scheduling tasks: scheduleAtFixedRate and
scheduleWithFixedDelay .
How to create ScheduledExecutor:
ExecutorService executor =
Executors.newScheduledThreadPool (4);
ScheduledExecutorService interface extends the ExecutorService
interface.
Now, apart from using Executors class to create executors, you can use
ThreadPoolExecutor and ScheduledThreadPoolExecutor class also. Using
these classes, you can manually configure and fine-tune various
parameters of the executor according to your need. Let’s see at some of
those parameters:
BlockingQueue:
The queue to use for holding tasks before they are executed. This queue
will hold only the Runnable tasks submi ed by the execute method, you
can use a ArrayBlockingQueue or LinkedBlockingQueue like:
BlockingQueue<Runnable> queue = new
ArrayBlockingQueue<>(100);
ThreadFactory:
The factory to use when the executor creates a new thread. Using thread
factories removes hardwiring of calls to new Thread , enabling
applica ons to use special thread subclasses, priori es, etc.
RejectedExecu onHandler:
This handler is used when a task is rejected by the executor because all
the threads are busy and the queue is full.
When this handler is not provided and the task submi ed to execute()
method is rejected, then an unchecked RejectedExecu onExcep on is
thrown.
But adding a handler is a good prac ce to follow, there is a method:
void rejectedExecution(Runnable r , ThreadPoolExecutor
executor );
This method will be invoked by ThreadPoolExecutor when execute()
cannot accept a task.
Pu ng it all together:
Question 89: Tell something about awaitTermination()
method in executor
Answer: This method blocks un l all tasks have completed execu on
a er a shutdown request, or the meout occurs, or the current thread is
interrupted, whichever happens first.
CountDownLatch can also be used to start mul ple threads at the same
me, you can create a CountDownLatch of size 1, make all the other
threads wait by calling countDownLatch.await(), then a single call to
countDownLatch.countDown() method will resume execu on for all the
wai ng threads at the same me.
CountDownLatch cannot be reused once the count reaches to zero,
therefore in those scenarios, CyclicBarrier is used.
As, you can see, the output is as expected because only one thread is
accessing the count, let’s see what will happen in case the count
variable is accessed by more than one thread, un-comment the code
regarding second thread t2 and run the main class:
Output:
The expected output was 100 but we got a different output, if you run
the above program you will see a different output and it will be
anywhere between 50 and 100. The reason for this is that 2 threads are
accessing a mutable variable without any synchroniza on. One solu on
that will be coming to your mind will be using synchroniza on block,
and yes this problem can be solved using that but it will have a
performance impact, as threads will acquire the lock, update the value
and release the lock, and then giving other threads access to the shared
mutable variable.
But java has provided Atomic wrapper classes for this purpose that can
be used to achieve this atomic opera on without using Synchroniza on.
Let’s see the change in our Runnable:
Output:
Question 94: What is Collection Framework?
Answer: Collec on framework represents an architecture to store and
manipulate a group of objects. All the classes and interfaces of this
framework are present in java.u l package.
Some points:
Output:
Question 100: How to make an ArrayList as Immutable
Answer: This is also a common interview ques on nowadays. If your
answer is making the list as “final” then see the code below:
Program 1:
Output:
Although, we have made the list as final but s ll we are able to add
elements into it, remember applying final keyword to a reference
variable ensures that it will not be referenced again meaning you cannot
give a new reference to list variable:
So, to make the list as unmodifiable, there is a method
unmodifiableList() in Collec ons u lity class,
Program 2:
Output:
Here, if you assign Collec ons.unmodifiableList (list); to a new reference
then you will be able to change the original list which will in turn change
the new list also, see below:
Program 3:
Output:
Guava library also provides certain ways to make immutable list and
Java 9 has List.of() method.
There are other u lity methods also, to make unmodifiable collec ons:
Load factor:
/**
* The load factor used when none specified in
constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
Node class:
static class Node<K,V> implements Map.Entry<K,V> {
final int hash ;
final K key ;
V value ;
Node<K,V> next ;
Node(int hash , K key , V value , Node<K,V> next ) {
this .hash = hash ;
this .key = key ;
this .value = value ;
this .next = next ;
}
Output:
Change the for loop condi on from i<13 to i<=13, see below:
Output:
Here, Employee class has not given equals() and hashCode() method
implementa on, so Object’s class equals() and hashCode() methods will
be used when we use this Employee class as hashmap’s key, and
remember, equals() method of Object class compares the reference.
TestHashMap.java:
Can you predict the output of this one?
Output:
Here, Employee objects e1 and e2 are same but they are both inserted
in the HashMap because both are created using new keyword and
holding a different reference, and as the Object’s equals() method
checks reference, they both are unique.
And as for objects e3 and e4, they both are poin ng to same reference
(e4 = e3), so they are equal according to Object’s equals() method hence
the value of e3 which was 300 gets replaced with the value 400 of the
same key e4, and finally size of HashMap is 3.
Well, nothing’s changed here. Because even though e1 and e2 are equal
according to our newly implemented equals() method, they s ll have
different hashCode as the Object’s class hashCode() is used. So the
equals and hashCode contract is not followed and both e1, e2 got
inserted in HashMap.
NOTE: If you are adding a custom class object inside the HashSet, do
follow equals and hashCode contract. You can be asked the equals and
hashCode scenarios ques ons, just like we discussed in HashMap
(Ques on 105).
Program 3:
Here, we are sor ng based on Employee name,
Output:
TreeSet Javadoc:
public class TreeSet<E> extends AbstractSet<E>
implements NavigableSet<E>, Cloneable,
java.io.Serializable
public TreeSet() {
this (new TreeMap<E,Object>());
}
But they don’t throw the excep on, if the collec on is modified by
Iterator’s remove() method.
Program 2:
Output:
Javadoc:
arrayList.iterator() method:
public Iterator<E> iterator() {
return new Itr();
}
Itr is a private nested class in ArrayList:
private class Itr implements Iterator<E> {
int cursor ; // index of next element to return
int lastRet = -1; // index of last element returned;
-1 if no such
int expectedModCount = modCount ;
Itr() {}
public boolean hasNext() {
return cursor != size ;
}
Itr.next() method:
@SuppressWarnings ("unchecked" )
public E next() {
checkForComodification();
int i = cursor ;
if (i >= size )
throw new NoSuchElementException();
Object[] elementData = ArrayList.this .elementData ;
if (i >= elementData .length )
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData [lastRet = i ];
}
Output:
Here, iterator is reflec ng the element which was added during the
itera on opera on.
- By Constructor
- By Se er
method
Constructor-based DI : when the required dependencies are provided as
arguments to the constructor, then it is known as constructor-based
dependency injec on, see the examples below:
Using XML based configura on:
Injec ng a dependency is done through the bean-configura on file, for
this <constructor-arg> xml tag is used:
Java class A:
Java class B:
Using Java based configura on:
The se er method needs to be annotated with @Autowired annota on.
There is also a Field injec on, where Spring injects the required
dependencies directly into the fields when those fields are annotated
with @Autowired annota on.
You can give any name to your ini aliza on and destroy methods, and
here is our Test class
By implemen ng Ini alizingBean and DisposableBean interfaces
Ini alizingBean interface has a erProper esSet() method which can be
used to execute some ini aliza on task for a bean and DisposableBean
interface has a destroy() method which can be used to execute some
cleanup task.
Here is our Test class,
And, in the xml file:
Spring uses CGLIB to create the proxy object and the proxy object
delegates method calls to the real object. In the above example, we are
using ScopedProxyMode.TARGET_CLASS which causes an AOP proxy to be
injected at the target injec on point. The default Proxy mode is
ScopedProxyMode.NO .
To avoid CGLIB usage, configure the proxy mode with
ScopedProxyMode.INTERFACES and it will use JDK dynamic proxy.
When you add the exclusion tag and save the pom.xml, you will see that
the tomcat dependency will be removed from Maven Dependencies,
then you can add another server’s dependency like the one below:
There are similar shortcut annota ons present for PUT, PATCH, DELETE
requests too.
Now, to resolve this you can give names to your Rectangle and Circle
class, like:
And you will use @Qualifier annota on to specify which bean should be
autowired, like:
Now, Spring will not get confused as to what bean it has to autowire.
NOTE , you can also use @Qualifier annota on to give names to your
Rectangle and Circle classes, like
- When using @Bean, you have the control over the bean
crea on logic.
- @Bean is a method level annota on, the body of the method
contains the logic for crea ng the bean instance and this
method returns the instance which will be registered in the
spring applica on context.
- Using @Bean, you can register the classes from 3rd party
libraries into the applica on context
- @Bean annota on is usually declared in configura on classes.
spring.profiles.active=uat
We can also set a par cular profile to be ac ve by passing it as a VM
argument, Maven se ngs, JVM system parameters, environment
variables. In xml, we use <beans profile=”uat”> to ac vate a profile.
There is one @Profile annota on which when applied to a component
tells that this component will be created only when a par cular profile is
set.
In this example, we are consuming a GET web service and conver ng the
response to the object of User class.
Similarly, there are other methods to consume POST, DELETE web
services like exchange() and delete() respec vely.
AOP terminology :
Aspect : Aspect is a class that implements the applica on concerns that
cuts across mul ple classes, such as transac on management and
logging. Aspects can be a normal class configured through Spring XML
configura on or we can use @Aspect annota on.
Join Point : a point during the execu on of a program, such as the
execu on of a method or the handling of an excep on. In Spring AOP, a
join point always represents a method execu on.
Advice : advices are ac ons that are taken for a par cular join point.
There are different types of advices, like, before, a er and around
advice.
Pointcut : pointcut is an expression that is matched with join points to
determine whether advice needs to be applied or not.
Target Object : objects on which advices are applied by one or more
aspects. Since Spring AOP is implemented using run me proxies, this
object will always be a proxied object.
AOP Proxy : an object created by the AOP framework in order to
implement the aspect contracts (advise method execu ons and so on).
In the Spring Framework, an AOP proxy will be a JDK dynamic proxy or a
CGLIB proxy.
Weaving : It is the process of linking aspects with other objects to create
the advised proxy objects. This can be done at compile me, load me
or at run me. Spring AOP performs weaving at the run me.
- SOAP stands for Simple Object Access Protocol and REST stands
for Representa onal State Transfer
- SOAP is a protocol whereas REST is an architectural style
- SOAP cannot use REST because it is a protocol whereas REST
can use SOAP web services as the underlying protocol, because
it is just an architectural pa ern
- SOAP uses service interfaces to expose its func onality to client
applica ons whereas REST uses URI to expose its func onality
- SOAP defines standards that needs to be strictly followed for
communica on to happen between client and server whereas
REST does not follow any strict standard
- SOAP requires more bandwidth and resources than REST
because SOAP messages contain a lot of informa on whereas
REST requires less bandwidth than SOAP because REST
messages mostly just contains a simple JSON message
- SOAP only works with XML format whereas REST allows
different data formats like Plain text, HTML, XML, JSON etc.
- SOAP defines its own security whereas REST inherits the
security
All the above topics are advanced but I will explain about them a li le,
so you can go out and read more about it.
Question 181: How can we see the SQL query that gets
generated by Hibernate?
Answer: If you are using hibernate.cfg.xml file, then use the below
property:
spring.jpa.hibernate.ddl-auto=update
Maven
Question 184: What is Maven?
Answer: Maven is a tool that is used for building and managing any Java
based project. It is a powerful project management tool that is based on
POM (Project Object Model). It simplifies the build process.
1. Inner join : Inner join selects all records from Table A and
Table B, where the join condi on is met.
Syntax:
SELECT Table1.column1, Table1.column2, Table2.column1, …..
FROM Table1
INNER JOIN Table2
On Table1.MatchingColumnName = Table2.MatchColumnName;
(Note: Use either INNER JOIN or JOIN for this opera on)
2. Le Join : Le join selects all records from Table A along with
records of Table B for which the join condi on is met.
Syntax:
SELECT Table1.column1, Table1.column2, Table2.column1, …..
FROM Table1
LEFT JOIN Table2
On Table1.MatchingColumnName = Table2.MatchColumnName;
3. Right Join : Right join selects all records from Table B along
with records of Table A for which the join condi on is met.
Syntax:
SELECT Table1.column1, Table1.column2, Table2.column1, …..
FROM Table1
RIGHT JOIN Table2
On Table1.MatchingColumnName = Table2.MatchColumnName;
4. Full Join : Full join selects all records from Table A and Table
B, regardless of whether the join condi on is met or not.
Syntax:
SELECT Table1.column1, Table1.column2, Table2.column1, …..
FROM Table1
FULL JOIN Table2
On Table1.MatchingColumnName = Table2.MatchColumnName;
Other than these common ques ons, you can be asked to write a lot of
queries which mostly contains Joins, so you should also prepare for
those types of database queries.
Question 201: Find first 3 largest numbers in an array
In this ques on, the interviewer will most probably ask you to not use
sor ng and pick the first/last 3 numbers from the array. Instead he will
ask you to use one “for loop” to solve this problem.
Output:
-9 -2 -15 -3 1 7 12 5 2
Here, the idea is to iterate through the array and when a nega ve
number is found, then bring that number to the beginning of the array
by swapping it with the first posi ve number.
As you can see that the output is not maintaining the original sequence
of array elements.
Now, let’s take a look at the solu on which maintains the element
sequence:
Output:
-9 -2 -15 -3 5 1 7 12 2
There are many programma c, puzzle problems that the interviewer can
ask. If you are a beginner, then prepare for programs like Palindrome,
Fibonacci, Array problems, String problems, Linked list programs etc.
First, try to solve them with whatever brute-force solu on that comes to
your mind, then try to find its me and space complexity, then try to
op mize it. If you are not able to think of a be er solu on, no problem,
look for the op mal solu on on the internet.
About the Author
Ja n Arora is a Computer Science graduate. He holds an exper se in Java
& SpringBoot. He has worked on a variety of interes ng projects across
different domains like Inventory management, DevOps, cloud & financial
domain.