0% found this document useful (0 votes)
15 views58 pages

Imp Question Bank

Uploaded by

infodata735
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views58 pages

Imp Question Bank

Uploaded by

infodata735
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 58

Imp Question Bank

1) What is Java?
Java is a cross-platform object-oriented programming language. It is
a general-purpose programming language intended to let application
developers “write once, run anywhere” (WORA),[17] meaning
that compiled Java code can run on all platforms that support Java without
the need for recompilation.

2) What are the java IDE’s?


Eclipse, IntelliJ IDEA, NetBeans are the java IDE’s.

3) Difference between Java and C++?


Java C++
Java is platform-independent. C++ is platform-dependent.
Java is mainly used for application C++ is mainly used for system
programming. It is widely used in programming.
window, web-based, enterprise and
mobile applications.
Java doesn't support multiple C++ supports multiple inheritance.
inheritance through class. It can be
achieved by interfaces in java.
Java has built-in thread support. C++ doesn't have built-in support
for threads. It relies on third-party
libraries for thread support.

4) What are the features of Java?


 Simple and Portable
 Support OOPs
 Platform Independent
 Secure and Robust
 Interpreted
 High performance
 Multithreaded
 Distributed
 Dynamic

5) What are the types of Java Applications?


There are mainly 4 types of applications that can be created using java
programming:
 Standalone Application
 Web Application
 Enterprise Application
 Mobile Application

6) What is JVM?
JVM stand for Java Virtual Machine. JVM is a virtual machine that enables
the computer to run the Java program. JVM acts like a run-time engine
which calls the main method present in the Java code. JVM is the
specification which must be implemented in the computer system. The
Java code is compiled by JVM to be a Bytecode which is machine
independent and close to the native code.

7) What is JRE?
JRE stands for Java Runtime Environment. It is the implementation of JVM.
The Java Runtime Environment is a set of software tools which are used for
developing Java applications. It is used to provide the runtime
environment. It is the implementation of JVM. It physically exists. It
contains a set of libraries + other files that JVM uses at runtime.

8) What is JDK?
JDK is an acronym for Java Development Kit. It is a software development
environment which is used to develop Java applications and applets. It
physically exists. It contains JRE + development tools. JDK is an
implementation of any one of the below given Java Platforms released by
Oracle Corporation:
 Standard Edition Java Platform
 Enterprise Edition Java Platform
 Micro Edition Java Platform

9) What is JIT?
JIT stand for Just-In-Time. It is compiler used to improve the
performance. JIT compiles parts of the bytecode that have similar
functionality at the same time, and hence reduces the amount of time
needed for compilation. Here the term “compiler” refers to a translator
from the instruction set of a Java virtual machine (JVM) to the instruction
set of a specific CPU.

10) Why we call java code “write once and run anywhere”?
The bytecode. Java compiler converts the Java programs into the class file
(Byte Code) which is the intermediate language between source code and
machine code. This bytecode is not platform specific and can be executed
on any computer.

11) What is classloader?


Classloader is a subsystem of JVM which is used to load class files.
Whenever we run the java program, it is loaded first by the classloader.
There are three built-in classloaders in Java.
 Bootstrap ClassLoader: This is the first classloader which is the
superclass of Extension classloader. It loads the rt.jar file which
contains all class files of Java Standard Edition like java.lang package
classes, java.net package classes, java.util package classes, java.io
package classes, java.sql package classes, etc.
 Extension ClassLoader: This is the child classloader of Bootstrap and
parent classloader of System classloader. It loads the jar files located
inside $JAVA_HOME/jre/lib/ext directory.
 System/Application ClassLoader: This is the child classloader of
Extension classloader. It loads the class files from the classpath. By
default, the classpath is set to the current directory. You can change
the classpath using "-cp" or "-classpath" switch. It is also known as
Application classloader.
12)Can we compile .java file?
Yes, to compile it write following command
 javac .java
 java ClassName

13)What are the access specifier in java?


In Java, access specifiers are the keywords which are used to define the
access scope of the method, class, or a variable. In Java, there are four
access specifiers given below.
 Public The classes, methods, or variables which are defined as public,
can be accessed by any class or method.
 Protected Protected can be accessed by the class of the same package,
or by the sub-class of this class, or within the same class.
 Default Default are accessible within the package only. By default, all
the classes, methods, and variables are of default scope.
 Private The private class, methods, or variables defined as private can
be accessed within the class only.

14)Difference b/w private and protected?


Private Protected
If a member is declared as private, If a member is declared as
then we can access that member protected, then we can access
only within the current class. that member within current
package anywhere, but outside
the package only in child class.

We can’t access private member Outside package, we can access


outside of package. protected members only by
giving child reference.

Private member can be access We can access protected member


within the class only in the child class and within the
class too
15)What is static keyword?
The static keyword in java is used for memory management mainly. We
can apply static keyword with variables, methods, blocks and nested
classes. The static keyword belongs to the class than an instance of the
class.

16)What is final keyword?


The final keyword in java is used to restrict the user. The java final
keyword can be used in many context. Final can be:
 variable
 method
 class

17)What is reference/instance variable?


Instance variable is defined inside the class and outside the method and
the scope of the variables exists throughout the class.

18)What is local variable?


Local variables are defined in the method and scope of the variables that
exist inside the method itself.

19)Difference b/w static and final?


Final Static
When we apply "final" keyword to When we apply "static" keyword to
a variable, the value of that a variable, it means it belongs to
variable remains constant. (or) class.
Once we declare a variable as final
the value of that variable cannot be
changed.
When we apply “final” keyword to When we apply "static" keyword to
method that means method cannot a method, it means
be overridden by subclasses, so you the method can be accessed
cannot modify a final method from without creating any instance of
a sub class the class
The main intention of making a The main content of static keyword
class member final would be that is that you can’t call static member
the content should not be changed by its class’s object.
by any outsider.

20)What is super keyword?


The super keyword in Java is a reference variable that is used to refer
parent class objects. The super() in Java is a reference variable that is used
to refer parent class constructors. super can be used to call parent class'
variables and methods. super() can be used to call parent class'
constructors only.

21)What is this keyword?


The this keyword refers to the current object in a method or constructor.
The most common use of the this keyword is to eliminate the confusion
between class attributes and parameters with the same name

22)Difference b/w super and this?


This Super
this keyword mainly represents the On other hand super keyword
current instance of a class. represents the current instance of
a parent class.
this keyword used to call default super keyword used to call default
constructor of the same class. constructor of the parent class.
this keyword used to access One can access the method of
methods of the current class as it parent class with the help of super
has reference of current class. keyword.
When invoking a current version of When invoking a superclass version
an overridden method the this of an overridden method the super
keyword is used. keyword is used.

23)Can we use super() and this() both in a constructor?


No, because this() and super() must be the first statement in the class
constructor.
24)What is Object?
The Object is the real-time entity having some state and behavior. In Java,
Object is an instance of the class having the instance variables as the state
of the object and the methods as the behavior of the object. The object of
a class can be created by using the new keyword.

25)What is Constructor?
The constructor can be defined as the special type of method that is used
to initialize the state of an object. It is invoked when the class is
instantiated, and the memory is allocated for the object. Every time, an
object is created using the new keyword, the default constructor of the
class is called. The name of the constructor must be similar to the class
name. The constructor must not have an explicit return type.

26)What is difference b/w Constructor and Method?


Constructor Method
A constructor is used to initialize A method is used to expose the
the state of an object. behavior of an object.
A constructor must not have a A method must have a return type.
return type.
The constructor is invoked The method is invoked explicitly.
implicitly.
The Java compiler provides a The method is not provided by the
default constructor if you don't compiler in any case.
have any constructor in a class.
The constructor name must be The method name may or may not
same as the class name. be same as class name.

27)What is constructor chaining?


Constructor chaining enables us to call one constructor from another
constructor of the class with respect to the current class object. We can
use this keyword to perform constructor chaining within the same class.
28)Which class is super class in java?
“Object” class is the super class in java.

29)What is Inheritance?

Inheritance is a mechanism by which one object acquires all the properties and
behavior of another object of another class. It is used for Code Reusability and
Method Overriding. The idea behind inheritance in Java is that you can create
new classes that are built upon existing classes. There are five types of
inheritance in Java.

 Single-level inheritance
 Multi-level inheritance
 Multiple Inheritance
 Hierarchical Inheritance
 Hybrid Inheritance

30)Why multiple inheritance is not supported in java?


To reduce the complexity and simplify the language, multiple inheritance
is not supported in java. Consider a scenario where A, B, and C are three
classes. The C class inherits A and B classes. If A and B classes have the
same method and you call it from child class object, there will be
ambiguity to call the method of A or B class.

31)What is association?
Association refers to the relationship between multiple objects. It refers to
how objects are related to each other and how they are using each other's
functionality. Composition and aggregation are two types of association.

32)What is aggregation?
Aggregation can be defined as the relationship between two classes where
the aggregate class contains a reference to the class it owns. Aggregation
is best described as a has-a relationship.

33)What is composition?
Holding the reference of a class within some other class is known as
composition. When an object contains the other object, if the contained
object cannot exist without the existence of container object, then it is
called composition. In other words, we can say that composition is the
particular case of aggregation which represents a stronger relationship
between two objects.

34)What is difference b/w aggregation and composition?


Aggregation represents the weak relationship whereas composition
represents the strong relationship. For example, the bike has an indicator
(aggregation), but the bike has an engine (composition).

35)Why java doesn’t support pointers?


The pointer is a variable that refers to the memory address. They are not
used in Java because they are unsafe(unsecured) and complex to
understand.

36) What is object cloning?


The object cloning is used to create the exact copy of an object. The
clone() method of the Object class is used to clone an object.
The java.lang.Cloneable interface must be implemented by the class
whose object clone we want to create.

37)What is polymorphism?
Polymorphism is a concept by which we can perform a single action in
different ways. There are two types of polymorphism in Java: compile-time
polymorphism and runtime polymorphism. We can perform
polymorphism in java by method overloading and method overriding.

38)What is method overloading?


If a class has multiple methods having same name but different in
parameters, it is known as Method Overloading.
39)What is method overriding?
If subclass (child class) has the same method as declared in the parent
class, it is known as method overriding in Java. In other words, if a subclass
provides the specific implementation of the method that has been
declared by one of its parent class, it is known as method overriding.

40)What is runtime polymorphism?


Runtime Polymorphism is achieved by Method overriding in which a child
class overrides a method in its parent. An overridden method is essentially
hidden in the parent class, and is not invoked unless the child class uses
the super keyword within the overriding method

41)What is compile time polymorphism?


Compile Time Polymorphism: Whenever an object is bound with their
functionality at the compile-time, this is known as the compile-time
polymorphism. At compile-time, java knows which method to call by
checking the method signatures. So this is called compile-time
polymorphism or static or early binding.

42)Can we overload main() method?


Yes, we can have any number of main methods in a Java program by using
method overloading.

43)What is difference b/w method overriding and method overloading?


Method Overriding Method Overloading
Method overriding provides the Method overloading increases the
specific implementation of the readability of the program.
method that is already provided by
its superclass.
Method overriding occurs in two Method overloading occurs within
classes that have IS-A relationship the class.
between them.
In this case, the parameters must In this case, the parameters must
be the same. be different
44)What is final method?
If we change any method to a final method, we can't override it.

45)What is final variable?


The final variable is used to restrict the user from updating it. If we
initialize the final variable, we can't change its value. In other words, we
can say that the final variable once assigned to a value, can never be
changed after that.

46)What is final class?


If we make any class final, we can't inherit it into any of the subclasses.

47)What is final black variable?


Final variable, not initialized at the time of declaration, is known as the
final blank variable. We can't initialize the final blank variable directly.
Instead, we have to initialize it by using the class constructor. It is useful in
the case when the user has some data which must not be changed by
others.

48)What is instanceOf operator?


The instanceof in Java is also known as type comparison operator because
it compares the instance with type. It returns either true or false. If we
apply the instanceof operator with any variable that has a null value, it
returns false.

49)What is abstraction?
Abstraction is a process of hiding the implementation details and showing
only functionality to the user. It displays just the essential things to the
user and hides the internal information. There are two ways to achieve
the abstraction.
 Abstract Class
 Interface
50)What is abstract class?
A class that is declared as abstract is known as an abstract class. It needs
to be extended and its method implemented. It cannot be instantiated. It
can have abstract methods, non-abstract methods, constructors, and
static methods. It can also have the final methods which will force the
subclass not to change the body of the method.

51)What is interface?
The interface is a blueprint for a class that has static constants and
abstract methods. It can be used to achieve full abstraction and multiple
inheritance. There can be only abstract methods in the Java interface, not
method body. It is used to achieve abstraction and multiple inheritance in
Java.

52)What is marker interface?


An empty interface in Java is known as a marker interface. It does not
contain any methods or fields.
java.lang.Cloneable and java.io.Serializable are examples of marker
interfaces.

53)What is difference b/w abstract class and interface?


Abstract class Interface
An abstract class can have a The interface has only abstract
method body (non-abstract methods.
methods).
An abstract class can have instance An interface cannot have instance
variables. variables.
An abstract class can have the The interface cannot have the
constructor. constructor.
An abstract class can have static The interface cannot have static
methods. methods.
The abstract class can provide the The Interface can't provide the
implementation of the interface. implementation of the abstract
class.
The abstract keyword is used to The interface keyword is used to
declare an abstract class. declare an interface.
An abstract class can extend An interface can extend another
another Java class and implement Java interface only.
multiple Java interfaces.
An abstract class can be extended An interface class can be
using keyword extends implemented using
keyword implements
A Java abstract class can have class Members of a Java interface are
members like private, protected, public by default.
etc.

54)Can we instantiate the abstract class?


No, the abstract class can never be instantiated even if it contains a
constructor and all of its methods are implemented.

55)How to make a class a read only class?


A class can be made read-only by making all of the fields private. The read-
only class will have only getter methods which return the private property
of the class to the main method. We cannot modify this property because
there is no setter method available in the class.

56)How to make a class a write only class?


A class can be made write-only by making all of the fields private. The
write-only class will have only setter methods which set the value passed
from the main method to the private fields. We cannot read the
properties of the class because there is no getter method in this class.

57)What is package?
A package is a group of similar type of classes, interfaces, and sub-
packages. It provides access protection and removes naming collision. The
packages in Java can be categorized into two forms, inbuilt package, and
user-defined package. There are many built-in packages such as Java, lang,
awt, javax, swing, net, io, util, sql, etc.
58)What is encapsulation?
Encapsulation in Java is a mechanism of wrapping the data (variables) and
code acting on the data (methods) together as a single unit. In
encapsulation, the variables of a class will be hidden from other classes,
and can be accessed only through the methods of their current class.
Therefore, it is also known as data hiding.

59)What is static import?


By static import, we can access the static members of a class directly, and
there is no to qualify it with the class name.

60)What is collection framework?


Collection Framework is a combination of classes and interface, which is
used to store and manipulate the data in the form of objects.

61)What are important interfaces of Collection Framework?


 List
 Set
 Queue
 Collection

62)What are important classes of Collection Framework?


 ArratList
 LinkedList
 HashSet
 Vector
 TreeSet

63)What is difference b/w List and Set?


List Set
The list provides positional access Set doesn't provide positional
of the elements in the collection. access to the elements in the
collection
We can store the duplicate We can’t store duplicate elements
elements in the list. in Set
List maintains insertion order of Set doesn’t maintain any order
elements in the collection
The list can store multiple null Set can store only one null element
elements

64)What is difference b/w Set and Map?


Set Map
Set contains values only Map contains key and values both
Set contains unique values Map can contain unique Keys with
duplicate values.
Set holds a single number of null Map can include a single null key
value with n number of null values.

65)What is difference b/w Array and Collection?


Array Collection
Arrays are always of fixed size, like Size can be changed dynamically as
a user can not increase or decrease per need.
the length of the array according to
their requirement or at runtime
Arrays can only store Collection can store heterogeneous
homogeneous or similar type and homogeneous as well.
objects.
Arrays cannot provide the ready- Collection provide the ready-made
made methods for user methods.
requirements as sorting, searching,
etc.

66)What is difference b/w Array and ArrayList?


Array ArrayList
An array is a dynamically-created The ArrayList is a class of
object. It serves as a container that collection framework of java.
holds the constant number of values
of the same type.
Array is static in size and fixed- ArrayList is dynamic in size and is
length data structure. a variable-length data structure.
It can be resized itself when
needed.
It is mandatory to provide the size of We can create an instance of
an array while initializing it directly or ArrayList without specifying its
indirectly size. Java creates ArrayList of
default size.
An array can store We cannot store primitive type
both objects and primitives type. in ArrayList. It automatically
converts primitive type to object.
Array provides a length variable ArrayList provides
which denotes the length of an array. the size() method to determine
the size of ArrayList.
We can add elements in an array by Java provides the add() method
using the assignment operator. to add elements in the ArrayList.
Array can be multi-dimensional. ArrayList is always single-
dimensional.

67)What is difference b/w ArrayList and HashSet?


ArrayList HashSet
ArrayList is the implementation of HashSet on the other hand is the
the list interface. implementation of a set interface.
ArrayList internally implements HashSet internally uses Hashmap
array for its implementation. for its implementation.
ArrayList maintains the insertion HashSet is an unordered collection
order i.e order of the object in and doesn't maintain any order.
which they are inserted.
ArrayList allows duplicate values in On other hand duplicate elements
its collection are not allowed in Hashset.
Any number of null value can be Hashset allows only one null value
inserted in arraylist without any in its collection,after which no null
restriction. value is allowed to be added.
68)What is difference b/w ArrayList and Vector?
ArrayList Vector
ArrayList is not synchronized. Vector is synchronized.
ArrayList increments 50% of Vector increments 100% means
current array size if the number of doubles the array size if the total
elements exceeds from its number of elements exceeds than
capacity. its capacity.
ArrayList is not a legacy class. It is Vector is a legacy class.
introduced in JDK 1.2.
ArrayList is fast because it is non- Vector is slow because it is
synchronized. synchronized, i.e., in a
multithreading environment, it
holds the other threads in runnable
or non-runnable state until current
thread releases the lock of the
object.
ArrayList uses A Vector can use
the Iterator interface to traverse the Iterator interface
the elements. or Enumeration interface to
traverse the elements.

69)What is difference b/w HashSet and TreeSet?


HashSet TreeSet
HashSet doesn’t maintain the TreeSet maintains ascending order.
order of insertion.
HashSet impended by hash table. TreeSet implemented by a Tree
structure.
HashSet performs faster than TreeSet is slower
TreeSet
HashSet is backed by HashMap TreeSet is backed by TreeMap

70)What is difference b/w Iterator and ListIterator?


Iterator ListIterator
The Iterator traverses the elements ListIterator traverses the elements
in the forward direction only. in backward and forward directions
both.
The Iterator can be used in List, ListIterator can be used in List only.
Set, and Queue.
The Iterator can only perform ListIterator can perform add,
remove operation while traversing remove, and set operation while
the collection. traversing the collection.

71)What is difference b/w Iterator and Enumerator?


Iterator Enumerator
The Iterator can traverse legacy Enumeration can traverse only
and non-legacy elements. legacy elements.
The Iterator is fail-fast. Enumeration is not fail-fast.
The Iterator is slower than Enumeration is faster than Iterator.
Enumeration.
The Iterator can perform remove The Enumeration can perform only
operation while traversing the traverse operation on the
collection. collection.

72)What is difference b/w HashMap and HashTable?


HashMap HashTable
HashMap is not synchronized. Hashtable is synchronized.
HashMap can contain one null key Hashtable cannot contain any null
and multiple null values. key or null value.
HashMap is not thread-safe, so it is Hashtable is thread-safe, and it can
useful for non-threaded be shared between various
applications. threads.
HashMap inherits the AbstractMap Hashtable inherits the Dictionary
class class.

73)What is difference b/w Collection and Collections?


Collection Collections
Collection is an interface Collections is a class.
The Collection interface provides Collections class is to sort and
the standard functionality of data synchronize the collection
structure to List, Set, and Queue elements.
The Collection interface provides Collections class provides the static
the methods that can be used for methods which can be used for
data structure. various operation on a collection.

74)What is difference b/w Comparable and Comparator?


Comparable Comparator
Comparable provides only one sort The Comparator provides multiple
of sequence. sorts of sequences.
It provides one method named It provides one method named
compareTo(). compare().
It is found in java.lang package. It is located in java.util package.
If we implement the Comparable The actual class is not changed.
interface, The actual class is
modified

75)What is difference b/w equals() and == ?


equals() ==
equals() is a method of Object class. == is an operator.
equals() method should be used for == should be used during reference
content comparison. equals() comparison. == checks if both
method evaluates the content to references points to same location
check the equality. or not.
equals() method if not present and == operator can not be overriden.
Object.equals() method is utilized,
otherwise it can be overridden.

76)What does hashCode() method?


The hashCode() method returns a hash code value (an integer number).
The hashCode() method returns the same integer number if two keys (by
calling equals() method) are identical.
77)What is exception?
An exception is an event, which occurs during the execution of a program
that disrupts the normal flow of the program's instructions.

78)What is exception handling?


Exception Handling is a mechanism that is used to handle runtime errors.
It is used primarily to handle checked exceptions. Exception handling
maintains the normal flow of the program. There are mainly two types of
exceptions: checked and unchecked. Here, the error is considered as the
unchecked exception.

79)What is checked exception?


Checked exception are the exceptions that are checked at compile time. In
other words The classes that extend Throwable class except
RuntimeException and Error are known as checked exceptions, e.g.,
IOException, SQLException, etc. are checked at compile-time.

80)What is unchecked exception?


An unchecked exception is the one which occurs at the time of execution.
These are also called as Runtime Exceptions. In other words the classes
that extend RuntimeException are known as unchecked exceptions, e.g.,
ArithmeticException, NullPointerException, etc. are unchecked exceptions.

81)What is try catch block?


The try statement allows you to define a block of code to be tested for
errors while it is being executed.
The catch statement allows you to define a block of code to be executed,
if an error occurs in the try block.

82)What is finally keyword?


The "finally" block is used to execute the important code of the program.
It is executed whether an exception is handled or not. In other words, we
can say that finally block is the block which is always executed. Finally
block follows try or catch block

83)Can finally block be used without catch block?


Yes, According to the definition of finally block, it must be followed by a
try or catch block, therefore, we can use try block instead of catch.

84)What is throw keyword?


The throw keyword is used to create a custom error. The throw statement
is used together with an exception type

85)What is throws keyword?


Throws clause is used to declare an exception, which means it works
similar to the try-catch block. Throws is used in method signature to
declare the exceptions that can occur in the statements present in the
method.

86)What is difference b/w throws and throw?


Throw Throws
The throw keyword is used to The throws keyword is used to
throw an exception explicitly. declare an exception.
The checked exceptions cannot be The checked exception can be
propagated with throw only. propagated with throws
The checked exceptions cannot be The throws keyword is followed by
propagated with throw only. class.
The throw keyword is used within The throws keyword is used with
the method. the method signature.
You cannot throw multiple You can declare multiple
exceptions. exceptions, e.g., public void
method()throws IOException,
SQLException.

87)What is string?
Strings, which are widely used in Java programming, are a sequence of
characters.

88)What is string pool?


String pool is the space reserved in the heap memory that can be used to
store the strings. The main advantage of using the String pool is whenever
we create a string literal; the JVM checks the "string constant pool" first. If
the string already exists in the pool, a reference to the pooled instance is
returned. If the string doesn't exist in the pool, a new string instance is
created and placed in the pool. Therefore, it saves the memory by
avoiding the duplicity.

89)Why string is immutable?


String is immutable, like once string object has been created, its value
can't be changed.

90)Why objects are immutable?


Because Java uses the concept of the string literal. Suppose there are five
reference variables, all refer to one object "sachin". If one reference
variable changes the value of the object, it will be affected by all the
reference variables. That is why string objects are immutable in java.

91)What is string buffer?


A string buffer is like a String, but can be modified. It contains some
particular sequence of characters, but the length and content of the
sequence can be changed through certain method calls

92)What is string builder?


A string builder objects are like string objects, except that they can be
modified. Internally, these objects are treated like variable-length arrays
that contain a sequence of characters. At any point, the length and
content of the sequence can be changed through method invocations.
93)What is difference b/w string buffer and string builder?
String Buffer String Builder
StringBuffer is synchronized, i.e., StringBuilder is non-
thread safe. It means two threads synchronized,i.e., not thread safe. It
can't call the methods of means two threads can call the
StringBuffer simultaneously. methods of StringBuilder
simultaneously.
StringBuffer is less efficient than StringBuilder is more efficient than
StringBuilder. StringBuffer.

94)Can we create immutable class?


We can create an immutable class by defining a final class having all of its
members as final.

95)What is toString() method?


The toString() method returns the string representation of an object. If
you print any object, java compiler internally invokes the toString()
method on the object. So overriding the toString() method, returns the
desired output, it can be the state of an object, etc. depending upon your
implementation

96)What is singleton class?


Singleton Pattern says that just "define a class that has only one instance
and provides a global point of access to it". In other words, a class must
ensure that only single instance should be created and single object can
be used by all other classes.

97)Difference b/w singleton class and static class?


Singleton Class Static Class
Singleton classes can be lazy Static class doesn't have such
loaded if it’s an heavy object advantages and always eagerly
loaded.
You can override methods defined Since static methods in Java cannot
in Singleton class by extending it. be overridden, they leads to
inflexibility.

98)What is nested class?


The nested class can be defined as the class which is defined inside
another class or interface. We use the nested class to logically group
classes and interfaces in one place so that it can be more readable and
maintainable. A nested class can access all the data members of the outer
class including private data members and methods.

99)What are the advantages of nested class?


 Nested classes represent a special type of relationship that is it can
access all the members (data members and methods) of the outer class
including private.
 Nested classes are used to develop a more readable and maintainable
code because it logically groups classes and interfaces in one place only.

100) What is inner class?


Inner class means one class which is a member of another class. Or a class
which is written inside the other class.

101) What are the types of inner class


 Member Inner class: A class created within class and outside method.
 Anonymous Inner class: A class created for implementing an interface or
extending class. Its name is decided by the java compiler.
 Local Inner class: A class created within the method.

102) Is there any difference b/w nested and inner class?


Yes, inner classes are non-static nested classes. In other words, we can say
that inner classes are the part of nested classes.

103) What is anonymous inner class?


Anonymous inner classes are the classes that are automatically declared
and instantiated within an expression. We cannot apply different access
modifiers to them. Anonymous class cannot be static, and cannot define
any static fields, method, or class. In other words, we can say that it a class
without the name and can have only one object that is created by its
definition.

104) What is nested interface?


An Interface that is declared inside the interface or class is known as the
nested interface. It is static by default. The nested interfaces are used to
group related interfaces so that they can be easy to maintain.

105) Can an interface have a class?


Yes, they are static implicitly.

106) What is garbage collector?


Garbage collection is a process of reclaiming the unused runtime objects.
It is performed for memory management. In other words, we can say that
it is the process of removing unused objects from the memory to free up
space and make this space available for JVM.

107) What is gc()?


The gc() method is used to invoke the garbage collector for cleanup
processing. This method is found in System and Runtime classes. This
function explicitly makes the Java Virtual Machine free up the space
occupied by the unused objects so that it can be utilized or reused.

108) When JVM calls garbage collector to free up the memory?


That we can’t say when it calls but we can say JVM to free up the memory
by gc() method.

109) What is finalize() method?


The finalize() method is invoked just before the object is garbage
collected. It is used to perform cleanup processing. The Garbage collector
of JVM collects only those objects that are created by new keyword. So if
you have created an object without new, you can use the finalize method
to perform cleanup processing (destroying remaining objects).

110) What is difference b/w final, finally and finalize?


Final Finally Finalize
Final is used to apply Finally is used to place Finalize is used to
restrictions on class, important code, it will perform clean up
method, and variable. be executed whether processing just before
The final class can't be an exception is an object is garbage
inherited, final method handled or not. collected.
can't be overridden,
and final variable value
can't be changed.
Final is a keyword. Finally is a block. Finalize is a method.

111) What is InputStream?


The InputStream is used to read data from a source.

112) What is OutputStream?


The OutputStream is used for writing data to a destination.

113) What is FileInputStream?


FileInputStream class obtains input bytes from a file. It is used for reading
byte-oriented data (streams of raw bytes) such as image data, audio,
video, etc. You can also read character-stream data.

114) What is FileOutputStream?


FileOutputStream class is an output stream used for writing data to a file.
If you have some primitive values to write into a file, use
FileOutputStream class. You can write byte-oriented as well as character-
oriented data through the FileOutputStream class.

115) What is BufferedInputStream?


BufferedInputStream class is used to read information from the stream. It
internally uses the buffer mechanism to make the performance fast.

116) What is BufferedOutputStream?


BufferedOutputStream class is used for buffering an output stream. It
internally uses a buffer to store data. It adds more efficiency than to write
data directly into a stream. So, it makes the performance fast.

117) What is serialization?


Serialization in Java is a mechanism of writing the state of an object into a
byte stream. It is mainly used to travel object's state on the network
(which is known as marshaling).

118) What is deserialization?


Deserialization is the process of reconstructing the object from the
serialized state. It is the reverse operation of serialization.

119) How can you make a class serializable?


A class can become serializable by implementing the Serializable interface.

120) What is transient keyword?


The transient keyword in Java is used to avoid serialization. If any object of
a data structure is defined as a transient, then it will not be serialized.

121) What is socket?


A socket is simply an endpoint for communications between the
machines. It provides the connection mechanism to connect the two
computers using TCP. The Socket class can be used to create a socket.

122) What is Multithreading?


Multithreading is a Java feature that allows concurrent execution of two
or more parts of a program for maximum utilization of CPU. Each part of
such program is called a thread.
123) What are the advantages of Multithreading?
 It doesn't block the user because threads are independent and you
can perform multiple operations at the same time.
 You can perform many operations together, so it saves time.
 Threads are independent, so it doesn't affect other threads if an
exception occurs in a single thread.

124) What is Multitasking?


Multitasking is a process of executing multiple tasks simultaneously. We
use multitasking to utilize the CPU.

125) How do you achieve the multitasking?


Multitasking can be achieved in two ways:
 Process-based Multitasking (Multiprocessing)
 Thread-based Multitasking (Multithreading)

126) What is Process-based Multitasking?


Each process has an address in memory. In other words, each process
allocates a separate memory area. A process is heavyweight. Cost of
communication between the process is high. Switching from one process
to another requires some time for saving and loading registers, memory
maps, updating lists, etc.

127) What is Thread-base Multitasking?


Threads share the same address space. A thread is lightweight. Cost of
communication between the thread is low.

128) What is difference b/w Process and Thread?


Process Thread
A process is a program under A thread is a lightweight process
execution i.e an active program. that can be managed
independently by a scheduler.
Processes are totally independent A thread may share some memory
and don’t share memory. with its peer threads.
Processes require more time for Threads require less time for
context switching as they are context switching as they are
heavier. lighter than processes.
Communication between Communication between threads
processes requires more time than requires less time than between
between threads. processes.
Processes require more resources Threads generally need less
than threads. resources than processes.
Individual processes are Threads are parts of a process and
independent of each other. so are dependent.

129) What is Thread?


A thread is a lightweight sub-process, the smallest unit of processing. It is
a separate path of execution. Threads are independent. If there occurs
exception in one thread, it doesn't affect other threads. It uses a shared
memory area.

130) What is Thread Class?


Thread class to achieve thread programming. Thread class
provides constructors and methods to create and perform operations on
a thread. Thread class extends Object class and implements Runnable
interface.

131) What is thread scheduler?


Thread scheduler in java is the part of the JVM that decides which thread
should run. There is no guarantee that which runnable thread will be
chosen to run by the thread scheduler. Only one thread at a time can run
in a single process.

132) List out some important thread methods.


 start(): It is used to start the execution of the thread.
 run(): It is used to do an action for a thread.
 sleep(): It sleeps a thread for the specified amount of time.
 join(): It waits for a thread to die.
 getPriority(): It returns the priority of the thread.
 setPriority(): It changes the priority of the thread.
 getId(): It returns the id of the thread.
 getName(): It returns the name of the thread.
 setName(): It changes the name of the thread.
 suspend(): It is used to suspend the thread.
 resume(): It is used to resume the suspended thread.
 stop(): It is used to stop the thread.
 destroy(): It is used to destroy the thread group and all of its
subgroups.

133) What is difference b/w sleep() and wait()?


sleep() wait()
Wait() method belongs to Object Sleep() method belongs to Thread
class class
Wait() releases the lock on an It does not release lock on an
object object
Wait() can be called on object Sleep() can be called on thread
itself
until call notify(), notifyAll() from until at least time expire or call
object interrupt
Program can get spurious It will not get spurious wakeups.
wakeups

134) How many ways to create the thread?


There are two ways to create a thread:
 By extending Thread class
 By implementing Runnable interface.

135) What is thread life cycle?


A thread goes through various stages in its life cycle.
136) What are the states of thread life cycle?
A thread can be in one of the five states. According to sun, there is only 4
states in thread life cycle in java new, runnable, non-runnable and
terminated. There is no running state.

137) What is new state in thread life cycle?


The thread is in new state if you create an instance of Thread class but
before the invocation of start() method.

138) What is runnable state in thread life cycle?


The thread is in runnable state after invocation of start() method, but the
thread scheduler has not selected it to be the running thread.

139) What is running state in thread life cycle?


The thread is in running state if the thread scheduler has selected it.

140) What is non-runnable(blocked) state in thread life cycle?


This is the state when the thread is still alive, but is currently not eligible
to run.

141) What is terminated state in thread life cycle?


A thread is in terminated or dead state when its run() method exits.

142) How to put thread in sleep mode?


The sleep() method of Thread class is used to sleep a thread for the
specified amount of time. The Thread class provides two methods for
sleeping a thread:
 public static void sleep(long miliseconds)throws
InterruptedException
 public static void sleep(long miliseconds, int nanos)throws
InterruptedException

143) What is thread priority?


Each thread have a priority. Priorities are represented by a number
between 1 and 10. In most cases, thread schedular schedules the threads
according to their priority (known as preemptive scheduling). But it is not
guaranteed because it depends on JVM specification that which
scheduling it chooses.

144) What are the constant defined in thread class for thread priority?
There are main 3 constant defined in thread class which are
 public static int MIN_PRIORITY
 public static int NORM_PRIORITY
 public static int MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY). The value of
MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.
145) What is thread pool?
Thread pool represents a group of worker threads that are waiting for
the job and reuse many times. In case of thread pool, a group of fixed
size threads are created. A thread from the thread pool is pulled out and
assigned a job by the service provider. After completion of the job,
thread is contained in the thread pool again.

146) What is thread group?


Java provides a convenient way to group multiple threads in a single
object. In such way, we can suspend, resume or interrupt group of
threads by a single method call. Java thread group is implemented
by java.lang.ThreadGroup class. A ThreadGroup represents a set of
threads. A thread group can also include the other thread group. The
thread group creates a tree in which every thread group except the initial
thread group has a parent.

147) What is Java Regex?


Regex or Regular Expression is an API to define a pattern for searching or
manipulating strings. It is widely used to define the constraint on strings
such as password and email validation. Regex resides in the
java.util.regex package.

148) What are the classes and interfaces provided in this regex package?
The Matcher and Pattern classes provide the facility of Java regular
expression. The java.util.regex package provides following classes and
interfaces for regular expressions.
 MatchResult interface
 Matcher class
 Pattern class
 PatternSyntaxException class

149) What is Matcher class? List out some important method.


It implements the MatchResult interface. It is a regex engine which is
used to perform match operations on a character sequence. And
methods are as follows
 boolean matches(): test whether the regular expression matches
the pattern.
 boolean find(): finds the next expression that matches the pattern.
 boolean find(int start): finds the next expression that matches the
pattern from the given start number.
 String group(): returns the matched subsequence
 int start(): returns the starting index of the matched subsequence.
 int end(): returns the ending index of the matched subsequence.
 int groupCount(): returns the total number of the matched
subsequence.

150) What is Patter class? List out some important method.


It is the compiled version of a regular expression. It is used to define a
pattern for the regex engine. And methods are as follows
 static Pattern compile(String regex): compiles the given regex and
returns the instance of the Pattern.
 Matcher matcher(CharSequence input): creates a matcher that
matches the given input with the pattern.
 static boolean matches(String regex, CharSequence input): It works
as the combination of compile and matcher methods. It compiles
the regular expression and matches the given input with the
pattern.
 String[] split(CharSequence input): splits the given input string
around matches of given pattern.
 String pattern(): returns the regex pattern.

151) What is Hibernate?


Hibernate is an open-source and lightweight ORM tool that is used to
store, manipulate, and retrieve data from the database.

152) What is ORM?


ORM is an acronym for Object/Relational mapping. It is a programming
strategy to map object with the data stored in the database. It simplifies
data creation, data manipulation, and data access.

153) What are the core interfaces of hibernate?


 Configuration
 SessionFactory
 Session
 Query
 Criteria
 Transaction

154) Why to use ORM over JDBC?


 Application development is fast.
 Management of transaction.
 Generates key automatically.
 Details of SQL Queries are hidden.

155) What is difference b/w Hibernate and JDBC?


Hibernate JDBC
It is a framework It is database connectivity
technology
Hibernate support lazy loading It does not support lazy loading
Hibernate itself manage all We need to maintain explicitly
transaction database connection and
transaction.
It provides two types of caching We need to write code for
 First level cache implementing caching
 Second level cache
No extra code is required to use
First level cache
High Performance Low performance

156) What is difference b/w Hibernate and JPA?


Hibernate JPA
Hibernate is an Object-Relational Java Persistence API (JPA) defines
Mapping (ORM) tool which is used the management of relational data
to save the state of Java object in the Java applications.
into the database.
It is one of the most frequently It is just a specification. Various ORM
used JPA implementation. tools implement it for data
persistence.
It is defined It is defined
in org.hibernate package. in javax.persistence package.
It uses SessionFactory interface to The EntityManagerFactory interface
create Session instances. is used to interact with the entity
manager factory for the persistence
unit. Thus, it provides an entity
manager.
It uses Session interface to create, It uses EntityManager interface to
read, and delete operations for create, read, and delete operations
instances of mapped entity for instances of mapped entity
classes. It behaves as a runtime classes. This interface interacts with
interface between a Java the persistence context.
application and Hibernate.
It uses Hibernate Query It uses Java Persistence Query
Language (HQL) as an object- Language (JPQL) as an object-
oriented query language to oriented query language to perform
perform database operations. database operations.

157) What is criteria in the hibernate?


The objects of criteria are used for the creation and execution of the
object-oriented criteria queries.

158) Which are the supported db’s by hibernate?


 DB2
 MySQL
 Oracle
 Sybase SQL Server
 PostgreSQL

159) What are the key components of hibernate?


 Configuration
 SessionFactory
 Session
 Query
 Criteria
 Transaction

160) What imp details we configure in hibernate configuration?


 DB Configuration
 Class mappings
 Pooling

161) What is HQL?


It’s a Hibernate Query Language. Hibernate Query Language (HQL) is an
object-oriented query language, similar to SQL, but instead of operating on
tables and columns, HQL works with persistent objects and their properties

162) How to create Query using HQL?


We can use createQuery() of Session interface. Like Session.createQuery().

163) How to create SQL Query in hibernate?


We can use createSQLQuery() of Session interface. Like
Session.createSQLQuery()

164) How to add criteria to SQL Query?


A criterion is added to a SQL query by using the Session.createCriteria.

165) What is difference b/w createQuery and createSQLQuery and


createCriteria?
createQuery createSQLQuery createCriteria
Creates Query Object Creates Query Object Creates Criteria Object
Uses HQL Syntax Uses DB Specific Uses Entity Class
Syntax
The Columns of the The Columns of the Create sql query using
rows retrieved would rows retrieved would Criteria object for
be name of the POJO be name of Native DB setting the query
Model Class fields parameters
CRUD operation could CRUD operation could Only Read Operation is
be done be done allowed
Supports Does not support Supports
Interoperability Interoperability since Interoperability
between different the query format between different
DB’s should be changed DB’s
when the DB is
changed
Does not work without Bean with columns of Does not work without
Model Class Table alone is Model Class
Enough.No need for
Entity class generation
No need for mapping The Bean Objects No need for mapping
between Entity class should be mapped
object and Table with table Columns
Columns

166) What is persistent class?


Classes whose objects are stored in a database table are called as
persistent classes.

167) What is SessionFactory?


SessionFactory provides the instance of Session. It is a factory of Session.
It holds the data of second level cache that is not enabled by default.

168) Is SessionFactory is thread-safe?


Yes, SessionFactory is a thread-safe object, many threads cannot access it
simultaneously.

169) What is Session?


It maintains a connection between the hibernate application and
database. It provides methods to store, update, delete or fetch data from
the database such as persist(), update(), delete(), load(), get() etc. It is a
factory of Query, Criteria and Transaction i.e. it provides factory methods
to return these instances.

170) Is Session thread-safe?


No, Session is not a thread-safe object, many threads can access it
simultaneously. In other words, you can share it between threads.

171) What is difference b/w SessionFactory and Session?


SessionFactory Session
SessionFactory is immutable and A Session is a single-threaded,
shared by all Session. It also lives short-lived object.
until the Hibernate is running.
It provides the second-level cache It provides the first-level cache
that we need to enable it. that is by default enabled.

172) What is difference b/w save() and persist()?


save() persist()
returns the identifier (Serializable) Return nothing because its return
of the instance. type is void.
Syntax : public Serializable Syntax : public void persist(Objecct
save(Objecct o) o)

173) What is difference b/w get() and load()?


get() load()
Returns null if an object is not Throws ObjectNotFoundException if
found. an object is not found.
It always hit the database It doesn’t hit the database
It returns the real object, not the It returns proxy object.
proxy.
It should be used if you are not It should be used if you are sure that
sure about the existence of instance exists.
instance

174) What is difference b/w update() and merge()?


update() merge()
Update means to edit something. Merge means to combine
something.
update() should be used if the merge() should be used if you don't
session doesn't contain an already know the state of the session,
persistent state with the same id. It means you want to make the
means an update should be used modification at any time.
inside the session only. After
closing the session, it will throw
the error.
175) List out the states of object in hibernate.
There are 3 states of the object (instance) in hibernate.
 Transient
 Persistent
 Detached

176) What is Transient?


The object is in a transient state if it is just created but has no primary key
(identifier) and not associated with a session.

177) What is Persistent?


The object is in a persistent state if a session is open, and you just saved
the instance in the database or retrieved the instance from the database.

178) What is Detached?


The object is in a detached state if a session is closed. After detached
state, the object comes to persistent state if you call lock() or update()
method.

179) What is automatic dirt checking?


The automatic dirty checking feature of Hibernate, calls update statement
automatically on the objects that are modified in a transaction.

180) What are the association mappings available in hibernate?


There can be 4 types of association mapping in hibernate.
 One to One
 One to Many
 Many to One
 Many to Many

181) What is Lazy Loading?


Lazy loading in hibernate improves the performance. It loads the child
objects on demand. Since Hibernate 3, lazy loading is enabled by default,
and you don't need to do lazy="true". It means not to load the child
objects when the parent is loaded.

182) What is Eager Loading?


Data loading happens at the time of their parent is fetched.

183) What is difference b/w Lazy and Eager Loading?


Lazy Loading Eager Loading
In Lazy loading, associated data In Eager loading, data loading
loads only when we explicitly call happens at the time of their parent
getter or size method. is fetched
ManyToMany and OneToMany ManyToOne and OneToOne
associations used lazy loading associations used lazy loading
strategy by default. strategy by default.
It can be enabled by using the It can be enabled by using the
annotation parameter : annotation parameter :

fetch = FetchType.LAZY fetch = FetchType.EAGER


Initial load time much smaller than Loading too much unnecessary
Eager loading data might impact performance

184) What is difference b/w First level cache and Second level cache?
First Level Cache Second Level Cache
First Level Cache is associated with Second Level Cache is associated
Session. with SessionFactory.
It is enabled by default. It is not enabled by default.

185) What are the important annotations of hibernate?


Hibernate supports JPA annotations that are from javax.persistence
package
 Entity: This is used with model classes to specify they are entity
beans.
 Table: It is used with entity beans to define the corresponding table
name in the database.
 Id: Defines the primary key in the entity bean.
 Column: Helps in defining the column name in the database table.
 GeneratedValue: It defines the strategy to be used for the
generation of the primary key. It is also used in conjunction
with javax.persistence.GenerationType enum.

186) What is getCurrentSession ()?


This getCurrentSession() method returns the session bound to the context
and for this to work, you need to configure it in Hibernate configuration
file. Since this session object belongs to the context of Hibernate, it is
okay if you don’t close it. Once the SessionFactory is closed, this session
object gets closed.

187) What is openSession ()?


openSession() method helps in opening a new session. You should close
this session object once you are done with all the database operations.
And also, you should open a new session for each request in a multi-
threaded environment.

188) What is difference b/w openSession() and getCurrentSession()?


openSession() getCurrentSession()
It always create new It creates a new Session if not exists , else
Session object use same session which is in current
hibernate context
You need to explicitly flush You do not need to flush and close session
and close session objects objects, it will be automatically taken care
by Hibernate internally
In single threaded In single threaded environment , It is
environment , It is slower faster than getOpenSession
than getCurrentSession
You do not need to You need to configure additional property
configure any property to “hibernate.current_session_context_class”
call this method to call getCurrentSession method,
otherwise it will throw exceptions.
189) Which are the design patterns used in hibernate?
There are a few design patterns used in Hibernate Framework, namely:
 Domain Model Pattern: An object model of the domain that
incorporates both behavior as well as data.
 Data Mapper: A layer of the map that moves data between objects
and a database while keeping it independent of each other and the
map itself.
 Proxy Pattern: It is used for lazy loading.
 Factory Pattern: Used in SessionFactory.

190) What is hibernate validation framework?


Hibernate validator can be used to validate data, which is a very
important issue in every layer of an application. Hibernate validator
framework provides many annotations, that can be used to validate input
fields of a form against constraints.

191) List out some important validation annotations.


 @Size: This annotation is used to set the size of the field. It has three
properties to configure, the min, max and the message to be set.
 @Min: This annotation is used to set the min size of a field
 @Max: This annotation is used to set the max size of a field
 @NotNull: With this annotation you can make sure that the field has
a value.
 @Length: This annotation is similar to @Size
 @Pattern: This annotation can be used when we want to check a
field against a regular expression. The regex is set as an attribute to
the annotation.

192) What is hibernate tuning?


Optimizing the performance of Hibernate applications is known as
Hibernate tuning. The performance tuning strategies for Hibernate are:
 SQL Optimization
 Session Management
 Data caching
193) What is Transaction Management?
Transaction Management is a process of managing a set of commands or
statements. In hibernate, Transaction Management is done by transaction
interface. It maintains abstraction from the transaction implementation
(JTA, JDBC). A transaction is associated with Session and is instantiated by
calling session.beginTransaction().

194) What is query caching?


Hibernate implements a separate cache region for queries resultset that
integrates with the Hibernate second-level cache. This is also an optional
feature and requires a few more steps in code.

195) What is Named SQL Query?


Hibernate provides another important feature called Named Query using
which you can define at a central location and use them anywhere in the
code. You can create named queries for both HQL as well as for Native
SQL. These Named Queries can be defined in Hibernate mapping files with
the help of JPA annotations @NamedQuery and @NamedNativeQuery.

196) What is JDBC?


JDBC stands for Java Database Connectivity. JDBC is a Java API that
communicates with the database and execute SQLquery.

197) What is JDBC Driver and types of driver?


JDBC driver contains classes and interfaces that help Java application and
database. There are 4 types of JDBC drivers.
 Type 1 driver or JDBC-ODBC bridge driver.
 Type 2 driver or Native-API, partly java driver.
 Type 3 driver or Network Protocol, pure java driver.
 Type 4 driver or Native-protocol, pure java driver.

198) What is Class.forName?


Class.forName creates an instance of JDBC driver and register with
DriverManager.

199) What are the JDBC API components?


There are four types of components
 JDBC API
 JDBC Driver Manager
 JDBC Test Suit
 JDBC-ODBC Bridge

200) What are the JDBC statements?


There are 3 types of JDBC Statements, as given below:
 Statement: It will execute SQL query (static SQL query) against the
database.
 Prepared statement: Used when we want to execute SQL statement
repeatedly. Input data is dynamic and taken input at the run time.
 Callable statement: Used when we want to execute stored
procedures.

201) What is Service Discovery in microservices?


It is a server which holds the list of URL’s of the different server at one
place so when a client needs the different URL’s, client can find those
URL’s at one place only.

202) Disadvantages of Service Discovery microservices?


It is time consuming
It works like mediator between services and client so if service discovery
is not working then it is problematic to find the URL’s.

203) What is Netflix OSS?


It is a library of microservices which is open source that used to work
with spring boot.
Libraries like Eureka, Ribbon, Hysterix, Zuul, etc.
204) What is Eureka Server?
Eureka server is nothing but the discovery server provided by Netflix
OSS. It is server in the form of library.

205) What is Eureka Client?


Eureka client is nothing but the different kind of microservices that are
registered in the Eureka server aka discovery server.

206) What is @EnableEurekaServer?


It tells to spring that this is Eureka server spring boot application.

207) What is @EnableEurekaClient?


It tells to spring that this is Eureka server’s client spring boot application.

208) What is default server port of Eureka server?


Default server port of eureka server is 8761

209) Does eureka server has caching functionality or not?


Yes it has cache functionality. First time by when client call for service, it
loads from server and next time it loads from cache memory.
210) If any service is not available or down then what happens?
When any service is running on server it pings to server in regular
interval so that server get to know that service is still in running
condition but if service is down it can’t pings to server and server send
response to client that there is no any kind of XXX service is available.

211) If discovery (Eureka) server is down then what?


If server is down then client gets the response from the default cache
that has been created by calling service before so client get response
from default cache. And if there is no cache then no response to client.

212) How to implement security in rest api?


213) What is the order of Junit test case method?
By default, JUnit runs tests using a deterministic, but unpredictable
order (MethodSorters.DEFAULT).

214) What is @TestInstance in junit?


@TestInstance is a type-level annotation that is used to configure the
lifecycle of test instances for the annotated test class or test interface. If
@TestInstance is not declared on a test class or implemented test
interface, the lifecycle mode will implicitly default to PER_METHOD.

It allows you to create only one instance of that test class on which it is
written otherwise instance of class will be created each time when a test
method is called of that class.

215) What is @DisplayName in junit?


@DisplayName is used to declare a custom display name for the
annotated test class or test method. Display names are typically used for
test reporting in IDEs and build tools and may contain spaces, special
characters, and even emoji.

216) What is @Disable in junit?


@Disabled is used to signal that the annotated test class or test method
is currently disabled and should not be executed. When applied at the
class level, all test methods within that class are
automatically disabled as well.

217) What is @EnabledOnOs(OS.Linux) in junit?


@EnabledOnOs(OS.Linux) is used to perform the test operation on that
particular OS only. It will not allow you to run that test on ther OS.

218) What is @EnabledOnJre(JRE.Java_11) in junit?


@EnabledOnJre(JRE.Java_11) same like OS it will not allow you to run
the test on other jre. It allow you to run this test only on the mentioned
jre version.

219) What is @EnableIf in junit?


@EnabledIf is used to determine whether the annotated test class or
test method is enabled by evaluating a script. The annotated element
will be enabled if the value is true.

220) What is @Nested in junit?


The @Nested annotation allows you to have an inner class that's
essentially a test class, allowing you to group several test classes under
the same parent (with the same initialization).

221) What is assertAll in junit?


Loading when this answer was accepted… The interesting thing
about assertAll is that it always checks all of the assertions that are
passed to it, no matter how many fail. If all pass, all is fine - if at least
one fails you get a detailed result of all that went wrong (and right for
that matter)

222) What is @RepetedTest in junit?


@RepeatedTest is used to signal that the annotated method is a test
template method that should be repeated a specified number of times
with a configurable display name.

223) Diff b/w Real DOM and Virtual DOM.


Real DOM Virtual DOM
It updates slow. It updates faster.
Can directly update HTML. Can’t directly update HTML.
Creates a new DOM if element Updates the JSX if element
updates. updates.
DOM manipulation is very DOM manipulation is very easy.
expensive.
Too much of memory wastage. No memory wastage.

224) What is React JS?


React is a front-end JavaScript library developed by Facebook in 2011. It
follows the component based approach which helps in building reusable
UI components. It is used for developing complex and interactive web
and mobile UI.Even though it was open-sourced only in 2015, it has one
of the largest communities supporting it.

225) What are the features of React JS?


It uses the virtual DOM instead of the real DOM.
It uses server-side rendering.
It follows uni-directional data flow or data binding.

226) What are the advantages of React?


It increases the application’s performance
It can be conveniently used on the client as well as server side
Because of JSX, code’s readability increases
React is easy to integrate with other frameworks like Meteor, Angular,
etc
Using React, writing UI test cases become extremely easy

227) What are the disadvantages or drawback of React?


React is just a library, not a full-blown framework
Its library is very large and takes time to understand
It can be little difficult for the novice programmers to understand
Coding gets complex as it uses inline templating and JSX

228) What is flexbox in react?


Flexbox is designed to provide a consistent layout on different screen
sizes. Normally we use a combination of flexDirection, allignitems, and
justifyContent to achieve the right layout
229) What is JSX?
JavaScript XML(JSX) is a type of file used by react which utilizes the
expressiveness of javascript along with html like template syntax. This
makes the HTML file really easy to understand. This file makes
applications robust and boosts its performance.

230) “In react, everything is a component” why?


Components are the building blocks of a React application’s UI. These
components split up the entire UI into small independent and reusable
pieces. Then it renders each of these components independent of each
other without affecting the rest of the UI.

231) What is the purpose of render()?


Each React component must have a render() mandatorily. It returns a
single React element which is the representation of the native DOM
component. If more than one HTML element needs to be rendered,
then they must be grouped together inside one enclosing tag such
as <form>, <group>,<div> etc. This function must be kept pure i.e., it
must return the same result each time it is invoked.

232) What is props?


Is use to pass data from parent to child component or child to parent
component. Simply it is use to pass data between two component. Here
parent component can change the data but child component couldn’t
change the data. Child component could use the data only but couldn’t
change the data.

233) What is state?


States are the heart of React components. States are the source of data
and must be kept as simple as possible. Basically, states are the objects
which determine components rendering and behavior. They are
mutable unlike the props and create dynamic and interactive
components. They are accessed via this.state().

234) What is arrow function?


Arrow functions are more of brief syntax for writing the function
expression. They are also called ‘fat arrow‘ (=>) the functions. These
functions allow to bind the context of the components properly since in
ES6 auto binding is not available by default. Arrow functions are mostly
useful while working with the higher order functions.

235) What is StateFull and StateLess component?


StateFul Component StateLess Component
Stores info about component’s Calculates the internal state of the
state change in memory components
Have authority to change state Do not have the authority to
change state
Contains the knowledge of past, Contains no knowledge of past,
current and possible future current and possible future state
changes in state changes
Stateless components notify them They receive the props from the
about the requirement of the Stateful components and treat
state change, then they send them as callback functions.
down the props to them.

236) Life cycle methods of class component in React?


componentWillMount() – Executed just before rendering takes place
both on the client as well as server-side.
componentDidMount() – Executed on the client side only after the first
render.
componentWillReceiveProps() – Invoked as soon as the props are
received from the parent class and before another render is called.
shouldComponentUpdate() – Returns true or false value based on
certain conditions. If you want your component to update,
return true else return false. By default, it returns false.
componentWillUpdate() – Called just before rendering takes place in
the DOM.
componentDidUpdate() – Called immediately after rendering takes
place.
componentWillUnmount() – Called after the component is unmounted
from the DOM. It is used to clear up the memory spaces.

237) What is event in React?


In React, events are the triggered reactions to specific actions like
mouse hover, mouse click, key press, etc. Handling these events are
similar to handling events in DOM elements. But there are some
syntactical differences like:

Events are named using camel case instead of just using the lowercase.
Events are passed as functions instead of strings.
The event argument contains a set of properties, which are specific to
an event. Each event type contains its own properties and behavior
which can be accessed via its event handler only.

238) What are synthetic events in React?


Synthetic events are the objects which act as a cross-browser wrapper
around the browser’s native event. They combine the behavior of
different browsers into one API. This is done to make sure that the
events show consistent properties across different browsers.

239) How to call Garbage collector?


1) Runtime.getRuntime().gc()
2) System.gc();

240) What is memory leaks in java?


Memory leak is a situation in java when the objects are present in
memory that are no longer useful and garbage collector is not able to
remove it from the memory.
241) What is string pool in java?
String pool is storage area in heap memory which is used to store the
string literal. So if we try to store same value using string variable then it
will not create the new memory

242) What is cohesion?

243) Diff prototype and singleton


244) Diff get and load
245) Transient, volatile
246) Try with resource
247) Debug application without logger

248) Scopes of bean


 Signleton
 Prototype
 Session
 Global Session
 Request

249) What is tight coupling in spring?


Tight coupling: one class is dependent on another class. Like We created
the object of class A inside the class B. and if we change any method of
class A then it will affect in the result of class B.

250) What is the default scope of bean in spring framework?


Singleton is the default scope for a Bean

251) If we create 2 instance of same class in bean then what happens? Like
<bean id=”one” class=”Employee.java”> <bean id=”two”
class=”Employee.java”>
https://stackoverflow.com/questions/19324508/define-two-beans-of-same-
class-in-single-application-context

252) Difference b/w fork and clone


Fork Clone
When you fork a repository, when you clone a repository, the
you create a copy of the repository is copied on to your local
original repository (upstream machine with the help of Git
repository) but the repository
remains on your GitHub
account.
Forked project is on your Cloned project is on your local machine (I
online repository usually clone after forking the repo).

253) What is the use of Junit?


JUnit is an open source framework designed by Kent Beck, Erich Gamma for
the purpose of writing and running test cases for java programs. In the
case of web applications JUnit is used to test the application with out
server. This framework builds a relationship between development and
testing process.

254) Calculate volume of sphere using unary operator

255) List the scope of beans


Singleton
Prototype
Request
Session
Global-session

256) Difference b/w Union and Union All


Union Union All
only keeps unique records keeps all records, including
duplicates
The UNION operator removes the UNION ALL operator does not
eliminate duplicate rows

257) What is pivot table


A pivot table is a table of statistics that summarizes the data of a more
extensive table. This summary might include sums, averages, or other
statistics, which the pivot table groups together in a meaningful way. Pivot
tables are a technique in data processing.

258) Difference b/w Put and Patch method


Put Patch
PUT is a method of modifying PUT is a method of modifying
resource where the client sends resource where the client sends
data that updates the entire partial data that to be updated
resource without modifying the entire data
In a PUT request, the enclosed With PATCH, however, the
entity is considered to be a enclosed entity contains a set of
modified version of the resource instructions describing how a
stored on the origin server, and resource currently residing on the
the client is requesting that the origin server should be modified
stored version be replaced to produce a new version.
HTTP PUT is said to be HTTP PATCH is basically said to be
idempotent, So if you send retry a non-idempotent. So if you retry
request multiple times, that the request N times, you will end
should be equivalent to a single up having N resources with N
request modification different URIs created on the
server.
It has High Bandwidth Since Only data that need to be
modified if send in the request
body as a payload , It has Low
Bandwidth

259) What is CORS?


It is Cross-Origin Resource Sharing (CORS) is an HTTP-header based
mechanism that allows a server to indicate any other origins (domain,
scheme, or port) than its own from which a browser should permit loading
of resources. ... For security reasons, browsers restrict cross-origin HTTP
requests initiated from scripts

260) What is SASS?


SASS stands for Syntactically Awesome Style Sheets is an extension of
CSS that enables you to use things like variables, nested rules, inline
imports and more. Sass is compatible with all versions of CSS. The only
requirement for using it is that you must have Ruby installed.

261) What is Flexbox?


Flexbox is a layout model that allows elements to align and distribute
space within a container. Using flexible widths and heights, elements
can be aligned to fill a space or distribute space between elements,
which makes it a great tool to use for responsive design systems.
The CSS3 flexbox is used to make the elements behave predictably when
they are used with different screen sizes and different display devices. It
provides a more efficient way to layout, align and distribute space among
items in the container.
It is mainly used to make CSS3 capable to change its item’s width and
height to best fit for all available spaces.

262) What if a microservice is down?


Now create multiple instances of a microservice, so if one microservice is
down then other can take place of it. And flow doesn’t breaks.

263) What is singleton design pattern?


Singleton Pattern says that "define a class that has only one instance and
provides a global point of access to it". In other words, a class must ensure
that only single instance should be created and single object can be used by all
other classes.

264) How to create singleton design pattern?


Static member: It gets memory only once because of static, itcontains the
instance of the Singleton class.
Private constructor: It will prevent to instantiate the Singleton class from
outside the class.
Static factory method: This provides the global point of access to the
Singleton object and returns the instance to the caller.

265) What is factory design pattern?


A Factory Pattern or Factory Method Pattern says that just define an interface or
abstract class for creating an object but let the subclasses decide which
class to instantiate. In other words, subclasses are responsible to create the
instance of the class. The Factory Method Pattern is also known as Virtual
Constructor.

266) What is prototype design pattern?


Prototype Pattern says that cloning of an existing object instead of
creating new one and can also be customized as per the requirement.
This pattern should be followed, if the cost of creating a new object is
expensive and resource intensive.

267) What is spring profile in spring boot?


A profile is a set of configuration settings. Spring Boot allows to
define profile specific property files in the form of application-
{profile}.properties. It automatically loads the properties in an
application.

268) What is @Embedded in hibernate?

269) What is @Embeddable in hibernate?


270) How to define constraints in hibernate?
271) Disadvantage of autowiring in spring?
Autowiring is less exact than explicit wiring. Spring is careful to avoid
guessing in the case of ambiguity that might have unexpected results, the
relationships between Spring-managed objects are no longer document
explicitly.

Wiring information may not be available to tools that generate


documentation from a Spring container.
Multiple bean definition within the container may match the type specified
by the constructor or setter method argument to be autowired.

272) What is early binding?


The binding which can be resolved at compile time by the compiler is known as static or
early binding. Binding of all the static, private and final methods is done at compile-time

273) What is late binding?

274) How to authenticate microservice?


275)
276)
277)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy