Jatin Arora - Grokking The Java Interview
Jatin Arora - Grokking The Java Interview
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 transmitted in any form or by any means,
including photocopying, recording or other electronic or
mechanical methods, without the prior written permission of
the author, except in the case of brief quotations embodied in
critical reviews and certain other non-commercial uses
permitted by copyright law.
For permission or any other information, contact me at:
[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 questions that are frequently asked during an
interview for Java, Spring, SpringBoot & Hibernate profile. Some of the
important topics like Multi-threading, Collection framework, Singleton
Pattern, SpringBoot Annotations 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.
Who is this book for?
This book is for you if you are either preparing for an interview, planning to
move into this field in future, brushing up your Java & Spring skills or just
want to get an in-depth overview of the field. This book provides the most
important and frequently asked questions along with their solutions.
Who is this book NOT for?
This book is not for you if you are looking for an in-depth study of Java or
Spring. The objective of this book is not to discuss the ongoing research or
challenges in this industry or serve as a substitute for a course book.
If you follow this book diligently, you would be better equipped to face any
Java interview. Whether you are a beginner or an intermediate level expert
in Java, this book has enough juice for you.
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:
https://github.com/reachjatin/Grokking-The-Java-Developer-Interview
Contact Information
I would love to hear from you.
For feedback or queries, you can contact me at
[email protected]
Your valuable suggestions 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 :)
-Jatin Arora
Acknowledgements
I thank my brother, Sumit Kumar, for encouraging me to take up this
project. From reading early drafts to advising me on the structure of
the book to making sure that it was written in a manner that was
coherent, organized and engaging at the same time, his role has
been pivotal in the making of this book.
To elaborate a little on his background, Sumit is an UChicago Alum,
and presently working for Amazon, Seattle as a Research Scientist
at Alexa AI. He has also worked with Samsung, India as a Lead
Engineer. He is an active blogger and regularly post articles on Data
structures and Algorithms, System Design, NLP and many more
interesting topics. You can find those at:
https://medium.com/@sumit.arora
https://blog.reachsumit.com
-Jatin Arora
Table of Content s
Preface
Acknowledgements
Question 1: What are the 4 pillars of OOPS?
Question 2: What is an abstract class?
Question 3: Does Abstract class have constructor?
Question 4: What is an Interface?
Question 5: Difference between abstract class and interface
Question 6: What to choose – interface or abstract class
Question 7: Why Java 8 has introduced default methods?
Question 8: Why Java 8 has introduced static methods?
Question 9: Why Java does not allow multiple inheritance?
Question 10: What are the rules for Method Overloading and Method
Overriding?
Question 11: Can we override final methods?
Question 12: Can constructors and private methods be overridden?
Question 13: What is final keyword and where it can be used?
Question 14: What is exception and exception handling?
Question 15: Difference between error and exception
Question 16: What are the different types of exceptions?
Question 17: How exception handling is done in java?
Question 18: Can we write a try block without catch block?
Question 19: How to handle multiple exceptions together?
Question 20: When finally block will not get executed
Question 21: Difference between throw and throws keyword. And discuss
Exception Propagation
Question 22: Exception handling w.r.t. method overriding
Question 23: Programs related to Exception handling and return keyword
Question 24: How to make your own custom exception class?
Question 25: How to make custom checked / unchecked exception?
Question 26: What happens when you throw an exception from finally
block?
Question 27: What will be Output of below program related to try-catch-
finally?
Question 28: Explain try-with-resources
Question 29: Why String is Immutable?
Question 30: What does the equals() method of String class do?
Question 31: Explain StringBuffer and StringBuilder
Question 32: Explain the output of below program related to equals()
method of StringBuilder
Question 33: When to use String/StringBuffer/StringBuilder
Question 34: Explain equals and hashcode contract
Question 35: What is Marker Interface?
Question 36: Can you write your own custom Marker interface?
Question 37: What is Comparable and Comparator?
Question 38: How to compare a list of Employees based on name and age
such that if name of the employee is same then sorting should be based on
age
Question 39: Difference between Comparable and Comparator
Question 40: Different methods of Object class
Question 41: What type of arguments are allowed in System.out.println()
method?
Question 42: Explain System.out.println() statement
Question 43: Explain Auto-boxing and Un-boxing
Question 44: Find the output of below program
Question 45: Can you pass primitive long value in switch statement?
Question 46: Explain static keyword in Java
Question 47: What is an Inner Class in Java, how it can be instantiated and
what are the types of Inner Classes?
Question 48: What is Constructor Chaining in java?
Question 49: What is init block?
Question 50: What is called first, constructor or init block?
Question 51: What is Variable shadowing and Variable hiding in Java?
Question 52: What is a constant and how we create constants in Java?
Question 53: Explain enum
Question 54: What is Cloneable?
Question 55: What is Shallow Copy and Deep Copy?
Question 56: What is Serialization and De-serialization?
Question 57: What is SerialVersionUID?
Question 58: Serialization scenarios with Inheritance
Question 59: Stopping Serialization and De-serialization
Question 60: What is Externalizable Interface?
Question 61: Externalizable with Inheritance
Question 62: Difference between Serializable and Externalizable
Question 63: How to make a class Immutable?
Question 64: Explain Class loaders in Java
Question 65: What is Singleton Design Pattern and how it can be
implemented?
Question 66: What are the different ways in which a Singleton Design
pattern can break and how to prevent that from happening?
Question 67: What are the different design patterns you have used in your
projects?
Question 68: Explain Volatile keyword in java
Question 69: What is Garbage Collection in Java, how it works and what
are the different types of Garbage Collectors?
Question 70: Explain Generics in Java
Question 71: What is Multi-threading?
Question 72: How to create a thread in Java?
Question 73: Which way of creating threads is better: Thread class or
Runnable interface
Question 74: What will happen if I directly call the run() method and not
the start() method to execute a thread
Question 75: Once a thread has been started can it be started again
Question 76: Why wait, notify and notifyAll methods are defined in the
Object class instead of Thread class
Question 77: Why wait(), notify(), notifyAll() methods must be called from
synchronized block
Question 78: difference between wait() and sleep() method
Question 79: join() method
Question 80: yield() method
Question 81: Tell something about synchronized keyword
Question 82: What is static synchronization?
Question 83: What will be output of below program where one
synchronized method is calling another synchronized method?
Question 84: Programs related to synchronized and static synchronized
methods
Question 85: What is Callable Interface?
Question 86: How to convert a Runnable to Callable
Question 87: Difference between Runnable and Callable
Question 88: What is Executor Framework in Java, its different types and
how to create these executors?
Question 89: Tell something about awaitTermination() method in executor
Question 90: Difference between shutdown() and shutdownNow() methods
of executor
Question 91: What is Count down latch in Java?
Question 92: What is Cyclic Barrier?
Question 93: Atomic classes
Question 94: What is Collection Framework?
Question 95: What is Collections?
Question 96: What is ArrayList?
Question 97: What is default size of ArrayList?
Question 98: Which data structure is used internally in an ArrayList?
Question 99: How add() method works internally or How the ArrayList
grows at runtime
Question 100: How to make an ArrayList as Immutable
Question 101: What is LinkedList?
Question 102: When to use ArrayList / LinkedList
Question 103: What is HashMap?
Question 104: Explain the internal working of put() and get() methods of
HashMap class and discuss HashMap collisions
Question 105: equals and hashCode method scenarios in HashMap when
the key is a custom class
Question 106: How to make a HashMap synchronized?
Question 107: What is Concurrent HashMap?
Question 108: What is HashSet class and how it works internally?
Question 109: Explain Java’s TreeMap
Question 110: Explain Java’s TreeSet
Question 111: Difference between fail-safe and fail-fast iterators
Question 112: Difference between Iterator and ListIterator
Question 113: Difference between Iterator.remove and Collection.remove()
Question 114: What is the difference between a Monolith and Micro-
service architecture?
Question 115: What is Dependency Injection in Spring?
Question 116: What are the different types of Dependency Injection?
Question 117: Difference between Constructor and Setter injection
Question 118: What is @Autowired annotation?
Question 119: What is the difference between BeanFactory and
ApplicationContext?
Question 120: Explain the life-cycle of a Spring Bean
Question 121: What are the different scopes of a Bean?
Question 122: What is the Default scope of a bean?
Question 123: What happens when we inject a prototype scope bean in a
singleton scope bean?
Question 124: How to inject a prototype scope bean in a singleton scope
bean?
Question 125: Explain Spring MVC flow
Question 126: What is the difference between <context:annotation-config>
and <context:component-scan>?
Question 127: What is the difference between Spring and SpringBoot?
Question 128: What is auto-configuration in SpringBoot?
Question 129: What are SpringBoot starters?
Question 130: What is @SpringBootApplication Annotation?
Question 131: Where does a Spring Boot application start from?
Question 132: How to remove certain classes from getting auto-configured
in SpringBoot?
Question 133: How to autowire a class which is in a package other than
SpringBoot application class’s package or any of its sub-packages
Question 134: What is application.properties file in a SpringBoot
application?
Question 135: How to configure the port number of a SpringBoot
application?
Question 136: Which jar builds our springboot application automatically
whenever we change some code just like a node.js application?
Question 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
Question 138: Where should we put our html and javascript files in a spring
boot application?
Question 139: What are the different stereotype annotations?
Question 140: Difference between @Component, @Controller, @Service,
@Repository annotations?
Question 141: Difference between @Controller and @RestController
annotation
Question 142: What is @RequestMapping and @RequestParam
annotation?
Question 143: How to define a Get or Post endpoint?
Question 144: Which annotation is used for binding the incoming json
request to the defined pojo class?
Question 145: What is @Qualifier annotation?
Question 146: What is @Transactional annotation?
Question 147: What is @ControllerAdvice annotation?
Question 148: What is @Bean annotation?
Question 149: Difference between @Component and @Bean
Question 150: How to do profiling in a SpringBoot application
Question 151: What is RestTemplate?
Question 152: What is Spring Data JPA?
Question 153: What is the difference between JPARepository,
CRUDRepository, PagingAndSortingRepository and which one you have
used in your applications?
Question 154: What is Spring AOP?
Question 155: Have you used Spring Security in your application
Question 156: What do you know about Spring Batch framework?
Question 157: Difference between SOAP and REST
Question 158: What is Restful api?
Question 159: What is a stateless object?
Question 160: What is the difference between Web Server and Application
Server?
Question 161: What do you know about CommandLineRunner and
ApplicationRunner?
Question 162: What do you know about Eureka Naming Server?
Question 163: What do you know about Zuul?
Question 164: What do you know about Zipkin?
Question 165: What do you know about Hysterix?
Question 166: What is JPA?
Question 167: What is Hibernate?
Question 168: Difference between JPA and Hibernate
Question 169: What is @Entity?
Question 170: How to give a name to a table in JPA?
Question 171: What is @Id, @GeneratedValue?
Question 172: How to use a custom database sequence in Hibernate to
generate primary key values?
Question 173: How to give names to the columns of a JPA Entity
Question 174: How to define a @OneToMany relationship between entities
Question 175: Why annotations should be imported from JPA and not from
Hibernate?
Question 176: What is the difference between get() and load() method of
Hibernate Session?
Question 177: What is the difference between save(), saveOrUpdate() and
persist() method of Hibernate Session?
Question 178: What is Session and SessionFactory in Hibernate?
Question 179: What is First Level and Second Level Cache in Hibernate?
Question 180: What is session.flush() method in Hibernate?
Question 181: How can we see the SQL query that gets generated by
Hibernate?
Question 182: What is Hibernate Dialect and why we need to configure it?
Question 183: What do you know about hibernate.hbm2ddl.auto property
in Hibernate?
Question 184: What is Maven?
Question 185: What is pom.xml?
Question 186: What is local repo and central repo?
Question 187: Where we define our local repo path?
Question 188: Where do we define proxies so that maven can download
jars from the internet in a corporate environment?
Question 189: Explain Maven build life-cycle
Question 190: What do you know about SQL Joins?
Question 191: Difference between TRUNCATE & DELETE statements
Question 192: Difference between Function and Stored Procedure
Question 193: What is DDL, DML statements?
Question 194: How to find the nth highest salary from Employee table
Question 195: Difference between UNION and UNION ALL commands in
SQL
Question 196: Difference between Unique Key and Primary Key in SQL
Question 197: What is the difference between Primary and Foreign key in
SQL?
Question 198: What is the difference between clustered and non-clustered
index?
Question 199: What is the difference between WHERE and HAVING
clause in SQL
Question 200: How to change the gender column value from Male to
Female and Female to Male using single Update statement
Question 201: Find first 3 largest numbers in an array
Question 202: Move all negative numbers at the beginning of an array and
all positive numbers at the end
About the Author
Question 1: What are the 4 pillars of OOPS?
Answer: 4 pillars of OOPS are:
1. Abstraction
2. Encapsulation
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 relationship 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.
Output:
Example 2:
Output:
Question 4: What is an Interface?
Answer:
- An interface in Java is a blueprint of a class. It has static
constants and abstract methods.
- Interface specify what a class must do but not how to do
- An interface is like defining a contract that is fulfilled by
implementing classes
- An interface is used to achieve full abstraction.
- All methods in an interface are public and abstract by
default and all variables declared in an interface are
constants i.e. public, static and final
- A class which implements an interface will have to
provide implementation of all the methods that are
defined in the interface
- A class can implement more than one interface, this is
how Java allows multiple inheritance.
- Since Java 8, we can have default and static methods in
an interface
Output:
Question 8: Why Java 8 has introduced static
methods?
Answer: Consider an example where you want to define a utility
class, what you usually do is you define a class which contains static
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 static methods inside your interface. This way of using
Interface for defining utility classes is better as it helps in
performance also, because using a class is more expensive
operation 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 application and the
program gets terminated in case of error occurrence e.g. running out
of memory: OutOfMemoryError , making too many recursive calls:
StackOverflowError etc.
Exception : Exceptions 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: NullPointerException , dividing
an integer by zero: ArithmeticException etc.
Output:
Output:
throws can be used with unchecked exceptions also, though it is of
no use because unchecked exceptions are by default propagated.
See this in the below program:
Output:
One thing you should remember is, if you write anything after return
statement / throw exception statement, then that will give Compile
time error as ‘Unreachable code’.
Program 1:
C:\Users\jjatin\Desktop\Different
Versions\All_Photos\Question 23\Problem1\color.png
C:\Users\jjatin\De
sktop\Different
Versions\All_Photo
s\Question
23\Problem1\error.
png
C:
Program 4 :
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
23\Problem4\color.png
Output:
Program 5 :
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
23\Problem5\color.png
Output:
SalaryComparator.java :
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
37\Comparator Example\SalaryComparator\color1.png
ComparatorDemo.java :
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
37\Comparator Example\SalaryComparator\color2.png
Output:
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
37\Comparator Example\SalaryComparator\output.png
Question 38: How to compare a list of Employees
based on name and age such that if name of the
employee is same then sorting should be based on
age
Answer: When comparing by name, if both names are same, then
comparison will give 0. If the compare result is 0, we will compare
based on age.
NameAgeComparator.java :
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
38\color1.png
ComparatorDemo.java :
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
38\color2.png
Output:
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
38\output.png
Question 39: Difference between Comparable and
Comparator
Answer:
- Comparable interface can be used to provide single way
of sorting whereas Comparator interface is used to
provide multiple ways of sorting
- Comparable interface is present in ‘java.lang’ package
whereas Comparator interface is present in ‘java.util’
package
- For using Comparable, the class needs to implement
Comparable interface whereas for using Comparator,
there is no need to make changes in the class
- Comparable provides compareTo() method to sort
elements, whereas Comparator provides compare()
method to sort elements
- We can sort the list elements of Comparable type by
using Collections.sort(listObj) method, whereas to sort
the list elements of Comparator type, we have to provide
a Comparator object like, Collections.sort(listObj,
Comparator)
At times, when you are using any third-party classes or the classes
where you are not the author of the class, then in that case
Comparator is the only choice to sort those objects
Example:
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
47\Inner Class instantiation\color1.png
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
47\Inner Class instantiation\color2.png
Output:
C:\Users\jjatin\
Desktop\Differe
nt
Versions\All_Ph
otos\Question
47\Inner Class
instantiation\out
put.png
Compile time error when static variable and static method is present
in Inner class:
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
47\Compile time error when Inner Class have static fields\color.png
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
47\Compile time error when Inner Class have static fields\error.png
There are 2 special types of Inner Classes:
- local inner class
- anonymous inner class
local inner class : Local Inner Classes are the inner classes that
are defined inside a block. Generally, this block is a method body.
Sometimes this block can be a for loop , or an if clause. Local Inner
classes are not a member of any enclosing classes. They belong to
the block in which they are defined in, due to which local inner
classes cannot have any access modifiers associated with them.
However, they can be marked as final or abstract. These classes
have access to the fields of the class enclosing it. Local inner class
must be instantiated in the block they are defined in.
Points to remember:
- local inner class cannot be instantiated from outside of
the block where they are defined
- local inner class has access to the members of the
enclosing class
- till Java 1.7, local inner class can access only final local
variable of the enclosing block where they are defined.
But from Java 1.8 onwards, it is possible to access the
non-final local variable of the enclosing block
- the scope of local inner class is restricted to the block
where they are defined
- A local inner class can extend an abstract class or can
implement an interface
Example:
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
47\local inner class\Example1\color1.png
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
47\local inner class\Example1\color2.png
Output:
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
47\local inner class\Example1\output.png
Remember, you can only access the block level variables, and
cannot change them. You will get compile time error if you try to
change them:
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
47\local inner class\Compile time error\color.png
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
47\local inner class\Compile time error\error.png
A variable whose value is not changed once initialized is called as
effectively final variable .
When to use :
Example 1 : Let’s understand this by an example, Suppose you are
want to return a list of employee class objects and they should be
sorted based on employee name, now for this you can write a
comparator in a separate class and pass its object inside the
Collections.sort(list, comparatorObject)
Instead, you can use the anonymous inner class and you don’t have
to create a new class just for writing a comparator that you are not
going to use later on.
Program:
Employee.java :
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
47\anonymous inner class\Example 1\color1.png
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
47\anonymous inner class\Example 1\color2.png
AnonymousInnerDemo.java :
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
47\anonymous inner class\Example 1\color3.png
Output:
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
47\anonymous inner class\Example 1\output.png
Example 2 : Using anonymous inner class, you can implement a
Runnable also
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
47\anonymous inner class\Example 2\color.png
Output:
C:\Users\jj
atin\Desktop
\Different
Versions\All_
Photos\Ques
tion
47\anonymo
i
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:
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
51\Variable Hiding\Example 1\color1.png
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
51\Variable Hiding\Example 1\color2.png
Output:
C:\Use
rs\jjatin\
Desktop\
Different
Versions
If you want to access parent’s class variable then you can do this
using super keyword:
Example 2:
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
51\Variable Hiding\Example 2\color1.png
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
51\Variable Hiding\Example 2\color2.png
Output:
C:\Users\
jjatin\Deskt
op\Differen
t
Versions\Al
l_Photos\Q
uestion
Deep Copy : in Deep copy, the non-primitive types are also cloned
to make the original and cloned object fully independent of each
other.
Program 1:
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
55\Program 1\color1.png
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
55\Program 1\color2.png
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
55\Program 1\color3.png
Output:
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
55\Program 1\output.png
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:
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
55\Program 2\color1.png
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
55\Program 2\color2.png
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
55\Program 2\color3.png
Output:
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
55\Program 2\output.png
There are 2 other methods by which you can perform deep copy:
- By using Serialization, 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
SerializationUtils.clone() method for performing deep
copy on an object. It expects all classes in the hierarchy
to implement Serializable interfaces else
SerializableException is thrown by the system
ExternalizableDemo.java:
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
61\Case 1\color7.png
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
61\Case 1\color8.png
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
61\Case 1\color9.png
Output:
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
61\Case 1\output.png
The capacity and age variable values are 0 because we did not
serialize these two variables.
ExternalizableDemo.java:
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
61\Case 2\color6.png
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
61\Case 2\color7.png
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
61\Case 2\color8.png
Output:
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
61\Case 2\output.png
Question 62: Difference between Serializable and
Externalizable
Answer:
- Serializable is a marker interface which means it does
not contain any method whereas Externalizable is a
child interface of Serializable and it contains two
methods writeExternal() and readExternal()
- When using Serializable, JVM takes full responsibility for
serializing the class object but in case of Externalizable,
the programmer has full control over serialization logic
- Serializable interface is a better fit when we want to
serialize the entire object whereas Externalizable is
better suited for custom serialization
- Default serialization is easy to implement but it comes
with some issues and performance cost whereas in case
of Externalizable, the programmer has to provide the
complete serialization logic which is a little hard but
results in better performance
- Default serialization does not call any constructor
whereas a public no-arg constructor is needed when
using Externalizable interface
- When a class implements Serializable interface, it gets
tied with default serialization which can easily break if
structure of the class changes like adding/removing any
variable whereas using Externalizable, you can create
your own binary format for your object
Output:
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
63\output.png
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 getter method:
Employee.java:
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
63\Wrong Implementation\color1.png
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
63\Wrong Implementation\color2.png
Now, if we run our TestImmutable.java class, below is the output:
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
63\Wrong Implementation\output.png
Why we perform deep copy in constructor:
- When you assign the actual address object in the
constructor, then remember it is storing the reference of
address object, so if you change the value in this
address object, it will reflect in the employee object
Why we don’t return original reference from the getter:
-
When you return the original address object from the getter
method then you can use the returned object reference to
change the values in employee object
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 ‘volatile’ keyword with the above approach like below:
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
65\double checked locking using volatile\color.png
localRef variable is there for the cases where instance is already
initialized (discussed above), the volatile field is only accessed once
because we have written return localRef not return instance .
There is another approach where an inner static 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
Implementation .
Bill Pugh Singleton Implementation Program:
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
65\Bill Pugh Singleton Implementation\color.png
The inner class does not get loaded at the time of class A loading,
only when someone calls getInstance() method, it gets loaded and
creates the Singleton instance.
Test.java:
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
66\Reflection\Break Singleton\color2.png
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
66\Reflection\Break Singleton\color3.png
Output:
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
66\Reflection\Break Singleton\output.png
As we can see from the output, the 2 instances have different
hashcode, thus destroying Singleton.
Now to prevent Singleton from Reflection, one simple solution is to
throw an exception from the private constructor, so when Reflection
tries to invoke private constructor, there will be an error.
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
66\Reflection\Prevent Singleton_Solution 1\color.png
Now, if you run Test.java , you will get below output:
The other solution to prevent Singleton from Reflection is using
Enums , as its constructor cannot be accessed via Reflection, JVM
internally handles the creation and invocation of enum constructor
SingletonEnum.java:
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
66\Reflection\Prevent Singleton_Solution 2\color1.png
TestSingletonEnum.java:
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
66\Reflection\Prevent Singleton_Solution 2\color2.png
Output:
C:\Users\jjatin\Desktop\Different
Versions\All_Photos\Question
66\Reflection\Prevent
Singleton_Solution 2\output.png
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 pattern.
See the program below:
TestSingleton.java:
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
66\Cloning\Break Singleton\color1.png
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
66\Cloning\Break Singleton\color2.png
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
66\Cloning\Break Singleton\color3.png
Output:
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
66\Cloning\Break Singleton\output.png
As you can see, both instances have different hashcodes indicating
our Singleton pattern is broken, so to prevent this we can override
clone method in our Singleton class and either return the same
instance or throw CloneNotSupportedException from it.
See the program changes below:
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
66\Cloning\Prevent Singleton by Throwing Exception\color.png
Output:
clone() returning the same instance, see the program changes
below:
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
66\Cloning\Prevent Singleton by Returning Same Instance\color.png
Output:
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
66\Cloning\Prevent Singleton by Returning Same
Instance\output.png
Question 67: What are the different design patterns
you have used in your projects?
Answer: You will be asked this question almost in all interviews
nowadays. So, be prepared with some design patterns that are used
in mostly all projects, like:
- Factory Design Pattern
- Abstract Factory Design
Pattern
- Strategy Design Pattern
- Builder Design Pattern
- Singleton Design Pattern
- Observer Design Pattern
And any other if you have used in your projects.
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 modification.
So, to prevent data inconsistency, we can make variable x as
volatile:
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
68\color2.png
Now, all the threads will read and write the variable x from/to the
main memory. Using volatile, also prevents compiler from doing any
reordering or any optimization 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 generation is included in a full garbage collection. And
Perm Gen was available till Java 7, it is removed from Java 8
onwards and JVM uses native memory for the representation 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 runtime as per the demand of the running
application.
Parallel/Throughput GC:
Parallel garbage collector uses multiple threads to perform the
garbage collection. By default, on a host with N CPUs, this collector
uses N garbage collector threads for collection. The number of
collector threads can be controlled with the command line option: -
XX:ParallelGCThreads=<N>
It is called Throughput collector as it uses multiple CPUs to speed up
the application throughput. A drawback of this collector is that it
pauses the application threads while performing minor or full GC, so
it is best suited for applications where long pauses are acceptable. It
is the default collector in JDK 8.
It can be turned on by using below 2 options:
-XX:+UseParallelGC
With this command line option, you get a multi-thread young
generation collector with a single-threaded old generation collector.
The option also does single-threaded compaction of old generation.
java -Xmx12m -Xms3m -Xmn1m -XX:PermSize=20m -
XX:MaxPermSize=20m -XX:+UseParallelGC -jar C:\temp\test.jar
-XX:+UseParallelOldGC
With this option, the GC is both a multithreaded young generation
collector and multithreaded old generation collector. It is also a
multithreaded compacting collector.
Compacting describes the act of moving objects in a way that there
are no holes between objects. After a garbage collection sweep,
there may be holes left between live objects. Compacting moves
objects so that there are no remaining holes. This compacting 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 compacting low-pause garbage collector
G1 collector partitions the heap into a set of equal-sized heap
regions. When G1 performs garbage collection then a concurrent
global marking phase is performed to determine the liveliness of
objects throughout the heap. After 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
options
java –Xmx25g –Xms5g -XX:+UseG1GC -jar C:\temp\test.jar
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
execution. start() method internally calls run() method .
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.
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,
- join(long milliseconds) : when this method is called, then
the current thread will wait at most for the specified
milliseconds
- join(long milliseconds, long nanoseconds) : when this
method is called, then the current thread will wait at
most for the specified milliseconds plus nanoseconds.
These join methods are dependent on the underlying Operating
system for timing. So, you should not assume that join() will wait
exactly as long as you specify.
You can execute threads in a sequence using CountDownLatch also.
FixedThreadPoolExecutor :
As its name suggests, this is an executor with a fixed number of
threads. The tasks submitted 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 time, 5 tasks can be managed by this executor.
If there are more active tasks, they will be added to a queue until one
of the 5 threads becomes free.
An important advantage of the fixed thread pool is that applications
using it degrade gracefully. To understand this, consider a web
server application where each HTTP request is handled by a
separate thread. If the application simply creates a new thread for
every new HTTP request, and the system receives more requests
than it can handle immediately, the application 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 application 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 executing 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 after 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:
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
88\color2.png
Core and Max Pool sizes:
A ThreadPoolExecutor will automatically adjust the pool size
according to the bounds set by corePoolSize and maximumPoolSize
When a new task is submitted to the executor then:
- If the number of threads running are less than the
corePoolSize, a new thread is created to handle the
request
- If the number of threads running are more than
corePoolSize but less than maximumPoolSize then a
new thread will be created only if the queue is full
Let’s understand this with an example:
You have defined the core pool size as 5, maximum pool size as 10
and the queue capacity as 100. Now as tasks are coming in, new
threads will be created up to 5, then other new tasks will be added to
queue until it reaches 100. Now when the queue is full and if new
tasks are coming in, threads will be created up to the
maximumPoolSize i.e. 10. Once all the threads are in use and the
queue is also full, the new tasks will be rejected. As the queue
reduces, so does the number of active threads.
BlockingQueue:
The queue to use for holding tasks before they are executed. This
queue will hold only the Runnable tasks submitted 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 applications to use special thread subclasses, priorities,
etc.
RejectedExecutionHandler:
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 submitted to
execute() method is rejected, then an unchecked
RejectedExecutionException is thrown.
But adding a handler is a good practice 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.
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:
C:\Users\jjatin\
Desktop\Different
Versions\All_Pho
tos\Question
93\Program
2\output.png
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 synchronization. One
solution that will be coming to your mind will be using
synchronization 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 operation without using
Synchronization.
Let’s see the change in our Runnable:
C:\Users\jjatin\Desktop\Different Versions\All_Photos\Question
93\Program 3\color.png
Output:
C:\Users\jjatin\Des
ktop\Different
Versions\All_Photos\
Question
93\Program
3\output.png
Question 94: What is Collection Framework?
Answer: Collection framework represents an architecture to store
and manipulate a group of objects. All the classes and interfaces of
this framework are present in java.util package.
Some points:
- Iterable interface is the root interface for all collection
classes, it has one abstract method iterator()
- Collection interface extends the Iterable interface
Output:
Although, we have made the list as final but still 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:
Output:
Guava library also provides certain ways to make immutable list and
Java 9 has List.of() method.
There are other utility methods also, to make unmodifiable
collections:
Question 101: What is LinkedList?
Answer: Java LinkedList class is an implementation of linked list data
structure and it uses a doubly linked list to store the elements. In
Java LinkedList, elements are not stored in contiguous locations,
they are stored at any available space in memory and they are linked
with each other using pointers and addresses.
As Java LinkedList internally uses doubly linked list, so LinkedList
class represents its elements as Nodes. A Node is divided into 3
parts:
Previous, Data, Next
Where Previous points to the previous Node in the list, Next points to
the next Node in the list and Data is the actual data.
Some points about LinkedList class:
- LinkedList class maintains insertion order
- LinkedList class can contain duplicate elements
- LinkedList class is not synchronized
- LinkedList class can be used as list, stack or queue
- You can add any number of null elements in LinkedList
Time complexity of LinkedList’s get(), add() and remove():
get(): As LinkedList does not store its elements in contiguous block
of memory, random access is not supported here, elements can be
accessed in sequential order only, so get() operation in LinkedList is
O(n).
add() and remove(): Both add and remove operations in LinkedList
is O(1), because no elements shifting is needed, just pointer
modification is done (although remember getting to the index where
you want to add/remove will still be O(n)).
Here, I am showing some portions of LinkedList Javadoc’s:
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable,
java.io.Serializable
{
transient int size = 0;
/**
* Pointer to first node.
* Invariant: (first == null && last == null) ||
* (first.prev == null && first.item
!= null)
*/
transient Node<E> first ;
/**
* Pointer to last node.
* Invariant: (first == null && last == null) ||
* (last.next == null && last.item !=
null)
*/
transient Node<E> last ;
/**
* Constructs an empty list.
*/
public LinkedList() {
}
We can see that the LinkedList class implements List and Deque
interfaces. There are first and last Node references also.
Let’s see the add() method:
public boolean add(E e ) {
linkLast(e );
return true ;
}
void linkLast(E e ) {
final Node<E> l = last ;
final Node<E> newNode = new Node<>(l , e , null
);
last = newNode ;
if (l == null )
first = newNode ;
else
l .next = newNode ;
size ++;
modCount ++;
}
Here, in linkLast() method, Node class is used, let’ see that:
private static class Node<E> {
E item ;
Node<E> next ;
Node<E> prev ;
Node(Node<E> prev , E element , Node<E> next ) {
this .item = element ;
this .next = next ;
this .prev = prev ;
}
}
Here, we can see that Node class has 3 fields: item, prev and next.
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 condition from i<13 to i<=13, see below:
Output:
Scenario 1: when custom class does not implement both equals and
hashCode methods
set.contains() method:
public boolean contains(Object o ) {
return map .containsKey(o );
}
The passed object is given to map.containsKey() method, as the
HashSet’s values are stored as the keys of internal map.
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 questions, just like we discussed in
HashMap (Question 105).
Program 3:
Here, we are sorting 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>());
}
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 reflecting the element which was added during the
iteration operation.
1. Inner join : Inner join selects all records from Table A and Table B,
where the join condition 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 operation)
2. Left Join : Left join selects all records from Table A along with
records of Table B for which the join condition 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 condition 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 condition is met or not.
Syntax:
SELECT Table1.column1, Table1.column2, Table2.column1, …..
FROM Table1
FULL JOIN Table2
On Table1.MatchingColumnName = Table2.MatchColumnName;
Question 191: Difference between TRUNCATE & DELETE statements
Answer: The differences are:
- TRUNCATE is a DDL command, whereas DELETE is a DML command
TRUNCATE removes all rows from a table, whereas DELETE can also
- remove all rows but it can be used with a ‘WHERE’ clause to remove
specific rows from a table
TRUNCATE command records very little entry in the transaction log,
whereas DELETE statement removes rows one at a time and records an
-
entry in the transaction log for each deleted row, because of this reason
TRUNCATE is faster than DELETE
To use TRUNCATE on a table, you need at least ALTER permission on
- the table, whereas to use DELETE, you need DELETE permission on the
table
- TRUNCATE uses less transaction space than DELETE
TRUNCATE operation cannot be rolled back, whereas DELETE
-
operation can be rolled back
TRUNCATE command Syntax:
TRUNCATE TABLE employee;
DELETE command Syntax:
DELETE FROM employee; -- delete all rows of the table
DELETE FROM employee WHERE name = ‘Mark’; -- delete
record where emp_name is Mark
Question 192: Difference between Function and Stored Procedure
Answer: The differences are:
Function must return a value, whereas Stored Procedure can return zero
-
or n values
A Function can have only input parameters, whereas a Stored Procedure
-
can have both input and output parameters
Functions can be called from a Stored Procedure, but a Stored Procedure
-
cannot be called from a Function
- In a Function, DML statements cannot be used, whereas DML statements
can be used in a Stored Procedure
Functions does not allow the usage of try-catch blocks, whereas in Stored
-
Procedure, try-catch block can be used for exception handling
Transactions are not allowed within Functions, whereas transactions can
-
be used within Stored Procedure
In a Function, we can only use the table variables, it does not allow using
- the temporary tables, whereas in a Stored Procedure, both table variables
and temporary tables can be used
Functions can be used in SELECT statement, WHERE clause, HAVING
-
clause, whereas Stored Procedure cannot be used with these
A Function can be used in JOIN clause as a result set, whereas a Stored
-
Procedure cannot be used in JOIN clause
Question 193: What is DDL, DML statements?
Answer: DDL: DDL stands for Data Definition Language. These
statements are used to define the database structure or schema. DDL
commands are auto-committed.
Examples of DDL commands are: CREATE, ALTER, DROP, TRUNCATE
DML: DML stands for Data Manipulation language. These statements
allows us to manage the data stored in the database. DML commands are
not auto-committed, so they can be rolled back.
Examples of DML commands are: INSERT, UPDATE, DELETE, SELECT
Question 194: How to find the nth highest salary from Employee table
Answer: The query to find nth highest salary is:
SELECT name, salary
FROM Employee e1
WHERE N-1 = (SELECT COUNT(DISTINCT salary) FROM Employee
e2
WHERE e2.salary > e1.salary);
Here, to find the 3rd highest salary, replace N with 3, for 5th highest salary,
replace N with 5 and so on.
The DISTINCT keyword is used to deal with the duplicate salaries in the
table. The highest salary means no salary is higher than it, the second
highest salary means only one salary is higher than it, and similarly Nth
highest salary means N-1 salaries are higher than it. This is a generic
solution and works in all databases, however it is a little slow because the
inner query will run for every row processed by the outer query.
Question 195: Difference between UNION and UNION ALL commands in
SQL
Answer: Both UNION and UNION ALL are used to combine results of two
separate queries, it could be on a same table or a different table but number
of columns should be same in both queries.
The Key difference between them is UNION removes duplicates, whereas
UNION ALL keeps the duplicates. Because of this, UNION ALL takes less
time, as there is no extra step of removing duplicate rows.
Question 196: Difference between Unique Key and Primary Key in SQL
Answer: Both Unique and Primary keys uniquely identifies each row of a
table.
The differences between them are:
There can be only one primary key in a table, whereas there can be
-
multiple unique keys in the table
- Primary key cannot be null, whereas Unique Keys can be null
In Primary key, default index is clustered, whereas in Unique key, default
-
index is non-clustered
Question 197: What is the difference between Primary and Foreign key in
SQL?
Answer: Primary key is used to uniquely identify a row in the table. A table
can have only one primary key. Primary key is of two types, simple and
composite primary key. A Simple Primary key is made up of just one
column, whereas a composite primary key is made up of more than one
column.
Primary key also enforces some constraints, like UNIQUE and NOT
NULL, which means a table cannot have duplicate primary keys and the
key cannot be null.
A Foreign key in a table is the primary key of another table. For example,
consider 2 tables, Employee & Department. Department table have a
primary key dept_id and this primary key can be used as foreign key in
Employee table to identify that this employee belongs to this department.
The differences between Primary key and Foreign key are given below:
Primary key uniquely identify a record in the table, whereas Foreign key
-
is the field in the table that is the primary key of another table
By default, a clustered index is created on primary key, whereas foreign
-
key do not automatically create an index
- We can have only one primary key in a table, whereas we can have more
than one foreign key in a table
Primary keys does not allow duplicate or Null values, whereas Foreign
-
keys allows both
Question 198: What is the difference between clustered and non-clustered
index?
Answer: Indexes are used to speed-up the data retrieval performance. There
are 2 types of indexes, clustered and non-clustered index and the difference
between them,
A clustered index defines the order in which data is physically sorted in a
- table, whereas non-clustered index does not sort the physical data inside
the table
By default, clustered index is automatically created on primary key,
-
whereas non-clustered index can be created on any key
There can be only one clustered index in a table, whereas there can be
-
any number of non-clustered index in a table
- Data Retrieval is faster using Clustered index than non-clustered index
- Data Update is faster using Non-clustered index than clustered index
Clustered index does not need any extra space, whereas non-clustered
-
index requires extra space to store the index separately
The size of clustered index is quite large as compared to non-clustered
-
index
Syntax of creating a custom clustered index:
CREATE CLUSTERED INDEX index_name
ON table_name (column_name ASC);
For example, creating a clustered index on Employee table, where data
should be stored in ascending order of age column:
CREATE CLUSTERED INDEX employee_asc_age_index
ON employee(age ASC);
Syntax of creating a custom non-clustered index:
CREATE NONCLUSTERED INDEX index_name
ON table_name (column_name ASC);
For example, creating a non-clustered index on Employee table, where data
should be stored in ascending order of name column:
CREATE NONCLUSTERED INDEX employee_asc_name_index
ON employee(name ASC);
Question 199: What is the difference between WHERE and HAVING
clause in SQL
Answer: The differences are:
WHERE clause can be used with SELECT, INSERT, UDPATE and
- DELETE statements, whereas HAVING clause can only be used with
SELECT statement
WHERE clause is used for filtering the rows and it applies on each and
-
every row, whereas HAVING clause is used to filter groups
WHERE clause is used before GROUP BY clause, whereas HAVING
clause is used after GROUP BY clause. It means that WHERE clause is
-
processed before GROUP BY clause while HAVING clause is executed
after groups are created
Aggregate functions cannot be used in WHERE clause, whereas we can
-
use aggregate functions in HAVING clause
Question 200: How to change the gender column value from Male to
Female and Female to Male using single Update statement
Answer: This is also a very common interview question. Mostly, this
question is asked in a telephonic round. The question is like, you are given
a table, say Employee which has a column named ‘Gender’ having only
“Male” or “Female” strings as values. You have to swap these values like
wherever the value is Male, it should become Female, and wherever the
value is Female, it should become Male. And you have to do this by writing
only one Update statement.
The Update query for this is:
UPDATE Employee SET Gender =
CASE Gender WHEN ‘Male’ THEN ‘Female’ WHEN ‘Female’ THEN
‘Male’ ELSE Gender END;
Other than these common questions, 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 question, the interviewer will most probably ask you to not use
sorting 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:
Three largest elements are: 78, 33, 20
Here, the idea is to have 3 numbers and then iterating through the
array and finding where the current element of array fits in.
At first, we check whether the current element is greater than first, if
true, assign the current element to first number by swapping the
values of first, second and third.
When the first condition is not true, then we compare the current
element with second largest number to find whether the current
number is second largest or not, same goes for third condition.
Here, the idea is to iterate through the array and when a negative
number is found, then bring that number to the beginning of the array
by swapping it with the first positive 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 solution which maintains the element
sequence:
Output:
-9 -2 -15 -3 5 1 7 12 2