0% found this document useful (0 votes)
3 views211 pages

Java Interview Questions(J2SE)

The document provides an overview of basic Java concepts, including its definition, features, and differences from C++. It explains Java's architecture, including the roles of JVM, JRE, and JDK, as well as memory management and the object-oriented paradigm. Additionally, it covers constructors, access specifiers, and the advantages of using packages in Java.

Uploaded by

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

Java Interview Questions(J2SE)

The document provides an overview of basic Java concepts, including its definition, features, and differences from C++. It explains Java's architecture, including the roles of JVM, JRE, and JDK, as well as memory management and the object-oriented paradigm. Additionally, it covers constructors, access specifiers, and the advantages of using packages in Java.

Uploaded by

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

BASIC JAVA QUESTIONS-1

1. What is Java?
Java is the high-level, object-oriented, robust, secure programming language, platform-
independent, high performance, Multithreaded, and portable programming language. It was
developed by James Gosling in June 1991. It can also be known as the platform as it provides
its own JRE and API.

2. What are the differences between C++ and Java?

COMPARISON
INDEX C++ JAVA
PARAMETER
C++ was developed by
Bjarne Stroustrup at Bell Java was developed by James Gosling
Developed /
1 Labs in 1979. It was at Sun Microsystems. Now, it is owned
Founded by
developed as an extension by Oracle.
of the C language.
It has support for both
Programming procedural programming Java has support only for object-
2
model and object-oriented oriented programming models.
programming.
C++ is platform dependent.
Java is platform-independent. It is
Platform It is based on the concept of
3 based on the concept of Write Once
dependence Write Once Compile
Run Anywhere.
Anywhere.
C++ supports features like Java does not support features like
Features operator overloading, Goto operator overloading, Goto
4
supported statements, structures, statements, structures, pointers,
pointers, unions, etc. unions, etc.
Compilation and C ++ is only compiled and Java can be both compiled and
5
Interpretation cannot be interpreted. interpreted.
Java, on the other hand, has more
C++ has very limited
diverse libraries with a lot of support
Library and Code libraries with low-level
for code reusability. In Java, only calls
6 reusability functionalities. C++ allows
through the Java Native Interface and
support direct calls to native system
recently Java Native Access are
libraries.
allowed.
Memory In C++, memory In Java, memory management is
7
Management management is manual. System controlled.

C++ is pretty consistent


In Java, semantics differs for primitive
8 Type semantics between primitive and
and object types.
object types.
In C++, both global and
9 Global Scope namespace scopes are Java has no support for global scope.
supported.
Access control In C++, a flexible model with
In Java, the model is cumbersome and
10 and object constant protection is
encourages weak encapsulation.
protection available.

3. List the features of Java Programming language.


There are the following features in Java Programming Language.

o Simple: Java is easy to learn. The syntax of Java is based on C++ which
makes easier to write the program in it.

o Object-Oriented: Java follows the object-oriented paradigm which allows


us to maintain our code as the combination of different type of objects
that incorporates both data and behavior.

o Portable: Java supports read-once-write-anywhere approach. We can


execute the Java program on every machine. Java program (.java) is
converted to bytecode (.class) which can be easily run on every machine.
o Platform Independent: Java is a platform independent programming
language. It is different from other programming languages like C and
C++ which needs a platform to be executed. Java comes with its platform
on which its code is executed. Java doesn't depend upon the operating
system to be executed.

o Secured: Java is secured because it doesn't use explicit pointers. Java


also provides the concept of ByteCode and Exception handling which
makes it more secured.

o Robust: Java is a strong programming language as it uses strong memory


management. The concepts like Automatic garbage collection, Exception
handling, etc. make it more robust.

o Architecture Neutral: Java is architectural neutral as it is not dependent


on the architecture. In C, the size of data types may vary according to the
architecture (32 bit or 64 bit) which doesn't exist in Java.

o Interpreted: Java uses the Just-in-time (JIT) interpreter along with the
compiler for the program execution.

o High Performance: Java is faster than other traditional interpreted


programming languages because Java bytecode is "close" to native code.
It is still a little bit slower than a compiled language (e.g., C++).

o Multithreaded: We can write Java programs that deal with many tasks at
once by defining multiple threads. The main advantage of multi-
threading is that it doesn't occupy memory for each thread. It shares a
common memory area. Threads are important for multi-media, Web
applications, etc.
o Distributed: Java is distributed because it facilitates users to create
distributed applications in Java. RMI and EJB are used for creating
distributed applications. This feature of Java makes us able to access files
by calling the methods from any machine on the internet.

o Dynamic: Java is a dynamic language. It supports dynamic loading of


classes. It means classes are loaded on demand. It also supports
functions from its native languages, i.e., C and C++.
4. What do you understand by Java virtual machine?
Java Virtual Machine 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.

5. What is the difference between JDK, JRE, and JVM?

JVM
JVM is an acronym for Java Virtual Machine; it is an abstract machine which provides the
runtime environment in which Java bytecode can be executed. It is a specification which
specifies the working of Java Virtual Machine. Its
implementation has been provided by Oracle and other companies. Its implementation is
known as JRE.
JVMs are available for many hardware and software platforms (so JVM is platform
dependent). It is a runtime instance which is created when we run the Java class. There are
three notions of the JVM: specification, implementation, and instance.
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.
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:

o Standard Edition Java Platform


o Enterprise Edition Java Platform
o Micro Edition Java Platform
6. How many types of memory areas are allocated by JVM?
Many types:

1. Class(Method) Area: Class Area stores per-class structures such as the


runtime constant pool, field, method data, and the code for methods.
2. Heap: It is the runtime data area in which the memory is allocated to the
objects
3. Stack: Java Stack stores frames. It holds local variables and partial
results, and plays a part in method invocation and return. Each thread
has a private JVM stack, created at the same time as the thread. A new
frame is created each time a method is invoked. A frame is destroyed
when its method invocation completes.
4. Program Counter Register: PC (program counter) register contains the
address of the Java virtual machine instruction currently being executed.
5. Native Method Stack: It contains all the native methods used in the
application.

7. What is JIT compiler?

Just-In-Time(JIT) compiler: It is 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.
8. What is the platform?

A platform is the hardware or software environment in which a piece of software is executed.


There are two types of platforms, software-based and hardware- based. Java provides the
software-based platform.

9. What are the main differences between the Java platform and other
platforms?

There are the following differences between the Java platform and other platforms.

o Java is the software-based platform whereas other platforms may be the


hardware platforms or software-based platforms.
o Java is executed on the top of other hardware platforms whereas other
platforms can only have the hardware components.

10. What gives Java its 'write once and run anywhere' nature?

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.

1. 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.
2. 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.
3. 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. What if I write static public void instead of public static void?
The program compiles and runs correctly because the order of specifiers doesn't matter in Java.

13. What is the default value of the local variables?


The local variables are not initialized to any default value, neither primitives nor object
references.

14. What are the various access specifiers 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.

o Public The classes, methods, or variables which are defined as public, can
be accessed by any class or method.
o 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.
o Default Default are accessible within the package only. By default, all the
classes, methods, and variables are of default scope.
o Private The private class, methods, or variables defined as private can be
accessed within the class only.

15. What is the purpose of static methods and variables?

o The methods or variables defined as static are shared among all the objects of
the class. The static is the part of the class and not of the object. The static
variables are stored in the class area, and we do not need to create the object
to access such variables. Therefore, static is used in the case, where we need to
define variables or methods which are common to all the objects of the class.
o For example, In the class simulating the collection of the students in a college,
the name of the college is the common attribute to all the students. Therefore,
the college name will be defined as static.
16. What are the advantages of Packages in Java?

There are various advantages of defining packages in Java.

o Packages avoid the name clashes.


o The Package provides easier access control.
o We can also have the hidden classes that are not visible outside and used
by the package.
o It is easier to locate the related classes.

17. What is the output of the following Java program?

1. class Test
2. {
3. public static void main (String args[])
4. {
5. for(int i=0; 0; i++)
6. {
7. System.out.println("Hello Javatpoint");
8. }
9. }
10.}

Answer: The above code will give the compile-time error because the for loop
demands a boolean value in the second part and we are providing an integer value, i.e.,
0.

18. What is object-oriented paradigm?

It is a programming paradigm based on objects having data and methods defined in the class
to which it belongs. Object-oriented paradigm aims to incorporate the advantages of
modularity and reusability. Objects are the instances of classes which interacts with one
another to design applications and programs. There are the following features of the object-
oriented paradigm.

o Follows the bottom-up approach in program design.


o Focus on data with methods to operate upon the object's data
o Includes the concept like Encapsulation and abstraction which hides the
complexities from the user and show only functionality.
o Implements the real-time approach like inheritance, abstraction, etc.
o The examples of the object-oriented paradigm are C++, Simula, Smalltalk,
Python, C#, etc.

19. What is an object?

o 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.

20. What is the difference between an object-oriented programming


language and object-based programming language?

There are the following basic differences between the object-oriented language
and object-based language.

o Object-oriented languages follow all the concepts of OOPs whereas, the


object-based language doesn't follow all the concepts of OOPs like
inheritance and polymorphism.
o Object-oriented languages do not have the inbuilt objects whereas
Object-based languages have the inbuilt objects, for example, JavaScript
has window object.
o Examples of object-oriented programming are Java, C#, Smalltalk, etc.
whereas the examples of object-based languages are JavaScript, VBScript,
etc.

21. What will be the initial value of an object reference which is defined
as an instance variable?

o All object references are initialized to null in Java.

22. What is the constructor?

o 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.
23. How many types of constructors are used in Java?

Based on the parameters passed in the constructors, there are two types of constructors
in Java.

o Default Constructor: default constructor is the one which does not accept
any value. The default constructor is mainly used to initialize the instance
variable with the default values. It can also be used for performing some
useful task on object creation. A default constructor is invoked implicitly
by the compiler if there is no constructor defined in the class.
o Parameterized Constructor: The parameterized constructor is the one
which can initialize the instance variables with the given values. In other
words, we can say that the constructors which can accept the arguments
are called parameterized constructors.

24. What is the purpose of a default constructor?

o The purpose of the default constructor is to assign the default value to the
objects. The java compiler creates a default constructor implicitly if there is no
constructor in the class.

25. Does constructor return any value?

yes, The constructor implicitly returns the current instance of the class (You can't use an explicit
return type with the constructor)

26. Is constructor inherited? And Can you make a constructor final?


No, The constructor is not inherited. and also the constructor can't be final.

27. Can we overload the constructors?


Yes, the constructors can be overloaded by changing the number of arguments accepted by
the constructor or by changing the data type of the parameters.

28. What do you understand by copy constructor in Java?

There is no copy constructor in java. However, we can copy the values from one object to
another like copy constructor in C++.

There are many ways to copy the values of one object into another in java. They are:
o By constructor
o By assigning the values of one object into another
o By clone() method of Object class

29. What are the differences between the constructors and methods?

There are many differences between constructors and methods. They are given below.

Java Constructor Java Method

A constructor is used to initialize the state of an object. A method is used to expose the
behavior of an object.

A constructor must not have a return type. A method must have a return type.

The constructor is invoked implicitly. The method is invoked explicitly.

The Java compiler provides a default constructor if you The method is not provided by the
don't have any constructor in a class. compiler in any case.

The constructor name must be same as the class The method name may or may not
name. be same as class name.

30. What is the static variable?

The static variable is used to refer to the common property of all objects (that is not unique for
each object), e.g., The company name of employees, college name of students, etc. Static
variable gets memory only once in the class area at the time of class loading. Using a static
variable makes your program more memory efficient (it saves memory). Static variable belongs
to the class rather than the object.

31. What is the static method?

o A static method belongs to the class rather than the object.


o There is no need to create the object to call the static methods.
o A static method can access and change the value of the static variable.
32. What are the restrictions that are applied to the Java static
methods?

Two main restrictions are applied to the static methods.

o The static method can not use non-static data member or call the non-
static method directly.
o this and super cannot be used in static context as they are non-static.

33. Why is the main method static?

Because the object is not required to call the static method. If we make the main
method non-static, JVM will have to create its object first and then call main() method
which will lead to the extra memory allocation.

34. Can we override the static methods?

No, we can't override static methods.

35. What is the static block?

Static block is used to initialize the static data member. It is executed before the main
method, at the time of classloading.

1. class A2{
2. static{System.out.println("static block is invoked");}
3. public static void main(String args[]){
4. System.out.println("Hello main");
5. }
6. }

36. Can we execute a program without main() method?

No, It was possible before JDK 1.7 using the static block. Since JDK 1.7, it is not
possible.

37. What if the static modifier is removed from the signature of the main
method?

Program compiles. However, at runtime, It throws an error


"NoSuchMethodError."
38. What is the difference between static (class) method and
instance method?

static or class method instance method

1)A method that is declared as static is known A method that is not


as the static method. declared as static is known as
the instance method.

2)We don't need to create the objects to call the The object is required to call
static methods. the instance methods.

3)Non-static (instance) members cannot be Static and non-static


accessed in the static context (static method, variables both can be
static block, and static nested class) directly. accessed in instance
methods.

4)For example: public static int cube(int n){ For example: public void
return n*n*n;} msg(){...}.

39. Can we make constructors static?


As we know that the static context (method, block, or variable) belongs to the class, not the
object. Since Constructors are invoked only when the object is created, there is no sense to
make the constructors static. However, if you try to do so, the compiler will show the compiler
error.

40. Can we make the abstract methods static in Java?


In Java, if we make the abstract methods static, It will become the part of the class, and we can
directly call it which is unnecessary. Calling an undefined method is completely useless
therefore it is not allowed.

41. Can we declare the static variables and methods in an abstract class?

Yes, we can declare static variables and methods in an abstract method. As we know that there
is no requirement to make the object to access the static context, therefore, we can access the
static context declared inside the abstract class by using the name of the abstract class.
42. What is the 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.
When you inherit from an existing class, you can reuse methods and fields of the parent class.
Moreover, you can add new methods and fields in your current class also. Inheritance
represents the IS-A relationship which is also known as a parent-child relationship.

There are five types of inheritance in Java.

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

Multiple inheritance is not supported in Java through class.

43. Why is Inheritance used in Java?


There are various advantages of using inheritance in Java that is given below.

o Inheritance provides code reusability. The derived class does not need to
redefine the method of base class unless it needs to provide the specific
implementation of the method.
o Runtime polymorphism cannot be achieved without using inheritance.
o We can simulate the inheritance of classes with the real-time objects
which makes OOPs more realistic.
o Inheritance provides data hiding. The base class can hide some data from
the derived class by making it private.
o Method overriding cannot be achieved without inheritance. By method
overriding, we can give a specific implementation of some basic method
contained by the base class.

44. Which class is the superclass for all the classes?

The object class is the superclass of all other classes in Java.


45. Why is multiple inheritance 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.

Since the compile-time errors are better than runtime errors, Java renders compile-
time error if you inherit 2 classes. So whether you have the same method or different,
there will be a compile time error.

46. 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. For example, The aggregate class Employee having various
fields such as age, name, and salary also contains an object of Address class having
various fields such as Address-Line 1, City, State, and pin-code. In other words, we can
say that Employee (class) has an object of Address class.

47. 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. Example: A class contains students. A student cannot
exist without a class. There exists composition between class and students.

48. What is the difference between 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).

49. Why does Java not 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.
50. What is super in java?

The super keyword in Java is a reference variable that is used to refer to the immediate
parent class object. Whenever you create the instance of the subclass, an instance of
the parent class is created implicitly which is referred by super reference variable. The
super() is called in the class constructor implicitly by the compiler if there is no super
or this.

51. What are the main uses of the super keyword?

There are the following uses of super keyword.

o super can be used to refer to the immediate parent class instance variable.
o super can be used to invoke the immediate parent class method.
o super() can be used to invoke immediate parent class constructor.

52. What is this keyword in java?

The this keyword is a reference variable that refers to the current object. There are the
various uses of this keyword in Java. It can be used to refer to current class properties
such as instance methods, variable, constructors, etc. It can also be passed as an
argument into the methods or constructors. It can also be returned from the method
as the current class instance.

53. What are the main uses of this keyword?

There are the following uses of this keyword.

o this can be used to refer to the current class instance variable.


o this can be used to invoke current class method (implicitly)
o this() can be used to invoke the current class constructor.
o this can be passed as an argument in the method call.
o this can be passed as an argument in the constructor call.
o this can be used to return the current class instance from the method.

54. Can we assign the reference to this variable?

o No, this cannot be assigned to any value because it always points to the current
class object and this is the final reference in Java. However, if we try to do so,
the compiler error will be shown.
55. Can this keyword be used to refer static members?

Yes, It is possible to use this keyword to refer static members because this is just a
reference variable which refers to the current class object. However, as we know that,
it is unnecessary to access static variables through objects, therefore, it is not the best
practice to use this to refer static members.

56. What are the advantages of passing this into a method instead of the
current class object itself?

As we know, that this refers to the current class object, therefore, it must be similar to
the current class object. However, there can be two main advantages of passing this
into a method instead of the current class object.

o this is a final variable. Therefore, this cannot be assigned to any new value
whereas the current class object might not be final and can be changed.
o this can be used in the synchronized block.

57. What are the differences between this and super keyword?

There are the following differences between this and super keyword.

o The super keyword always points to the parent class contexts whereas this
keyword always points to the current class context.
o The super keyword is primarily used for initializing the base class variables
within the derived class constructor whereas this keyword primarily used to
differentiate between local and instance variables when passed in the class
constructor.
o The super and this must be the first statement inside constructor otherwise the
compiler will throw an error.

58. Can you use this() and super() both in a constructor?

o No, because this() and super() must be the first statement in the class
constructor.
o public class Test{
o Test()
o {
o super();
o this();
o System.out.println("Test class object is created");
o }
o public static void main(String []args){
o Test t = new Test();
o }
o }

Output:

Test.java:5: error: call to this must be first statement in constructor

59. 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. If we don't
implement Cloneable interface, clone() method generates
CloneNotSupportedException.

60. What is method overloading?

Method overloading is the polymorphism technique which allows us to create multiple


methods with the same name but different signature. We can achieve method
overloading in two ways.

o By Changing the number of arguments


o By Changing the data type of arguments

Method overloading increases the readability of the program. Method overloading is


performed to figure out the program quickly.

61. Why is method overloading not possible by changing the return type in
java?

In Java, method overloading is not possible by changing the return type of the
program due to avoid the ambiguity.

1. class Adder{
2. static int add(int a,int b){return a+b;}
3. static double add(int a,int b){return a+b;}
4. }
5. class TestOverloading3{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));//ambiguity
8. }}
Output:

Compile Time Error: method add(int, int) is already defined in class Adder

62. Can we overload the methods by making them static?

No, We cannot overload the methods by just applying the static keyword to
them(number of parameters and types are the same).

63. Can we overload the main() method?

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

64. What is method overriding?

If a subclass provides a specific implementation of a method that is already provided


by its parent class, it is known as Method Overriding. It is used for runtime
polymorphism and to implement the interface methods.

Rules for Method overriding

o The method must have the same name as in the parent class.
o The method must have the same signature as in the parent class.
o Two classes must have an IS-A relationship between them.

65. Can we override the static method?

o No, you can't override the static method because they are the part of the class,
not the object.

66. Why can we not override static method?

o It is because the static method is the part of the class, and it is bound with class
whereas instance method is bound with the object, and static gets memory in
class area, and instance gets memory in a heap.
67. Difference between method Overloading and Overriding.

Method Overloading Method Overriding

1) Method overloading increases Method overriding provides the specific


the readability of the program. implementation of the method that is already
provided by its superclass.

2) Method overloading occurs Method overriding occurs in two classes that have
within the class. IS-A relationship between them.

3) In this case, the parameters In this case, the parameters must be the same.
must be different.

68. Can we change the scope of the overridden method in the


subclass?
Yes, we can change the scope of the overridden method in the subclass. However, we
must notice that we cannot decrease the accessibility of the method. The following
point must be taken care of while changing the accessibility of the method.

o The private can be changed to protected, public, or default.


o The protected can be changed to public or default.
o The default can be changed to public.
o The public will always remain public.

69. Can we modify the throws clause of the superclass method while
overriding it in the subclass?

Yes, we can modify the throws clause of the superclass method while overriding it in
the subclass. However, there are some rules which are to be followed while overriding
in case of exception handling.

o If the superclass method does not declare an exception, subclass overridden


method cannot declare the checked exception, but it can declare the unchecked
exception.
o If the superclass method declares an exception, subclass overridden method
can declare same, subclass exception or no exception but cannot declare parent
exception.
70. What is the final variable?

o In Java, 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.
The final variable which is not assigned to any value can only be assigned
through the class constructor.

71. Can we declare a constructor as final?


o The constructor can never be declared as final because it is never inherited.
Constructors are not ordinary methods; therefore, there is no sense to declare
constructors as final. However, if you try to do so, The compiler will throw an error.

72. Can we declare an interface as final?

o No, we cannot declare an interface as final because the interface must be


implemented by some class to provide its definition. Therefore, there is
no sense to make an interface final. However, if you try to do so, the
compiler will show an error.

73. What is the difference between the final method and abstract
method?

o The main difference between the final method and abstract method is
that the abstract method cannot be final as we need to override them in
the subclass to give its definition.

74. What is the difference between compile-time polymorphism and runtime


polymorphism?

Sr. Compile-time
Key Runtime polymorphism
No. polymorphism

Compile time R un time polymorphism


polymorphism means where at run time we came
1 Basic
binding is occuring at to know which method is
compile time going to invoke

It can be achieved It can be achieved through


2 Static/DynamicBinding
through static binding dynamic binding
Sr. Compile-time
Key Runtime polymorphism
No. polymorphism

Inheritance is not
4. Inheritance Inheritance is involved
involved

Method overloading is
Method overriding is an
an example of compile
5 Example example of runtime
time
polymorphism
polymorphism

75. Can you achieve Runtime Polymorphism by data members?

No, because method overriding is used to achieve runtime polymorphism and data
members cannot be overridden. We can override the member functions but not the
data members.

76. What is Java 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.

77. What is the 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, for example, sending SMS where you type the text and send the
message. You don't know the internal processing about the message delivery.
Abstraction enables you to focus on what the object does instead of how it does it.
Abstraction lets you focus on what the object does instead of how it does it.

78. What is the 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.

79. Can you use abstract and final both with a method?

No, because we need to override the abstract method to provide its implementation,
whereas we can't override the final method.
80. What is the 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. It is a mechanism to
achieve abstraction. There can be only abstract methods in the Java interface, not
method body. It is used to achieve abstraction and multiple inheritance in Java. In other
words, you can say that interfaces can have abstract methods and variables. Java
Interface also represents the IS-A relationship. It cannot be instantiated just like the
abstract class. However, we need to implement it to define its methods. Since Java 8,
we can have the default, static, and private methods in an interface.

81. Can you declare an interface method static?

No, because methods of an interface are abstract by default, and we can not use static
and abstract together.

82. Can the Interface be final?

No, because an interface needs to be implemented by the other class and if it is final,
it can't be implemented by any class.

83. What are the differences between abstract class and interface?

Abstract class Interface

An abstract class can have a method body The interface has only abstract methods.
(non-abstract methods).

An abstract class can have instance An interface cannot have instance


variables. variables.

An abstract class can have the constructor. The interface cannot have the
constructor.

An abstract class can have static methods. The interface cannot have static
methods.

You can extend one abstract class. You can implement multiple interfaces.

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 declare The interface keyword is used to
an abstract class. declare an interface.

An abstract class can extend another Java An interface can extend another Java
class and implement multiple Java interface only.
interfaces.

An abstract class can be extended using An interface class can be implemented


keyword extends using keyword implements

A Java abstract class can have class Members of a Java interface are public
members like private, protected, etc. by default.

Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

84. What is the 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.
Consider the following example to create a package in Java.

85. What are the advantages of defining packages in Java?

By defining packages, we can avoid the name conflicts between the same class names
defined in different packages. Packages also enable the developer to organize the
similar classes more effectively. For example, one can clearly understand that the
classes present in java.io package are used to perform io related operations.

86. Can I import same package/class twice? Will the JVM load the package
twice at runtime?

One can import the same package or the same class multiple times. Neither compiler
nor JVM complains about it. However, the JVM will internally load the class only once
no matter how many times you import the same class.
87. 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.

88. What is the difference between Checked Exception and Unchecked


Exception?

1) Checked Exception

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

2) Unchecked Exception

The classes that extend RuntimeException are known as unchecked exceptions, e.g.,
ArithmeticException, NullPointerException, etc. Unchecked exceptions are not checked at
compile-time.

89. Is it necessary that each try block must be followed by a catch block?
It is not necessary that each try block must be followed by a catch block. It should be followed by
either a catch block OR a finally block. So whatever exceptions are likely to be thrown should
be declared in the throws clause of the method.

90. What is finally block?


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. If you don't handle the exception,
before terminating the program, JVM runs finally block, (if any). The finally block is mainly used
to place the cleanup code such as closing a file or closing a connection. Here, we must know
that for each try block there can be zero or more catch blocks, but only one finally block. The
finally block will not be executed if program exits.
91. 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 duplicacy.

92. What is the meaning of immutable regarding String?


The simple meaning of immutable is unmodifiable or unchangeable. In Java, String is
immutable, i.e., once string object has been created, its value can't be changed. Consider the
following example for better understanding.

93. Why are the objects immutable in java?


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.

94. What are the differences between String and StringBuffer?

No. String StringBuffer

1) The String class is immutable. The StringBuffer class is


mutable.

2) The String is slow and consumes more The StringBuffer is fast and
memory when you concat too many consumes less memory when
strings because every time it creates a you cancat strings.
new instance.

3) The String class overrides the equals() The StringBuffer class


method of Object class. So you can doesn't override the equals()
compare the contents of two strings by method of Object class.
equals() method.
95. What are the differences between StringBuffer and StringBuilder?
The differences between the StringBuffer and StringBuilder is given below.

No. StringBuffer StringBuilder

1) 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.

2) StringBuffer is less efficient than StringBuilder is more efficient than


StringBuilder. StringBuffer.

96. What is the purpose of toString() method in Java?


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. By overriding the toString() method of the Object class, we can return the
values of the object, so we don't need to write much code.

97. What are the advantages of Java inner classes?


There are two types of advantages of Java inner classes.

o 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.
o Nested classes are used to develop a more readable and maintainable
code because it logically groups classes and interfaces in one place only.
o Code Optimization: It requires less code to write.

98. What is a nested class?

o 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. The syntax of the nested class
is defined below.
o class Java_Outer_class{
o //code
o class Java_Nested_class{
o //code
o }
o }
o There are two types of nested classes, static nested class, and non-static
nested class. The non-static nested class can also be called as inner-class

99. What are the disadvantages of using inner classes?


There are the following main disadvantages of using inner classes.

o Inner classes increase the total number of classes used by the developer
and therefore increases the workload of JVM since it has to perform some
routine operations for those extra classes which result in slower
performance.
o IDEs provide less support to the inner classes as compare to the top level
classes and therefore it annoys the developers while working with inner
classes.

100. What are anonymous inner classes?

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.

101. 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. Consider
the following example for the better understanding of how the gc() method invoke the garbage
collector.
102. What is Garbage Collection?
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 Java Virtual
Machine. Due to garbage collection java gives 0 as output to a variable whose value is not set,
i.e., the variable has been defined but not initialized. For this purpose, we were using free()
function in the C language and delete() in C++. In Java, it is performed automatically. So, java
provides better memory management.

103. What is the purpose of the 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). The cleanup processing is the
process to free up all the resources, network which was previously used and no longer needed.
It is essential to remember that it is not a reserved keyword, finalize method is present in the
object class hence it is available in every class as object class is the superclass of every class in
java.

105. Which containers use a border layout as their default layout?


The Window, Frame and Dialog classes use a border layout as their default layout.

106. Which containers use a FlowLayout as their default layout?


The Panel and Applet classes use the FlowLayout as their default layout.

107. is there is any difference between a Scrollbar and a ScrollPane?


The Scrollbar is a Component whereas the ScrollPane is a Container. A ScrollPane handles its
events and performs its scrolling.
108. What is multithreading?
Multithreading is a process of executing multiple threads simultaneously. Multithreading is
used to obtain the multitasking. It consumes less memory and gives the fast and efficient
performance. Its main advantages are:

o Threads share the same address space.


o The thread is lightweight.
o The cost of communication between the processes is low.

109. What is the thread?

o A thread is a lightweight subprocess. It is a separate path of execution


because each thread runs in a different stack frame. A process may contain
multiple threads. Threads share the process resources, but still, they execute
independently.

110. Differentiate between process and thread?

There are the following differences between the process and thread.

A Program in the execution is called the process whereas; A thread is a


o
subset of the process
o Processes are independent whereas threads are the subset of process.
o Process have different address space in memory, while threads contain a
shared address space.
o Context switching is faster between the threads as compared to processes.
o Inter-process communication is slower and expensive than inter-
thread communication.
o Any change in Parent process doesn't affect the child process whereas
changes in parent thread can affect the child thread.

111. What is the purpose of wait() method in Java?


The wait() method is provided by the Object class in Java. This method is used for
inter-thread communication in Java. The java.lang.Object.wait() is used to pause the
current thread, and wait until another thread does not call the notify() or notifyAll()
method. Its syntax is given below. public final void wait().
112. What does join() method?
The join() method waits for a thread to die. In other words, it causes the currently running
threads to stop executing until the thread it joins with completes its task. Join method is
overloaded in Thread class in the following ways.

o public void join()throws InterruptedException


o public void join(long milliseconds)throws InterruptedException

113. Describe the purpose and working of sleep() method.

The sleep() method in java is used to block a thread for a particular time, which
means it pause the execution of a thread for a specific time. There are two
methods of doing so.

114. Why is Java a platform independent language?

Java language was developed so that it does not depend on any hardware or software
because the compiler compiles the code and then converts it to platform-independent
byte code which can be run on multiple systems.

 The only condition to run that byte code is for the machine to have a runtime
environment (JRE) installed in it.

115. Why is Java not a pure object oriented language?

 Java supports primitive data types - byte, boolean, char, short, int,
float, long, and double and hence it is not a pure object oriented
language.

116. What do you understand by an instance variable and a local


variable?

 Instance variables are those variables that are accessible by all the
methods in the class. They are declared outside the methods and inside
the class. These variables describe the properties of an object and
remain bound to it at any cost.
 All the objects of the class will have their copy of the variables for
utilization. If any modification is done on these variables, then only that
instance will be impacted by it, and all other class instances continue to
remain unaffected.
Local variables are those variables present within a block, function, or constructor and can
be accessed only inside them. The utilization of the variable is restricted to the block scope.
Whenever a local variable is declared inside a method, the other class methods don’t have
any knowledge about the local variable.

117. What is primitive data types?


Primitive data types in Java are predefined by the Java language and named as the reserved
keywords.

1. Boolean data type


2. byte data type
3. int data type
4. long data type
5. float data type
6. double data type
7. char data type
8. short data type

118. What is JDK?


JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a
software development environment which is used to develop java applications and
applets. It physically exists. It contains JRE + development tools.

119. what is Heap? How it works Explain.


When a Java program started Java Virtual Machine gets some memory from Operating
System. Java Virtual Machine or JVM uses this memory for all its need and part of this
memory is call java heap memory.

The heap is created when the JVM starts up and may increase or decrease in size while the
application runs

When the heap becomes full, garbage is collected

120. What is platform independent?


Java is a class-based, object-oriented programming language that is designed to have as few
implementation dependencies as possible. It is intended to let
application developers write once and run anywhere (WORA), meaning that compiled Java
code can run on all platforms that support Java without
recompilation.

BASIC JAVA INTERVIEW QUESTIONS 2

1.What is the Collection framework in Java?


Collection Framework is a combination of classes and interface, which is used to store and
manipulate the data in the form of objects. It provides various classes such as ArrayList,
Vector, Stack, and HashSet, etc. and interfaces such as List, Queue, Set, etc. for this purpose.

2.What are the main differences between array and collection?


Array and Collection are somewhat similar regarding storing the references of objects and
manipulating the data, but they differ in many ways. The main differences between the array
and Collection are defined below:
o Arrays are always of fixed size, i.e., a user can not increase or decrease the length of
the array according to their requirement or at runtime, but In Collection, size can be
changed dynamically as per need.
o Arrays can only store homogeneous or similar type objects, but in Collection,
heterogeneous objects can be stored.
o Arrays cannot provide the ?ready-made? methods for user requirements as sorting,
searching, etc. but Collection includes readymade methods to use.

3.Explain various interfaces used in Collection framework?


o Collection framework implements various interfaces, Collection interface and Map interface
(java.util.Map) are the mainly used interfaces of Java Collection Framework. List of interfaces of
Collection Framework is given below:
o 1. Collection interface: Collection (java.util.Collection) is the primary interface, and every
collection must implement this interface.
o Syntax:
o public interface Collection<E>extends Iterable
o Where <E> represents that this interface is of Generic type
o 2. List interface: List interface extends the Collection interface, and it is an ordered collection
of objects. It contains duplicate elements. It also allows random access of elements.
o Syntax:
o public interface List<E> extends Collection<E>
o 3. Set interface: Set (java.util.Set) interface is a collection which cannot contain duplicate
elements. It can only include inherited methods of Collection interface
o ADVERTISEMENT
o ADVERTISEMENT
o Syntax:
o public interface Set<E> extends Collection<E>
o Queue interface: Queue (java.util.Queue) interface defines queue data structure, which stores
the elements in the form FIFO (first in first out).
o Syntax:
o public interface Queue<E> extends Collection<E>
o 4. Dequeue interface: it is a double-ended-queue. It allows the insertion and removal of
elements from both ends. It implants the properties of both Stack and queue so it can
perform LIFO (Last in first out) stack and FIFO (first in first out) queue, operations.
o Syntax:
o public interface Dequeue<E> extends Queue<E>
o 5. Map interface: A Map (java.util.Map) represents a key, value pair storage of elements. Map
interface does not implement the Collection interface. It can only contain a unique key but
can have duplicate elements. There are two interfaces which implement Map in java that are
Map interface and Sorted Map.

4.What is the difference between ArrayList and LinkedList?

No. ArrayList LinkedList

1) ArrayList uses a dynamic array. LinkedList uses a doubly linked list.

2) ArrayList is not efficient for LinkedList is efficient for manipulation.


manipulation because too much
is required.

3) ArrayList is better to store and LinkedList is better to manipulate data.


fetch data.

4) ArrayList provides random LinkedList does not provide random access.


access.

5) ArrayList takes less memory LinkedList takes more memory overhead,


overhead as it stores only object as it stores the object as well as the address
of that object.

5.What is the difference between Iterator and ListIterator?


Iterator traverses the elements in the forward direction only whereas ListIterator traverses the
elements into forward and backward direction.
No. Iterator ListIterator

1) The Iterator traverses the ListIterator traverses the elements in


elements in the forward direction backward and forward directions both.
only.

2) The Iterator can be used in List, ListIterator can be used in List only.
Set, and Queue.

3) The Iterator can only perform ListIterator can perform ?add,?


remove operation while ?remove,? and ?set? operation while
traversing the collection. traversing the collection.

6.What is the difference between Iterator and Enumeration?

No. Iterator Enumeration

1) The Iterator can traverse legacy and Enumeration can traverse only
non-legacy elements. legacy elements.

2) The Iterator is fail-fast. Enumeration is not fail-fast.

3) The Iterator is slower than Enumeration is faster than Iterator.


Enumeration.

4) The Iterator can perform remove The Enumeration can perform only
operation while traversing the traverse operation on the collection.
collection.

7.What is the difference between List and Set?


The List and Set both extend the collection interface. However, there are some differences
between the both which are listed below.

o The List can contain duplicate elements whereas Set includes unique items.
o The List is an ordered collection which maintains the insertion order whereas Set is an
unordered collection which does not preserve the insertion order.
o The List interface contains a single legacy class which is Vector class whereas Set
interface does not have any legacy class.
o The List interface can allow n number of null values whereas Set interface only allows a
single null value.

8.What is the difference between HashSet and TreeSet?


The HashSet and TreeSet, both classes, implement Set interface. The differences between the
both are listed below.

o HashSet maintains no order whereas TreeSet maintains ascending order.


o HashSet impended by hash table whereas TreeSet implemented by a Tree structure.
o HashSet performs faster than TreeSet.
o HashSet is backed by HashMap whereas TreeSet is backed by TreeMap.

9.What is the difference between Set and Map?


The differences between the Set and Map are given below.

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

10.What is the difference between HashSet and HashMap?


The differences between the HashSet and HashMap are listed below.

o HashSet contains only values whereas HashMap includes the entry (key, value).
HashSet can be iterated, but HashMap needs to convert into Set to be iterated.
o HashSet implements Set interface whereas HashMap implements the Map interface
o HashSet cannot have any duplicate value whereas HashMap can contain duplicate
values with unique keys.
o HashSet contains the only single number of null value whereas HashMap can hold a
single null key with n number of null values.

11.What is the difference between HashMap and TreeMap?


The differences between the HashMap and TreeMap are given below.

o HashMap maintains no order, but TreeMap maintains ascending order.


o HashMap is implemented by hash table whereas TreeMap is implemented by a Tree
structure.
o HashMap can be sorted by Key or value whereas TreeMap can be sorted by Key.
o HashMap may contain a null key with multiple null values whereas TreeMap cannot
hold a null key but can have multiple null values.

12.What is the difference between HashMap and Hashtable?

No. HashMap Hashtable


1) HashMap is not synchronized. Hashtable is synchronized.

2) HashMap can contain one null key Hashtable cannot contain any null
and multiple null values. key or null value.

3) HashMap is not ?thread-safe,? so it is Hashtable is thread-safe, and it can


useful for non-threaded applications. be shared between various threads.

4) 4) HashMap inherits the AbstractMap Hashtable inherits the Dictionary


class class.

13.What is the difference between Collection and Collections?


The differences between the Collection and Collections are given below.

o The Collection is an interface whereas Collections is a class.


o The Collection interface provides the standard functionality of data structure to List,
Set, and Queue. However, Collections class is to sort and synchronize the collection
elements.
o The Collection interface provides the methods that can be used for data structure
whereas Collections class provides the static methods which can be used for various
operation on a collection.
14.What is the difference between Comparable and Comparator?
No. Comparable Comparator

1) Comparable provides only one The Comparator provides


sort of sequence. multiple sorts of
sequences.

2) It provides one method named It provides one method


compareTo(). named compare().

3) It is found in java.lang package. It is located in java.util


package.

4) If we implement the Comparable The actual class is not


interface, The actual class is changed.
modified.
15.What do you understand by BlockingQueue?
BlockingQueue is an interface which extends the Queue interface. It provides concurrency in
the operations like retrieval, insertion, deletion. While retrieval of any element, it waits for
the queue to be non-empty. While storing the elements, it waits for the available space.
BlockingQueue cannot contain null elements, and implementation of BlockingQueue is
thread-safe.
16.What does the 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.
However, it is possible that two hash code numbers can have different or the same keys.
If two objects do not produce an equal result by using the equals() method, then the
hashcode() method will provide the different integer result for both the objects.
17.What is hash-collision in Hashtable and how it is handled in Java?
Two different keys with the same hash value are known as hash-collision. Two separate
entries will be kept in a single hash bucket to avoid the collision. There are two ways to avoid
hash-collision.

o Separate Chaining
o Open Addressing
18.What is the difference between Array and ArrayList?
o The main differences between the Array and ArrayList are given below.

SN Array ArrayList

1 The Array is of fixed size, means we ArrayList is not of the fixed size we can
cannot resize the array as per need. change the size dynamically.

2 Arrays are of the static type. ArrayList is of dynamic size.

3 Arrays can store primitive data types ArrayList cannot store the primitive data
as well as objects. types it can only store the objects.

19.What is the difference between length of an Array and size of ArrayList?


The length of an array can be obtained using the property of length whereas ArrayList does
not support length property, but we can use size() method to get the number of objects in
the list.
20.How to convert Array to ArraList and ArrayList to Array?
We can convert an Array to ArrayList by using the asList() method of Arrays class. asList()
method is the static method of Arrays class and accepts the List object. Consider the
following syntax:

1. Arrays.asList(item)

We can convert an ArrayList to Array using toArray() method of the ArrayList class. Consider
the following syntax to convert the ArrayList to the List object.

1. List_object.toArray(new String[List_object.size()])

21.How to make java ArrayList Read-Only?


We can obtain java ArrayList Read-only by calling the Collections.unmodifiableCollection()
method. When we define an ArrayList as Read-only then we cannot perform any modification
in the collection through add(), remove() or set() method.

22.How to remove duplicates from ArrayList?


There are two ways to remove duplicates from the ArrayList.

o Using HashSet: By using HashSet we can remove the duplicate element from the
ArrayList, but it will not then preserve the insertion order.
o Using LinkedHashSet: We can also maintain the insertion order by using
LinkedHashSet instead of HashSet.
The Process to remove duplicate elements from ArrayList using the LinkedHashSet:

o Copy all the elements of ArrayList to LinkedHashSet.


o Empty the ArrayList using clear() method, which will remove all the elements from the
list.
o Now copy all the elements of LinkedHashset to ArrayList.

23.How to synchronize ArrayList?


We can synchronize ArrayList in two ways.

o Using Collections.synchronizedList() method


o Using CopyOnWriteArrayList<T>

24.When to use ArrayList and LinkedList?


LinkedLists are better to use for the update operations whereas ArrayLists are better to use
for the search operations.

25. Why is Java not a pure object oriented language?


Java supports primitive data types - byte, boolean, char, short, int, float, long, and double
and hence it is not a pure object oriented language.

26. Difference between Heap and Stack Memory in java. And how java utilizes
this.
Stack memory is the portion of memory that was assigned to every individual program. And
it was fixed. On the other hand, Heap memory is the portion that was not allocated to the
java program but it will be available for use by the java program when it is required, mostly
during the runtime of the program.

Java Utilizes this memory as -

 When we write a java program then all the variables, methods, etc are stored in the
stack memory.
 And when we create any object in the java program then that object was created in
the heap memory. And it was referenced from the stack memory.

27. How is Java different from C++?


 C++ is only a compiled language, whereas Java is compiled as well as an interpreted
language.
 Java programs are machine-independent whereas a c++ program can run only in the
machine in which it is compiled.
 C++ allows users to use pointers in the program. Whereas java doesn’t allow it. Java
internally uses pointers.
 C++ supports the concept of Multiple inheritances whereas Java doesn't support this.
And it is due to avoiding the complexity of name ambiguity that causes the diamond
problem.

28. What are the default values assigned to variables and instances in java?
 There are no default values assigned to the variables in java. We need to initialize the
value before using it. Otherwise, it will throw a compilation error of (Variable might
not be initialized).
 But for instance, if we create the object, then the default value will be initialized by the
default constructor depending on the data type.
 If it is a reference, then it will be assigned to null.
 If it is numeric, then it will assign to 0.
 If it is a boolean, then it will be assigned to false. Etc.

29. What do you mean by data encapsulation?


 Data Encapsulation is an Object-Oriented Programming concept of hiding the data
attributes and their behaviours in a single unit.
 It helps developers to follow modularity while developing software by ensuring that
each object is independent of other objects by having its own methods, attributes, and
functionalities.
 It is used for the security of the private properties of an object and hence serves the
purpose of data hiding.

30. A single try block and multiple catch blocks can co-exist in a Java Program.
Explain.
Yes, multiple catch blocks can exist but specific approaches should come prior to the
general approach because only the first catch block satisfying the catch condition is
executed. The given code illustrates the same:

 public class MultipleCatch {


 public static void main(String args[]) {
 try {
 int n = 1000, x = 0;
 int arr[] = new int[n];
 for (int i = 0; i <= n; i++) {
 arr[i] = i / x;
 }
 }
 catch (ArrayIndexOutOfBoundsException exception) {
 System.out.println("1st block = ArrayIndexOutOfBoundsException");
 }
 catch (ArithmeticException exception) {
 System.out.println("2nd block = ArithmeticException");
 }
 catch (Exception exception) {
 System.out.println("3rd block = Exception");
 }
 }
 }

Here, the second catch block will be executed because of division by 0 (i / x). In case x
was greater than 0 then the first catch block will execute because for loop runs till i =
n and array index are till n-1.

31. Explain the use of final keyword in variable, method and class.
In Java, the final keyword is used as defining something as constant /final and represents
the non-access modifier.

 final variable:
o When a variable is declared as final in Java, the value can’t be modified once it
has been assigned.
o If any value has not been assigned to that variable, then it can be assigned only
by the constructor of the class.
 final method:
o A method declared as final cannot be overridden by its children's classes.
o A constructor cannot be marked as final because whenever a class is inherited,
the constructors are not inherited. Hence, marking it final doesn't make sense.
Java throws compilation error saying - modifier final not allowed here
 final class:
o No classes can be inherited from the class declared as final. But that final class
can extend other classes for its usage.

32. Do final, finally and finalize keywords have the same function?
All three keywords have their own utility while programming.

Final: If any restriction is required for classes, variables, or methods, the final keyword
comes in handy. Inheritance of a final class and overriding of a final method is restricted by
the use of the final keyword. The variable value becomes fixed after incorporating the final
keyword.

Finally: It is the block present in a program where all the codes written inside it get
executed irrespective of handling of exceptions.
Finalize: Prior to the garbage collection of an object, the finalize method is called so that
the clean-up activity is implemented.

33. Is it possible that the ‘finally’ block will not be executed? If yes then list the
case.
Yes. It is possible that the ‘finally’ block will not be executed. The cases are-

 Suppose we use System.exit() in the above statement.


 If there are fatal errors like Stack overflow, Memory access error, etc.

34. When can you use super keyword?


 The super keyword is used to access hidden fields and overridden methods or
attributes of the parent class.
 Following are the cases when this keyword can be used:
o Accessing data members of parent class when the member names of the class
and its child subclasses are same.
o To call the default and parameterized constructor of the parent class inside the
child class.
o Accessing the parent class methods when the child classes have overridden
them.

35. Can the static methods be overloaded?

Yes! There can be two or more static methods in a class with the same name but differing
input parameters.

36. Why is the main method static in Java?


The main method is always static because static members are those methods that belong to
the classes, not to an individual object. So if the main method will not be static then for every
object, It is available. And that is not acceptable by JVM. JVM calls the main method based on
the class name itself. Not by creating the object.
Because there must be only 1 main method in the java program as the execution starts from
the main method. So for this reason the main method is static.
37.What is the purpose of static methods and static variables?
Static variables and static methods are two important concepts in Java.
Whenever a variable is declared as static, this means there is only one copy of it for the
entire class, rather than each instance having its own copy. A static method means it can be
called without creating an instance of the class.
Static variables and methods in Java provide several advantages, including memory efficiency,
global access, object independence, performance, and code organization.

38.what is singleton class? give a practical example?


A Singleton class is a class that allows only one instance of itself to be created and provides a
global point of access to that instance. This is achieved by making the constructor private.

39.What is the difference between continue and break in java

40.Classes are derived as?


Class is a set of objects that share same characteristics/behaviour and common properties.
41.can main() method in java return any data?
The main() is the starting point for JVM to start execution of a Java program. Without the
main() method, JVM will not execute the program.it is does not return any thing.

42.What is an abstract class give an example?


A class which is declared with the abstract keyword is known as an abstract class in Java. It
can have abstract and non-abstract methods (method with the body).

1. abstract class A{}


43.Does importing a package imports it’s sub package as well as?
No, importing a package does not imports it’s sub packages but it imports the
classes and methods of the package.
If you want you can import the sub package also.

44.Can we declare main method of our class as private?


Yes, but it can not be taken as entry point of your application. It will run if it is invoked from
somewhere else.

45.What is serialization and deserialization ? give an example?


Serialization is a mechanism of converting the state of an object into a byte stream.
Deserialization is the reverse process where the byte stream is used to recreate the actual
Java object in memory. This mechanism is used to persist the object.

46. What is a ClassLoader?


 Java Classloader is the program that belongs to JRE (Java Runtime Environment). The
task of ClassLoader is to load the required classes and interfaces to the JVM when
required.
 Example- To get input from the console, we require the scanner class. And the Scanner
class is loaded by the ClassLoader.

47. How would you differentiate between a String, StringBuffer, and a


StringBuilder?
 Storage area: In string, the String pool serves as the storage area. For StringBuilder and
StringBuffer, heap memory is the storage area.
 Mutability: A String is immutable, whereas both the StringBuilder and StringBuffer are
mutable.
 Efficiency: It is quite slow to work with a String. However, StringBuilder is the fastest in
performing operations. The speed of a StringBuffer is more than a String and less than
a StringBuilder. (For example appending a character is fastest in StringBuilder and very
slow in String because a new memory is required for the new String with appended
character.)
 Thread-safe: In the case of a threaded environment, StringBuilder and StringBuffer are
used whereas a String is not used. However, StringBuilder is suitable for an
environment with a single thread, and a StringBuffer is suitable for multiple threads.

48. Using relevant properties highlight the differences between interfaces and
abstract classes.
 Availability of methods: Only abstract methods are available in interfaces, whereas
non-abstract methods can be present along with abstract methods in abstract classes.
 Variable types: Static and final variables can only be declared in the case of interfaces,
whereas abstract classes can also have non-static and non-final variables.
 Inheritance: Multiple inheritances are facilitated by interfaces, whereas abstract
classes do not promote multiple inheritances.
 Data member accessibility: By default, the class data members of interfaces are of the
public- type. Conversely, the class members for an abstract class can be protected or
private also.
 Implementation: With the help of an abstract class, the implementation of an interface
is easily possible. However, the converse is not true;

49. What is a Comparator in java?

Consider the example where we have an ArrayList of employees like( EId, Ename, Salary),
etc. Now if we want to sort this list of employees based on the names of employees. Then
that is not possible to sort using the Collections.sort() method. We need to provide
something to the sort() function depending on what values we have to perform sorting.
Then in that case a comparator is used.

Comparator is the interface in java that contains the compare method. And by overloading
the compare method, we can define that on what basis we need to compare the values.

50. In Java, static as well as private method overriding is possible. Comment on


the statement.
The statement in the context is completely False. The static methods have no relevance
with the objects, and these methods are of the class level. In the case of a child class, a
static method with a method signature exactly like that of the parent class can exist
without even throwing any compilation error.

The phenomenon mentioned here is popularly known as method hiding, and overriding is
certainly not possible. Private method overriding is unimaginable because the visibility of
the private method is restricted to the parent class only. As a result, only hiding can be
facilitated and not overriding.

51. What makes a HashSet different from a TreeSet?


Although both HashSet and TreeSet are not synchronized and ensure that duplicates are
not present, there are certain properties that distinguish a HashSet from a TreeSet.

 Implementation: For a HashSet, the hash table is utilized for storing the elements in
an unordered manner. However, TreeSet makes use of the red-black tree to store the
elements in a sorted manner.
 Complexity/ Performance: For adding, retrieving, and deleting elements, the time
amortized complexity is O(1) for a HashSet. The time complexity for performing the
same operations is a bit higher for TreeSet and is equal to O(log n). Overall, the
performance of HashSet is faster in comparison to TreeSet.
 Methods: hashCode() and equals() are the methods utilized by HashSet for making
comparisons between the objects. Conversely, compareTo() and compare() methods
are utilized by TreeSet to facilitate object comparisons.
 Objects type: Heterogeneous and null objects can be stored with the help of
HashSet. In the case of a TreeSet, runtime exception occurs while inserting
heterogeneous objects or null objects.

52. What do we get in the JDK file?


 JDK- For making java programs, we need some tools that are provided by JDK (Java
Development Kit). JDK is the package that contains various tools, Compiler, Java
Runtime Environment, etc.
 JRE - To execute the java program we need an environment. (Java Runtime
Environment) JRE contains a library of Java classes + JVM. What are JAVA Classes? It
contains some predefined methods that help Java programs to use that feature, build
and execute. For example - there is a system class in java that contains the print-
stream method, and with the help of this, we can print something on the console.
 JVM - (Java Virtual Machine) JVM is a part of JRE that executes the Java program at
the end. Actually, it is part of JRE, but it is software that converts bytecode into
machine-executable code to execute on hardware.

53. What are the differences between JVM, JRE and JDK in Java?
Criteria JDK JRE JVM
Abbreviation Java Runtime
Java Development Kit Java Virtual Machine
Environment
Definition JDK is a complete JRE is a software JVM is a platform-dependent, abstract
software development package providing machine comprising of 3 specifications
kit for developing Java Java class libraries, - document describing the JVM
applications. It JVM and all the implementation requirements,
comprises JRE, required components computer program meeting the JVM
Criteria JDK JRE JVM
JavaDoc, compiler, to run the Java requirements and instance object for
debuggers, etc. applications. executing the Java byte code and
provide the runtime environment for
execution.
Main JRE is mainly used
JDK is mainly used for
Purpose for environment JVM provides specifications for all the
code development and
creation to execute implementations to JRE.
execution.
the code.
Tools JDK provides tools like JRE provides
JVM does not include any tools, but
provided compiler, debuggers, libraries and classes
instead, it provides the specification for
etc for code required by JVM to
implementation.
development run the program.
Summary JRE = (JVM) +
JDK = (JRE) + JVM = Runtime environment to
Libraries to execute
Development tools execute Java byte code.
the application

54. What are the differences between HashMap and HashTable in Java?

HashMap HashTable
HashMap is not synchronized thereby making it HashTable is synchronized and hence it is
better for non-threaded applications. suitable for threaded applications.
Allows only one null key but any number of null This does not allow null in both keys or
in the values. values.
Supports order of insertion by making use of its Order of insertion is not guaranteed in
subclass LinkedHashMap. HashTable.

55. What is the difference between the program and the process?
 A program can be defined as a line of code written in order to accomplish a particular
task. Whereas the process can be defined as the programs which are under execution.
 A program doesn't execute directly by the CPU. First, the resources are allocated to
the program and when it is ready for execution then it is a process.

56. What is the difference between the ‘throw’ and ‘throws’ keyword in java?
 The ‘throw’ keyword is used to manually throw the exception to the calling method.
 And the ‘throws’ keyword is used in the function definition to inform the calling
method that this method throws the exception. So if you are calling, then you have to
handle the exception.

57. What are the differences between constructor and method of a class in
Java?
Constructor Method
Method is used for exposing the
Constructor is used for initializing the object state.
object's behavior.
Constructor Method
Method should have a return type.
Constructor has no return type. Even if it does not return anything,
return type is void.
Method has to be invoked on the
Constructor gets invoked implicitly.
object explicitly.
If the constructor is not defined, then a default constructor is If a method is not defined, then the
provided by the java compiler. compiler does not provide it.
The name of the method can have
The constructor name should be equal to the class name.
any name or have a class name too.
A constructor cannot be marked as final because whenever
A method can be defined as final but
a class is inherited, the constructors are not inherited. Hence,
it cannot be overridden in its
marking it final doesn't make sense. Java throws compilation
subclasses.
error saying - modifier final not allowed here
A final variable if initialised inside a
Final variable instantiations are possible inside a constructor
method ensures that the variable
and the scope of this applies to the whole class and its
cant be changed only within the
objects.
scope of that method.

58. Java works as “pass by value” or “pass by reference” phenomenon?


Java always works as a “pass by value”. There is nothing called a “pass by reference” in
Java. However, when the object is passed in any method, the address of the value is passed
due to the nature of object handling in Java. When an object is passed, a copy of the
reference is created by Java and that is passed to the method. The objects point to the
same memory location. 2 cases might happen inside the method:

 Case 1: When the object is pointed to another location: In this case, the changes
made to that object do not get reflected the original object before it was passed to
the method as the reference points to another location.
 Case 2: When object references are not modified: In this case, since we have the
copy of reference the main object pointing to the same memory location, any
changes in the content of the object get reflected in the original object.

59. What is the ‘IS-A ‘ relationship in OOPs java?

‘IS-A’ relationship is another name for inheritance. When we inherit the base class from the
derived class, then it forms a relationship between the classes. So that relationship is
termed an ‘IS-A’ Relationship.

Example - Consider a Television (Typical CRT TV). Now another Smart TV that is inherited
from television class. So we can say that the Smart iv is also a TV. Because CRT TV things
can also be done in the Smart TV.

60. Which among String or String Buffer should be preferred when there are lot
of updates required to be done in the data?
StringBuffer is mutable and dynamic in nature whereas String is immutable. Every updation
/ modification of String creates a new String thereby overloading the string pool with
unnecessary objects. Hence, in the cases of a lot of updates, it is always preferred to use
StringBuffer as it will reduce the overhead of the creation of multiple String objects in the
string pool.

61. What happens if the static modifier is not included in the main method
signature in Java?
There wouldn't be any compilation error. But then the program is run, since the JVM cant
map the main method signature, the code throws “NoSuchMethodError” error at the
runtime.

62. Can we make the main() thread a daemon thread?


In java multithreading, the main() threads are always non-daemon threads. And there is no
way we can change the nature of the non-daemon thread to the daemon thread.

63. How does an exception propagate in the code?


When an exception occurs, first it searches to locate the matching catch block. In case, the
matching catch block is located, then that block would be executed. Else, the exception
propagates through the method call stack and goes into the caller method where the
process of matching the catch block is performed. This propagation happens until the
matching catch block is found. If the match is not found, then the program gets terminated
in the main method.

64. How do exceptions affect the program if it doesn't handle them?


Exceptions are runtime errors. Suppose we are making an android application with java.
And it all works fine but there is an exceptional case when the application tries to get the
file from storage and the file doesn’t exist (This is the case of exception in java). And if this
case is not handled properly then the application will crash. This will be a bad experience
for users. This is the type of error that cannot be controlled by the programmer. But
programmers can take some steps to avoid this so that the application won’t crash. The
proper action can be taken at this step.

65. Contiguous memory locations are usually used for storing actual values in an
array but not in ArrayList. Explain.
In the case of ArrayList, data storing in the form of primitive data types (like int, float, etc.)
is not possible. The data members/objects present in the ArrayList have references to the
objects which are located at various sites in the memory. Thus, storing of actual objects or
non-primitive data types (like Integer, Double, etc.) takes place in various memory
locations.
66. Why does the java array index start with 0?
It is because the 0 index array avoids the extra arithmetic operation to calculate the
memory address.

Example - Consider the array and assume each element takes 4-byte memory space. Then
the address will be like this -

Now if we want to access index 4. Then internally java calculates the address using the
formula-

[Base Address + (index * no_of_bytes)]. So according to this. The starting address of the
index 4 will be - [100 + (4*4)] = 116. And exactly that's what the address is calculated.

67. Why is the remove method faster in the linked list than in an array?
In the linked list, we only need to adjust the references when we want to delete the
element from either end or the front of the linked list. But in the array, indexes are used. So
to manage proper indexing, we need to adjust the values from the array So this adjustment
of value is costlier than the adjustment of references.

68. What is the difference between ‘>>’ and ‘>>>’ operators in java?
These 2 are the bitwise right shift operators. Although both operators look similar. But
there is a minimal difference between these two right shift operators.

 ‘>>’ Bitwise Right Shift Operator- This operator shifts each bit to its right position.
And this maintains the signed bit.
 ‘>>>’ Bitwise Right Shift Operator with trailing zero- This operator also shifts each
bit to its right. But this doesn’t maintain the signed bit. This operator makes the Most
significant bit to 0.
69. Is exceeding the memory limit possible in a program despite having a
garbage collector?

Yes, it is possible for the program to go out of memory in spite of the presence of a garbage
collector. Garbage collection assists in recognizing and eliminating those objects which are
not required in the program anymore, in order to free up the resources used by them.

In a program, if an object is unreachable, then the execution of garbage collection takes


place with respect to that object. If the amount of memory required for creating a new
object is not sufficient, then memory is released for those objects which are no longer in
the scope with the help of a garbage collector. The memory limit is exceeded for the
program when the memory released is not enough for creating new objects.

70. Why is synchronization necessary? Explain with the help of a relevant


example.
Concurrent execution of different processes is made possible by synchronization. When a
particular resource is shared between many threads, situations may arise in which multiple
threads require the same shared resource.

Synchronization assists in resolving the issue and the resource is shared by a single thread
at a time. Let’s take an example to understand it more clearly. For example, you have a URL
and you have to find out the number of requests made to it. Two simultaneous requests
can make the count erratic.

71. Define System.out.println().


System.out.println() is used to print the message on the console. System - It is a class
present in java.lang package. Out is the static variable of type PrintStream class present in
the System class. println() is the method present in the PrintStream class.

72. Will the finally block be executed if the code System.exit(0) is written at the
end of try block?
NO. The control of the program post System.exit(0) is immediately gone and the program
gets terminated which is why the finally block never gets executed.

73. What do you understand by marker interfaces in Java?


Marker interfaces, also known as tagging interfaces are those interfaces that have no
methods and constants defined in them. They are there for helping the compiler and JVM
to get run time-related information regarding the objects.
74.How can you differenciate C and java?

75.What is the pre-requisite for java Eclipse?


Eclipse is a Java-based application and, as such, requires a Java Runtime Environment or Java
Development Kit (JRE or JDK) in order to run.
Note that on recent versions of Mac, a full JDK needs to be installed, not just a JRE.

76.Can a class have multiple constructors ?if yes give your answer?
Yes, a class can have multiple constructors with different parameters. Which constructor gets
used for object creation depends on the arguments passed while creating the objects.

77.is String is a data type in java?


In Java, string is basically an object that represents sequence of char values.

String is a primitive data type.

78.Why Strings in java are called immutable?


The key benefits of keeping this class as immutable are caching, security, synchronization,
and performance.
79.What is multi-threading?
Multithreading is a Java feature that allows concurrent execution of two or more parts of a
program(thread) for maximum utilization of CPU.
Each part of such program is called a thread. So, threads are light-weight processes within a
process.
80.How garbage collection is done in java?
Garbage Collection is process of reclaiming the runtime unused memory automatically. In
other words, it is a way to destroy the unused objects.
81.There are two classes in names A and B.Both classes are in the same
package.Can a private member of class A access by any object in class B?Explain.
There are two classes named class A and class B which are in the same package. A private
member of class A can't be accessed by an object of class B as Private members of a class
aren’t accessible outside the scope of that class and any other class even if it is in the same
package can’t access them.

82.Can we have two methods in a class with the same name? Explain with
example?
Yes, we can define multiple methods in a class with the same name but with different types of
parameters. Which method is to get invoked will depend upon the parameters passed.

83.What is inheritance ?Benifites?


Inheritance is a process of acquiring the properties and behaviour of parent class to child class.
1.code reusability.
2.time save

84. What is a Memory Leak? Discuss some common causes of it.


The Java Garbage Collector (GC) typically removes unused objects when they are no longer
required, but when they are still referenced, the unused objects cannot be removed. So this
causes the memory leak problem. Example - Consider a linked list like the structure below -
In the above image, there are unused objects that are not referenced. But then also Garbage
collection will not free it. Because it is referencing some existing referenced object. So this
can be the situation of memory leak.
Some common causes of Memory leaks are -
 When there are Unbounded caches.
 Excessive page swapping is done by the operating system.
 Improper written custom data structures.
 Inserting into a collection object without first deleting it.
etc.

85.What is keyword in java?


A keyword is a reserved word in a programming language that has a predefined meaning and
cannot be used for any other purpose, such as naming variables or functions. Keywords form
the basic building blocks of a program’s syntax. Keywords are essential because they define
the structure and control flow of the program.
86.What are Literals in java?
In Java, literals are the constant values that appear directly in the program. It can be
assigned directly to a variable. Java has various types of literals.
87.Types Of Literals in java?
Integer Literals:
Integer literals are sequences of digits.
Real Literals:
The numbers that contain fractional parts are known as real literals. We can also represent
real literals in exponent form. For example, 879.90, 99E-3, etc.
Backslash Literals:
Java supports some special backslash character literals known as backslash literals. They are
used in formatted output. For example:
\n: It is used for a new line
\t: It is used for horizontal tab
Character Literals:
A character literal is expressed as a character or an escape sequence, enclosed in
a single quote ('') mark. It is always a type of char. For example, 'a', '%', '\u000d', etc.
String Literals:
String literal is a sequence of characters that is enclosed between double quotes ("") marks.
It may be alphabet, numbers, special characters, blank space, etc. For example, "Jack",
"12345", "\n", etc.
Floating Point Literals:
The vales that contain decimal are floating literals. In Java, float and double primitive types
fall into floating-point literals. Keep in mind while dealing with floating-point literals.
88.Why use literals?
To avoid defining the constant somewhere and making up a label for it. Instead, to write the
value of a constant operand as a part of the instruction.
89.What is polymorphism? Give an example?
Polymorphism is an important concept of object-oriented programming. It simply means
more than one form.

That is, the same entity (method or operator or object) can perform different operations in
different scenarios.

90.What is primitive data types?


Primitive data types in Java are predefined by the Java language and named as the reserved
keywords.
1. Boolean data type
2. byte data type
3. int data type
4. long data type
5. float data type
6. double data type
7. char data type
8. short data type

91. What is JDK?


JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software
development environment which is used to develop java applications and applets. It
physically exists. It contains JRE + development tools.
92.what is Heap? How it works Explain.
When a Java program started Java Virtual Machine gets some memory from Operating
System. Java Virtual Machine or JVM uses this memory for all its need and part of this
memory is call java heap memory.

The heap is created when the JVM starts up and may increase or decrease in size while the
application runs When the heap become full, garbage is collected.

93.What is an IDE?
An integrated development environment (IDE) is software for building applications that
combines common developer tools into a single graphical user interface (GUI).

94.What is Collection?What is a collection Frame work?What are the benefits of


java Collections framework?

The Collection in Java is a framework that provides an architecture to store and manipulate the
group of objects.

Java Collections can achieve all the operations that you perform on a data such as searching,
sorting, insertion, manipulation, and deletion.

95.What do you understand by inter-thread communication?


o The process of communication between synchronized threads is termed as inter-
thread communication.
o Inter-thread communication is used to avoid thread polling in Java.
o The thread is paused running in its critical section, and another thread is allowed to
enter (or lock) in the same critical section to be executed.
o It can be obtained by wait(), notify(), and notifyAll() methods.

96.What are the states in the lifecycle of a Thread?


A thread can have one of the following states during its lifetime:

1. New: In this state, a Thread class object is created using a new operator, but the
thread is not alive. Thread doesn't start until we call the start() method.
2. Runnable: In this state, the thread is ready to run after calling the start() method.
However, the thread is not yet selected by the thread scheduler.
3. Running: In this state, the thread scheduler picks the thread from the ready state, and
the thread is running.
4. Waiting/Blocked: In this state, a thread is not running but still alive, or it is waiting for
the other thread to finish.
5. Dead/Terminated: A thread is in terminated or dead state when the run() method
exits.

97.Differentiate between the Thread class and Runnable interface for creating a
Thread?
The Thread can be created by using two ways.

o By extending the Thread class


o By implementing the Runnable interface

However, the primary differences between both the ways are given below:

o By extending the Thread class, we cannot extend any other class, as Java does not
allow multiple inheritances while implementing the Runnable interface; we can also
extend other base class(if required).
o By extending the Thread class, each of thread creates the unique object and associates
with it while implementing the Runnable interface; multiple threads share the same
object
o Thread class provides various inbuilt methods such as getPriority(), isAlive and many
more while the Runnable interface provides a single method, i.e., run().

98.What is the difference between wait() and sleep() method?

Feature wait() sleep()

Method
Defined in the Object class Defined in the Thread class
Location

Used for inter-thread communication and Used to pause the execution of a


Usage
synchronization thread

Lock Releases the lock on the object being


Does not release the lock
Release waited on
Feature wait() sleep()

Object Called on an object within Called directly on


Dependency a synchronized block the Thread object

Also
Throws InterruptedException when
Interruption throws InterruptedException when
interrupted
interrupted

Requires notify() or notifyAll() to resume Not applicable, thread resumes


Notification
execution automatically after sleep

Associated Puts the thread in Puts the thread in


State the WAITING or TIMED_WAITING state the TIMED_WAITING state

Time Time duration specified in


No time duration specified
Specification milliseconds
99.What is an iterator?
In Java, an Iterator is one of the Java cursors. Java Iterator is an interface that is practiced in
order to iterate over a collection of Java object components entirety one by one. It is free to
use in the Java programming language.

100.What is Enumeration?
The Enum in Java is a data type which contains a fixed set of constants. It can be used for
days of the week, season , colour etc.
Enums are used to create our own data type like classes. The enum data type (also known as
Enumerated Data Type) is used to define an enum in Java. Unlike C/C++, enum in Java is
more powerful. Here, we can define an enum either inside the class or outside the class.

101. Is it possible to start a thread twice?


No, we cannot restart the thread, as once a thread started and executed, it goes to the Dead
state. Therefore, if we try to start a thread twice, it will give a runtimeException
"java.lang.IllegalThreadStateException".

102.Can we call the run() method instead of start()?


Yes, calling run() method directly is valid, but it will not work as a thread instead it will work
as a normal object. There will not be context-switching between the threads. When we call
the start() method, it internally calls the run() method, which creates a new stack for a thread
while directly calling the run() will not create a new stack.
103.What about the daemon threads?
The daemon threads are the low priority threads that provide the background support and
services to the user threads. Daemon thread gets automatically terminated by the JVM if the
program remains with the daemon thread only, and all other user threads are ended/died.
There are two methods for daemon thread available in the Thread class:
o public void setDaemon(boolean status): It used to mark the thread daemon thread or
a user thread.
o public boolean isDaemon(): It checks the thread is daemon or not.

104.What is shutdown hook?


The shutdown hook is a thread that is invoked implicitly before JVM shuts down. So we can
use it to perform clean up the resource or save the state when JVM shuts down normally or
abruptly.

105.When should we interrupt a thread?


We should interrupt a thread when we want to break out the sleep or wait state of a thread. We
can interrupt a thread by calling the interrupt() throwing the InterruptedException.

106.What is the synchronization?


Synchronization is the capability to control the access of multiple threads to any shared
resource. It is used:

1. To prevent thread interference.


2. To prevent consistency problem.

When the multiple threads try to do the same task, there is a possibility of an erroneous result,
hence to remove this issue, Java uses the process of synchronization which allows only one
thread to be executed at a time. Synchronization can be achieved in three ways:

o by the synchronized method


o by synchronized block
o by static synchronization

107.What is the purpose of the Synchronized block?


The Synchronized block can be used to perform synchronization on any specific resource of
the method. Only one thread at a time can execute on a particular resource, and all other
threads which attempt to enter the synchronized block are blocked.

o Synchronized block is used to lock an object for any shared resource.


o The scope of the synchronized block is limited to the block on which, it is applied. Its
scope is smaller than a method.

108.What is static synchronization?


If you make any static method as synchronized, the lock will be on the class not on the object.
If we use the synchronized keyword before a method so it will lock the object (one thread can
access an object at a time) but if we use static synchronized so it will lock a class (one thread
can access a class at a time)

109.What is the difference between notify() and notifyAll()?


The notify() is used to unblock one waiting thread whereas notifyAll() method is used to
unblock all the threads in waiting state.

110.What is the deadlock?


Deadlock is a situation in which every thread is waiting for a resource which is held by some
other waiting thread. In this situation, Neither of the thread executes nor it gets the chance
to be executed. Instead, there exists a universal waiting state among all the threads.
Deadlock is a very complicated situation which can break our code at runtime.

111.What is the volatile keyword in java?


Volatile keyword is used in multithreaded programming to achieve the thread safety, as a
change in one volatile variable is visible to all other threads so one variable can be used by
one thread at a time.

112.What do you understand by thread pool?


o Java Thread pool represents a group of worker threads, which are waiting for the task
to be allocated.
o Threads in the thread pool are supervised by the service provider which pulls one
thread from the pool and assign a job to it.
o After completion of the given task, thread again came to the thread pool.
o The size of the thread pool depends on the total number of threads kept at reserve for
execution.

The advantages of the thread pool are :


o Using a thread pool, performance can be enhanced.
o Using a thread pool, better system stability can occur.

113.What is the difference between Java Callable interface and Runnable


interface?
The Callable interface and Runnable interface both are used by the classes which wanted to
execute with multiple threads. However, there are two main differences between the both :

o A Callable <V> interface can return a result, whereas the Runnable interface cannot
return any result.
o A Callable <V> interface can throw a checked exception, whereas the Runnable
interface cannot throw checked exception.
o A Callable <V> interface cannot be used before the Java 5 whereas the Runnable
interface can be used.

114.What is the difference between Synchronous programming and Asynchronous


programming regarding a thread?
Synchronous programming: In Synchronous programming model, a thread is assigned to
complete a task and hence thread started working on it, and it is only available for other tasks
once it will end the assigned task.

Asynchronous Programming: In Asynchronous programming, one job can be completed by


multiple threads and hence it provides maximum usability of the various threads.

115.What is the difference between Iterator and ListIterator?


Iterator traverses the elements in the forward direction only whereas ListIterator traverses the
elements into forward and backward direction.

No. Iterator ListIterator

1) The Iterator traverses the ListIterator traverses the elements in


elements in the forward direction backward and forward directions
only. both.

2) The Iterator can be used in List, ListIterator can be used in List only.
Set, and Queue.

3) The Iterator can only perform ListIterator can perform add,


remove operation while remove,and set operation while
traversing the collection. traversing the collection.
BASIC INTERVIEW QUESTIONS-3

Q1: What is an identifier in Java?

A1: In Java, an identifier is a name used to identify a variable, class, method, or other
program elements. Identifiers follow specific naming rules, such as starting with a
letter, underscore, or dollar sign and consisting of letters, digits, underscores, and
dollar signs.

Q2: What are keywords in Java?

A2: Keywords in Java are reserved words with predefined meanings and special
purposes. They cannot be used as identifiers. Examples of keywords in Java include
"public," "class," "if," and "static."

Q3: What is the use of the "static" keyword in Java?

A3: The "static" keyword in Java is used to define class-level members (variables and
methods) rather than instance-level members. Static variables are shared among all
instances of a class, and static methods can be called on the class itself without
creating an instance. This makes static members suitable for utility methods and
shared data that doesn't vary per instance.

Q4: What is the "public" keyword used for in Java?

A4: The "public" keyword in Java is an access modifier used to declare that a class,
method, or variable is accessible from any other class or package. It makes the
associated element visible and accessible to other parts of your program.

Q5: What is a Java class?

A5: In Java, a class is a blueprint or template for creating objects. It defines the
properties (fields or variables) and behaviors (methods) that objects of the class will
have.

Q6: What is a constructor in Java?

A6: A constructor in Java is a special method used to initialize objects of a class. It has
the same name as the class and is called when an object is created. Constructors set
initial values for object properties.

Q7: What is an object in Java?

A7: An object in Java is an instance of a class. It represents a real-world entity, and it


has its own state (defined by class variables) and behavior (defined by class methods).
Q8: What is the purpose of the "new" keyword in Java?

A8: The "new" keyword in Java is used to create an instance of a class, i.e., an object. It
allocates memory and calls the class constructor to initialize the object.

Q9: What is the main method in Java, and why is it significant?

A9: The main method is a special method in Java that serves as the entry point for a
Java application. It is the method executed when you run a Java program. The "public
static void main(String[] args)" method is required in every Java application and
defines the starting point of execution.

Q10: What is the purpose of the "this" keyword in Java?

A10: The "this" keyword in Java is used to refer to the current instance of a class. It is
often used to disambiguate between instance variables and parameters with the
same name and to access instance methods and fields within a class.

Q11: What is a Java package?

A11: A Java package is a way to organize and group related classes and interfaces. It
helps in avoiding naming conflicts and provides a hierarchical structure for your code.

Q12: What is the purpose of the "private" access modifier in Java?

A12: The "private" access modifier restricts access to class members (variables and
methods) within the same class. They are not visible or accessible from outside the
class.

Q13: What is the difference between an instance variable and a class variable in
Java?

A13: An instance variable is associated with an instance of a class and has a separate
copy for each object. A class variable, marked with the "static" keyword, is shared
among all instances of the class.

Q14: What is method overloading in Java?

A14: Method overloading in Java refers to the ability to define multiple methods in
the same class with the same name but different parameter lists. Java determines
which method to call based on the method's parameters.

Q15: What is method overriding in Java?


A15: Method overriding occurs when a subclass provides a specific implementation
for a method that is already defined in its superclass. The overridden method in the
subclass must have the same name, return type, and parameters.

Q16: What is the "super" keyword used for in Java?

A16: The "super" keyword is used to access or call methods, variables, or constructors
in the parent class (superclass) from within the child class (subclass).

Q17: What is a Java interface?

A17: An interface in Java is a collection of abstract methods (methods without


implementations) that a class can implement. It defines a contract for the methods
that implementing classes must provide.

Q18: How is exception handling done in Java?

A18: Java provides a mechanism for handling exceptions using "try," "catch," and
"finally" blocks. Code that might throw an exception is placed in a "try" block, and
exception handling code is placed in the "catch" block.

Q19: What is the purpose of the "throws" clause in a Java method declaration?
A19: The "throws" clause specifies the exceptions that a method may throw. It allows
the method to delegate the handling of exceptions to the calling code or to other
methods.

Q20: What is a Java constructor, and why is it important?

A20: A constructor is a special method in Java used for initializing objects. It's
essential because it ensures that an object is properly initialized when it's created.

Q21: What is the "null" value in Java?

A21: "null" is a special value in Java that represents the absence of a value or an
uninitialized reference. It's often used to indicate that an object reference does not
point to any valid object.

Q22: What is the purpose of the "final" keyword in Java?

A22: The "final" keyword can be applied to classes, methods, and variables. For
classes, it indicates that the class cannot be extended. For methods, it means the
method cannot be overridden. For variables, it signifies that the variable's value
cannot be changed once assigned.

Q23: What is method chaining in Java?


A23: Method chaining, also known as fluent API design, is a technique where
methods return the object they belong to, allowing you to chain method calls
together. It's often used for creating expressive and readable code.

Q24: What is the "equals" method in Java used for?

A24: The "equals" method in Java is used to compare the contents of two objects for
equality. It's often overridden in user-defined classes to provide custom comparison
logic.

Q25: What is a Java array?

A25: A Java array is a data structure that stores a fixed-size, ordered collection of
elements of the same data type. Elements in an array can be accessed by their index.

Q26: What is the "for-each" loop in Java, and how is it used?

A26: The "for-each" loop (also known as the enhanced for loop) is used to iterate
over elements of an array or other iterable collections. It simplifies looping through
arrays and collections.

Q27: What is the difference between "break" and "continue" statements in


Java?

A27: The "break" statement is used to exit a loop prematurely, while the "continue"
statement is used to skip the current iteration and move to the next one in a loop.

Q28: What is the "switch" statement in Java used for?

A28: The "switch" statement is used to select one of many code blocks to be executed
based on the value of an expression. It's an alternative to multiple "if-else"
statements.

Q29: What is a Java thread, and how is it different from a process?

A29: A Java thread is a lightweight, independent execution unit within a Java


program. Threads within the same process share the same memory space, while
processes have their separate memory space.

Q30: What is the purpose of the "synchronized" keyword in Java?

A30: The "synchronized" keyword is used to create synchronized methods or blocks,


which ensure that only one thread can access a synchronized section of code at a
time. It's used to prevent data corruption in multithreaded programs.
Q31: What is the purpose of the "volatile" keyword in Java?

A31: The "volatile" keyword is used to declare a variable as volatile, which ensures
that changes to the variable are visible to other threads immediately. It's often used
in multithreading to prevent variable caching.

Q32: What is the Java Memory Model (JMM)?

A32: The Java Memory Model defines how threads interact with memory in a
multithreaded program. It provides rules and guarantees for thread safety and
visibility of changes to variables.

Q33: What is the purpose of the "try-with-resources" statement in Java?

A33: The "try-with-resources" statement is used to manage resources like file streams
or network connections. It automatically closes the resources when they are no longer
needed, reducing the chance of resource leaks.

Q34: What is the purpose of the "instanceof" operator in Java?

A34: The "instanceof" operator is used to check whether an object is an instance of a


particular class or interface. It helps with type checking and safe casting.

Q35: What is method visibility in Java, and what are the access modifiers used
for it?

A35: Method visibility refers to who can access a method. Java provides access
modifiers like "public," "protected," "default," and "private" to control the visibility
and accessibility of methods.

Q36: What is the purpose of the "this" reference in a constructor?

A36: The "this" reference in a constructor is used to refer to the current object being
created. It's often used to disambiguate between instance variables and constructor
parameters with the same names.

Q37: What is method scope in Java, and how is it defined?

A37: Method scope refers to the region in code where


method variables are accessible. The scope of a variable in a method is limited to the method
block where it is declared. Method scope is defined by the opening and closing curly braces of
the method.

Q38: What is method overloading, and how is it determined at compile time?

A38: Method overloading is the ability to define multiple methods in the same class with the
same name but different parameter lists. Overloaded methods are determined at compile time
based on the number and types of arguments provided when calling the method.
Q39: What is a constructor, and why is it important in Java?

A39: A constructor is a special method used for initializing objects. It's essential because it ensures
that an object is properly initialized when it's created. Constructors have the same name as the
class and do not have a return type.

Q40: What is the purpose of the "super" keyword in Java?

A40: The "super" keyword is used to access or call methods, variables, or constructors in the
parent class (superclass) from within the child class (subclass). It is often used in constructor calls
to initialize the superclass part of an object.

Q41: What is a Java package, and why is it used?

A41: A Java package is a way to organize and group related classes and interfaces. Packages help
in avoiding naming conflicts and provide a hierarchical structure for code organization. They also
facilitate modularity and code reusability.

Q42: What is the "final" keyword used for in Java?

A42: The "final" keyword can be applied to classes, methods, and variables. When applied to a
class, it means the class cannot be extended (subclassed). For methods, it prevents them from
being overridden. For variables, it signifies that the variable's value cannot be changed once
assigned.

Q43: What is a Java interface, and how does it differ from a class?

A43: A Java interface is a collection of abstract methods (methods without implementations) that
a class can implement. Interfaces define a contract for the methods that implementing classes
must provide. Unlike classes, a class can implement multiple interfaces, but it can only extend one
class.

Q44: What is the "throws" clause in a Java method declaration used for?

A44: The "throws" clause specifies the exceptions that a method may throw. It allows the method
to delegate the handling of exceptions to the calling code or other methods. It is part of the
method signature.

Q45: What is a Java array, and how is it declared and initialized?

A45: A Java array is a data structure that stores a fixed-size, ordered collection of elements of the
same data type. To declare and initialize an array, you specify the data type, followed by the array
variable name, and the size in square brackets.

Q46: What is method chaining in Java, and how is it achieved?


A46: Method chaining, also known as fluent API design, is a technique where methods return the
object they belong to, allowing you to chain method calls together. It is achieved by having
methods return "this" (the current object).

Q47: What is the "null" value in Java, and how is it used?

A47: "null" is a special value in Java that represents the absence of a value or an uninitialized
reference. It's often used to indicate that an object reference does not point to any valid object.

Q48: What is the "for-each" loop in Java, and when is it useful?

A48: The "for-each" loop, also known as the enhanced for loop, is used to iterate over elements of
an array or other iterable collections. It simplifies looping through arrays and collections and is
useful when you want to process all elements sequentially.

Q49: What is the difference between the "break" and "continue" statements in Java?

A49: The "break" statement is used to exit a loop prematurely, terminating the loop's execution.
The "continue" statement is used to skip the current iteration and proceed to the next iteration of
the loop.

Q50: What is the "switch" statement in Java, and how does it work?

A50: The "switch" statement is used to select one of many code blocks to be executed based on
the value of an expression. It is often used as an alternative to multiple "if-else" statements. Each
case within the "switch" statement specifies a value to match, and the code block associated with
the matching case is executed.

INHERITANCE

1. What is Inheritance in Java?

Inheritance is a mechanism through which an object acquires all the properties and behavior of another
class. It is usually used for Method Overriding and Code Reusability.

2. Why is inheritance necessary?


Inheritance is a critical concept of OOPs. Some classes share similar traits and behaviours in
Java. A sub-class acquires features, actions, and attributes of the superclass. This is called
inheritance. It offers a lot of benefits, justifying its usage in Java.

 The existing features of a class are used through inheritance.


 Inheritance supports code reusability.
 Inheritance in Java is used to implement method overriding, known as runtime
polymorphism.
 Overriding allows us to extend the functionality of a class through inheritance.
3. How many types of inheritances available in the Java programming language?
In the Java programming language, there are five types of Inheritances as below:

Single inheritance, multilevel inheritance, hierarchical inheritance, hybrid inheritance, and multiple
inheritances.

 Single Inheritance: In this one class is inherited or extended by only one class only.
 Hybrid Inheritance: Hybrid inheritance is a combination of Single, Multilevel and
hierarchical inheritances.
 Multilevel Inheritance: In multilevel inheritance, one class is extended by one class. That
extended class or the subclass is being extended by another class and forms a chain of
relationships between the classes multilevel inheritance.
 Hierarchical Inheritance: In this inheritance, one class is being extended to more than one
class.
 Multiple Inheritance: In this inheritance, one class extends more than one classes, and Java is
not supporting it.

4.Can a class extend more than one classes or does java support multiple
inheritance? If not, Why?
No, a class in java cannot extend more than one classes or java does not support multiple inheritance.
To avoid ambiguity, complexity and confusion, java does not support multiple inheritance.

5.What is the difference between superclass and subclass?


A class from where a subclass inherits features is called superclass. It is also called base class or parent
class.
A class that inherits all the members (fields, method, and nested classes) from other class is called
subclass. It is also called a derived class, child class, or extended class.

6.What are the Rules of Inheritance in Java?

Rule#1: Java Does Not Support Multiple Inheritance


There’s no way that Java enables multiple inheritances. The Java compiler generates a compilation error
whenever the user attempts multiple inheritances in a program.
Rule#2: Java does not permit Cyclic Inheritance
Cyclic inheritance is where a class inherits itself to a form or structure of a cycle.

Rule#3: We cannot inherit private data from members


If you know about ‘access modifiers,’ you’ll recall that inheritance isn’t applicable to members
with private access.

Rule#4: Constructors are not inherited


The fact that constructors are leveraged for creating class objects means that they aren’t
inherited from class to class.
Rule#5: We can use parent reference to access child objects
You already know quite a lot of inheritance examples. You can make a reference to the parent
class type and then use the new keyword to create a derived class object that you’ll assign to
the parent class.
Rule#6: Parent constructors are executed because of super () in derived constructors

According to a rule, it’s clear that the inheritance of constructors isn’t possible. However, the
superclass’s constructor could be implemented within the derived class’s constructor,
leveraging the super () call.

7.How do you restrict a member of a class from inheriting to it’ s sub classes?
By declaring that member as a private. Because, private members are not inherited to sub
classes.

8. What are the advantages of inheritance in Java?


The advantages of inheritance in java are as follows:
 We can minimize the length of duplicate code in an application by putting the common code in
the superclass and sharing it amongst several subclasses.
 Due to reducing the length of code, the redundancy of the application is also reduced.
 Inheritance can also make application code more flexible to change.

9.What are the Disadvantages of inheritance in java?

 The inherited methods lag in performance

 Some of the data members of the parent class may not be of any use—as a result, they waste memory

 Inheritance causes strong coupling between parent and child classes. This means, either of the two
(Parent class or Child class) become incapable of being used independent of each other.

10.What is the use of extends keyword in inheritance?


The extends keyword is used to declare a class that inherits from another class, known as the superclass.
This inheritance mechanism allows the subclass to inherit fields and methods from the superclass.

11.Why multiple inheritance is not supported in Java?


In Java, a class cannot extend more than one class. Therefore following is illegal −
Example
public class extends Animal, Mammal{}

However, a class can implement one or more interfaces, which has helped Java get rid of the
impossibility of multiple inheritances.

The reason behind this is to prevent ambiguity.

Consider a case where class B extends class A and Class C and both class A and C have the same
method display().

Now java compiler cannot decide, which display method it should inherit. To prevent such situation,
multiple inheritances is not allowed in java.
12. What is order of calling constructors in case of inheritance?

In case of inheritance, constructors are called from the top to down hierarchy.

13. Can we access subclass members if we create an object of superclass?


No, we can access only superclass members but not the subclass members

14. What is Hybrid inheritance in java? How will you achieve it?
A hybrid inheritance in java is a combination of single and multiple inheritance. It can be achieved
through interfaces.

15.what is method overriding?


Overriding is a feature that allows a subclass or child class to provide a specific implementation of a
method that is already provided by one of its super-classes or parent classes. When a method in a
subclass has the same name, the same parameters or signature, and the same return type (or sub-type)
as a method in its super-class, then the method in the subclass is said to override the method in the
super-class.
16.What is class?
A class--the basic building block of an object-oriented language such as Java A class is a user defined
blueprint in which individual objects are created. In general, class declarations can include these
components, in order:

• Modifiers : A class can be public

• Class name: The name must begin with an UPPER CASE LETTER.
• Superclass (if any): The name of the class’s parent (superclass), if any, preceded by the
keyword Extends. A class (subclass) can only extend one parent.

• Interfaces (if any): A comma-separated list of interfaces implemented by the class, if any,
preceded by the keyword implements.
17.What is an object?
Object is an instance of a class. Class is a template or blueprint from which objects are created. So object
is the instance(result) of a class.
An object has TWO characteristics:
state: represents data (value) of an object.
behavior: represents the behavior (functionality) of an object such as deposit, withdraw etc. An object
stores its state in fields (variables in some programming languages) and exposes its behavior through
methods (functions in some programming languages).
Object Definitions:
o Object is a real world entity.
o Object is a run time entity.
o Object is an entity which has state and behavior.
Object is an instance of a class.
POLYMORPHISM

1.what is polymorphism?
 Polymorphism means "many forms", and it occurs when we have many classes that are related
to each other by inheritance.
 Polymorphism is the ability of an object to take on many forms.

2. How is inheritance related to polymorphism in Java?

Inheritance and polymorphism are closely related in Java. Polymorphism refers to the ability of objects
of different classes to be treated as if they were objects of a common parent class. Inheritance allows us
to create a hierarchy of classes that share common properties, and this hierarchy can be used to achieve
polymorphism. By defining methods in the parent class and overriding them in the child classes, we can
achieve runtime polymorphism in Java OR

Inheritance represents the parent-child relationship between two classes and polymorphism take the
advantage of that relationship to add dynamic behavior in the code (or to make the program more
dynamic).

3. What are the types of Polymorphism in Java?


There are two types of polymorphism in java. They are:
 Static polymorphism (Compile time Polymorphism)
 Dynamic polymorphism (Runtime Polymorphism)

4. What is Compile time polymorphism (Static polymorphism)?


A polymorphism where object binding with methods happens at compile time is called static
polymorphism or compile-time polymorphism.
In static polymorphism, the behavior of method is decided at compile-time based on the parameters or
arguments of method.

5. What is Run time polymorphism (Dynamic polymorphism)?


 It is also known as Dynamic Polymorphism or Late Polymorphism. A polymorphism that is
resolved during run time is known as dynamic polymorphism. The Dynamic Polymorphism
feature is implemented with dynamic binding. In Java, dynamic polymorphism is achieved
through method overriding.
 In the case of Runtime Polymorphism for a given method call, we can recognize which method
has to be executed exactly at runtime but not in compilation time because in case of overriding
we have multiple methods with the same signature.
 So, which method to be given preference and executed that is identified at Runtime and binds
the method call with its suitable method. It is also called dynamic polymorphism or late binding.
Dynamic Polymorphism is achieved by using method overriding.

6.What are the rules for method overriding in java?


Rules for Method Overriding in Java:
 The method name must be the same.
 Method parameter types must be the same.
 The method return type must be the same.

7. what are the advantages of polymorphism?


 It helps programmers reuse the code and classes once written, tested and implemented. They can
be reused in many ways.
 Single variable name can be used to store variables of multiple data types (Float, double, Long,
Int etc).
 Polymorphism helps in reducing the coupling between different functionalities.

8.what are the disadvantages of polymorphism?


 One of the disadvantages of polymorphism is that developers find it difficult to implement
polymorphism in codes.
 Run time polymorphism can lead to the performance issue as machine needs to decide which method
or variable to invoke so it basically degrades the performances as decisions are taken at run time.
 Polymorphism reduces the readability of the program. One needs to identify the runtime behavior
of the program to identify actual execution time.

9.Where is polymorphism used?


 Polymorphism is widely used in object-oriented programming (OOP) in various scenarios where
flexibility, extensibility, and code reuse are desired. Here's a detailed explanation of where
polymorphism is commonly used:
 1. Inheritance and Subtyping
 2. Method Overriding
 3. Interfaces and Abstract Classes
 4. Collections and Data Structures
 5. Dependency Injection and Inversion of Control
 6. Frameworks and Libraries
 7. Event Handling and Callbacks

10. What is static and dynamic binding?


Objects that are determined at the time of compilation are known as static binding. On the other hand,
dynamic binding types of objects are determined at the run-time. The former is used during method
overloading and the latter during method overriding.

11. How Java compiler differentiate between methods in Compile time


Polymorphism?
During compilation, Java compiler differentiates multiple methods having the same name by
their signatures.

12.Why static binding is also called early binding in Java?


Static binding is also called early binding because it takes place before the program actually runs. An
example of static binding is method overloading.

13. What is Binding in Java?


The connecting (linking) between a method call and method definition is called binding in java.
14. What is a real life example of polymorphism in Java?
A person at the same time can have different characteristics. Like a man at the same time is a father,
a husband, and an employee. So the same person possesses different behaviors in different
situations. This is called polymorphism.

15. What is method overriding?


Method overriding is a feature of OOPs by which the child class or the subclass can redefine methods
present in the base class or parent class. Here, the method that is overridden has the same name as
well as the signature meaning the arguments passed and
ABSTRACTION
1.What is “abstract” in Java?
Abstract is a non-access modifier in Java that is used to declare classes, methods, and interfaces
that cannot be instantiated directly. An abstract class or method must be extended or implemented
by a subclass before it can be used.

2.What is Abstraction in Java


Abstraction in Java refers to hiding the implementation details of a code and exposing only the
necessary information to the user. It provides the ability to simplify complex systems by ignoring
irrelevant details and reducing complexity.

3. Can an abstract method be declared with private modifier?


No, it cannot be private because the abstract method must be implemented in the child class. If
we declare it as private, we cannot implement it from outside the class.

4. When to use Abstract method in Java?


An abstract method can be used when:

a) When the same method has to perform different tasks depending on the object calling it.
b) When you need to be overridden in its non-abstract subclasses.

5.Can an abstract class have constructor? Why?


Yes, an abstract class can have a constructor in Java.

A constructor is a special method that is used to initialize the state of an object when it is created.

6.Can we instantiate a class which does not have even a single abstract
methods but declared as abstract?

No, We can’t instantiate a class once it is declared as abstract even though it does not have
abstract methods.

7. How to achieve or implement Abstraction in Java?


There are two ways to implement abstraction in java. They are as follows:
a)Abstract class (0 to 100%)
b) Interface (100%)
8. Can we make an abstract class without abstract keyword?
No, a class must be declared with abstract keyword to make an abstract class.
9. What is the advantage of Abstract class in Java?
The main advantages of using abstract class are as follows:
 Abstract class makes programming better and more flexible by giving the scope of
implementing abstract methods.
 Programmer can implement abstract method to perform different tasks depending on the
need.
 We can easily manage code.

10. Can we define an abstract method inside non-abstract class (concrete


class)?
No, we cannot define an abstract method in non-abstract class.
For example:
class Test {

abstract void show();

The above code will generate a compile-time error.


11. Is abstract class a pure abstraction in Java?
No, It provides 0 to 100% abstraction.
12. Is abstract class allow to define private, final, static, and concrete
methods?
Yes.

13. Can we an overload abstract method in Java?


 Yes, abstract methods can be overloaded
 And its extending class will provide an implementation for all abstract methods

14. How is Abstraction different from Encapsulation?


Abstraction happens at class level design. It results in hiding the implementation details.
Encapsulation is also known as “Information Hiding”. An example of encapsulation is
marking the member variables private and providing getter and setter for these member
variables.

15. Can we instantiate an abstract class in Java?


No. We cannot create an instance of an abstract class in Java.
ENCAPSULATION

1. What is Encapsulation in Java?


Encapsulation is a mechanism in which data and methods are combined into a single unit called
a class. Encapsulation provides data hiding, which means that the internal implementation
details of a class are hidden from the outside world.
2. Are encapsulation and data hiding the same?
No. In data hiding, the data can only be defined as private, whereas the data can be public or
private in data encapsulation. Encapsulation is a sub-process in data hiding. And data hiding is
a process and technique both in itself.

3.Real life example of Encapsulation?

Real life example of encapsulation is; capsule is mixed of several medicines.

4.Advantage of Encapsulation in java?


 Encapsulated Code is more flexible and easy to change with new requirements.
 Encapsulation in Java makes unit testing easy.
 Encapsulation in Java allows you to control who can access what.
 Encapsulation allows you to change one part of code without affecting other parts of
code.

5. How to achieve encapsulation in Java? Give an example.


There are two key points that should be kept in mind to achieve the encapsulation in Java. They
are as follows:
 Declare the variable of the class as private.
 Provide public setter and getter methods to modify the values of variables.

6.Disadvantages of Encapsulation in Java


 Can lead to increased complexity, especially if not used properly.
 Can make it more difficult to understand how the system works.
 May limit the flexibility of the implementation.

7. What are access modifiers in Java?

Access modifiers are keywords that determine the visibility of a class, method, or variable in
Java.

8. Why do we make instance variables private in encapsulation?


By making instance variables private, we restrict direct access to them from outside the class.
This allows us to control how the variables are accessed and modified, ensuring data
encapsulation and preventing unauthorized changes or invalid values.
9. Can encapsulation be achieved across packages in Java?
Encapsulation can be achieved across packages in Java by using appropriate access modifiers
(public, protected, default, private) along with packages and classes. By setting the access
modifiers correctly, you can control the visibility and accessibility of classes and members
between different packages.

10. Why Is Encapsulation used in Java?


Encapsulation in Java is mostly useful to hide the data. Or in other words, to decide about the
access given to data as to who can access it, and who cannot.

11. What are getter and setter methods in Java?


In Java, setter method is a method that is used for updating the values of a variable. This method
is also known as mutator method.
Getter method is a method that is used to retrieve the value of a variable or return the value of
the private member variable. This method is also known as an accessor method.

12.What are Access modifiers in Java?

Access modifier class Sub-class Package Whole Application


Public yes yes yes yes
Protected yes yes yes No
Private yes No No No
13. What is the difference between encapsulation and abstraction?
1. Abstraction solves the problem at design level while encapsulation solves the problem
at implementation level.
2. Abstraction is used for hiding the unwanted data and provide only the required data. On
the other hand encapsulation means hiding the code and data into a single unit to protect
the data from outside world.
3. Abstraction lets you focus on what the object does instead of how it does it while
Encapsulation means hiding the internal details or mechanics of how an object does
something.
4. For example: Outer Look of a Television i.e. it has a display screen and channel buttons
to change channel explains 'abstraction' but inner implementation detail of a television
i.e. how CRT and display screen are connected with each other using different circuits
explains 'encapsulation'.

14. What are the features of encapsulation?


 Encapsulation means combining the data of our application and its manipulation at one
place.
 Encapsulation allows the state of an object to be accessed and modified through
behaviour.
 It reduces the coupling of modules and increases the cohesion inside them.
15. What is the primary benefit of encapsulation?
The main benefit of encapsulation is the ability to modify the implemented code without
breaking the code of others who use our code. It also provides us with maintainability, flexibility
and extensibility to our code.

LINKEDLIST INTERVIEW QUESTIONS

1) Explain Linked List in short.


A linked list may be defined as a linear data structure which can store a collection of
items. Each element or unit of the list is indicated as a node.

2) How will you represent a linked list in a graphical view?


A linked list may be defined as a data structure in which each element is a separate
object. Linked list elements are not kept at the contiguous location. The pointers are
used to link the elements of the Linked List.

3) How many types of Linked List exist?


There are multiple types of Linked Lists available:
o Singly Linked List
o Doubly Linked List
o Multiply Linked List
o Circular Linked List

4) Explain Singly Linked List in short.


o The singly linked list includes nodes which contain a data field and next field.
The next field further points to the next node in the line of nodes
o A singly linked list is shown below whose nodes contain two fields: an integer
value and a pointer value (a link to the next node).

5) What do you understand by Doubly Linked List?


The doubly linked list includes a pointer (link) to the next node as well as to the previous
node in the list. The two links between the nodes may be called "forward" and
"backward, "or "next" and "prev (previous)." A doubly linked list is shown below whose
nodes consist of three fields: an integer value, a link that points to the next node, and
a link that points to the previous node.

6) Explain Multiply Linked List in short.


In a multiply linked list, each node consists of two or more link fields. Each field is used
to join the same set of records in a different order of the same set, e.g. "by name, by
date of birth, by the department, etc.".

7) How will you explain Circular Linked List?


In the last node of a linked list, the link field often contains a null reference. Instead of
including a null pointer at the end of the list, the last node in circular linked lists includes
a pointer pointing to the first node.
8) How many pointers are necessary to implement a simple
Linked List?
There are generally three types of pointers required to implement a simple linked list:

o A 'head' pointer which is used for pointing to the start of the record in a list.
o A 'tail' pointer which is used for pointing to the last node. The key factor in the
last node is that its subsequent pointer points to nothing (NULL).
o A pointer in every node which is used for pointing to the next node element.

9) How can you represent a linked list node?


The simplest method to represent a linked list node is wrapping the data and the link
using typedef structure.

10) Which type of memory allocation is referred for Linked List?


Dynamic memory allocation is referred for Linked List.

11) What do you know about traversal in linked lists?


The term 'traversal' refers to the operation of processing each element present in the
list.

12) What are the main differences between the Linked List and
Linear Array?

Linked List Linear Array

Deletion and insertion are easy. Deletion and insertion are tough.

The linked list doesn't require movement Linear Array requires movement of
of nodes while performing deletion and nodes while performing deletion
insertion. and insertion.

In the Linked List, space is not wasted. In Linear Array, space is wasted.
Linked List is not expensive. Linear Array is a bit expensive.

It has an option to be extended or It cannot be reduced or extend


reduced as per the requirements.

13) What does the dummy header in the linked list contain?
In a linked list, the dummy header consists of the first record of the actual data.

14) Mention a few applications of Linked Lists?


Few of the main applications of Linked Lists are:

o Linked Lists let us implement queues, stacks, graphs, etc.


o Linked Lists let us insert elements at the beginning and end of the list.

15) How can you insert a node to the beginning of a singly linked
list?
To insert the node to the beginning of the list, we need to follow these steps:

o Create a new node


o Insert new node by assigning the head pointer to the new node's next pointer
o Update the head pointer to point the new node

16) Name some applications which use Linked Lists.


Both queues and stacks can be implemented using a linked list. Some of the other
applications that use linked list are a binary tree, skip, unrolled linked list, hash table,
etc.

17) Differentiate between singly and doubly linked lists?


Doubly linked list nodes consist of three fields: an integer value and two links pointing
to two other nodes (one to the last node and another to the next node).

On the other hand, a singly linked list consists of a link which points only to the next
node.
18) What is the main advantage of a linked list?
The main advantage of a linked list is that we do not need to specify a fixed size for the
list. The more elements we add to the chain, the bigger the chain gets.

19) How can someone add an item to the beginning of the list?
Adding an item to the beginning of the list, we need to follow the given steps:

o Create a new item and set up its value.


o Link the newly created item pointing to the head of the list.
o Set up the head of the list as our new item.

20) How can we delete the first node from the singly linked list?
To delete the first node from the singly linked list, we need to follow below steps:

o Copy the first node address to some temporary variable.


o Change the head to the second node of the linked list.
o Remove the connection of the first node to the second node.
o Delete temp and free up the memory occupied by the first node.

Doubly Linked List


1. What are Doubly Linked Lists?
A doubly linked list is a type of linked list in which each node has two pointers,
one pointing to the previous node and one pointing to the next node. This
allows for traversal of the list in both directions.
2. Can you explain what a doubly linked list is and how it differs from a singly
linked list?
A doubly linked list is a type of linked list in which each node has two pointers,
one pointing to the previous node and one pointing to the next node. This
allows for traversal in both directions. A singly linked list, on the other hand,
only has a single pointer per node, meaning that traversal is only possible in
one direction.
3. How do you add an item to the end of a doubly linked list?
You would add an item to the end of a doubly linked list by creating a new node
with the data you want to add, and then linking that node to the last node in
the list. The new node would then become the new last node in the list.
4. How can you delete a node in a doubly linked list given only access to that
node?
In order to delete a node in a doubly linked list, you need to have access to both
the node that you want to delete as well as the node that precedes it in the list.
Once you have access to both of those nodes, you can simply adjust the
pointers so that the node that precedes the one you want to delete now points
to the node that follows the one you want to delete, and vice versa.
5. How does a circular doubly-linked list differ from other types of doubly linked
lists?
In a circular doubly-linked list, the last node in the list is linked to the first node
in the list. This creates a loop, so that you can move through the list from the
first node to the last node and back again endlessly. Other types of doubly
linked lists do not have this loop, so you can only move through the list in one
direction.

6. Is it possible to create a doubly linked list with zero nodes? If yes, then how?
Yes, it is possible to create a doubly linked list with zero nodes. This can be
accomplished by setting the head and tail pointers to null.
7. Is it possible to have both head and tail pointers point to NULL at the same
time? What about when traversing forward or backward through a doubly
linked list?
Yes, it is possible for both head and tail pointers to point to NULL at the same
time. This would happen if the doubly linked list is empty. When traversing
forward through a doubly linked list, the head pointer will point to the first
node in the list and the tail pointer will point to the last node in the list. When
traversing backward through a doubly linked list, the head pointer will point to
the last node in the list and the tail pointer will point to the first node in the list.
8. Why would you use a doubly linked list instead of a single linked list?
A doubly linked list offers a few advantages over a single linked list. First,
because each node has pointers to both the next and previous nodes in the list,
it is easier to navigate backwards through a doubly linked list than a single
linked list. Additionally, because each node has a pointer to both the next and
previous nodes, it is easier to insert and delete nodes from a doubly linked list
than a single linked list.
9. Are there any disadvantages to using a doubly linked list over a singly linked
list?
The main disadvantage of using a doubly linked list over a singly linked list is
that it requires twice as much memory to store the same amount of data. This
is because each node in a doubly linked list contains two pointers (one pointing
to the previous node and one pointing to the next node), whereas each node in
a singly linked list only contains one pointer.
10. What’s the difference between deleting a node from the front or back of a
doubly linked list?
If you delete a node from the front of a doubly linked list, then you will need to
update the head pointer to point to the new first node in the list. If you delete a
node from the back of the list, then you will need to update the tail pointer to
point to the new last node in the list.
11. Is it possible to make all nodes in a doubly linked list point to the same
previous element? What about the next element?
It is not possible to make all nodes in a doubly linked list point to the same
previous element, as this would break the structure of the list. However, it is
possible to make all nodes in a doubly linked list point to the same next
element. This would result in a circular linked list.
12. Is it possible to sort a doubly linked list? If yes, then how?
Yes, it is possible to sort a doubly linked list. There are a few different ways to
do this, but one common approach is to use a merge sort algorithm. This will
involve breaking the list down into smaller sublists, sorting each of those
sublists, and then merging the sorted sublists back together into one overall
sorted list.
15. What are some advantages of doubly linked lists over arrays?
One advantage of doubly linked lists over arrays is that they allow for easier
insertion and deletion of elements. This is because with an array, all elements
after the one being inserted or deleted would need to be shifted in order to
make room or close the gap. With a doubly linked list, there are pointers to
both the next and previous elements, so no shifting is necessary.
Another advantage of doubly linked lists is that they can be traversed in either
direction. With an array, you can only move forward through the elements.
With a doubly linked list, you can move both forward and backward, which can
be helpful in some situations.
16. What is the maximum number of elements that can be stored in a doubly
linked list?
The maximum number of elements that can be stored in a doubly linked list is
2^64 – 1, or 4294967295. This is due to the fact that each node in a doubly
linked list requires two pointers, one for the next node and one for the previous
node.
17. What are the main differences between vectors, stacks, queues, and doubly
linked lists?
The main differences between vectors, stacks, queues, and doubly linked lists
are their size, their structure, and their functionality. Vectors are arrays that can
grow and shrink as needed, while stacks and queues are fixed-size collections.
Stacks are last-in-first-out data structures, while queues are first-in-first-out.
Doubly linked lists are linked lists that have links going in both directions, while
singly linked lists only have links going in one direction.
18. What are the different insertion methods for doubly linked lists?
There are three different insertion methods for doubly linked lists:
1. Inserting at the head of the list
2. Inserting at the tail of the list
3. Inserting in the middle of the list
19. Which one of these do you think is faster: inserting an element at the
beginning, middle, or end of a doubly linked list?
Inserting an element at the beginning of a doubly linked list is the fastest
option. This is because you only need to update the pointers for the head and
tail nodes, and you do not need to traverse the entire list to find the correct
insertion point. Inserting an element in the middle or end of a list requires
traversing the list to find the correct insertion point, which takes more time.
20. What are some common algorithms used on doubly linked lists?
Some common algorithms used on doubly linked lists include insertion,
deletion, searching, and sorting.
ARRAYLIST

1. What is ArrayList in Java?


ArrayList is a resizable array that can grow or shrink in the memory whenever needed. It is
dynamically created with an initial capacity. It uses a dynamic array internally for storing a
group of elements or data.
2. Which marker interfaces are implemented by Java ArrayList?
Java ArrayList class implements three marker interfaces such as RandomAccess, Cloneable,
and Serializable.
3. Which collection classes implement List interface in Java?
The collection classes that implement List interface, are as:
 ArrayList
 LinkedList
 CopyOnWriteArrayList
 Vector
 Stack
4. Why is ArrayList called a dynamically growing array in Java?
ArrayList is called a dynamically growing array in java because ArrayList uses a dynamic array
internally for storing a group of elements.
When elements are removed from the array list, the size of array list can be shrunk
automatically.
5. How to add elements to Java ArrayList?
List interface provides three useful methods to add elements into an ArrayList. They are:
 add(E element): Appends the specified element to the end of the array list.
 add(int index, E element): Inserts the specified element at the specified
position in the list.
 addAll(int index, Collection<? extends E > c): Inserts all of the elements of the
specified collection into the list, starting at the specified position.
6. Does ArrayList allow to insert duplicate elements?
Yes, ArrayList allows to insert duplicate elements.
7. Is it possible to add null into ArrayList?
Yes, we can add any number of nulls into the array list.

8. Is it possible to join two or more ArrayLists in Java?


Yes, we can join two or more ArrayLists in java. List interface provides a method addAll() to
join two or more lists in java.
If we have one list list1 and another list2, we can join them with the help of addAll() like this:
list1.addAll(list2);

9. What will be the output of the following program?


import java.util.ArrayList;

import java.util.List;

public class ArrayListTest {

public static void main(String[] args)

List<String> list = new ArrayList<String>();

list.add("Dhanbad");

list.add(0, "New York");

list.add("Mumbai");

list.add(3, "Sydney");

System.out.println(list);

10. Why adding or inserting elements to ArrayList can be slow?


When the size of ArrayList is unknown then adding elements to ArrayList is slow. When the
size of ArrayList grows, a lot of shifting takes place in the memory while adding elements.
Due to which the performance of ArrayList becomes slow.

11. What is the output of the following code snippet?


import java.util.ArrayList;

import java.util.List;

public class ArrayListTest {

public static void main(String[] args)

List<String> list = new ArrayList<String>();


list.add("Orange");

list.add(0, "Banana");

ArrayList<String> arList = new ArrayList<>();

arList.add("Apple");

list.add("Grapes");

list.addAll(3, arList);

System.out.println(list);

12. What is the difference between the length of an array and size of ArrayList?
The length of an array can be determined by using property length. But ArrayList does not
support the length property. It provides size() method that can be used to find the number
of elements in the list.

13. Both ArrayList and LinkedList provide get() method to retrieve an element
at the specified position from the list. Which one is faster, ArrayList or
LinkedList?
ArrayList’s get() method is faster than LinkedList’s get() because LinkedList does not
implement Random Access Interface.
Due to which it will traverse from the beginning or ending over the list until it reaches the
index specified.

14. What are the advantages of ArrayList over Arrays?


The advantages of ArrayList over Arrays are as follows:
 ArrayList can grow or shrink dynamically.
 ArrayList provides a more powerful insertion and search mechanism as compared to
arrays.

15.How do you access elements in an ArrayList in Java?


To access an element from the arraylist, we use the get () method of the ArrayList class. For
example, In the above example, we have used the get () method with parameter 1. Here, the
method returns the element at index 1. To learn more, visit the Java ArrayList get ().
16.What is the difference between array and ArrayList in Java?
Arrays in Java are static in nature. ArrayLists, on the other hand, can only store elements as
objects. ArrayLists in Java, unlike arrays, are dynamic in nature. An ArrayList is a collection
class present in java.util package that implements java.util.List interface.

17.Can we add elements to an ArrayList obtained from Arrays.asList() ?


Arrays.asList() method creates a fixed-size arraylist from an array. We can not add more
elements to it.

18. How do you convert an ArrayList to an array in Java?

We can obtain the array from an arraylist using toArray() method of ArrayList.
List<Integer> numbers = new ArrayList<Integer>();

numbers.add(1);

numbers.add(2);

Integer[] arr = new Integer[numbers.size()];

arr = numbers.toArray(arr);

19.What is the differences between ArrayList and Vector ?

– ArrayList is not synchronized whereas Vector is synchronized.

– ArrayList allows a null key and null values. Vector does not allow null keys or values.

– Since methods in ArrayList are not synchronized, ArrayList performs better compared to a
Vector.

20.How can we synchronize an ArrayList ?

ArrayList can be synchronized using Collections.synchronizedList() method as follows:


List list = Collections.synchronizedList(new ArrayList(...));

21.What is the difference between ArrayList’s clear() and removeAll() methods


?
clear() method removes all the elements from an ArrayList.

removeAll() method takes a collection as parameter. It removes all of the ArrayList elements
that are part of the collection.
STACK & QUEUE
1.what is stack?
Stack:A stack is a linear list of elements for which all insertions and deletions(usually accesses) are
made at only one end of the list.

2.what is another name for the stack?


They are also called as LIFO lists(Last Input First Output).

3.what are the operations performed on stack?


1)IsEmpty(S): returns whether the stack is empty or not.

2)IsFull(S): return whether the stack is full or not.

3)Push(Element X,S): pushes element X on to the top of the stack.

4)Pop(S) : pops an element from the top of the stack on to the output(printing on to the output console
isn't necessary though in which case we can define another function Top(S) which gives the top
element of the stack).

4.what is the complexity of the stack operations?


All the above mentioned operations are of O(1) complexity.

5.what is queue?
Queue: Queue is a linear list for which all insertions are made at one end and deletions(accesses as
well)
are made at the other end of the list and the lists are also called as FIFO lists(First Input First Output ).

6.what are the operations performed on queue?


1)IsEmpty(Q):returns whether the queue is empty or not.

2)IsFull(Q): return whether the queue is full or not.

3)Enqueue(Element X,Q): inserts an element X on the rear side of the queue.

4)Dequeue(Q): removes the element pointed to by the front end of the queue.

7.what is the complexity of the queue operations?


Similar to a stack ,the operations of the queue are also of O(1) complexity.

8.what is Dequeue?
Deletion of stack element is known as dequeue.

QUEUE

1.What is Queue?
A queue is a container of objects (a linear collection) that are inserted and removed
according to the first-in first-out (FIFO) principle. The process to add an element into queue is
called Enqueue and the process of removal of an element from queue is called Dequeue.

2. Can you explain what a Queue data structure is and where it is primarily
used?
A Queue is a linear data structure that follows the First-In-First-Out (FIFO) principle. It has
two main operations: enqueue, which adds an element to the end of the queue, and
dequeue, which removes an element from the front. Queues are primarily used in scenarios
where order matters such as CPU scheduling, Disk Scheduling, and when implementing
caches. They’re also utilized in certain types of network devices like routers and switches for
managing packets due to their ability to maintain the order of elements.

3. How is a Queue different from a Stack data structure?


A Queue and a Stack are both linear data structures, but they differ in how elements are
added and removed. In a Queue, insertion (enqueue) happens at the end (rear) and removal
(dequeue) occurs at the beginning (front). This follows the First-In-First-Out (FIFO) principle
where the oldest element is the first one to be removed.
On the other hand, a Stack operates on the Last-In-First-Out (LIFO) principle. Insertion (push)
and removal (pop) both occur at the top of the stack. The most recently added item is the
first one to be removed.
In terms of usage, Queues are often used in scenarios that require maintaining order of
elements, like CPU scheduling or print spooling. Stacks are utilized in situations needing
reversal operations or memory storage such as backtracking algorithms or function call
stacks.

4. How would you implement a Queue data structure using two Stacks?
To implement a Queue using two Stacks, we’ll name them stack1 and stack2. Stack1 will be
used for enqueue operation and stack2 for dequeue operation.
For the enqueue operation (inserting elements into the queue), push the elements into
stack1. Time complexity here is O(1).
The dequeue operation (removing elements from the queue) is slightly more complex. If
stack2 is empty, while stack1 is not, pop all elements from stack1 and push them to stack2.
The popped element is the result of the dequeue operation. If stack2 has elements, simply
perform a pop operation on it. This gives us an amortized time complexity of O(1).

5. What is the difference between a static and dynamic Queue?


A static queue has a fixed size, defined at the time of its creation. Once it’s full, no more
elements can be added until some are removed. This could lead to overflow if not managed
properly. On the other hand, a dynamic queue doesn’t have a predefined size limit. It grows
and shrinks as elements are added or removed, which prevents overflow but requires more
memory management. The choice between static and dynamic queues depends on specific
requirements regarding memory usage and flexibility.

6. Can you explain the terms Enqueue and Dequeue with respect to Queue
operations?
Enqueue and Dequeue are fundamental operations in Queue data structure. Enqueue is the
process of adding an element to the end of the queue. It’s performed when there is space
available in the queue, otherwise it results in overflow condition. On the other hand,
Dequeue is the removal of an element from the front of the queue. This operation is
executed if the queue isn’t empty; if it is, underflow condition occurs. Both operations
maintain the FIFO (First In First Out) principle inherent to queues: items added first are
removed first.

7. What is a Deque (Double Ended Queue)? How does it differ from a regular
Queue?
A Deque (Double Ended Queue) is a specific type of queue data structure that allows
insertion and removal of elements from both ends, namely front and rear. Unlike a regular
queue which operates on the FIFO (First In First Out) principle where insertions occur at the
rear end and deletions at the front, a deque provides more flexibility by allowing operations
at both ends. This makes it possible to use deques in applications requiring dynamic memory
allocation or navigation through a data set in both forward and backward directions.

8. How would you detect a Queue underflow or overflow condition in your


program?
Queue underflow and overflow conditions are detected by monitoring the front and rear
pointers of the queue.
Underflow occurs when we attempt to dequeue an empty queue. This can be checked by
comparing the front and rear pointers. If they’re equal, the queue is empty, indicating an
underflow condition.
Overflow happens when we try to enqueue an element into a full queue. In a static array
implementation, if the rear pointer equals the size of the array minus one, it signifies that the
queue is full. For dynamic arrays or linked list implementations, overflow is typically not a
concern unless memory allocation fails.
9. Explain the time complexity of enqueue, dequeue, and peek operations in a
Queue.
A queue is a linear data structure that follows the First In First Out (FIFO) rule. The time
complexity of operations in a Queue are as follows:
Enqueue: This operation adds an element to the end of the queue. It has a constant time
complexity, O(1), because it only involves adding an element at one position – the end.
Dequeue: This operation removes an element from the front of the queue. Similar to
enqueue, dequeue also has a constant time complexity, O(1). This is due to the fact that
removing an element only happens at one place – the beginning of the queue.
Peek: Peek operation retrieves the element at the front of the queue without removing it.
Like enqueue and dequeue, peek also has a constant time complexity, O(1), since it only
involves reading the value at one specific location – the start of the queue.

10. Can you explain what a blocking Queue is ?


A blocking queue is a type of data structure that controls the flow of data by maintaining a
queue. It allows operations like insertion and removal, but with an added feature: if the
queue is full, it blocks the insertion operation until there’s space; if empty, it blocks the
removal operation until there’s data.

11. What is the difference between LIFO and FIFO Queue models? Provide
examples where each would be appropriate.
LIFO (Last In, First Out) and FIFO (First In, First Out) are two different queue models. LIFO is a
stack model where the last element added is the first one to be removed. This is useful in
memory management or undo operations in software applications. For instance, when you
press ‘undo’ in a text editor, it reverts the most recent change.
On the other hand, FIFO operates on the principle that the first element added will be the
first one out. It’s used in scheduling processes in operating systems, print spooling, and CPU
task scheduling. For example, in a printer queue, the first document sent to the printer is the
first one printed.

12.What are some types of Queue?


 Simple Queue
 Circular Queue
 Priority Queue
 Input restricted deque
 Output restricted deque
LINKED HASH MAP
1. What is a LinkedHashMap in Java?
A LinkedHashMap is a class in Java that extends HashMap and maintains a
doubly-linked list across all of its entries. This means that it preserves the
insertion order of the elements, unlike HashMap which does not guarantee any
order.

2. How does LinkedHashMap maintain the insertion order?

Answer: LinkedHashMap maintains the insertion order by linking each entry


(key-value pair) to the next one through a doubly-linked list. The order is either
the order in which keys were inserted or the order in which they were last
accessed, depending on the access order.

3. What is the difference between HashMap and LinkedHashMap?


 Order: HashMap does not maintain any order of elements, whereas
LinkedHashMap maintains the order of insertion or access.
 Performance: LinkedHashMap has a slight performance overhead due to
maintaining the order using a linked list.
 Memory: LinkedHashMap consumes more memory than HashMap
because of the extra linked list that it maintains.

4. Can you explain the internal working of LinkedHashMap?


LinkedHashMap internally uses a combination of a hash table (inherited from
HashMap) and a doubly-linked list. The hash table provides fast access to
elements, while the linked list maintains the order of entries. Each entry has
three pointers: one to the key, one to the value, and one to the next entry in
the linked list.

5. How do you create a LinkedHashMap in Java?


LinkedHashMap<Integer, String> map = new LinkedHashMap<>();
map.put(1, "One");
map.put(2, "Two");
6. What is the access order in LinkedHashMap?
In LinkedHashMap, access order refers to the order of elements based on their
most recent access. If the LinkedHashMap is created with the accessOrder
parameter set to true, the iteration order will be based on the order in which
the entries were last accessed, from least-recently accessed to most-recently
accessed.
7. Can LinkedHashMap be synchronized?
By default, LinkedHashMap is not synchronized. However, you can synchronize
it by wrapping it with Collections.synchronizedMap() like this:
java
Copy code
Map<Integer, String> syncMap = Collections.synchronizedMap(new
LinkedHashMap<>());

8. When would you use LinkedHashMap over HashMap?


You would use LinkedHashMap when you need to maintain a predictable
iteration order, such as insertion order or access order. It's useful in cases
where you want to create a cache with a specific eviction policy (e.g., Least
Recently Used - LRU cache).

9. What are the features of a LinkedHashMap?


Features of a LinkedHashMap: A LinkedHashMap contains values based on the
key. It implements the Map interface and extends the HashMap class. It
contains only unique elements. It may have one null key and multiple null
values. It is non-synchronized. It is the same as HashMap with an additional
feature that it maintains insertion order.

Hash Map

1. Which property of a hashmap is used to find the intersection of two arrays?


 Since a hashmap stores only unique elements, this property of a hashmap can be
used to find intersections i.e common elements of two arrays.
 The approach to this problem is: first we will create a hashmap and fill the elements
of the first array in it.
 The next step is to iterate over the second array and check whether the element is
present in the hashmap or not.
 In this way, we can find all common elements of two arrays in O(n) time complexity.

2. What is collision in HashMap?


 A collision occurs when more than one key generates the same hashCode() value.
 An inefficient hashCode() algorithm causes considerable collisions in a hashmap.
 An increased number of collisions can affect the performance of a hashmap.

3. How Does Java's Capacity And Size Of Hashmap Differ?

So basically, HashMap's capacity indicates the number of entries it can hold, while its
length indicates how many key-value pairs are presently in existence.

4. What is the order in which keys are stored in a hashmap?

 There is no particular order for storing keys in a hashmap. All the keys are stored in
an unsorted order.
 For storing the elements in a particular order a Treemap can be used in Java but a
hashmap does not guarantee the ordering of your elements.

5. Does hashmap allow you to store null values?

Yes, We can store as many null values in a hashmap as we want but only one null key can
be stored not more than that.

6. Specify whether hashmaps in Java are thread-safe or not?

 The answer is "NO" i.e java.lang.HashMap does not support thread-safety. If several
threads are altering the HashMap, for example, insertions or removals, then a
HashMap should not be shared with other threads.
 If you want to implement thread-safety then you can either use
a ConcurrentHashMap or by using the Collections.synchronizedMap() method.

7. Specify different methods of creating a hashmap in java along with


implementation.

Different methods of creating a hashmap are:

1) Constructing a hashmap with default capacity

 Syntax:

HashMap<String, Integer> InterviewBIt_map1 = new HashMap<String, Integer>();

2) Constructing a hashmap with a defined capacity i.e 50 in our example

 Syntax:
HashMap<String, Integer> InterviewBIt_map2 = new HashMap<String, Integer>(50);

3) Specifying lead factor along with the capacity

 Syntax:

HashMap<String, Integer> InterviewBIt_map3= new HashMap<String, Integer>(50, 0.5f);

4) By copying another map into our map

 Syntax:

HashMap<String, Integer> InterviewBIt_map4 = new HashMap<String, Integer>(


InterviewBIt_map1);

8. Can you store multiple keys with the same value in a hashmap?

 No, multiple keys with the same value can’t be stored in a hashmap.
 When you try to insert a new key that is already present in the hashmap then
overriding will happen and the old key will be replaced with the new key and a new
value.

9. What is the time complexity in terms of big o notation of pushing and


retrieving an element from a hashmap?

 Time complexity is the measure of the number of CPU cycles utilized by a program
to execute.
 Hashmap time complexity for pushing and retrieving the elements is the order of 1
i.e O(1) using put and get methods respectively.

10. What are the time complexities of the basic operations (insert, remove,
search) in a Hashmap?

A Hashmap, also known as a Hash table, is a data structure that implements an associative
array abstract data type. It uses a hash function to compute an index into an array of buckets
or slots from which the desired value can be found.

The time complexity for basic operations in a Hashmap are:

1. Insertion: The average case for insertion in a Hashmap is O(1), meaning it takes constant
time. However, in the worst-case scenario where all keys collide, it could go up to O(n).

2. Removal: Similar to insertion, removal operation also has an average case time complexity
of O(1). But again, in the worst-case scenario, it could take linear time i.e., O(n).

3. Search: Searching for an element in a Hashmap on average takes constant time, O(1). In
the worst-case scenario, if there’s a collision, it may take up to O(n) time.

11. How would you implement a method to remove an element from a


Hashmap?
To remove an element from a Hashmap, you would use the remove() method. This method
takes in one parameter which is the key of the element to be removed. The syntax for this
operation is hashmap.remove(key). If the key exists within the map, the associated value will
be returned and the key-value pair will be deleted. If the key does not exist, it returns null.
Here’s an example:

HashMap<String, Integer> map = new HashMap<>();

map.put("One", 1);

map.put("Two", 2);

Integer removedValue = map.remove("One");

12. What are the differences between a Hashmap and a Hashtable?

A Hashmap and Hashtable, both part of Java’s collection framework, differ in several ways.
Firstly, Hashmap is non-synchronized, allowing multiple threads to access it simultaneously,
making it better for non-threaded applications due to its performance advantage.
Conversely, Hashtable is synchronized, ensuring only one thread can access the table at a
time, providing thread safety.

Secondly, Hashmap allows one null key and multiple null values, while Hashtable doesn’t
permit any null keys or values, throwing NullPointerException.

Thirdly, Hashmap inherits AbstractMap class, whereas Hashtable extends Dictionary class.

Lastly, Hashmap’s iterator is fail-fast, meaning if the map is structurally modified after the
iterator’s creation, except through the iterator’s own remove method, it will throw
ConcurrentModificationException. On the other hand, Hashtable’s enumerator isn’t fail-fast.

13. What are the best practices for using Hashmaps in terms of memory
efficiency and performance?

Hashmaps are powerful data structures, but they must be used wisely for optimal memory
efficiency and performance. Here are some best practices:

1. Initial Capacity: Set an initial capacity to avoid rehashing. If you know the number of
elements that will be stored, set it at initialization.
2. Load Factor: Adjust load factor based on usage. A higher value reduces space overhead
but increases lookup time. Conversely, a lower value speeds up access but uses more
memory.
3. Null Keys/Values: Avoid using null keys or values as they can lead to confusion and errors.
4. Synchronization: Hashmaps aren’t thread-safe. Use ConcurrentHashMap for multi-
threaded environments.
5. Iteration: When iterating, use entrySet() instead of keySet() if both key and value are
needed, to prevent looking up the value for each key.

14. Can you write a function to retrieve all keys or all values present in a
Hashmap?
Yes, in Java you can retrieve all keys or values from a HashMap using the keySet() and
values() methods respectively. Here’s an example:

import java.util.HashMap;

public class Main {

public static void main(String[] args) {

HashMap<String, Integer> map = new HashMap<>();

map.put("One", 1);

map.put("Two", 2);

System.out.println("Keys: " + map.keySet());

System.out.println("Values: " + map.values());

15. Can you discuss some scenarios where Hashmap would not be the ideal
data structure to use?

Hashmap may not be ideal in scenarios where data order matters. It doesn’t maintain
insertion order, so if retrieval based on input sequence is required, Hashmap isn’t suitable.
LinkedHashSet or TreeMap would serve better here.

Another scenario is when memory usage is a concern. Hashmaps require more memory due
to the storage of key-value pairs, making them less efficient for large datasets compared to
arrays or linked lists.

Lastly, Hashmaps are not synchronized and hence aren’t suitable for multithreaded
environments without explicit synchronization. ConcurrentHashmap or
Collections.synchronizedMap() should be used instead in such cases.

17. Can you explain the difference between a Hashmap and a TreeMap?

A Hashmap and a TreeMap are both implementations of the Map interface in Java, but they
differ in their underlying data structures and performance. A Hashmap uses a hashtable,
providing constant-time performance for basic operations like get() and put(), regardless of
the number of elements. It doesn’t guarantee any specific order of entries.

On the other hand, a TreeMap is based on a red-black tree structure, which means it
maintains its elements in sorted order according to their natural ordering or a custom
comparator provided at map creation time. This results in log(n) time cost for the
containsKey, get, put and remove operations.

18. What is a Hashmap ?


A Hashmap, also known as a Hashtable or dictionary, is a data structure that implements an
associative array abstract data type. It uses a hash function to compute an index into an
array of buckets from which the desired value can be found.

19. Can you write a function for inserting an element into a Hashmap?

Yes, I can write a function for inserting an element into a Hashmap. Here’s an example in
Java:

public void insert(HashMap<String, Integer> map, String key, int value) {

if(map.containsKey(key)) {

System.out.println("Key already exists");

} else {

map.put(key, value);

System.out.println("Inserted successfully");

20. What major factors affect the performance of a Hashmap?

The performance of a Hashmap is influenced by three major factors: initial capacity, load
factor, and hash function. The initial capacity refers to the number of buckets in the
Hashmap when it’s created. A higher initial capacity reduces the need for resizing operations
but increases memory consumption. The load factor determines when the Hashmap needs
to be resized. A lower load factor reduces collision probability but requires more space.
Lastly, the hash function affects how evenly keys are distributed across the buckets. An ideal
hash function distributes keys uniformly to minimize collisions, which can degrade
performance due to increased time complexity during retrieval or insertion.

Hash Set
1.Can you briefly explain what a HashSet is and its purpose in Java?
A HashSet is a class in Java that implements the Set interface. It is part of the Java Collections
Framework and is used to store a collection of unique elements. The purpose of a HashSet is
to provide efficient retrieval, insertion, and deletion of elements, while ensuring that
duplicate values are not allowed.Behind the scenes, a HashSet uses a hash table to store its
elements.

2.How does a HashSet differ from other collection classes in Java?


A HashSet in Java is a collection class that implements the Set interface, providing a way to
store unique elements without any specific ordering. It differs from other collection classes in
Java in several ways:

1. Element uniqueness: HashSet ensures that it contains only unique elements. When
attempting to add a duplicate element, the HashSet ignores it and does not add it again.
Other collection classes like ArrayList or LinkedList allow duplicate elements.
2. Hashing mechanism: HashSet internally uses a hashing mechanism to store and retrieve
elements efficiently. It calculates a hash code for each element and uses that code to
determine the bucket where the element will be stored. This allows for constant time
complexity O(1) for basic operations like add(), remove(), or contains().
3. No specific ordering: Unlike List implementations that maintain insertion order or
SortedSet implementations that store elements in a sorted order, HashSet does not provide
any specific ordering. The elements are stored in an unordered manner based on their hash
code.

3.Can elements in a HashSet be duplicated?


In a HashSet, elements cannot be duplicated. The purpose of a HashSet is to maintain a
collection of unique elements. When adding elements to a HashSet, it internally uses hashing
to determine the bucket where the element should be placed. If multiple elements end up in
the same bucket due to hash collisions, the HashSet will use additional mechanisms, such as
linked lists or balanced trees, to handle these collisions efficiently.

4.How does a HashSet handle duplicate elements internally?


A HashSet is a collection class in Java that stores elements in a hash table, which allows for
efficient insertion, deletion, and retrieval operations. One significant feature of HashSet is
that it does not allow duplicate elements. Whenever you try to add a duplicate element to a
HashSet, it will be disregarded, without causing an exception or error.
To handle duplicates, HashSet internally checks the equality of elements using the `equals()`
method.

5.What happens if you try to add a null value to a HashSet?


When you attempt to add a null value to a HashSet, several things happen. Firstly, it's
important to understand what a HashSet is. It is an implementation of the Set interface in
Java, which means it represents a collection of unique elements, where duplicate values are
not allowed.

In the case of adding a null value to a HashSet, the HashSet itself accepts null values.
However, there are a few key points to consider. Firstly, since HashSet does not allow
duplicates, adding a null value when there is already a null value present in the set will have
no effect. The null value will not be added again.
6.How do you iterate through the elements of a HashSet?
To iterate through the elements of a HashSet, you can utilize the Iterator interface in Java.
The Iterator allows you to traverse and access elements sequentially in a HashSet.

7.Are elements stored in a HashSet in a particular order?


No, elements in a HashSet are not stored in a particular order. HashSet is an implementation
of the Set interface in Java, which means it does not guarantee the maintenance or
preservation of the insertion order. The elements in a HashSet are organized based on their
hash codes, which allow for efficient retrieval and storage.

8.How can you check if a specific element exists in a HashSet?


To check if a specific element exists in a HashSet, you can utilize the HashSet's `contains()`
method. Let's dive into the implementation details.
The `contains()` method in HashSet returns a boolean value indicating whether the HashSet
contains the specified element or not. It internally uses the `equals()` method to compare
the elements for existence.

9.Is it possible to modify an element in a HashSet directly?


In Java, the HashSet class does not provide a direct method to modify an element directly.
However, you can achieve this by removing the element from the HashSet and then adding
the modified element back. When modifying an element in a HashSet, you first need to
remove the existing element using the remove() method. After modifying the element, you
can add it back into the HashSet using the add() method.

10.Can you compare two HashSets for equality? If yes, how?


Yes, two HashSets can be compared for equality. In Java, you can accomplish this by using the
`equals()` method. The `equals()` method is a generic method defined in the `Set` interface,
which is implemented by the HashSet class.

When comparing two HashSets for equality, the `equals()` method checks whether the two
sets have the same number of elements and if each element in one set is present in the
other set. Additionally, it verifies that the order of the elements is the same.

11. Can you explain what thread-safety means in the context of using hash
sets?
Thread-safety means that the hash set can be used by multiple threads simultaneously
without running into any concurrency issues. This is important because it means that you can
safely use the hash set from multiple threads without having to worry about any data
corruption or race conditions.

12. How do you create an empty hash set?


You can create an empty HashSet by using the default constructor:
HashSet set = new HashSet();
13. Is it possible to copy all items from one hash set to another? If yes, then
how?
Yes, it is possible to copy all items from one hash set to another. This can be done using the
addAll() method.

14. Is it possible to copy all items from one hash set to another? If yes, then
how?
Yes, it is possible to copy all items from one hash set to another. This can be done using the
addAll() method.

15. What happens when we remove an element from a hash set that doesn’t
exist?
If you try to remove an element from a hash set that doesn’t exist, nothing happens. The
hash set will remain unchanged.

16. What do you understand by the term hashing?


Hashing is a technique used to map data of any size to data of a fixed size. This is done by
using a hash function to calculate a hash code, which is then used to index into an array. The
array stores the data associated with the hash code. When data is inserted into the hash set,
the hash function is used to calculate the hash code, and then the data is stored at the
corresponding index in the array. When data is retrieved from the hash set, the hash function
is used again to calculate the hash code, and then the data is retrieved from the
corresponding index in the array.

17. How does Java calculate hash values?


Java uses a hashing algorithm to calculate hash values. This algorithm is designed to produce
a unique hash value for each object, based on its contents. The exact details of the algorithm
are not important, but it is important to know that it exists and that it is used to calculate
hash values.

18. Why is hashing preferred over other data structures like trees?
Hashing is preferred over other data structures like trees because it is more efficient in terms
of both time and space. With hashing, you can quickly insert and retrieve data from a large
data set without having to traverse the entire data set. This makes hashing an ideal choice for
applications where speed is critical.

19. Does a hash set have fixed size?


No, a hash set does not have a fixed size. It can grow and shrink as needed.

20. Is it possible to sort a hash set? If so, how?


Yes, it is possible to sort a hash set. There are a few different ways to do this, but one
common way is to use the TreeSet class. The TreeSet class implements the Set interface and
provides a way to store elements in a sorted order.

21. Isn’t HashSet equivalent to HashMap with null key?


No, HashSet is not equivalent to HashMap with null key. HashSet is a data structure that
stores data in a hash table, and it can only store unique data. HashMap, on the other hand, is
a key-value pair data structure that can store duplicate data.

HASH TABLE
1. What is a Hash Table?

A Hash Table, also known as a Hash Map, is a data structure that provides a mechanism to
store and retrieve data based on key-value pairs.

It is an associative array abstract data type where the key is hashed, and the resulting hash
value is used as an index to locate the corresponding value in a bucket or slot.
2. What are the Key Features of hash table

Unique Keys: Each key in the hash table maps to a single value.

Dynamic Sizing: Can adjust its size based on the number of

elements. Fast Operations: Average time complexity for most

operations is o(1).

3. What is Hashing?

Hashing is a method that maps data to fixed-size values, known as hash values, for efficient
storage and retrieval. A hash function generates these values, serving as the data's unique
identifier or key.
4. what is Hash Functions and Hash Values

A hash function generates a fixed-size hash value, serving as the data's unique identifier or
key for various applications like data indexing and integrity checks. Hash values are typically
represented as hexadecimal numbers.
5. Explain the difference between Hashing and Hash Tables.

When discussing Hashing and Hash Tables, it's crucial to recognize that one is a technique
while the other is a data structure. Here's a side-by-side comparison
Hashing: A computational technique that converts input (often a string) into a fixed-size
value, referred to as a hash value.
Hash Tables: A data structure that utilizes hash values as keys to efficiently store
and retrieve data in memory.

6. Provide a simple example of a Hash Function.


The parity function can serve as a rudimentary example of a hash function. It takes a single
input, usually an integer, and returns either 0 or 1 based on whether the input number is
even or odd.
7. What are Hash Collisions?

In hash functions and tables, a hash collision occurs when two distinct keys generate the
same hash value or index. Efficiently addressing these collisions is crucial for maintaining the
hash
table's performance.
Name some Collision Handling Techniques.

In hash tables, collisions occur when different keys yield the same index after being
processed by the hash function. Let's look at common collision-handling techniques:
Chaining

Linear

Probing

Double Hashing
8. Explain the Time and Space Complexity of a Hash Table.

Time Complexity

Case O(1)
: With uniform distribution and no collisions, fundamental operations like lookup, insertion,
and deletion are constant-time.
Space Complexity O(n)
The primary storage revolves around the n elements in the table. Additional overhead from
the structure itself is minimal, ensuring an upper bound of O(n)
. The "load factor," indicating the ratio of stored elements to the table's capacity,
can impact memory use.
9. What is a Load Factor in the context of Hash Tables?

The load factor is a key performance metric for hash tables, serving as a threshold for
resizing the table. It balances time and space complexity by determining when the table is
full enough to warrant expansion.
13. How does the load factor affect performance in a hash table?

The load factor is a key parameter that influences the performance and memory efficiency of
a hashtable. It's a measure of how full the hashtable is and is calculated as:

Load Factor=Number of Entries/Number of Buckets


14. What is the main purpose of hash table?

Hash tables are a type of data structure in which the address/ index value of the data
element is generated from a hash function. This enables very fast data access as the index
value behaves as a key for the data value.
15.What are the real life uses of hash tables?

Frequent examples of real-life problems where hash tables might be implemented are in
phone number lookups, social security databases, libraries, and in username-password
retrievals. In the phonebook example, the name would be the key and the number would be
the value.
15. What is the advantage of hash table?

The main advantage of hash tables over other data structures is speed . The access time of
an element is on average O(1), therefore lookup could be performed very fast. Hash tables
are particularly efficient when the maximum number of entries can be predicted in
advance.
16. What are the disadvantages of hash tables?

Hash tables offer efficient data storage and retrieval, but they come with some drawbacks.
These include collision resolution, variable performance, space overhead, lack of ordered
data, and dependency on a quality hash function. They are not ideal for range queries, and
resizing can introduce overhead.
17. Why not always use a hash table?

Hash tables are vulnerable to denial of service (DoS) attacks. One type of DoS attack on
hash tables is known as a “collision attack.” Hash tables use a hash function to map keys to
indices in an
array (buckets).
18. What is the difference between hash table and collection?

The Hashtable class has all its methods synchronized i.e. the locking is done at the method
level and hence one can say that the mutex is always at the Hashtable object ( this ) level.
The method Collections. synchronizedMap(Map) returns an instance of SynchronizedMap
which is an inner class to the Collections class.
19. What are the different types of hash tables?

 Closed Hashing
 Linear probing.
 Quadratic probing.
 Double Hashing technique.
TREE MAP

1. What is the concept of TreeMap in Java?

A TreeMap is implemented using a Red-Black tree, which is a type of self-balancing binary


search tree. This provides efficient performance for common operations such as adding,
removing, and retrieving elements, with an average time complexity of O(log n). These
properties help the tree maintain a balanced structure, ensuring that operations like
insertion, deletion, and lookup have a time complexity of O(log n). This efficient balancing
mechanism makes the Red-Black tree a suitable choice for implementing the sorted map
behavior in TreeMap, where keys are automatically kept in order and operations remain fast
regardless of the size of the map.

2. What data structure is used in TreeMap?

Red-Black tree
TreeMap uses a Red-Black tree as its data structure which is a self-balancing tree consisting
of red and black nodes. A tree is said to be self-balancing if it automatically maintains a
balanced structure, ensuring that the depth (or height) of the tree remains logarithmic in
relation to the number of elements. This balanced nature ensures that operations such as
insertion, deletion, and lookup can be performed efficiently. Every path from the root to a
leaf or a null child must have the same number of black nodes. The longest path from the root
to a leaf is no more than twice as long as the shortest path. These properties maintain the
balance of the tree, which in turn guarantees that the time complexity for search, insertion,
and deletion operations is O(log n).
.
3. How are elements stored in a TreeMap?

In a TreeMap, elements are stored as key-value pairs, where each key is associated with a
corresponding value. The keys are stored in a sorted order, based on their natural ordering or
a custom Comparator provided at the time of the TreeMap creation. Internally, TreeMap uses
a Red-Black tree, a balanced binary search tree, to store the key-value pairs. This ensures that
the elements are stored in a sorted manner according to the keys. The keys in a TreeMap are
automatically sorted. For example, if you insert keys 3, 1, and 2, the TreeMap will store them
in the order 1, 2, 3.

4. Can TreeMap have duplicate keys?

Since TreeMap does not allow duplicate keys, the existing value associated with key 2 (“Two”)
will be replaced by the new value (“New Two”). In a TreeMap, each key must be unique. If
you try to insert a key that already exists in the map, the new value will replace the old value
associated with that key. This ensures that each key in the map points to exactly one value,
maintaining the uniqueness of keys in the data structure.The uniqueness of keys allows for
efficient retrieval of values, ensuring that each key maps to a single, distinct value.
5. Does TreeMap use hashCode?

TreeMap does not use hashing for storing key unlike the HashMap and LinkedHashMap use
hashing for storing the key. HashMap and LinkedHashMap use array data structure to store
nodes but the TreeMap uses a data structure called Red-Black tree. Also, all its elements
store in the TreeMap are sorted by key. Instead of relying on hashCode(), TreeMap uses the
natural ordering of the keys or a custom Comparator to maintain its sorted order. The
sorting is achieved through the Red-Black tree structure, where keys are compared using
the compareTo() method (for natural ordering) or the compare() method (if a Comparator is
provided). This means that TreeMap's key comparisons are based on these methods rather
than on hash codes.

6. What are the Constructors in TreeMap?

TreeMap in Java provides several constructors to create instances of the map with different
configurations. Here are the key constructors:

1. Default Constructor

Creates an empty TreeMap that is sorted according to the natural ordering of its keys. This
means the keys must implement the Comparable interface. Use this constructor when you
want to store key-value pairs and have the keys automatically sorted in their natural order (e.g.,
alphabetical for strings, numerical for integers).

2. Comparator-based Constructor

Creates an empty TreeMap that is sorted according to a custom Comparator provided by the
user. Use this constructor when you need the keys to be sorted in a custom order, which is defined
by the Comparator you provide.

3. Map-based Constructor

Creates a TreeMap that contains all the mappings from the specified Map. The new TreeMap
is sorted according to the natural ordering of the keys. Use this constructor when you have
an existing Map and want to create a TreeMap from it with the keys sorted naturally.

4. SortedMap-based Constructor

Creates a TreeMap that contains all the mappings from the specified SortedMap,
maintaining the same sorting order as the SortedMap.Use this constructor when you have an
existing SortedMap and want to create a TreeMap that preserves the existing sorting order.
7. Can you explain what a TreeMap is and how it is different from other
map implementations in Java?
A TreeMap is a part of Java’s Collection Framework and implements the NavigableMap
interface, which in turn extends the SortedMap interface. It is used to store key-value pairs
in a sorted order based on the keys. Here’s an overview of what a TreeMap. A TreeMap
automatically sorts the entries based on the natural ordering of the keys (i.e., the keys must
implement the Comparable interface) or according to a specified Comparator provided at
the time of the TreeMap creation. Internally, TreeMap uses a Red-Black Tree, a balanced
binary search tree, to store the map entries. This ensures that all operations (like insertion,
deletion, and lookup) take O(log n) time.

8. How does a TreeMap maintain a sorted order of its elements?


A TreeMap maintains a sorted order of its elements by using a Red-Black Tree, a type of self-
balancing binary search tree. Here’s how it works. TreeMap stores key-value pairs in a binary
search tree structure, where each node has at most two children: a left child and a right
child.For any given node, all keys in the left subtree are less than the key of the node, and all
keys in the right subtree are greater. To maintain balance and ensure efficient performance,
TreeMap uses a Red-Black Tree, which is a self-balancing BST. These properties ensure the
tree remains balanced, meaning that the longest path from the root to a leaf is no more than
twice the length of the shortest path.

9. What is the time complexity of common operations on a


TreeMap, such as insertion, deletion, and retrieval?

The time complexity of common operations on a TreeMap—such as insertion, deletion, and


retrieval—is determined by its underlying data structure, the Red-Black Tree. Here's a brief
overview:

1. Insertion

 Time Complexity: O(log n)


 Explanation: When a new key-value pair is inserted, the TreeMap locates the correct
position in the Red-Black Tree, which takes O(log n) time due to the balanced nature of the
tree. If necessary, the tree is rebalanced to maintain the Red-Black Tree properties, but this
rebalancing also occurs in O(log n) time.

2. Deletion

 Time Complexity: O(log n)


 Explanation: Deleting a key-value pair involves finding the node to remove, which takes
O(log n) time. After removal, the tree may need to be rebalanced to maintain the Red-Black
Tree properties, which also takes O(log n) time.
3. Retrieval (Search)

 Time Complexity: O(log n)


 Explanation: To retrieve a value associated with a key, the TreeMap performs a search
operation within the Red-Black Tree. Since the tree is balanced, this search operation takes
O(log n) time.

10. What key types can be used in a TreeMap? Are there any
restrictions on the key types?

In a TreeMap, the key types must meet certain criteria to ensure proper functioning,
particularly because TreeMap relies on sorting the keys. Here are the key points:

Key Requirements:

1. Comparable Interface:
o Natural Ordering: By default, the keys must implement the Comparable interface if
you want the TreeMap to sort them in their natural order. This means the key class
must define a compareTo() method, which determines how keys are ordered.
o Examples: Common classes like Integer, String, Double, and Date already
implement Comparable, so they can be used as keys without additional effort.
2. Custom Comparator:
o Custom Ordering: Alternatively, you can provide a custom Comparator when
constructing the TreeMap. In this case, the keys do not need to implement
Comparable, but they still must be compatible with the comparator you provide.
o Examples: If you want to sort strings by their length instead of lexicographically, you
could provide a custom Comparator that defines this sorting logic.

Restrictions:

1. No null Keys:
o Restriction: TreeMap does not allow null keys. Attempting to insert a null key
will result in a NullPointerException.
o Reason: This restriction exists because the compareTo() method or custom
comparator needs to compare keys, and comparing a null key to a non-null key is
not defined.
2. Consistent Comparison:
o Requirement: Whether you use Comparable or a custom Comparator, the
comparison logic must be consistent with equals(). This means that if
compareTo() (or compare() in a comparator) considers two keys as equal
(returns 0), then equals() should also return true when comparing those keys.
o Reason: Inconsistent comparison logic can lead to unpredictable behavior in the
TreeMap, such as missing entries or incorrect sorting.
11. How does a TreeMap handle duplicate keys In TreeMap? Duplicate
keys are not directly supported. It follows the SortedMap and NavigableMap interfaces,
which do not allow duplicate keys. Instead, when you attempt to insert a key-value pair
with a key that already exists in the map, the value associated with that key is updated.
The old value is replaced with the new value, effectively overwriting the previous one. Key
Uniqueness: If you try to insert an entry with a key that already exists in the TreeMap, the
new value will replace the old value associated with that key. When you attempt to insert a
key-value pair, the TreeMap first searches for the key in the tree.If the key already exists,
the old value is overwritten with the new value you’re inserting.If the key does not exist, the
new key-value pair is added to the TreeMap.

12. Can you provide an example of how to create and populate a


TreeMap in Java?
 Import the necessary classes from the Java collections framework
 Declare a TreeMap and specify the types for the key and value
TreeMap<String, Integer> treeMap = new TreeMap<>();
 This creates an empty TreeMap where the keys are of type String and the values are
of type Integer.
 Add key-value pairs to the TreeMap using the put() method
 Access and print the elements of the TreeMap

13. Can you explain the difference between a natural ordering and a
custom ordering in a TreeMap?
Natural Ordering:
The natural ordering in a TreeMap refers to the default sorting
mechanism based on the natural order of elements. For example, if
you have a TreeMap of integers, the natural ordering will sort the
elements in ascending order. Similarly, if you have a TreeMap of
strings, the natural ordering would sort the elements
lexicographically.
Custom Ordering:
On the other hand, a custom ordering in a TreeMap allows you to
define your own criteria for sorting elements. You need to provide a
custom comparator that determines the order of elements based
on your requirements.
14. Are the elements in a TreeMap mutable or immutable? How
does this affect the use and behavior of the map?
In a TreeMap, the elements are mutable as they can be modified after being inserted into
the map. This mutable nature of the elements in a TreeMap can affect its usage and
behavior in a few ways.
when the elements are mutable, any modifications made to an element's key that affect
its comparative order may break the internal structure of the TreeMap. The TreeMap
relies on the proper sorting of its elements based on their keys. If the keys are mutable
and modified after insertion, their relative ordering in the TreeMap may no longer be
accurate, leading to incorrect or unexpected behavior.

15. What is the significance of the compareTo() method in a TreeMap?


The compareTo() method in Integer class is responsible for comparing two Integer objects
and determining their order. The TreeMap relies on the compareTo() method (or a
custom Comparator) to maintain the order of its keys. When keys are inserted into the
TreeMap, the compareTo() method is used to determine the position of each key in relation
to the others. For example, if the keys are Integer objects, the compareTo() method in the
Integer class will compare two integers to determine which is greater, smaller, or equal,
ensuring that the keys are stored in ascending order.

16. What is the first key in TreeMap?


FirstKey() method is present in the TreeMap class inside the java. util package. The TreeMap.
firstKey() is used to obtain the least key currently present in the map. In a TreeMap, the first
key is the smallest key according to the map's sorting order. The sorting can be based on the
natural ordering of the keys (if the keys implement the Comparable interface) or based on a
custom Comparator provided when the TreeMap was created. The TreeMap automatically
sorts the keys in ascending order (alphabetically for strings in this case). The firstKey() method
returns the smallest key, which is "apple" in this example.The first key in a TreeMap is the
smallest key according to the map’s ordering.You can retrieve it using the firstKey() method.

17. Which algorithm used in TreeMap in Java?


Red-Black Tree algorithm
Internally, it uses a data structure called the Red-Black Tree. In other words, it sorts the
TreeMap object keys using the Red-Black Tree algorithm. For understanding the internal
working of TreeMap, we must understand the Red-Black Tree algorithm. A TreeMap in Java
uses a Red-Black Tree as its underlying data structure. The Red-Black Tree is a type of self-
balancing binary search tree, which helps maintain a sorted order of keys while providing
efficient performance for basic operations. Here’s a brief explanation of the algorithm and
its characteristics. The Red-Black Tree maintains the binary search tree property, where for
any given node:

 All keys in the left subtree are less than the node’s key.
 All keys in the right subtree are greater than the node’s key.

18. What is the best use of TreeMap?

Tree Maps are primarily used to display data that is grouped and nested in a hierarchical (or
tree-based) structure. Example: There are approx 10-15 major categories of cause of death
– Circulatory System Diseases, Cancers, Respiratory Diseases, External Causes of Mortality
etc. A TreeMap is best used in scenarios where you need a sorted map with efficient
operations for key-based access. Here are some common use cases. When you need to
maintain a collection of key-value pairs in a naturally sorted order (e.g., alphabetical or
numerical order). Storing and accessing dictionary words or a leaderboard where scores are
sorted from highest to lowest. When you need to perform operations based on key ranges,
such as retrieving a subset of entries within a specified key range Querying a map for all
entries with keys between two dates, or getting all users with scores within a certain range.

19. Is TreeMap synchronized?


It provides an efficient alternative to store the key-value pairs in sorted order. By default, a
TreeMap is not synchronized. In this article, we will explain the need for synchronization
and its practical implementation through example programs. The TreeMap class is designed
for performance and sorting, not thread safety. This means that if multiple threads access a
TreeMap concurrently and at least one of the threads modifies the map structurally (i.e.,
changes the key-value mappings), it must be synchronized externally to avoid unpredictable
behavior or concurrency issues. If you need to use a TreeMap in a multithreaded
environment, where multiple threads might access or modify the map concurrently, you can
synchronize it externally. This can be done using Collections.synchronizedSortedMap() to
wrap the TreeMap in a synchronized map.
20. What are the characteristics of TreeMap?

It doesn't allow null keys (like Map). However, there can be multiple null values in a
TreeMap. It throws NullPointerException in the case of any null key insertion. It stores the
key-value pairs in the natural sorting order of the keys or a sorting order defined with the
help of a Comparator. Keys in a TreeMap are sorted according to their natural order or by a
custom Comparator provided at the time of creation.Ensures that the entries are always
maintained in ascending key order. TreeMap implements the NavigableMap interface,
which extends SortedMap. This provides additional methods for navigation, such as
firstKey(), lastKey(), ceilingKey(), and floorKey().Enables efficient access and querying based
on the sorted order of keys. TreeMap permits null values, but only one null value is allowed
(since values are not used for ordering).Provides flexibility in storing values even if they are
null.

TREE SET
1.What is a TreeSet in Java?
A TreeSet in Java is a NavigableSet implementation that stores elements in a
tree structure, which allows for efficient sorting and retrieval of elements.
It is a part of the Java Collections Framework and implements the Set
interface. TreeSet ensures that elements are unique and sorted in
ascending order, either naturally or according to a Comparator provided
at set creation time. The tree structure used by TreeSet is a red-black tree,
which provides a balance between insertion and lookup performance.

2.how does TreeSet differ from HashSet?


Sorting:
- TreeSet: Sorted in ascending order (either naturally or according to a
Comparator)
- HashSet: No sorting, elements are stored in a hash table
Ordering:
- TreeSet: Maintains insertion order (or sorted order)
- HashSet: No guarantee of insertion order
Performance:
- TreeSet: Slower insertion and lookup due to tree structure
- HashSet: Faster insertion and lookup due to hash table
Uniqueness:
- TreeSet: Ensures uniqueness of elements
- HashSet: Also ensures uniqueness of elements
Implementation:
- TreeSet: Implemented as a red-black tree
- HashSet: Implemented as a hash table

Use cases:
- TreeSet: When sorting and ordering are important (e.g., sorting names)
-HashSet: When fast lookup and insertion are important (e.g.,
caching, set operations)
3.What are the main characteristics of a TreeSet?
The main characteristics are:
 Elements are stored in ascending order.
 It does not allow duplicate elements.
 It does not allow null values.
 It offers log(n) time complexity for basic operations like add, remove, and
search.
4.How do you create a TreeSet?
To create a TreeSet in Java, you can use the TreeSet() constructor to create a
new, empty tree set. Alternatively, you can use the TreeSet(Collection c)
constructor to create a new tree set containing the elements of the
specified collection. You can also use the TreeSet(Comparator
comparator) constructor to create a new tree set with a custom
comparator for sorting elements.

5.Can TreeSet Contain Null elements?


No, a TreeSet in Java cannot contain null elements. Attempting to add a null
element to a TreeSet will result in a NullPointerException. This is because
TreeSet relies on the natural ordering of its elements or a Comparator to
sort and store elements, and null elements cannot be compared.
Additionally, the TreeSet documentation explicitly states that null
elements are not allowed. If you need to store null elements, consider
using a different data structure, such as a List or a HashMap.

6.Is TreeSet Synchronized?


No, a TreeSet in Java is not synchronized, meaning it is not thread-safe. This
means that if multiple threads try to access and modify a TreeSet
simultaneously, it may lead to unpredictable behavior and errors. To make
a TreeSet thread-safe, you can use the Collections.synchronizedSet()
method to wrap the TreeSet in a synchronized set.
7.what is the Initial capacity and Load Factor of TreeSet?
TreeSet in Java has an initial capacity of 0, meaning it starts empty and grows
as elements are added. The load factor is not applicable to TreeSet, as it
is a NavigableSet implementation that uses a tree structure to store
elements, rather than a hash table. The tree structure is self-balancing,
meaning it adjusts its size and structure as elements are added or
removed. Therefore, there is no need for an initial capacity or load factor,
unlike HashSet which uses a hash table and requires these parameters.
8.How does TreeSet ensure the elements are in sorted order?
TreeSet ensures elements are in sorted order by using a Red-Black Tree
internally, which is a self-balancing binary search tree. This tree structure keeps
the elements sorted as they are inserted.
9.How does TreeSet maintain Sorted Order?
TreeSet maintains sorted order by using a red-black tree data structure,
which is a self-balancing binary search tree. Each node in the tree
represents an element, and the tree is arranged so that all elements to the
left of a node are less than the node, and all elements to the right are
greater. When elements are added or removed, the tree is rebalanced to
maintain this ordering property, ensuring that the elements are always
sorted in ascending order.

10.How do You add elements to a TreeSet?


You can add elements to a TreeSet using the add() method, which takes an
object as an argument and adds it to the set if it doesn't already exist. The
element is inserted into the tree in a way that maintains the sorted order.
If the element is already present in the set, the add() method returns false
and has no effect. You can also use the addAll() method to add multiple
elements from a collection to the TreeSet.

11.How do you remove elements from a TreeSet?


You can remove elements from a TreeSet using the remove() method, which
takes an object as an argument and removes it from the set if it exists. The
remove() method returns true if the element was removed and false if it
wasn't present in the set. You can also use the clear() method to remove
all elements from the TreeSet, effectively emptying the set.

12.How do you check if a TreeSet contains a specific element?


You can check if a TreeSet contains a specific element using the contains()
method, which takes an object as an argument and returns a boolean
value indicating whether the element is present in the set. The contains()
method uses the sorted order of the TreeSet to perform a fast binary
search, making it more efficient than searching through a linear data
structure. If the element is found, the method returns true; otherwise, it
returns false. This method is useful for quickly verifying the presence of
an element in the set without having to manually iterate
through the elements.

13.How do you iterate over a TreeSet?


You can iterate over a TreeSet using an Iterator object, obtained by calling
the iterator() method, which allows you to traverse the elements in
ascending order. Alternatively, you can use a for-each loop to iterate over
the elements of the TreeSet, which is a more concise and readable way to
access each element. You can also use the descendingIterator() method
to iterate over the elements in descending order.

14.How do you clear all elements from the TreeSet?


You can clear all elements from a TreeSet by calling the clear() method, which
removes all elements from the set and leaves it empty. This method has no
return value and does not throw any exceptions. After calling clear(), the
TreeSet is empty and ready to have new elements added to it.

15.How do get the size of a TreeSet?


You can get the size of a TreeSet by calling the size() method, which returns
the number of elements currently stored in the set. The size() method
returns an integer value representing the number of elements in the set.
This method is useful for determining the number of elements in the set
without having to iterate over them. The size of the TreeSet can change
dynamically as elements are added or removed.

16.what is the time complexity of basic operations in TreeSet?


The time complexity of basic operations in TreeSet is as follows:

- Insertion (add): O(log n)


- Deletion (remove): O(log n)
- Search (contains): O(log n)
- Traversal (iteration): O(n)
17.How does TreeSet Handle Duplicates?
TreeSet in Java does not allow duplicate elements, as it is a Set
implementation that follows the Set interface's contract. When you try to
add a duplicate element to a TreeSet, the add method returns false,
indicating that the element was not added. This is because TreeSet uses a
unique sorting order, and if an element is already present in the set, it is
considered a duplicate and is not added again. This ensures that each
element in the TreeSet is unique, maintaining the set's integrity and
preventing duplicates.

18.Can TreeSet be used in Place of HashSet?


TreeSet can be used in place of HashSet in some cases, but not always. While
both sets are collections that store unique elements, TreeSet maintains a
sorted order, whereas HashSet does not guarantee any order. If your
application requires a sorted collection, TreeSet is a good choice, but if you
don't need sorting, HashSet is generally faster and more efficient.
However, if you need to maintain a sorted collection and ensure
uniqueness, TreeSet is a suitable replacement for HashSet.

19.How do you Convert TreeSet to a List?


You can convert a TreeSet to a List using the new ArrayList() constructor and
passing the TreeSet as an argument. This creates a new List containing all
the elements of the TreeSet, in the same sorted order. Alternatively, you
can use the List=list(enumeration) method, where enumeration is an
Enumeration of the TreeSet's elements. You can also use Java 8's Stream
API: List=list = new
ArrayList<>(treeSet.stream().collect(Collectors.toList())).

20.How do you Convert a TreeSet to an Array?


You can convert a TreeSet to an array using the toArray() method, which
returns an array containing all the elements of the TreeSet, in the same
sorted order. Alternatively, you can use the toArray(T[] a) method, which
returns an array containing all the elements of the TreeSet, and also
accepts an array to store the elements. You can also use Java 8's Stream
API: Object[] array = treeSet.stream().toArray(). Additionally, you can use
the toArray() method with a generator function to convert the TreeSet to
an array of a specific type.

21.What happens if you try to remove an element that does not exist
in TreeSet?
If you try to remove an element that does not exist in a TreeSet, the remove()
method will simply return false, indicating that the element was not found
and therefore not removed. No exception is thrown, and the TreeSet remains
unchanged. This allows you to safely attempt to remove an element without
worrying about causing an error. The method returns false to signal that the
removal was not successful, allowing you to handle this
situation appropriately.
22.what is the difference TreeSet and Set?
Here are the differences between TreeSet and Set:
Set:

- Interface that defines a collection of unique elements


- Does not maintain any order
- Allows null elements
- Has multiple implementations (HashSet, LinkedHashSet, etc.)
- Fastest implementation is HashSet

TreeSet:

- Class that implements the Set interface


- Maintains elements in a sorted order (natural order or custom comparator)
- Does not allow null elements
- Implemented as a red-black tree
- Slower than HashSet due to sorting overhead
- Provides additional methods for navigating the sorted set (e.g., first(), last(),
headSet(), tailSet())

DATA STRUCTURES INTERVIEW QUESTIONS

What are Data Structures?

A data structure is a mechanical or logical way that data is organized within a program. The
organization of data is what determines how a program performs. There are many types of
data structures, each with its own uses. When designing code, we need to pay particular
attention to the way data is structured. If data isn't stored efficiently or correctly structured,
then the overall performance of the code will be reduced.
1. Why Create Data Structures?

Data structures serve a number of important functions in a program. They ensure that each
line of code performs its function correctly and efficiently, they help the programmer identify
and fix problems with his/her code, and they help to create a clear and organized code base.

2. What are some applications of Data structures?

 Decision Making
 Genetics
 Image Processing
 Blockchain
 Numerical and Statistical Analysis
 Compiler Design
 Database Design and many more

6. Describe the types of Data Structures?


Linear Data Structure: A data structure that includes data elements arranged sequentially or
linearly, where each element is connected to its previous and next nearest elements, is
referred to as a linear data structure. Arrays and linked lists are two examples of linear data
structures.

Non-Linear Data Structure: Non-linear data structures are data structures in which data
elements are not arranged linearly or sequentially. We cannot walk through all elements in
one pass in a non-linear data structure, as in a linear data structure. Trees and graphs are two
examples of non-linear data structures

7. How can we remove loops in a linked list? What are the functions of fast
and slow pointers?
The main concept to detect and remove a loop in a linked list is to use two pointers (one slow
pointer and a fast pointer). The slow pointer traverses single node at a time, whereas the fast
pointer traverses twice as fast as the first one. If the linked list contains loop in it, the fast and
slow pointer will be at the same node. On the other hand, if the list doesn't consist loop in it,
obviously the fast pointer will reach the end before the slow pointer does. A loop is detected
if these two pointers ever met. If the loop is detected, the start of the loop can help us remove
the detected loop in the linked list. It is called Floyd's Cycle-Finding Algorithm. The given
diagram shows how a loop looks like in a linked list:
8. Explain the Red-Black tree data structure?

A Red-Black Tree is a self-balancing binary search tree where each node has an additional
attribute: a color, which can be either red or black.

Node Color:Each node in a Red-Black Tree is either red or black.The root of the tree is
always black.

Red Property:Red nodes cannot have red children (no two consecutive red nodes on any
path).

Black Property:Every path from a node to its descendant null nodes (leaves) has the same
number of black nodes.

All leaves (NIL nodes) are black.

9. How to calculate the length of a singly linked list in Java?

We can iterate over the linked list and keep a count of nodes until we reach the end of the
linked list where the next node will be null. The value of the counter is considered as the
length of the linked list.

10. Mention some interfaces implemented by Linked List in Java.

Some of the main interfaces implemented by Java Linked Lists are:

 Serializable
 Queue
 List
 Cloneable
 Collection
 Deque
 Iterable

11. List the area of applications of Data Structure.

Data structures are applied extensively in the following areas of computer science:

 Compiler Design,
 Operating System,
 Database Management System,
 Statistical analysis package,
 Numerical Analysis,
 Graphics,
 Artificial Intelligence,
 Simulation
12. List the area of applications where stack data structure can be used?

 Expression evaluation
 Backtracking
 Memory Management
 Function calling and return

13. What are the operations that can be performed on a stack?

 Push Operations
 Pop Operations
 Peek Operations

14. Where we use stack and queue in real time in two lines?
Stacks are used in real-time applications such as:

 Undo/Redo functionality in text editors and browsers


 Evaluating postfix expressions in calculators
 Implementing recursive algorithms
 Managing function calls in programming languages
 Parsing syntax in compilers

Queues are used in real-time applications such as:

 Job scheduling in operating systems


 Print queues in printers
 Network packet processing
 Customer service chat systems
 Order processing in e-commerce platforms

15. Write the steps involved in the insertion and deletion of an element in the
stack.
Push:
Increment the variable top so that it can refer to the next memory allocation.Copy the item
to the at the array index value equal to the top.Repeat step 1 and 2 until stack overflows
Pop:
Store the topmost element into the an another variable.Decrement the value of the
top.Return the topmost element
16. What is a multidimensional array?
The multidimensional array can be defined as the array of arrays in which, the data is stored
in tabular form consists of rows and columns. 2D arrays are created to implement a
relational database lookalike data structure. It provides ease of holding the bulk of data at
once which can be passed to any number of functions wherever required.

17. Are linked lists considered linear or non-linear data structures?


A linked list is considered both linear and non-linear data structure depending upon the
situation.On the basis of data storage, it is considered as a non-linear data structure.On the
basis of the access strategy, it is considered as a linear data-structure.

18. What are the advantages of Linked List over an array?


 The size of a linked list can be incremented at runtime which is impossible in the
case of the array.
 The List is not required to be contiguously present in the main memory, if the
contiguous space is not available, the nodes can be stored anywhere in the memory
connected through the links.
 The List is dynamically stored in the main memory and grows as per the program
demand while the array is statically stored in the main memory, size of which must
be declared at compile time.
 The number of elements in the linked list are limited to the available memory space
while the number of elements in the array is limited to the size of an array.

19. If you are using C language to implement the heterogeneous linked list,
what pointer type should be used?
The heterogeneous linked list contains different data types, so it is not possible to use
ordinary pointers for this. For this purpose, you have to use a generic pointer type like void
pointer because the void pointer is capable of storing a pointer to any type.

20. What are the drawbacks of array implementation of Queue?


Memory Wastage: The space of the array, which is used to store queue elements, can never
be reused to store the elements of that queue because the elements can only be inserted at
front end and the value of front might be so high so that, all the space before that, can
never be filled.
Array Size: There might be situations in which, we may need to extend the queue to insert
more elements if we use an array to implement queue, It will almost be impossible to
extend the array size, therefore deciding the correct array size is always a problem in array
implementation of queue.
21. What are the drawbacks of array implementation of Queue?
Memory Wastage: The space of the array, which is used to store queue elements, can never
be reused to store the elements of that queue because the elements can only be inserted at
front end and the value of front might be so high so that, all the space before that, can
never be filled.
Array Size: There might be situations in which, we may need to extend the queue to insert
more elements if we use an array to implement queue, It will almost be impossible to
extend the array size, therefore deciding the correct array size is always a problem in array
implementation of queue.

22. What is the minimum number of queues that can be used to implement a
priority queue?
Two queues are needed. One queue is used to store the data elements, and another is used
for storing priorities.

23. What is the Collection framework in Java?


Collection Framework is a combination of classes and interface, which is used to store and
manipulate the data in the form of objects. It provides various classes such as ArrayList,
Vector, Stack, and HashSet, etc. and interfaces such as List, Queue, Set, etc. for this purpose.

24. Write the stack overflow condition.


Overflow occurs when top = Maxsize -1

25. What are the main differences between array and collection?
Array and Collection are somewhat similar regarding storing the references of objects and
manipulating the data, but they differ in many ways. The main differences between the
array and Collection are defined below:
Arrays are always of fixed size, i.e., a user can not increase or decrease the length of the
array according to their requirement or at runtime, but In Collection, size can be changed
dynamically as per need.
Arrays can only store homogeneous or similar type objects, but in Collection, heterogeneous
objects can be stored.
Arrays cannot provide the ?ready-made? methods for user requirements as sorting,
searching, etc. but Collection includes readymade methods to use.
26. Difference between stack and queue?

Here's a summary of the main differences between stacks and queues:

Stack:

- Last In, First Out (LIFO) order


- Elements are added and removed from the top
- Push (add) and pop (remove) operations
- Top element is accessible

- Examples: undo/redo, function calls, recursive algorithms

Queue:

- First In, First Out (FIFO) order


- Elements are added to the end (enqueue) and removed from the front (dequeue)
- Enqueue (add) and dequeue (remove) operations
- Front and rear elements are accessible
- Examples: job scheduling, print queues, network packet processing

27. What do you understand by BlockingQueue?

BlockingQueue is an interface which extends the Queue interface. It provides


concurrency in the operations like retrieval, insertion, deletion. While retrieval
of any element, it waits for the queue to be non-empty. While storing the
elements, it waits for the available space. BlockingQueue cannot contain null
elements, and implementation of BlockingQueue is thread-safe.
Syntax:
public interface BlockingQueue<E> extends Queue <E>
28. Give an example program of stack and queue?

Here are simple example programs in Java for a Stack and a Queue:

Stack Example:

import java.util.Stack;

public class StackExample {


public static void main(String[] args) {
Stack<String> stack = new Stack<>();
stack.push("Apple");
stack.push("Banana");
stack.push("Cherry");
System.out.println(stack.pop()); // Cherry

System.out.println(stack.peek()); // Banana
stack.push("Date");
System.out.println(stack.pop()); // Date
System.out.println(stack.size()); // 2

}
}

Queue Example:
import java.util.Queue;
import java.util.LinkedList;

public class QueueExample {


public static void main(String[] args) {
Queue<String> queue = new LinkedList<>();
queue.add("Apple");

queue.add("Banana");
queue.add("Cherry");

System.out.println(queue.remove()); // Apple
System.out.println(queue.element()); // Banana
queue.add("Date");
System.out.println(queue.remove()); // Banana
System.out.println(queue.size()); // 2

}
}
These programs demonstrate basic operations like adding, removing, and
inspecting elements in a Stack and a Queue.
29. What does the 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.
 However, it is possible that two hash code numbers can have different or the same
keys.
 If two objects do not produce an equal result by using the equals() method, then the
hashcode() method will provide the different integer result for both the objects.
30. Why we override equals() method?
The equals method is used to check whether two objects are the same or not. It needs to be
overridden if we want to check the objects based on the property.
For example, Employee is a class that has 3 data members: id, name, and salary. However,
we want to check the equality of employee object by the salary. Then, we need to override
the equals() method.

31. How to synchronize List, Set and Map elements?


Yes, Collections class provides methods to make List, Set or Map elements as synchronized:
public static List synchronizedList(List l){}
public static Set synchronizedSet(Set s){}
public static SortedSet synchronizedSortedSet(SortedSet s){}
public static Map synchronizedMap(Map m){}
public static SortedMap synchronizedSortedMap(SortedMap m){}

32. What is the advantage of the generic collection?


 There are three main advantages of using the generic collection.
 If we use the generic class, we don't need typecasting.
 It is type-safe and checked at compile time.
 Generic confirms the stability of the code by making it bug detectable
at compile time.

34. What is hash-collision in Hashtable and how it is handled in Java?


Two different keys with the same hash value are known as hash-collision. Two separate
entries will be kept in a single hash bucket to avoid the collision. There are two ways to
avoid hash-collision.

 Separate Chaining
 Open Addressing
35. What are data structure operations.
Data structure operations are the actions that can be performed on a data structure to
manage and manipulate the data stored within it. Here are some common data structure
operations:
1. Insert: Adding a new element to the data structure.
2. Delete: Removing an element from the data structure.
3. Search: Finding a specific element in the data structure.
4. Update: Modifying an existing element in the data structure.
5. Sort: Arranging the elements in a specific order.
6. Traverse: Iterating through the elements in the data structure.
7. Access: Retrieving a specific element from the data structure.

8. Modify: Changing the value of a specific element.


9. Enumerate: Iterating through the elements in a specific order.
10. Filter: Selecting a subset of elements based on a condition.

11. Reduce: Combining elements to produce a single output.


12. Split: Dividing a data structure into smaller parts.

13. Merge: Combining two or more data structures into one.


14. Clone: Creating a copy of a data structure.
15. Clear: Removing all elements from a data structure.
These operations can be performed on various data structures such as arrays, linked lists,
stacks, queues, trees, graphs, hash tables, and more. The specific operations supported can
vary depending on the data structure and its implementation.

36. What is the Dictionary class?


The Dictionary class provides the capability to store key-value pairs.

37. What is a heap data structure?


Heap is a special tree-based non-linear data structure in which the tree is a complete binary
tree. A binary tree is said to be complete if all levels are completely filled except possibly the
last level and the last level has all elements as left as possible. Heaps are of two types:
Max-Heap:
In a Max-Heap the data element present at the root node must be the greatest among all
the data elements present in the tree.
This property should be recursively true for all sub-trees of that binary tree.
Min-Heap:
In a Min-Heap the data element present at the root node must be the smallest (or
minimum) among all the data elements present in the tree.

This property should be recursively true for all sub-trees of that binary tree.
38. What do you understand by fail-fast?
The Iterator in java which immediately throws ConcurrentmodificationException, if any
structural modification occurs in, is called as a Fail-fast iterator. Fail-fats iterator does not
require any extra space in memory.

39. How to make Java ArrayList Read-Only?


We can obtain java ArrayList Read-only by calling the Collections.unmodifiableCollection()
method. When we define an ArrayList as Read-only then we cannot perform any
modification in the collection through add(), remove() or set() method.

40. What are dynamic Data Structures? Name a few.


They are collections of data in memory that expand and contract to grow or shrink in size as
a program runs. This enables the programmer to control exactly how much memory is to be
utilized.
Examples are the dynamic array, linked list, stack, queue, and heap.

41. How to remove duplicates from ArrayList?


There are two ways to remove duplicates from the ArrayList.
Using HashSet: By using HashSet we can remove the duplicate element from the ArrayList,
but it will not then preserve the insertion order.
Using LinkedHashSet: We can also maintain the insertion order by using LinkedHashSet
instead of HashSet.
The Process to remove duplicate elements from ArrayList using the LinkedHashSet:
Copy all the elements of ArrayList to LinkedHashSet.

Empty the ArrayList using clear() method, which will remove all the elements from the list.
Now copy all the elements of LinkedHashset to ArrayList.

42. Explain the process behind storing a variable in memory.


A variable is stored in memory based on the amount of memory that is needed. Following
are the steps followed to store a variable:
The required amount of memory is assigned first.
Then, it is stored based on the data structure being used.
Using concepts like dynamic allocation ensures high efficiency and that the storage units can
be accessed based on requirements in real-time.
43. Define the Tree data structure.
A single node is identified as the tree's root, while the remaining nodes are referred to as
the root's progeny. The Tree is a recursive data structure comprising one or more data
nodes. All nodes that have the root node are divided into nonempty sets, with each node
being referred to as a sub-tree.

44. Name the types of hash collision?


Accidental or random collisions and intentional or malicious collisions.

Accidental Collisions: Accidental collisions occur when two different inputs produce the same hash
value due to the nature of hashing algorithms and the limited range of possible hash values. These
collisions are unintended and usually considered rare and coincidental.

Intentional Collisions: Intentional collisions occur when an attacker purposefully generates two or
more different inputs that produce the same hash value. These collisions are often the result of
exploiting vulnerabilities or weaknesses in the hashing algorithm.

45. What is the requirement for an object to be used as key or value in


HashMap?
The key or value object that gets used in the hashmap must implement equals() and hashcode()
method.

The hash code is used when inserting the key object into the map and the equals method is used
when trying to retrieve a value from the map.

46. How is a stack implemented in an array?

A stack can be implemented using an array by maintaining a pointer to the top of the stack.

46. What are the disadvantage of Linked List?


Answer: Disadvantages of Linked Lists:

 Slow random access


 More memory overhead
 Difficult to debug
 Not cache-friendly
 Can suffer from memory leaks

47. What is the load factor of a hash table?


The load factor of a hash table is the ratio of the number of keys stored in the table to the
size of the table.

48. How is a stack implemented in an array?


Answer: A stack can be implemented using an array by maintaining a pointer to the top of the stack.
49. What is a hash function?
Answer: A hash function is a function that takes an input of any size and produces an output of a
fixed size. The output is called a hash value or hash code.

50. Explain how a hash function works.


Answer: A hash function takes an input key and maps it to a fixed-size index (hash value) within the
hash table’s array. Ideally, the function distributes keys evenly across the array to minimize
collisions. Common hash functions include modulo division, bitwise operations, and

polynomial hashing.

51. Explain the concept of load factor and its impact on performance.
Answer: Load factor (number of elements / size of hash table) measures how full the table is. Higher
load factors increase collision frequency and impact performance. Optimal values vary based on
implementation and trade-offs.

52. What are the disadvantages of using a hash data structure?


Answer: Hash data structures can suffer from collisions, which can slow down lookup operations.
They also require a hash function that is both efficient and effective.

53. How would you design. A memory allocator using data structures
consider aspects like memory fragmention and efficient allocation?
To design a memory allocator using data structures, I would:

1. Use a linked list to store free memory blocks


2. Use a binary search tree (BST) to store allocated memory blocks
3. Use a bit vector to track block status (free/allocated)

4. Implement algorithms for allocation (first-fit, best-fit, worst-fit) and deallocation


5. Handle fragmentation by coalescing and splitting blocks

6. Optimize with caching and binning

54. Discuss the role of free lists in memory management and how different
data structure can be used in implement them?
Free lists help manage memory by Storing free memory blocks
- Reducing fragmentation
- Enabling efficient allocation
Data structures used to implement free lists
- Linked lists
- Arrays
- Trees (BST, AVL, etc.)
- Hash tables
- Stacks
- Bit vectors

Choose the best data structure based on: Memory block size and variability
- Allocation and deallocation patterns
- Performance requirements

55. How would you design a stack that supports push pop and retrieving the
minimum element in constant time?
Free lists:
- Store empty memory spaces
- Help reduce waste (fragmentation)
- Make it easy to allocate memory

Data structures used:


-Linked lists
- Arrays
- Trees
- Hash tables

- Stacks
- Bit vectors

56. How would you modify this stack to also support retrieving the maximum
element in constant time?
Design a stack that:
- Pushes elements onto a main stack
- Keeps track of the smallest element in a separate "min stack"
- Allows pushing, popping, and getting the smallest element quickly (in constant time)
This way, you can:

- Push and pop elements quickly


- Always know the smallest element quickly

- Use memory efficiently!

57. How would you implement a circular queue using an array discuss the
advantages over a standard queue implementation?
To support retrieving the maximum element in constant time, add another stack called
"max stack" that keeps track of the maximum elements.

Now, the stack has:


- Main stack (actual elements)
- Min stack (smallest elements)
- Max stack (largest elements)
This way, you can:-

-Push and pop elements quickly


- Get the smallest element quickly
- Get the largest element quickly

58. Which data structure HashMap represents?


The HashMap is an implementation of hash table data structure, which is idle for mapping
one value to other like id to name as you can search for value in O(1) time if
you have the key.

59. Which data structure is used to implement HashMap in Java?


Even though HashMap represents a hash table, it is internally implemented by using an
array and linked list data structure in JDK. The array data structure is used as a bucket,
while a linked list is used to store all mappings which land in the same bucket. From Java 8
onwards, the linked list is dynamically replaced by binary search tree, once a number of
elements in the linked list cross a certain threshold to improve performance.

60. Explain why stack is a recursive data structure ?


A stack is a recursive data structure so,its
* a stack is either empty
*it consists of a top and the rest which is a stack by itself.

61. What will happen if you use HashMap in a multithreaded Java


application?
If you use HashMap in a multithreaded environment in such a way that multiple threads
structurally modify the map like add, remove or modify mapping, then the internal data
structure of HashMap may get corrupt like some links may go missing, some may point to
incorrect entries, and the map itself may become completely useless. Hence, it is advised
not to use HashMap in the concurrent application; instead, you should use a thread-safe
map e.g., ConcurrentHashMap or Hashtable.

62. How would u. Handle the case where the queue becomes full would you
prefer dynamic resizing or some other approaches?
When the queue is full, I would:
- Increase the queue size (dynamic resizing)

- Make more space for new elements


- Avoid losing data or causing errors
This way, the queue can grow and adapt to changing needs, making it a flexible and
efficient solution!

63. In which order mappings are stored in HashMap?


Random order because HashMap doesn't provide any ordering guarantee for keys, values,
or entries. When you iterate over a HashMap, you may get a different order every time you
iterate over it.

64. Can you sort HashMap in Java?


No, you cannot sort a HashMap because, unlike List, it is not an ordered collection. Albeit,
you can sort contents of HashMap by keys, values, or by entries by sorting and then storing
the result into an ordered map like LinkedHashMap or a sorted map e.g., TreeMap.

65. What is space complexity of a hashtable?


The space complexity of a hash table (also known as a hash map) typically depends on the
implementation and is O(n), where n represents the number of key-value pairs stored in the
hash table. Each key-value pair occupies constant space, and the overall space required
grows linearly with the number of elements.

66. How many entries you can store in HashMap? What is the maximum
limit?
There is no maximum limit for HashMap, you can store as many entries as you want because
when you run out of the bucket, entries will be added to a linked list which can support an
infinite number of entries, of course until you exhaust all the memory you have.Btw, the
size() method of HashMap return an int, which has a limit, once a number of entries cross
the limit, size() will overflow, and if your program relies on that, then it will break.

67. What will happen if two different keys of HashMap return the same
hashcode()?
If two keys of HashMap return the same hash code, then they will end up in the same
bucket; hence collision will occur. They will be stored in a linked list together.

68. Are linked lists Linear or Non-linear Data Structures?


Linked lists are considered to be the best of both worlds here. Based on usage, if it is a
storage policy, then it can be considered as non-linear. Whereas, if a person is considering it
based on retrieval strategies, then it can be considered linear.

69. What are the Features of a LinkedHashMap:


A LinkedHashMap contains values based on the key. It implements the Map interface and
extends the HashMap class.
It contains only unique elements.
It may have one null key and multiple null values.
It is non-synchronized.
It is the same as HashMap with an additional feature that it maintains insertion order. For
example, when we run the code with a HashMap, we get a different order of elements.

70. What is the difference between void and null in Data Structures?
Void is a data type identifier in data structures, while null is considered to be a value with no
physical presence. When void is used, it indicates that there is no size while initializing
the data structure.

71. How is a variable stored in memory when using Data Structures?


A variable is stored based on the amount of memory that is needed. First, the required
quantity of memory is assigned, and later, it is stored based on the data structure being
used. Using concepts such as dynamic allocation ensures high efficiency and that the
storage units can be supplied based on the requirements in real time.
72. What is difference between HashMap and ConcurrentHashMap in Java?
The ConcurrentHashMap is an scalable and concurrent version of HashMap. The key
difference again is same as it was in previous question, HashMap is not thread-safe but
ConcurrentHashMap is thread-safe, though it is more scalable than Hashtable or
synchronized HashMap because of its implementation e.g. it divides the map into several
segments and it never lock whole map, instead only segments are locked when you add or
remove entries from ConcurrentHashMap. You can learn more about its implementation on
my post How ConcurrentHashMap works in Java.

73. How do you get all keys from HashMap in Java?


you can call the keySet() method which return all keys on the HashMap.

74. How do you sort HashMap by values in Java?


As I said, you cannot sort HashMap because it is an un-ordered collection, but you can
capture all its values and sort them just like any other collection using Comparator and then
store all entries in the order of values into a LinkedHashMap, which keeps mapping in the
order they were added.

75. Are Stack and Queue the Same Thing? If Not, Explain Why.
Stacks and queues are different data structures. The key differences between them are:

 Stacks follow a first-in-first-out logic whereas queues employ a last-in-first-out logic.


 You can insert and delete elements only at the top of a stack. On the other hand,
elements are added at one end of a queue and deleted at the other.
 Stacks use only one pointer, which is for the top of the stack. Queues need two
pointers to address the front of the queue and back of the queue.
 Stacks are mainly used in problems requiring recursion whereas queues are better
used in applications that require sequential processing.

76. Can you explain the basic principle of a Hash Table?


A hash table is a data structure that implements an associative array abstract data type,
which can map keys to values. It uses a hash function to compute an index into an array of
buckets or slots from which the desired value can be found. Ideally, the hash function will
assign each key to a unique bucket, but most hash table designs employ an imperfect hash.

77. Diffrence Between LIFO and FIFO?


78. How does the choice of a hash function affect the performance of a Hash
Table?
The choice of a hash function significantly impacts the performance of a Hash Table. A good
hash function distributes keys uniformly across the table, minimizing collisions and ensuring
an average-case time complexity of O(1) for search, insert, and delete operations.
Conversely, a poor hash function causes clustering, leading to more collisions. This results in
increased time complexity due to collision resolution methods like chaining or
open addressing.

79. How would a Hash Table change if it were implemented with a linked list?
Implementing a hash table with a linked list would introduce changes in terms of collision
handling and performance. In case of collisions, instead of overwriting existing data or
finding an empty slot (linear probing), the collided elements are stored as nodes in a linked
list at that particular index. This method is known as chaining.

80. How would you resolve the issue of fixed size in a Hash Table?
To resolve the issue of fixed size in a Hash Table, we can use dynamic resizing. This involves
increasing or decreasing the table’s capacity based on its current load factor. When the
number of entries exceeds a certain threshold (usually 0.7), we double the size of the array
and rehash all existing keys to new indexes.
81. How does the concept of ‘buckets’ work in a Hash Table?
In a hash table, ‘buckets’ are used to handle collisions. A collision occurs when two different keys
map to the same index in the array. To resolve this, each index points to a linked list of entries,
known as a bucket. When a new key-value pair is inserted and a collision happens, the pair gets
added to the end of the corresponding bucket.

82. Why is hashing preferred over other data structures like trees?
Hashing is preferred over other data structures like trees because it is more efficient in terms of
both time and space. With hashing, you can quickly insert and retrieve data from a large data set
without having to traverse the entire data set. This makes hashing an ideal choice for applications
where speed is critical.

83. When should you not use a HashSet?


There are a few reasons why you might not want to use a HashSet. First, if you need to maintain
the order of elements, a HashSet is not the right data structure because it does not guarantee the
order of elements. Second, if you need to perform a lot of operations that require a key (such as
searching or deleting), a HashSet is not the most efficient data structure because it does not
provide direct access to elements by key. Finally, if you need to be able to look up elements by
value, a HashSet is not the right data structure because it only provides access to elements by
key.

84. What are the Java HashSet Features?


A few important features of HashSet are mentioned below:

 Implements Set Interface.


 The underlying data structure for HashSet is Hashtable.
 As it implements the Set Interface, duplicate values are not allowed.
 Objects that you insert in HashSet are not guaranteed to be inserted in the same
order. Objects are inserted based on their hash code.
 NULL elements are allowed in HashSet.
 HashSet also implements Serializable and Cloneable interfaces.

85. Describe the characteristics of a good hash function.


A good hash function is fundamental for efficient data management in hash tables or when
employing techniques such as hash-based encryption. Here, let's go through what it means for a
hash function to be high-quality.

Bubble Sort
1.What is Bubble Sort?
Bubble Sort is a simple sorting algorithm that repeatedly steps through the list to be sorted,
compares each pair of adjacent items, and swaps them if they are in the wrong order.Bubble Sort
is a simple comparison-based sorting algorithm that repeatedly steps through a list, compares
adjacent elements, and swaps them if they are in the wrong order. This process is repeated until the
list is sorted. The algorithm gets its name because smaller elements "bubble" to the top of the list.
Bubble Sort has a time complexity of O(n^2) in the worst and average cases, making it inefficient for
large datasets. However, it is easy to understand and implement, making it useful for educational
purposes.

2.What type of algorithm is bubble sort?

Bubble Sort is a comparison-based sorting algorithm. This means it sorts a list by comparing
pairs of adjacent elements and swapping them if they are in the wrong order. The algorithm
repeatedly passes through the list until no swaps are needed, indicating that the list is sorted.It's
also classified as a brute-force algorithm because it systematically checks and compares each pair
of adjacent elements without using any additional data structures or advanced techniques. While
Bubble Sort is straightforward and easy to understand, it's generally inefficient for large datasets
due to its O(n^2) time complexity, where n is the number of elements in the list.

3.Explain the main advantage of Bubble Sort.

The main advantage of Bubble Sort is its simplicity and ease of implementation. It's a
straightforward algorithm that is easy to understand, making it a good choice for educational
purposes when introducing the concepts of sorting algorithms. Additionally, Bubble Sort has a built-
in optimization where it can detect if the list is already sorted, potentially reducing the number of
passes needed in best-case scenarios, where the time complexity can be O(n). This feature allows it
to perform better than its average-case time complexity in certain situations.
4.What is the main disadvantage of Bubble Sort?

The main disadvantage of Bubble Sort is its inefficiency for large datasets. Its time
complexity is O(n^2) in both the worst and average cases, meaning it performs poorly as the
number of elements increases. This inefficiency arises because the algorithm repeatedly compares
and swaps adjacent elements, even when only a few elements are out of order. As a result, Bubble
Sort is much slower compared to more advanced sorting algorithms like Quick Sort or Merge Sort,
making it impractical for large-scale sorting tasks. With a time complexity of O(n²) in both the
worst and average cases, it requires a significant number of comparisons and swaps, making it
much slower compared to more advanced sorting algorithms like Quick Sort or Merge Sort. This
quadratic time complexity leads to poor performance, especially as the size of the dataset
increases, making Bubble Sort impractical for large-scale sorting tasks.

5.When is Bubble Sort a good choice for sorting data?

Bubble Sort is a good choice for sorting data when:

1. The dataset is small: Bubble Sort can be effective for small lists where the inefficiency of
its O(n^2) time complexity isn't a significant drawback.
2. The list is nearly sorted: If the list is already mostly sorted or has only a few elements out
of place, Bubble Sort can quickly sort it, especially with its ability to detect if the list is
already sorted.
3. Simplicity is important: When the priority is ease of implementation and understanding,
such as in educational contexts or simple programming tasks, Bubble Sort's straightforward
approach makes it a suitable choice.

6. Explain the process of Bubble Sort with an example.


The process of Bubble Sort involves comparing adjacent elements and swapping them if they
are in the wrong order. This process is repeated until the list is sorted. Bubble Sort works by
repeatedly stepping through a list, comparing adjacent elements, and swapping them if they are in
the wrong order. This process continues until no more swaps are needed, indicating that the list is
sorted.
For example, if we have an array [5, 2, 9, 3], Bubble Sort would compare 5 and 2, swap them, then
compare 5 and 9, leaving the array as [2, 5, 9, 3].
7.Explain the concept of an “in-place” sorting algorithm.

An "in-place" sorting algorithm is a type of algorithm that sorts the elements of a list
directly within the original array or list without needing additional storage or memory. This means
the algorithm rearranges the elements by swapping them or moving them within the same space,
using only a small, constant amount of extra memory, typically for variables like counters or
temporary storage during swaps.

Key Points:

 No extra memory: The algorithm doesn’t require significant extra space proportional to the
input size. It only uses a fixed amount of additional memory.
 Original array: The elements are sorted within the original array, so there’s no need to
create a copy or use another data structure to hold sorted elements.
 Examples: Bubble Sort, Insertion Sort, and Selection Sort are common examples of in-place
sorting algorithms.

8.Can Bubble Sort be used for sorting linked lists?


Although linked lists can be sorted using bubble sort, this isn’t the most effective
technique, especially for big linked lists. Better sorting algorithms exist for this particular data
structure.

1. Compare Nodes: You compare adjacent nodes in the linked list.


2. Swap Nodes: If the nodes are out of order, you adjust the pointers to swap them.
3. Repeat: You continue this process, passing through the list multiple times until no swaps
are needed.

Challenges with Linked Lists:

1. Pointer Adjustments: Swapping nodes in a linked list requires changing pointers, which can
be more complex and time-consuming than swapping array elements.
2. Efficiency: Bubble Sort's O(n^2) time complexity is less efficient for linked lists compared to
more suitable algorithms for linked lists, like Merge Sort, which has a time complexity of
O(n log n).
9.What is the main advantage of Bubble Sort compared to other sorting
algorithms?
Bubble Sort is simple to implement and understand, making it suitable for educational
purposes. It is a good option for educational purposes and small datasets where complexity is not
an issue because it is simple to understand and apply.

The main advantage of Bubble Sort compared to other sorting algorithms is its simplicity. Here’s
why:

1. Easy to Understand: Bubble Sort is straightforward and easy to grasp, making it a good
introductory algorithm for learning basic sorting concepts.
2. Simple Implementation: Its algorithmic steps are simple—just compare adjacent elements
and swap them if they’re out of order. This makes it easy to implement and debug.
3. Adaptive Behavior: In its optimized version, Bubble Sort can detect if the list is already
sorted. If no swaps are needed in a pass through the list, it stops early, potentially saving
some time in cases where the list is nearly sorted.
4. No Extra Memory Needed: It’s an in-place sorting algorithm, meaning it doesn’t require
additional storage beyond a few variables for swaps, unlike some other algorithms that
might need extra memory.

10.How can you optimize Bubble Sort?


We can optimize Bubble Sort by adding a flag to check if any swaps were made during a pass
through the array. If no swaps were made, the array is already sorted, and the algorithm can stop
early. Bubble Sort can be optimized to improve its performance, particularly when dealing with
nearly sorted lists. One key optimization is the early exit technique, where the algorithm includes a
flag to detect if any swaps occurred during a pass through the list. If no swaps are made, it indicates
that the list is already sorted, and the algorithm can exit early, thus saving time. Another
optimization involves reducing the range of passes by tracking the last position where a swap
occurred. This allows the algorithm to avoid re-checking elements that are already sorted, as the
sorted portion of the list grows with each pass. By implementing these optimizations, Bubble Sort
can become more efficient and handle partially sorted lists more effectively.

Insertion Sort
1.What is Insertion Sort?
A simple sorting algorithm called insertion sort builds the final sorted array one element at a
time. It selects an element from the unsorted list and inserts it into the sorted section of the list
at the proper location. Until the entire list is sorted, this process is repeated. Insertion Sort is a
straightforward sorting algorithm that builds a sorted list one item at a time, similar to how you
might sort playing cards in your hands. It starts by assuming the first element is already sorted. For
each subsequent element, it compares it with the elements before it and shifts those that are larger
to the right, making room for the current element. This element is then inserted into its correct
position within the sorted portion of the list. The process is repeated for each element until the
entire list is sorted. Insertion Sort is particularly efficient for small or nearly sorted lists, and while it
has a time complexity of O(n^2) in the average and worst cases, it can be O(n) if the list is already
sorted.

2.How does the Insertion Sort Algorithm work?


One element at a time, iterating through the array, is how the insertion sort operates. It
inserts the element in the appropriate location after comparing it with the elements in the array’s
sorted section. This procedure keeps going until every component is in the proper order. Insertion
Sort works by gradually building a sorted portion of the list, one element at a time. It starts by treating
the first element as the beginning of the sorted portion and then moves through the rest of the list,
inserting each new element into its proper place within the already sorted portion. For each element,
it compares it to elements in the sorted portion, shifting larger elements to the right to make room.
The current element is then placed in its correct position. This process is repeated for each element
until the entire list is sorted. Insertion Sort is particularly effective for small or nearly sorted lists and
has a time complexity of O(n^2) in average and worst cases, but can be more efficient if the list is
already close to being sorted.

3.When should you use Insertion Sort over other sorting algorithms?
When working with small datasets or lists that have been partially sorted, Insertion Sort is a
good option. It is perfect for situations where memory usage and code simplicity are more
important than speed because of its simplicity and low space requirements.

Insertion Sort should be used over other sorting algorithms in specific scenarios due to its unique
advantages:

1. Small Datasets: Insertion Sort is efficient for small lists or arrays because its simple
implementation and low overhead can outperform more complex algorithms for small
sizes. Its constant factors can make it faster for small inputs despite its O(n^2) time
complexity.
2. Nearly Sorted Lists: When the list is already mostly sorted, Insertion Sort can be very
efficient. It can achieve a best-case time complexity of O(n) if the list requires minimal
adjustments, making it faster than algorithms with higher worst-case complexities.
3. Real-Time Systems: Insertion Sort’s predictable performance and low memory usage make
it suitable for real-time systems where consistent and quick sorting with minimal memory
overhead is critical.
4. Stability Requirement: Insertion Sort is a stable sorting algorithm, meaning it preserves the
relative order of equal elements. If stability is important and other stable sorting algorithms
(like Merge Sort) are not feasible, Insertion Sort can be a good choice.
5. Adaptive Sorting Needs: Insertion Sort adapts well to different data scenarios. If data is
incrementally added or modified, Insertion Sort can efficiently handle such dynamic
changes, making it suitable for applications with frequent small updates.

4.Can you explain the advantages and disadvantages of Insertion Sort?

Insertion Sort offers several advantages and disadvantages. Its main strengths include
simplicity, making it easy to understand and implement, and efficiency for small or nearly sorted
datasets, where it can operate quickly and achieve a best-case time complexity of O(n).
Additionally, it is a stable sorting algorithm, preserving the relative order of equal elements, and it
sorts in-place, requiring minimal extra memory. However, Insertion Sort is less effective for large
datasets due to its quadratic time complexity of O(n^2), which results in slower performance as
the list size increases. It also requires multiple passes through the list for large, unsorted datasets,
making it less practical compared to more advanced sorting algorithms like Quick Sort or Merge
Sort for handling large volumes of data.

5. What are the key differences between Insertion Sort and Selection Sort?

Insertion Sort and Selection Sort are both simple sorting algorithms, but they differ significantly in
their approach and efficiency. Insertion Sort builds the sorted portion of the list one element at a
time, inserting each new element into its correct position within the already sorted portion, making
it adaptive and efficient for small or nearly sorted lists. Its time complexity is O(n^2) in average and
worst cases, but it can be faster if the list is already sorted. Selection Sort, on the other hand,
consistently selects the smallest element from the unsorted portion and moves it to the beginning
of the sorted portion, with a fixed time complexity of O(n^2) regardless of the initial order. It
performs fewer swaps compared to Insertion Sort but does not adapt to partially sorted lists and is
less stable, potentially changing the relative order of equal elements. Overall, Insertion Sort is more
suited for smaller or nearly sorted lists, while Selection Sort is consistent but less efficient for larger
datasets.

6. When is Insertion Sort not a suitable choice for sorting data?


Insertion Sort isn’t the best for sorting really big sets of data because it can take a long time when
there’s a lot to sort. Also, it struggles when the data is all mixed up randomly since it doesn’t do
well with finding any patterns in the data to make sorting faster.

Performance Issues: Insertion Sort has a time complexity of O(n^2) in the average and worst cases.
This means that its performance degrades quickly as the size of the dataset increases. For large
datasets, algorithms with better time complexities, like Quick Sort or Merge Sort, are more efficient.

Inefficiency: When dealing with data that is highly unsorted, Insertion Sort requires many passes
through the list and numerous comparisons and shifts to sort the elements, leading to poor
performance.

Time Sensitivity: In scenarios where quick sorting is essential, such as real-time systems or
applications with stringent time requirements, Insertion Sort’s slower performance on large datasets
makes it less suitable compared to faster algorithms.
7.What is the significance of the term ‘Insertion’ in Insertion Sort?

In Insertion Sort, the word “Insertion” refers to the fundamental process of picking an element
from the unsorted portion of the list and placing it in the properly designated spot within the
portion of the list that has already been sorted. The term ‘Insertion’ in Insertion Sort highlights the
key operation of the algorithm: inserting elements into their correct position within a sorted portion
of the list.

Significance:

 Incremental Building: Insertion Sort works by gradually building a sorted section of the list.
Each new element from the unsorted portion is inserted into its appropriate position within
the already sorted section. This process continues until all elements are placed in the correct
order.
 Direct Insertion: The algorithm inserts each element directly into its correct position by
comparing it with the elements in the sorted portion and shifting those that are larger to the
right. This insertion operation ensures that the sorted portion remains in order as new
elements are added.
 Analogy: The term reflects the way the algorithm mimics the process of inserting cards into
a hand while sorting them. As you pick up a new card, you place it in its correct position
among the cards already sorted.

8.What happens when there’s a duplicate key in a list that needs to be sorted using
Insertion Sort?
The algorithm will simply insert the duplicate key into the list in the appropriate sorted position
when there is a duplicate key in a list that needs to be sorted using insertion sort. This indicates
that there will be duplicate keys in the list, but the list will still be correctly sorted. When using
Insertion Sort to sort a list with duplicate keys, the algorithm maintains the relative order of these
duplicate elements due to its stable nature. As each element is inserted into its correct position
within the sorted portion of the list, duplicate keys are compared and placed without changing their
original order relative to each other. Insertion Sort shifts elements greater than the current key to
the right to make space, but the position of equal keys remains unchanged. This stability ensures
that if two elements have the same key, their relative order from the original list is preserved in the
sorted list.
9.Explain the role of the outer loop in the Insertion Sort algorithm.
The outer loop of Insertion Sort iterates through each element in the unsorted part of the array,
ensuring that the entire array is considered for sorting. The outer loop in the Insertion Sort
algorithm is essential for iterating through the list and managing the sorting process. It starts from
the second element, assuming the first element is already sorted by itself. Its primary role is to select
each element from the unsorted portion and insert it into the correct position within the already
sorted portion of the list. The outer loop ensures that every element is processed, allowing the
algorithm to gradually build the sorted list. By continuing until all elements have been examined and
inserted, the outer loop facilitates the complete sorting of the list. This loop essentially drives the
sorting process, ensuring that each element finds its proper place and that the entire list becomes
fully sorted by the end of the algorithm.

10.What is the role of the inner loop in Insertion Sort?

The inner loop of Insertion Sort compares and shifts elements in the sorted part of the array until
the correct position for the current element is found. The inner loop in Insertion Sort is essential
for placing each element into its correct position within the sorted portion of the list. Its primary
role is to compare the current element, selected by the outer loop, with the elements in the already
sorted section of the list. The inner loop starts from the end of the sorted portion and moves
backward, shifting elements that are greater than the current element to the right to make space.
This shifting process ensures that the current element can be inserted in the correct position,
maintaining the sorted order. By continuing comparisons and shifts until the right spot is found, the
inner loop effectively integrates each element into its proper place, ensuring the list is sorted as the
algorithm progresses.

Selection Sort
1.What is the Selection Sort?
Selection Sort is a straightforward sorting algorithm that sorts a list by repeatedly selecting the
smallest (or largest) element from the unsorted portion and moving it to the beginning of the sorted
portion. The process begins by finding the smallest element in the entire unsorted list and swapping
it with the first element, effectively placing the smallest element in its correct position. This process
is then repeated for the remaining unsorted portion of the list: the algorithm finds the next smallest
element and places it in the next position of the sorted portion. This continues until the entire list is
sorted. Although Selection Sort is easy to implement and understand, it is less efficient for large
datasets due to its O(n^2) time complexity, as it requires multiple passes through the list to find and
place each element.

2.Explain the algorithm of Selection Sort.


Selection Sort is a simple sorting algorithm that organizes a list by repeatedly selecting the
smallest element from the unsorted portion and moving it to the beginning of the sorted portion.
The algorithm starts by initializing the entire list as unsorted. It then iterates through the list, finding
the smallest element in the unsorted portion using an inner loop. Once identified, this smallest
element is swapped with the first element of the unsorted portion, effectively growing the sorted
portion of the list. The process is repeated: the boundary between sorted and unsorted portions is
moved forward, and the next smallest element is found and placed in the appropriate position. This
continues until the entire list is sorted. Although Selection Sort is easy to understand and implement,
its time complexity of O(n^2) makes it inefficient for large datasets, as it requires multiple passes
through the list to sort all elements.

3.What is the Time and Space Complexity of Selection Sort?


The Selection sort algorithm has a time complexity of O(n2) and a space complexity
of O(1) since it does not require any additional memory space apart from a temporary variable
used for swapping.
Time Complexity:

 Best Case: O(n^2)


 Average Case: O(n^2)
 Worst Case: O(n^2)

Explanation:

 Comparison Operations: Selection Sort always performs a fixed number of comparisons


regardless of the initial order of the list. For each position in the list, it scans the remaining
unsorted portion to find the minimum element. This results in approximately (n-1) + (n-2) +
... + 1 comparisons, which sums up to O(n^2) operations.
 Swaps: The algorithm performs a fixed number of swaps (n-1), but these do not
significantly impact the overall time complexity compared to the number of comparisons.
 Independence from Initial Order: Unlike some algorithms, Selection Sort does not benefit
from a partially sorted list. Its time complexity remains O(n^2) in all cases—best, average,
and worst.

4.How is Selection Sort different from other sorting algorithms like Bubble Sort and
Insertion Sort?
Selection Sort continuously selects the smallest (or largest) element and swaps it with the first
unsorted element. Bubble Sort compares adjacent elements and swaps them if they are in the
wrong order, and Insertion Sort builds the final sorted array one element at a time by repeatedly
taking the next element and inserting it into the correct position. Selection Sort, Bubble Sort, and
Insertion Sort each use distinct methods to sort a list and differ significantly in their efficiency and
characteristics. Selection Sort operates by repeatedly finding the smallest element in the unsorted
portion and moving it to the beginning of the sorted portion, resulting in a time complexity of O(n^2)
in all cases and a space complexity of O(1). It is not stable, meaning it can change the relative order
of equal elements. In contrast, Bubble Sort repeatedly compares and swaps adjacent elements,
"bubbling" the largest element to its correct position with a best-case time complexity of O(n) if
optimized for already sorted lists, and O(n^2) for average and worst cases.

5.Can Selection Sort be considered stable or unstable?


Selection Sort is generally considered an unstable sorting algorithm. This is because the process
of repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it
with the first unsorted element can disrupt the relative order of equal elements. In Selection Sort,
if two elements have the same value, their original order in the list may be changed due to the swaps
performed by the algorithm. For instance, if two elements with equal values are swapped because
of their position in the sorting process, their initial relative arrangement can be lost. Unlike stable
sorting algorithms such as Bubble Sort and Insertion Sort, which preserve the order of equal
elements, Selection Sort does not ensure this stability due to its swapping mechanism.

6. What happens if there are duplicate elements in the array during Selection Sort?
Selection Sort does not maintain the relative order of duplicate elements. They might get
swapped during the sorting process. When duplicate elements are present in an array being sorted
with Selection Sort, the algorithm can disrupt their original relative order. During the sorting
process, Selection Sort finds the smallest element in the unsorted portion and swaps it with the first
unsorted element. If the smallest element is a duplicate, this swap can change the relative positions
of those duplicate elements if they are not already in their final sorted positions. As a result, while
the algorithm will correctly sort the array, the initial order of duplicate elements may not be
preserved. This lack of stability means that Selection Sort does not maintain the relative
arrangement of equal elements, which is a key characteristic of stable sorting algorithms.

7.Can Selection Sort be implemented recursively?


Yes, Selection Sort can be implemented recursively, but it’s not commonly done due to the
overhead of function calls and the potential risk of stack overflow for large datasets. Selection Sort
can indeed be implemented recursively, though it is often presented in its iterative form. In a
recursive version, the algorithm works by repeatedly identifying the smallest element in the
unsorted portion of the list and swapping it with the element at the current index. The base case for
the recursion is when the starting index reaches the last element, at which point the list is
considered sorted. In the recursive case, the algorithm finds the minimum element in the unsorted
portion, performs the swap, and then makes a recursive call to sort the remaining subarray starting
from the next index. This process continues until the entire list is sorted. While the recursive
approach provides a different method of implementation, it does not alter the time complexity of
O(n^2) inherent to Selection Sort and adds overhead due to the recursion stack.

8.Is Selection Sort stable if implemented carefully?

It is possible to implement Selection Sort in a stable manner by modifying the swapping process
to ensure that the relative order of equal elements is preserved. However, this would increase the
complexity of the algorithm and might not be practical compared to other stable sorting
algorithms like Merge Sort or Insertion Sort. Selection Sort is inherently an unstable sorting
algorithm, and this characteristic remains even if the algorithm is implemented with care. This
instability arises from its method of selecting the smallest (or largest) element from the unsorted
portion and swapping it with the element at the current position. If the smallest element is a
duplicate, swapping can disrupt the relative order of these duplicate elements.
9.Why is it called Selection Sort?
Selection Sort is so named because of the way it selects the smallest (or largest, depending
on the sorting order) element from the unsorted portion of the array and swaps it with the
element at the beginning of the unsorted portion. This process is repeated until the entire array
is sorted.Selection Sort is named for its primary operation of "selecting" the smallest element
from the unsorted portion of the list and placing it in its correct position within the sorted portion.
In each iteration, the algorithm identifies the smallest element in the unsorted part of the list and
swaps it with the first element of the unsorted portion. This process incrementally builds the
sorted portion of the list as elements are selected and positioned correctly.

10.How can Selection Sort be improved?


The Selection sort can be improved by selecting both the minimum and the maximum value
simultaneously and placing them in their respective positions in a single pass. The time
complexity would still be O(N*N), therefore it is not a major optimization. Selection Sort can be
improved to some extent, although its fundamental approach remains the same. One common
enhancement involves optimizing the algorithm to reduce unnecessary operations. For example, in
a typical Selection Sort, the algorithm continues to search for the minimum element in the entire
unsorted portion even if it becomes clear that the remaining elements are already sorted. An
improvement is to track and skip sections that are already sorted or where no further swaps are
needed, although this does not change the algorithm’s overall time complexity of O(n^2).

Merge sort

1.Is Merge sort In Place?

No, Merge sort is not an in place algorithm. During the “merge” step of the algorithm, we use
an additional array to merge the subarrays in sorted and then the content of the merged array is
copied to the actual array. Merge sort works by dividing the input array into two halves, sorting
each half recursively, and then merging the sorted halves back together. The merging step
requires additional space proportional to the size of the array being sorted.During the merge step,
merge sort uses extra space to hold the combined result of the two sorted halves before copying it
back into the original array. This extra space is used to temporarily store the merged result.

2.How can we make Merge sort more efficient?


To make merge sort more efficient, especially in terms of memory usage, you can use techniques to
reduce the extra space required during the merge process. One common approach is to implement
in-place merge sort, which involves modifying the merge step to work within the original array
without needing additional temporary storage. This can be complex and may involve intricate
algorithms for in-place merging, such as using gap algorithms or buffer techniques to manage
merging efficiently. Another improvement is to optimize the base case, where instead of using a
constant-sized auxiliary array, you can use more sophisticated methods like iterative merging or even
combining merge sort with other sorting algorithms for smaller subarrays (hybrid approaches like
Timsort, which combines merge sort with insertion sort). Additionally, improving the cache
performance by ensuring data locality and minimizing cache misses can enhance overall efficiency.

3.What types of Datasets work best for Merge Sort?

Merge sort is especially effective for large datasets, particularly those that don't fit entirely into
memory. It excels in such cases because it processes data in manageable chunks, making it suitable
for external sorting where data is stored on disk. Additionally, merge sort works well with linked lists,
as it handles the sequential access pattern of linked lists efficiently without needing random access.
This sorting algorithm is also beneficial when dealing with datasets with unpredictable access
patterns or when stable sorting is required, as it preserves the relative order of equal elements.
These characteristics make merge sort a versatile and reliable choice for various data types and
structures.

4.Comparison between Merge Sort and other sorting algorithms?

Merge sort is comparatively more efficient than most of the other sorting algorithms in most
cases. It has a logarithmic time complexity in every situation. It is also a stable sorting algorithm.
However, there is a requirement of extra space for merge sort that can be considered as a
drawback. Because of these in some cases, Quick Sort proves to be a better choice. In some
special cases, Bucket Sort and Radix Sort are optimal choices because of their less runtime
complexity.

5.When does the worst case occur in Merge Sort?

The worst case of Merge Sort will occur when the number of comparisons is maximum. In Merge
Sort, the number of comparisons between two subarrays is maximum when the subarrays contain
alternate elements of the sorted subarray formed by combining them. For example, comparing {1,
3} and {2, 4} will have the maximum number of comparisons as it has the alternate elements of
the sorted subarray {1, 2, 3, 4}. See the below image to find the arrangement corresponding to a
sorted array which will give the worst case.

6.Can you give me some examples of problems that can be solved by using merge sort?
Merge sort is well-suited for a variety of problems, particularly those involving large or complex
datasets. For instance, it is ideal for sorting large files or datasets that exceed memory capacity,
such as massive log files or big data records, by efficiently handling data in chunks and merging the
results. It is also highly effective for sorting linked lists, where its ability to handle sequential access
makes it a natural choice. Additionally, merge sort’s stability, which preserves the relative order of
records with equal keys, is beneficial for sorting tasks where maintaining the original order of
elements is crucial, such as in sorting employee records by hire date while keeping their
department order intact. Furthermore, merge sort excels in external sorting scenarios, where data
is too large to fit into memory and needs to be managed efficiently across disk storage.
7.What are the advantages of working with sorted data?
a sorted dataset, reducing the search time to O(log n) compared to O(n) in an unsorted dataset.
Sorting also facilitates efficient data management and organization, making it easier to perform tasks
like merging multiple lists, identifying duplicates, or performing range queries. Additionally, sorted
data enhances the performance of other algorithms and operations that rely on order, such as
certain types of optimization problems or statistical analyses. Moreover, sorted data can improve
data presentation and reporting, allowing for clearer and more meaningful insights.
8.What happens if we try to sort all the elements of a linked list at once?
Sorting all elements of a linked list at once presents challenges due to the linked list’s lack of
random access, which makes some sorting algorithms less efficient. For instance, algorithms like
quicksort and heap sort, which rely on direct access to elements, are not well-suited for linked lists.
Instead, merge sort is a preferred choice for linked lists, as it works efficiently by dividing the list into
smaller parts, sorting them, and then merging them back together without needing random access.
Merge sort leverages the sequential nature of linked lists and can sort the list with minimal additional
space. Alternatively, insertion sort can also be effective for linked lists, especially when dealing with
nearly sorted lists.

9.Is merge sort adaptive or not?

Merge sort is generally not considered an adaptive sorting algorithm. Adaptiveness in sorting
algorithms refers to their ability to take advantage of existing order within the dataset to improve
performance. Merge sort has a consistent time complexity of O(n log n) regardless of the initial
order of the elements, meaning it doesn’t adjust its performance based on the degree of pre-
existing order. This is because merge sort always performs a full divide-and-conquer process,
dividing the dataset and merging the sorted halves, irrespective of how sorted or unsorted the
data is.

10. What is the best time for merge sort?


The best time complexity for merge sort is O(n log n). This performance is achieved regardless of the
initial order of the data, whether it is already sorted or completely unsorted. Merge sort consistently
divides the dataset into smaller sublists, sorts these sublists, and then merges them back together
in a way that ensures the entire dataset is sorted. This divide-and-conquer approach results in a time
complexity of O(n log n), where n is the number of elements in the dataset and log n represents the
number of levels in the recursive division. This efficiency makes merge sort a reliable choice for
sorting tasks, offering a stable performance even in the best-case scenario.
Quick Sort

1.What is the Quick Sort algorithm?


Quick Sort is an efficient sorting algorithm that uses a divide-and-conquer strategy to sort
elements in an array. It starts by selecting a "pivot" element and then rearranges the other elements
into two groups: those smaller than the pivot go to its left, and those larger go to its right. This step,
called partitioning, ensures that the pivot is in its correct position in the sorted array. The algorithm
then recursively applies the same process to the sub-arrays on either side of the pivot until all
elements are sorted. Quick Sort is known for its speed, with an average-case time complexity of O(n
log n), making it a popular choice for sorting large datasets. However, its performance can slow down
to O(n²) if the pivot selection is poor.

2.How does QuickSort work?

QuickSort is a divide-and-conquer sorting algorithm that works as follows:


 Choose a pivot element: Select an element from the array as the pivot.
 Partition the array: Rearrange the array such that all elements smaller than the pivot are on
the left side of the pivot, and all elements larger than the pivot are on the right side. The pivot
element is placed in its correct sorted position.
 Recursively sort the two subarrays: Apply QuickSort to the left subarray (elements smaller
than the pivot) and the right subarray (elements larger than the pivot).

3.What do you understand about partitioning in the context of the Quick Sort
algorithm?
The goal of partitioning is to rearrange the elements in such a way that all elements smaller than
the pivot are placed on its left side, and all elements greater than the pivot are placed on its right
side.

Here's how partitioning works:

1. Choosing a Pivot: First, a pivot element is selected from the array. This can be any element,
though the first, last, or middle element is often chosen.
2. Rearranging Elements: The algorithm then scans the array, comparing each element to the
pivot. Elements less than the pivot are swapped to move them towards the left side of the
array, while elements greater than the pivot are moved towards the right side.
3. Final Positioning of the Pivot: After all elements have been compared and placed on the
appropriate side, the pivot is moved to its final position in the array. This position is where
all elements to its left are smaller, and all elements to its right are larger.

4.Is Quick Sort suitable for use on large datasets? Why or why not?

Yes, Quick Sort is generally suitable for use on large datasets, and this is due to several reasons:

1. Efficiency: Quick Sort has an average-case time complexity of O(n log n), which makes it very
efficient for sorting large datasets. This time complexity is comparable to other efficient
sorting algorithms like Merge Sort, but Quick Sort often outperforms them in practice due
to lower overhead and better cache performance.
2. In-Place Sorting: Quick Sort is an in-place sorting algorithm, meaning it requires only a small,
constant amount of additional memory (for the stack space during recursion). This is
particularly advantageous when working with large datasets, as it minimizes the need for
extra memory, unlike some other sorting algorithms like Merge Sort that require additional
space proportional to the size of the input.
3. Versatility: Quick Sort is highly versatile and can be optimized in various ways to suit
different types of data and hardware environments. For example, by choosing a good pivot
selection strategy (like using the median of three elements), the chances of encountering
the worst-case scenario (O(n²) time complexity) can be significantly reduced, even with large
datasets.

5.What are the advantages and disadvantages of using Quick Sort over other
sorting algorithms?
The Quick Sort algorithm has several advantages over other sorting algorithms:
Advantages of QuickSort over other sorting algorithms:
 Efficiency: QuickSort has an average time complexity of O(n log n), which is optimal for most
sorting scenarios.
 In-place sorting: QuickSort sorts the array in-place, meaning it doesn’t require additional
memory space.
 Simplicity: The algorithm is relatively easy to understand and implement.
Disadvantages of QuickSort over other sorting algorithms:
 Worst-case performance: QuickSort has a worst-case time complexity of O(n^2), which
occurs when the array is already sorted or nearly sorted.
 Tail recursion: QuickSort uses tail recursion, which can lead to stack overflow errors for very
large arrays.
 Not stable: QuickSort is not a stable sorting algorithm, meaning it may change the order of
equal elements in the array.

6.What’s the difference between merge sort and quick sort?


The main difference between Merge Sort and Quick Sort is their approach to sorting:
Merge Sort:
 Uses a divide-and-conquer strategy by dividing the array into two halves, sorting each half, and
then merging them.
 Guarantees a time complexity of O(n log n) in all cases.
 Requires additional space for merging the sub-arrays.
Quick Sort:
 Uses a divide-and-conquer strategy by selecting a pivot, partitioning the array based on the
pivot, and then recursively sorting the sub-arrays.
 Has an average time complexity of O(n log n) but can degrade to O(n^2) in the worst case.
 It is an in-place sorting algorithm, meaning it doesn’t require additional space for sorting.

7.What’s the best way to perform the partition step during Quick Sort?
The best way to perform the partition step during Quick Sort is by selecting a good pivot element,
typically the median of the first, middle, and last elements of the array. Using a random pivot is
also a common and effective strategy in Quick Sort. By randomly selecting a pivot element from
the array, you can reduce the likelihood of encountering worst-case scenarios and improve the
overall performance of the algorithm. This approach can help achieve a good balance in
partitioning the array and enhance the efficiency of Quick Sort.

8.What are some ways that Quick Sort could be optimized?


Some ways to optimize Quick Sort include:
 Choosing a good pivot: Selecting a good pivot element, such as the median of three elements,
can improve partitioning and reduce the likelihood of worst-case time complexity.
 Randomized pivot selection: Using a random pivot can help avoid worst-case scenarios and
improve the overall performance of Quick Sort.
 Optimizing the base case: Implementing an alternative sorting algorithm for small sub-arrays
can reduce the overhead of recursion in Quick Sort.

9.When should Quick Sort be used?

Quick Sort is a versatile and efficient sorting algorithm that can be used in a variety of situations. It
is particularly well-suited for the following scenarios:

1. Large Datasets: Quick Sort is often a good choice when dealing with large datasets due to its
average-case time complexity of O(n log n) and its in-place nature, which minimizes memory
usage.
2. When Memory is a Concern: Since Quick Sort is an in-place algorithm, it uses very little
additional memory. This makes it ideal for situations where memory is limited or where you
need to sort large datasets without significant memory overhead.
3. Arrays with Random Data: Quick Sort performs well on data that is randomly ordered. Its
efficiency comes from dividing the array into smaller sub-arrays that are easier to manage,
and it typically outperforms other algorithms like Merge Sort on randomly distributed data
due to lower constant factors.

10.What is the difference between Quick Sort and Heap Sort?

Quick Sort and Heap Sort are both efficient sorting algorithms, but they differ significantly in
their approach and characteristics. Quick Sort uses a divide-and-conquer method, selecting a pivot
element and partitioning the array into two sub-arrays, which are then recursively sorted. It has an
average-case time complexity of O(n log n) but can degrade to O(n²) in the worst case if the pivot
selection leads to unbalanced partitions. Despite this, Quick Sort is often faster in practice due to its
better cache performance and lower overhead. On the other hand, Heap Sort is based on the heap
data structure, where it builds a max heap and repeatedly extracts the maximum element to sort
the array. It consistently operates with a time complexity of O(n log n) in all cases, making it more
predictable.

Threads
1. What is a thread in Java?
A thread is a lightweight process that runs concurrently with other threads. Threads share the same
memory space as the parent process. Threads are used to improve system utilization and responsiveness.
Java supports multithreading through the Thread class. Threads can be created by extending the Thread
class or implementing the Runnable interface.

2. What is thread synchronization?


Thread synchronization is the process of coordinating access to shared resources. Synchronization is used to
prevent data inconsistency and ensure data integrity. Java provides synchronization through the
synchronized keyword and the Lock interface. Synchronization can be used to lock objects or methods.
Synchronization is essential in multithreaded programming.

3. What is the difference between the start() and run() methods?


The start method starts the thread and calls the run method. The run method contains the code to be
executed. The start method returns immediately, while the run method runs concurrently. The start method
is used to start the thread, while the run method is used to execute the code. The start method is called
once, while the run method is called continuously.

4. How do you create a thread in Java?


Threads can be created by extending the Thread class or implementing the Runnable interface. The Thread
class provides a constructor that takes a Runnable object. The Runnable interface has a run method that
contains the code to be executed. The Thread class has a start method that starts the thread. The run
method is called when the thread is started.

5. What is the difference between a process and a thread?


A process is a heavyweight process that runs independently. A thread is a lightweight process that runs
concurrently with other threads. Processes have separate memory spaces, while threads share the same
memory space. Processes are more expensive to create and manage than threads. Threads are used for
concurrent programming, while processes are used for parallel programming.
6. How do you implement thread synchronization in Java?
Thread synchronization in Java is implemented using the synchronized keyword or the Lock interface. The
synchronized keyword is used to lock a method or a block of code, ensuring that only one thread can
execute it at a time. The Lock interface provides more flexibility and features, such as locking and unlocking,
and can be used to implement more complex synchronization logic. Java also provides other
synchronization utilities, such as Semaphores and Monitors, which can be used to implement thread
synchronization. Additionally, Java 8 introduced the java.util.concurrent.locks package, which provides a
range of synchronization utilities, including ReentrantLock and Condition.

7. How do you handle thread interruption in Java?


Thread interruption in Java is handled using the interrupt() method, which sets the interrupt status of the
thread. The isInterrupted() method can be used to check if a thread has been interrupted. When a thread is
interrupted, it can choose to ignore the interruption or terminate its execution. Additionally, the try-catch
block can be used to catch the InterruptedException, which is thrown when a thread is interrupted while
waiting or sleeping.

8. How do you use the ThreadLocal class in Java?


The ThreadLocal class in Java is used to create thread-local variables, which are variables that have a
separate value for each thread. The ThreadLocal class provides a way to store and retrieve values that are
specific to a thread. The set() method is used to set the value of the thread-local variable, and the get()
method is used to retrieve the value. ThreadLocal instances are typically used to store data that is specific to
a thread, such as user ID or transaction ID, and are often used in multi-threaded programming to avoid
shared data issues.

9. What is the difference between a thread's notify() and notifyAll() methods?


The notify() method notifies a single thread that is waiting on a particular object, while the notifyAll()
method notifies all threads that are waiting on the same object. The notify() method is used to wake up a
single thread, whereas the notifyAll() method is used to wake up multiple threads. The notify() method is
typically used when only one thread is waiting for a resource, while the notifyAll() method is used when
multiple threads are waiting for the same resource. Using notifyAll() can help prevent thread starvation,
where a single thread is continuously notified and other threads are left waiting.

10. What is the difference between a daemon thread and a user thread?
A daemon thread runs in the background and is used for system tasks, while a user thread is a normal
thread that runs in the foreground. Daemon threads are used for tasks such as garbage collection and
memory management. User threads are used for tasks that require user interaction. Daemon threads are
typically used for background tasks that do not require user interaction.

11. How do you prioritize threads in Java?


Threads can be prioritized in Java using the setPriority() method and the Thread.NORM_PRIORITY constant.
The priority of a thread can be set to a value between 1 and 10, with higher numbers indicating higher
priority. The default priority of a thread is 5. Prioritizing threads can help ensure that critical threads are
executed promptly.

12. What is a thread group in Java?


A thread group is a collection of threads that can be managed together. Thread groups can be used to group
related threads and perform operations on them as a group. Thread groups can also be used to set the
priority and daemon status of a group of threads. Thread groups are typically used in multi-threaded
programming to simplify thread management.

13. How do you use the join() method in threads?

The join() method is used to wait for a thread to finish execution before continuing with the current thread.
The join() method can be used to ensure that a thread completes its execution before another thread starts.
The join() method can also be used to wait for multiple threads to finish execution. The join() method is
typically used in multi-threaded programming to synchronize the execution of threads.

14. What is a deadlock in Java?

A deadlock is a situation where two or more threads are blocked indefinitely, each waiting for the other to
release a resource. Deadlocks occur when multiple threads are trying to access shared resources and each
thread is holding onto a resource that the other thread needs. Deadlocks can be prevented by using
synchronization techniques such as locking and semaphore. Deadlocks can also be detected using tools such
as Java VisualVM.

15. How do you handle exceptions in threads?


Exceptions in threads can be handled using try-catch blocks and the Thread.UncaughtExceptionHandler
interface. The try-catch block can be used to catch and handle exceptions within a thread. The
Thread.UncaughtExceptionHandler interface can be used to handle uncaught exceptions that are thrown by
a thread. Uncaught exceptions can also be handled by using the setUncaughtExceptionHandler method.

16. What is the difference between a daemon thread and a user thread?

A daemon thread is a thread that runs in the background and is used for system tasks, while a user thread is
a normal thread that runs in the foreground. Daemon threads are used for tasks such as garbage collection
and memory management, while user threads are used for tasks that require user interaction. Daemon
threads are typically used for background tasks that do not require user interaction. User threads are
typically used for tasks that require user interaction and are the main focus of the program.
Enum

1. What is Enum in Java?

 Enumeration (Enum) in Java was introduced in JDK 1.5.

 Most of the other programming languages like C, C++, etc also


provide support for enumerations.

 Enum is a keyword, a feature which is used to represent a fixed


number of well-known values in Java, For example, number of days
in a week.

 Enum constants are implicitly static and final and you can not change
their value once created. In short, enumeration is a list of named
constants.

 Enum in Java provides type-safety and can be used inside switch


statements like int variables.
2. Can Enum extend class in Java?
No, Enum can not extend class since all Enum by default extend abstract
base class java.lang.Enum, obviously they can not extend another class,
because Java doesn’t support multiple inheritance for classes. Because of
extending the java.lang.Enum class, all enums get methods like ordinal(),
values() or valueOf().
3. Can we create an instance of Enum outside of Enum itself?
No, you can not create enum instances outside of Enum boundary,
because Enum doesn’t have any public constructor, and the compiler
doesn’t allow you to provide any public constructor in Enum. Since the
compiler generates a lot of code in response to enum type declaration, it
doesn’t allow public constructors inside Enum, which enforces declaring
enum instances inside Enum itself.
4. Can we use Enum with TreeSet or TreeMap in Java?
Enum implements Comparable interface, which is the main requirement
to be used in Sorted Collection like TreeSet and TreeMap. That’s why
Enum can be safely used inside TreeSet or TreeMap in Java.
5. How do you declare an enum in Java?
An enum is declared using the enum keyword followed by the name of
the enum. The enum constants are defined inside the enum block. Each
constant is separated by a comma. The enum can also have methods and
fields.
6. What are the benefits of using enums in Java?
1. Enum enhances security
2. Enum can be included or excluded from a class.
3. Enum is simple to employ in switch cases
4. Enum cannot extend any class
5. An enum object cannot be created.
6. Enums can have constructors, methods, and variables
7. What is the difference between an enum and a class?
An enum is a special type of class that represents a fixed set of constants.
A class can have multiple instances, but an enum has only one instance
per constant. Enums are implicitly final, but classes are not. Enums have
a fixed set of values, but classes can have any values.
8. How do you use enums in an array?
Enums can be used in an array to restrict the values. Enums can be used
as array elements. Enums can be used in array initialization. Enums can
be used in array methods.
9. How do you use enums in a method parameter?
Enums can be used as method parameters to restrict the input values.
Enums can be used in method overloading. Enums can be used in
method overriding. Enums can be used in constructor parameters.

10. Can you use enums in a constructor?


Yes, enums can be used in a constructor to restrict the input values.
Enums can be used as constructor parameters. Enums can be used in
constructor overloading. Enums can be used in constructor chaining.
11. How do you use enums in a switch statement?
Enums can be used in a switch statement to perform different actions
based on the enum constant. The enum constant is used in the case label.
The switch statement can have a default label. The enum constant can be
used in the switch expression.
12. Can you use enums in an interface?
Yes, enums can be used in an interface. Enums can be defined inside an
interface. Enums can be used as method return types. Enums can be
used as method parameters.
13. Can you use enums in a collection?
Yes, enums can be used in a collection to restrict the values. Enums can
be used as collection elements. Enums can be used in collection methods.
Enums can be used in collection initialization
14. Can you use enums in an annotation?
Yes, enums can be used in an annotation to restrict the values. Enums
can be used as annotation elements. Enums can be used in annotation
methods. Enums can be used in annotation initialization.
15. How can an Enum be created without any instances? Without
compile-time errors, is it possible?

One of the challenging Java interview questions is this one. Having an Enum
without any instances may appear strange because Enum is thought of as a
collection of a well-defined set number of instances, such as Days of the
Week or Months in a Year.

However, it is possible to build Enum in Java without any instances, for


example, to create a utility class. Another creative method to use Enum in
Java is this.

16. Can you use enums in a record?


Yes, enums can be used in a record to restrict the values. Enums can be used as record
components. Enums can be used in record methods. Enums can be used in record
initialization.
17.what is enumeration?
In short it can be called as enum
Enumeration in java is a special data type
It contains set of constants
18. Can the function toString() method for Enum be modified? What
would occur if we didn't?
Naturally, you can override function toString() { [native code] } in Enum because it extends
java.lang like all other classes do.

Even if the function toString() { [native code] }() method on Object is available, you won't
really regret not overriding it because the abstract base class of enum takes care of it and
returns name, which is the name of the enum instance itself.

String Builder and Buffer


1.State the difference between String and StringBuffer.

String objects in Java are immutable and final, so we can't change their value after they are created.
Since strings are commonly used in applications, we need to perform several operations on them
such as substring(), equals(), indexof(), toUppercase(), etc. Each time we manipulate a string, a new
String object is created, and all previous objects will be garbage, placing a strain on the garbage
collector. This is why The Java team developed StringBuffer. A StringBuffer is a mutable object,
meaning it can be changed, but the string is an immutable object, so it cannot be changed once it
has been created.

2. State the difference between StringBuffer and StringBuilder in Java.


StringBuffer and StringBuilder are two Java classes for manipulating strings. These are mutable
objects, i.e., they can be modified, and provide various methods such as insert(), substring(),
delete(), and append(), for String manipulation.

 StringBuffer: The StringBuffer class was created by the Java Team when they realized the need for an
editable string object. Nevertheless, StringBuffer has all methods synchronized, meaning they are thread-
safe. Therefore, StringBuffer allows only one thread to access a method at once, so it is not possible to call
StringBuffer methods from two threads simultaneously, which means it takes more time to access. The
StringBuffer class has synchronized methods, making it thread-safe, slower, and less efficient than
StringBuilder.
 StringBuilder: It was at that point that the Java Team realized that making all methods of StringBuffer
synchronized wasn't the best idea, which led them to introduce StringBuilder. The StringBuilder class has
no synchronized methods. Unlike StringBuffer, StringBuilder does not offer synchronized methods, which
makes it less thread-safe, faster, and more efficient. StringBuilder was introduced in Java 1.5 in response
to StringBuffer's shortcomings.

3. What is the difference between StringBuffer and String class ?

Ans. A string buffer implements a mutable sequence of characters. A string buffer is like a String,
but can be modified. At any point in time it contains some particular sequence of characters, but
the length and content of the sequence can be changed through certain method calls. The String
class represents character strings. All string literals in Java programs, such as "abc" are constant
and implemented as instances of this class; their values cannot be changed after they are
created.

4.what will be the output of this code ?

public static void main(String[] args)


{
StringBuffer s1=new StringBuffer("Buggy");

test(s1);

System.out.println(s1);

private static void test(StringBuffer s){


s.append("Bread");
}

Ans. BuggyBread

5. what will be the output of this code ?

public static void main(String[] args)


{
String s1=new String("Buggy");

test(s1);

System.out.println(s1);

private static void test(StringBuffer s){


s.append("Bread");
}
Ans. Buggy

6. what will be the output of this code ?

public static void main(String[] args)


{
StringBuffer s1=new StringBuffer("Buggy");

test(s1);

System.out.println(s1);

private static void test(StringBuffer s){


s=new StringBuffer("Bread");
}

Ans. Buggy

POINTERS
1. What is a pointer?
Pointer is a variable that stores the address of another variable. The syntax of a pointer is
represented as
Data_Type * Pointer_Name;

An example to understand this syntax:


int *ptr;

2. Describe the usage of pointers in C.


Some of the areas where pointers are used are:
 To access array elements
 Used to return multiple values
 Used in Dynamic memory Allocation
 To pass arguments by reference
 Reduces the execution time of the program
 Pointers help us to build complex data structures like a linked list, stack, queues, trees, and
graphs.
3.How many pointers can point to the same address?
Multiple pointers can point to the same memory address.

4. Where is the pointer variable stored in memory?


Pointer variables are stored in stack memory.

5. What is an array of pointers?


It is an array of the pointer variables. It is also known as pointer arrays.
Declaration:
data_type *name_of_array[array_size];

Example:
int *a[5];

Here “a” is an array of 5 integer pointers.

6.What is the difference between arrays and pointers?


Arrays are used to store elements of same types whereas Pointers are address variables
that store the address of a variable.

7. Is the pointer faster than the array?


Arrays will always be faster as memory allocation of an array is continuous. So accessing
an array is much faster compared to a pointer where memory allocation might or might not
be continuous.
8. What is the size of a generic pointer?
For a system of 16-bit, the size of a generic pointer is 2 bytes. If the system is 32-bit, the
size of a generic pointer is 4 bytes. If the system is 64-bit, the size of a generic pointer is 8
bytes.

9.What are the two ways to pass the data into the function?

Call by value: While calling a function, we pass values of variables to it. Such functions
are known as “Call By Values”.

Call by reference: While calling a function, instead of passing the values of variables, we
pass address of variables(location of variables) to the function known as “Call By
References.

10. What is a dangling pointer in C?


A pointer pointing to a non-existing memory location is a dangling pointer. A dangling
pointer is a pointer that has a value (not NULL) which refers to some memory that is not
valid or does not exists.

11. What is the difference between & and * operators?


& is the address-
of operator, which returns the address of a variable1. * is the dereference ope
rator, which accesses the value at the address stored in a pointer1

12. what are pointers in string give one example?


Pointers in C are used to store the address of another variable, and they can
be used with strings, which are essentially arrays of characters. Pointers are
particularly useful with strings for manipulating and accessing string data effici
ently.

#include <stdio.h>

int main() {

char str[] = "Hello, World!";

char *ptr = str;

// Printing the string using the pointer

printf("String: %s\n", ptr);

// Accessing each character using the pointer

while (*ptr != '\0') {

printf("%c ", *ptr);

ptr++;

return 0;

13.How do you pass pointers to functions?


You pass pointers to functions by specifying the pointer type in the function parameter, e.g
., void func(int *p);

14.How do you dynamically allocate memory using pointers?


You dynamically allocate memory using malloc, calloc, or realloc functions, e.g., int *p = (in
t *)malloc(10 * sizeof(int));

15.What is a null pointer?


A null pointer is a pointer that does not point to any valid memory address, typically repres
ented by NULL or nullptr
16.What are the benefits of using pointers with arrays?

Benefits of using pointers with arrays include efficient access and manipulation of element
s, ability to pass arrays to functions without copying, and dynamic memory allocation.

17.What is the difference between int *p and int (*p)[10]?

int *p is a pointer to an integer, whereas int (*p)[10] is a pointer to an array of 10 integers.

18.What is the relationship between arrays and pointers?

Arrays and pointers are closely related, as an array name acts like a constant pointer to th
e first element of the array.

19. How do you dereference a pointer?

The operator * is used to do this, and is called the dereferencing operator. Dereferencing a
pointer means getting the value, stored in the memory location pointed by the pointer. For
example,

int a=5;

int* p=&a;

printf(“%d”,*p); //dereferencing the pointer p.

20.What is the difference between a null pointer and an


uninitialized pointer?
An uninitialized pointer is one that points to a memory location that isn't known. If we try to
dereference the uninitialized pointer, code behavior will be undefined.
According to C standard, an integer constant expression having the value 0, or such an
expression cast to type void *, is known as a null pointer constant. If you try to dereference
the null pointer then your code will crash.

GIT AND GITHUB


1.What is Git?
 Git is a version control system that lets you manage and keep track of your source
code history.
 It is a free and open-source version control system used to handle small to very
large projects efficiently.
 Git is used to tracking changes in the source code, enabling multiple developers to
work together on non-linear development.

2.What is a Git stand for?


"Global information tracker": you're in a good mood, and it actually works for you.
3. what is github ?
 GitHub is a web-based platform that allows developers to store, share, and
collaborate on code, web pages, and other content.
 Git hub is an hosting service platform.
 On git hub we can store any type of files by creating a repository.and also we
can share the all files using single url to another person.so they can also acess
memory.
 Github encourages teames to work together to build and edit their
document.
4.What is difference between GitHub and Git?

 Git is a version control system that lets you manage and keep track of your
source code history.
 GitHub is a cloud-based hosting service that lets you manage Git
repositories.

5.What is GitHub application used for?


GitHub Apps are tools that extend GitHub's functionality. GitHub Apps can do things
on GitHub like open issues, comment on pull requests, and manage projects. They
can also do things outside of GitHub based on events that happen on GitHub. For
example, a GitHub App can post on Slack when an issue is opened on GitHub.

6.What is GitHub best for?


GitHub is a platform for hosting code that allows for version control and collaboration. It allows
you and others to collaborate on projects from anywhere.

7.What are the steps to be follow to push localhost to github?


1.Create a new repository
2.Open your git bash(we should install)
3.Create your local project in your desktop directed towards a current working directory
4.Intialize the git repository
5.Add the file to the new local repository
6.commit the files staged in your local repository
7.copy your remote repository url from github
8.Add the url copied
9.Push the code in your local repository to github

8.What is fork?
Using fork we can able to clone our code to the local repository.We can do perform any
type of commits.
9.What is Branch?
Branch is the copy of the oritented code.The content stored in a single copy is called
branch.
10.what is pull request?
It will pull repository code from one branch to another branch and it will store the code.
11.What is a Git repository?
A Git repository stores a project's files and revision history and facilitates version control by
tracking changes made over time. It can be located locally within a folder on your device or
an online platform like GitHub. This enables users to collaborate, revert to previous
versions, and efficiently manage project development using commands like commit, push.
12.How does Git work?
Git operates by recording changes made to files and directories in a project, capturing
snapshots of its evolving condition. Users can oversee alterations, create branches for
simultaneous development, merge branches, and revert to previous states if required. It
also promotes collaboration and ensures effective version control in software
development endeavors.

13.What is git add?


The git add command is used in Git to stage changes for inclusion in the next commit. It
prepares modifications, additions, or deletions made to files in the working directory,
marking them to be included in the upcoming commit snapshot. Note this command does
not actually commit the changes but prepares them for staging.
14. What is git status?
The git status command displays the current state of the repository in Git. It provides
information about which files have been modified, which are staged for the next commit,
and which are untracked. It helps users track the progress of their work and identify any
changes that need to be committed or staged.

15.What is a commit in Git?


A commit represents a snapshot of the changes made to files in a repository at a specific
point in time. When you commit changes in Git, you are effectively saving the current state
of your files and can provide a descriptive message that explains the changes made
(which is recommended).Each commit creates a unique identifier, allowing you to track the
history of changes in the repository. Commits play a crucial role in version control, as they
provide a way to revert to previous states of the project, review the history of changes, and
collaborate with others by sharing updates.
16. What is a conflict in Git?
Conflicts arise when conflicting changes are made to the same part of a file or files by
different contributors, typically during a merge or rebase operation. Git cannot
automatically resolve these conflicting changes, requiring manual intervention by the user
to resolve the discrepancies.Thus, to resolve conflicts, the conflicted files must be
reviewed and edited based on the best suited reconciliation before the resolved version is
committed.

17. What is merge in Git?


Merging is a fundamental operation in Git that facilitates collaboration and the integration
of changes across different branches in a project. Namely, a merge is the process of
combining the changes from different branches into a single branch, typically the main
branch (e.g., master or main).merge integrates the changes made in one branch with
another, resulting in a new commit that combines the histories of both branches. You can
learn more about how to resolve merge conflicts in Git with our separate tutorial.

18.What is the difference between git fetch and git pull?


The main difference between git fetch and git pull lies in what they do and how they update
the local repository.The git fetch command retrieves changes from a remote repository to
the local repository. It updates the remote-tracking branches (e.g., origin/master) in the
local repository to reflect the state of the remote repository, but it does not update the
working directory or merge any changes into the current branch. This means that after
fetching, you can review the changes made in the remote repository without affecting your
local work.
The git pull command also retrieves changes from a remote repository, but it goes a step
further by fetching changes and merging them into the current branch in one step. It
essentially performs a git fetch followed by a git merge to incorporate the changes from the
remote repository into the current branch.
19. How do you make an existing Git branch track a remote branch?
To make an existing Git branch track a remote branch, you can use the git branch
command with the --set-upstream-to or -u option, followed by the name of
the remote branch.

20. How do you revert a commit that has already been pushed and made
public?
The git revert <commit-hash> command can be used to revert a commit that has already
been pushed and made public.

The step-by-step process is as follows:


1. Identify the commit you want to revert to by finding its commit hash. This can be done using
the git log command to view the commit history and find the commit hash you want to revert.

2. Once you have the commit hash, use the git revert command followed by the commit hash to
create a new commit that undoes the changes introduced by the specified commit

SDLC
1. What is SDLC?

The Software Development Life Cycle (SDLC) is a well-defined procedure for producing high-
quality, low-cost software in the shortest amount of time possible. The SDLC's purpose is to create
exceptional software that exceeds all customer expectations and demands. The SDLC develops and
describes a detailed plan that includes stages, or phases, each with its own process and deliverables.
It describes the entire development process, including all tasks involved in planning, developing,
testing, and distributing a software product.

2. Explain LLD.

LLD (Low-LevelLevel Design) is a term that refers to the process of detailing. It provides a full
description of each module, including actual logic for each system component and a thorough
examination of each module's specifications. Every program undergoes logic design, which is
subsequently recorded as program specifications. A unit test plan is prepared for each software. The
micro-level or intricate design is another name for it. After the High-Level Design, the Low-Level
Design is created.

3. Explain HLD.

It refers to the general design of the system. It describes the application's overall description and
architecture. It includes a system architecture description, database design, a brief overview of
systems, services, platforms, and module relationships. From the primary module to all submodules,
it creates the overall architecture of the system. Architects will provide the High-Level Design in
order to begin the development process. This is quite helpful for developers in comprehending the
system's flow.

4. What are the disadvantages of the SDLC process?

Before you begin, make sure you understand all of the details of the project. During the
development phase, there was a lot of paperwork. It is difficult to alter or change due to a lack of
flexibility. If the planning isn't done properly, the project will take longer and cost more. When
there are a lot of flaws in the code, fixing them can take a long time and cause deadlines to be
missed.
5. What are the advantages of the SDLC process?

At the end of each stage, a formal review is established to provide for maximum management
oversight. SDLC aids in the creation of extensive system documentation. This guarantees that
system needs can be linked to specified business goals. It generates a large number of intermediate
products that may be evaluated to see if they fit the user's requirements and adhere to industry
standards. These can be improved further if necessary, ensuring that the company receives exactly
what it requires.

6. Which SDLC model is best and Why?

According to the annual State of Agile report, Agile is the best SDLC methodology and also one of
the most widely utilised SDLC in the IT industry. Unlike other predictive approaches, the adaptive
agile methodology does not necessitate comprehensive preparation. If a change is required, it can be
made during the sprint. It's ideal for projects that require a lot of customer involvement and projects
that have a constantly changing environment.

7. What is the testing phase in the SDLC model?


One of the most important procedures in the Software Development Lifecycle is testing (SDLC).
It enables businesses to do a thorough evaluation of software and verify that their product meets
the expectations of their customers. The testing procedures' main purpose is to report, monitor,
troubleshoot, and retest software components until they meet the quality requirements
established in the initial SRS. During the testing phase, there are numerous forms of testing,
including quality assurance testing (QA), system integration testing (SIT), and user acceptability
testing (UAT).
8. What is a Feasibility Study?

As the name implies, a feasibility study is an analysis or measurement of a software product in


terms of how advantageous product development will be for the business in terms of practicality. It
determines whether the project is legally, technically, and commercially feasible.

9. What is SRS?

A Software Requirements Specification (SRS) is a document that explains what the software will
accomplish and how it will work. It is a formal report that serves as a representation of software and
allows customers to assess whether it (SRS) meets their needs. It also outlines the functionality that
the product must have in order to meet the needs of all stakeholders. This report is created after all
requirements have been solicited and analysed, and it serves as a foundation for software
engineering tasks.

10. Explain the types of SDLC models.

 Waterfall model: The waterfall model is a prominent software engineering and product
development approach that takes a linear, sequential approach to the software
development life cycle (SDLC). The waterfall approach emphasises a logical step-by-
step process. It was the first model in the software business to be extensively adopted. It
is divided into phases, with one phase's output becoming the input for the next. Learn
More.
 Agile model: Agile approaches divide jobs into smaller iterations or sections and avoid
long-term planning entirely. The scope and requirements of the project are defined at the
start of the development phase. The number of iterations, duration, and scope of each
iteration are all clearly determined ahead of time. In the Agile process model, each
iteration is a small-time "frame" that lasts anywhere from one to four weeks. Learn More.
 Iterative model: One of the most straightforward software development life cycle models
is the iterative approach. There are several situations when the initial or basic software
requirements are well-defined, but the project's complete scope or set of features is
unclear. It primarily focuses on preliminary growth and design, then gradually develops
momentum as more complex and needs are met until the final software is completely
constructed. Learn More.
 Spiral model: The spiral model is a risk management strategy that combines the
iterative development process model with parts of the Waterfall approach. The spiral
approach is preferred by software engineers for large, expensive, and complex
projects. Learn More.
 V-model model: The V-model is an SDLC paradigm in which processes are executed in
a V-shape in a sequential manner. The Verification and Validation model is another name
for it. The waterfall model is extended by the V-Model. Every phase of the development
cycle has a testing phase that is directly linked to it.

11. Explain the phases in a typical SDLC process briefly.

 Planning: The first stage of the SDLC is all about determining, what do clients want. Project
planning is an important component of the software delivery lifecycle because it is here that the
team estimates the cost and outlines the new program's needs.
 Gathering Requirements: Defining requirements is part of the planning process to figure out what
the application is supposed to perform and what it needs. The development team examines the
requirements while keeping the software's design and code in mind.
 Design: The following phase entails distilling all of the software project's requirements, analysis,
and design information. This phase is the culmination of the previous two, such as customer
feedback and requirement collecting. It is a simulation of how a software application will work.
Some particulars of this phase are architecture, platform, security and user interface.
 Development: This is where the code is really written. Writing code is the first step in putting a
design into action. Developers must adhere to the coding requirements set forth by their bosses.
Many other jobs are included in the coding process. Many developers need to brush up on their
abilities or collaborate with others. It's vital to find and resolve problems and flaws. If any changes
or upgrades are needed, the developers can show the work to the business analysts.
 Testing: Before making an application available to users, it's vital to test it. The testing team
examines the system's overall functionality. This phase aids with reducing the number of faults and
issues seen by consumers. As a result, there is a higher level of user satisfaction and a higher rate of
utilisation.
 Deployment: Once the product has been thoroughly tested and is ready for deployment, it is made
available to customers. The deployment's complexity is determined by the project's size. Many
businesses prefer to have the deployment step automated.
 Maintenance: The developed product is looked after throughout this period. The programme is
updated on a regular basis to keep up with the changing user end environment or technology. Users
find flaws that were not discovered during testing. These issues must be addressed, which may
result in new development cycles.
12. What is the importance of the SDLC process?

 It explains why project planning, scheduling, and budgeting are necessary.


 It allows for some control over the development process in order to guarantee that the
final product meets the original criteria.
 It provides a structure for a standard set of projects and deliverables.
 It helps in the growth process by increasing the visibility of project planning to all involved
parties.
 It assures that the design and testing processes that lead to a solution's release are
good and well-managed.
 It is the most effective method for project management and tracking.
 It aids in the acceleration of development and the improvement of client relationships.
 It aids in the reduction of project risk and overhead in the project administration plan.

13. Briefly describe the RAD model.

The Rapid Application Development (RAD) paradigm is a software development method that relies
on prototyping rather than detailed design. It should be utilised when a system that can be
modularized in two to three months is required. It should be employed if there is a large number of
designers available for modelling and the budget allows for their costs as well as the costs of
automated code generation technologies.

3. Differentiate between quality assurance and quality control?

 Quality Assurance ensures that the software delivered has the fewest possible defects. Quality
Control is the process of ensuring that a product's quality is maintained over time.
 Quality Assurance is handled by the project's testing team, whereas Quality Control is handled by a
dedicated support team that is accountable for the product's quality even if it is in the maintenance
phase of software engineering.

14. What is the main aim of prototyping?

It mainly offers a mini-model of the proposed system.

15. What are the different environments related to development while following
SDLC?

Following environments is used while following SDLC:

 Dev: A development environment is a workspace where developers may make changes without
damaging anything in a live environment. The development environment is frequently referred to as
a workspace for developers.
 SIT/QA: System Integration Testing/ Quality Analysis: In a QA environment, you test your update
operation against data, hardware, and software that closely resembles the production environment,
and you allow intended users to test the outcome.
 UAT: User Acceptance Testing: User acceptance testing (UAT) environments, also known as
staging environments, let the application's primary users try out new features before they're
deployed into production.
 PROD: The "Production" environment, sometimes known as "Live" is where real customers/users
interact with the software product.
16. List Top SDLC tools.

 Jira: This software is intended to make workflow management easier for a wide range of groups.
Jira was created with the intention of being a simple system for recording tasks and errors.
However, it has since matured into a robust workflow management solution.
 Git is a distributed version management system that is open-source. Developers aiming to examine
changes and contributions to the overall code might considerably benefit from a version control
system or VCS. This software customisation management tool is an important part of the SDLC.
 Confluence: During this stage, Confluence is a wonderful tool for developing product research
docs and sharing design assets.
 Asana: From daily activities to larger projects, Asana assists teams in orchestrating their work.
Teams are more confident, move faster, and accomplish more with less when they use Asana,
regardless of where they are based.

17. What is Software Configuration Management, and how does it work?

The process of tracking and regulating changes that occur during the software development
lifecycle is known as software configuration management. Any modification made during the
development of software must be tracked using a well-defined and controlled process. Any
modifications performed during software development are regulated through a well-defined
process, thanks to configuration management. Revision control and the establishment of baselines
are two SCM procedures.

18. What do a Software Project Manager's responsibilities entail?

The Software Project Manager is in charge of seeing the project through to completion. The
Software Project Manager is responsible for ensuring that the entire team follows a methodical and
well-defined approach to software development. They also handle project planning, tracking project
status, resource management, and risk management.

19. What do you know about Scrum impediments?

Obstacles or challenges that the scrum team faces slow down their work speed are referred to
as impediments. An obstacle is anything that tries to prevent the scrum team from getting work
"Done." Impediments can take many different forms. Some of the roadblocks include resource
shortages or sick team members, technical, operational, and organisational issues, a lack of
management support systems, and business issues.

20. Briefly explain Scrum methodology in the Agile model.


Scrum is an agile development approach based on iterative and incremental procedures that are
used in the creation of software. It's an agile structure that's adaptable, rapid, flexible, and
excellent at delivering value to customers throughout the project's development. Companies of
all sizes employ the Agile Scrum technique because of its ability to provide high-end cooperation
and efficiency for project-based work. Scrum is a sort of agile approach that breaks projects
down into manageable parts known as "sprints." The Agile Scrum methodology is ideal for
companies who need to complete projects fast
HTML5
1. What is HTML?

HTML stands for Hypertext Markup Language, the language of the Internet. It is the standard
text formatting language used for creating and displaying pages on the Internet.

HTML documents comprise the elements and the tags that format it for proper page display.

2. What are HTML tags?

We use HTML tags to place the elements in the proper and appropriate format. Tags use the
symbols < and > to set them apart from the HTML content.

The HTML tags need not always be closed. For example, in the case of images, the closing
tags are not required as <img> tags.

3. What are HTML Attributes?

Attributes are the properties that can be added to an HTML tag. These attributes change the
way the tag behaves or is displayed. For example, a <img> tag has an src attribute, which you
use to add the source from which the image should be displayed.

We add attributes right after the name of the HTML tag inside the brackets. We can
only add the attributes to opening or self-closing tags but never to closing tags.

4. What is a marquee in HTML?

Marquee is used for scrolling text on a web page. It automatically scrolls the image or
text up, down, left, or right. You must use </marquee> tags to apply for a marquee.
5. How do you separate a section of text in HTML?

We separate a section of text in HTML using the below tags:

 <br> tag – It separates the line of text. It breaks the current line and shifts the flow of
the text to a new line.

 <p> tag–This tag is used to write a paragraph of text.

 <blockquote> tag–This tag defines large quoted sections.

6. Define the list types in HTML.

The list types in HTML are as follows:

 Ordered list–The ordered list uses <ol> tag and displays elements in a numbered format.

 Unordered list–The unordered list uses <ul> tag and displays elements in a bulleted format.

 Definition list–The definition list uses <dl>, <dt>, <dd> tags and displays elements in
definition form like in a dictionary.

7. How do you align list elements in an HTML file?

We can align the list elements in an HTML file using indents. If you indent each nested
list further than the parent list, you can easily align and determine the various lists and
their elements.

8. Differentiate between an Ordered list and an Unordered list.

An unordered list uses <ul> </ul> tags, and each element of the list is written between
<li> </li> tags. The list items are displayed as bullets rather than numbers.

An ordered list uses <ol> </ol> tags, and each element of the list is written between
<li> </li> tags. The list items are displayed as numbers rather than bullet points.
<!DOCTYPE html>

<html>

<body>

<h2>HTML List Example</h2>

<ul>

<li>Coffee</li>

<li>Tea</li>

<li>Milk</li>

</ul>

<ol>

<li>Coffee</li>

<li>Tea</li>

<li>Milk</li>

</ol>

9).What is an element in HTML?

An element in HTML is a set of tags that define a specific part of a web page. It consists
of a start tag, content, and an end tag.
10. What is the difference between HTML and CSS?

HTML creates a web page's structure and content, while CSS defines its appearance
and layout.

11. Can we display a web page inside a web page or Is nesting of webpages
possible?

Yes, we can display a web page inside another HTML web page. HTML provides a
tag <iframe> using which we can achieve this functionality.

12. What are void elements in HTML?

HTML elements which do not have closing tags or do not need to be closed are Void
elements. For Example <br />, <img />, <hr />, etc.

13. What is the advantage of collapsing white space?

In HTML, a blank sequence of whitespace characters is treated as a single space character,


Because the browser collapses multiple spaces into a single space character and this helps a
developer to indent lines of text without worrying about multiple spaces and maintain
readability and understandability of HTML codes.

14. What are HTML Entities?

In HTML some characters are reserved like ‘<’, ‘>’, ‘/’, etc. To use these characters
in our webpage we need to use the character entities called HTML Entities. Below
are a few mapping between the reserved character and its respective entity
character to be used.

Character Entity Name Entity Number


< &lt; &#60;
> &gt; &#62;
& &amp; &#38;
(non-breaking space) Eg. 10 PM &nbsp; Eg. <p>10&nbsp&nbspPM</p> &#160;

15. . What is the ‘class’ attribute in HTML?

The class attribute is used to specify the class name for an HTML element. Multiple elements
in HTML can have the same class value. Also, it is mainly used to associate the styles written
in the stylesheet with the HTML elements.
16. What is the difference between the ‘id’ attribute and the ‘class’
attribute of HTML elements?

Multiple elements in HTML can have the same class value, whereas a value of id attribute of
one element cannot be associated with another HTML element.

17. Define multipart form data?

Multipart form data is one of the values of the enctype attribute. It is used to send the file
data to the server-side for processing. The other valid values of the enctype attribute are
text/plain and application/x-www-form-urlencoded.

18. Describe HTML layout structure.

Every web page has different components to display the intended content and a specific UI.
But still, there are few things which are templated and are globally accepted way to structure
the web page, such as:

 <header>: Stores the starting information about the web page.


 <footer>: Represents the last section of the page.
 <nav>: The navigation menu of the HTML page.
 <article>: It is a set of information.
 <section>: It is used inside the article block to define the basic structure of a page.
 <aside>: Sidebar content of the page.

19. How to optimize website assets loading?

To optimize website load time we need to optimize its asset loading and for that:

 CDN hosting - A CDN or content delivery network is geographically distributed servers to help reduce
latency.
 File compression - This is a method that helps to reduce the size of an asset to reduce the data
transfer
 File concatenation - This reduces the number of HTTP calls
 Minify scripts - This reduces the overall file size of js and CSS files
 Parallel downloads - Hosting assets in multiple subdomains can help to bypass the download limit of
6 assets per domain of all modern browsers. This can be configured but most general users never
modify these settings.
 Lazy Loading - Instead of loading all the assets at once, the non-critical assets can be loaded on a
need basis.
20. What are the various formatting tags in HTML?

HTML has various formatting tags:

 <b> - makes text bold


 <i> - makes text italic
 <em> - makes text italic but with added semantics importance
 <big> - increases the font size of the text by one unit
 <small> - decreases the font size of the text by one unit
 <sub> - makes the text a subscript
 <sup> - makes the text a superscript
 <del> - displays as strike out text
 <strong> - marks the text as important
 <mark> - highlights the text
 <ins> - displays as added text

21. What are the different kinds of Doctypes available?

The three kinds of Doctypes which are available:

 Strict Doctype
 Transitional Doctype
 Frameset Doctype

22. Please explain how to indicate the character set being used by a
document in HTML?

The character set is defined in <meta> tag inside <head> element.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">

...
...
</head>
...
</html>
23. What is the difference between <strong>, <b> tags and <em>, <i> tags?

The effect on a normal webpage of the tags <strong>, <b> and <em>, <i> is the same. <b>
and <i> tags stands for bold and italic. These two tags only apply font styling and bold tag
<b>, just adds more ink to the text, these tags don't say anything about the text.

Whereas, <strong> and <em> tags represent that the span of text is of strong importance
or more importance and emphatic stress respectively than the rest of the text. These tags
have semantic meaning.

24. What is the significance of <head> and <body> tag in HTML?

<head> tag provides the information about the document. It should always be enclosed in the
<html> tag. This tag contains the metadata about the webpage and the tags which are
enclosed by head tag like <link>, <meta>, <style>, <script>, etc. are not displayed on the
web page. Also, there can be only 1 <head> tag in the entire Html document and will always
be before the <body> tag.

<body> tag defines the body of the HTML document. It should always be enclosed in the
<html> tag. All the contents which needs to be displayed on the web page like images, text,
audio, video, contents, using elements like <p>, <img>, <audio>, <heading>, <video>,
<div>, etc. will always be enclosed by the <body> tag. Also, there can be only 1 body
element in an HTML document and will always be after the <head> tag.

25. Are the HTML tags and elements the same thing?

No. HTML elements are defined by a starting tag, may contain some content and a closing
tag.For example, <h1>Heading 1</h1> is a HTML element but just <h1> is a starting tag and
</h1> is a closing tag.

26. How is Cell Padding different from Cell Spacing?

Cell Spacing is the space or gap between two consecutive cells. Whereas, Cell Padding is the
space or gap between the text/ content of the cell and the edge/ border of the cell. Please
refer to the above figure example to find the difference.

27. How can we club two or more rows or columns into a single row or
column in an HTML table?

HTML provides two table attributes “rowspan” and “colspan” to make a cell span to multiple
rows and columns respectively.

28. Is it possible to change an inline element into a block level element?

Yes, it is possible using the “display” property with its value as “block”, to change the inline
element into a block-level element.
29. In how many ways can we position an HTML element? Or what are
the permissible values of the position attribute?

There are mainly 7 values of position attribute that can be used to position an HTML
element:

1. static: Default value. Here the element is positioned according to the normal flow of the
document.
2. absolute: Here the element is positioned relative to its parent element. The final position is
determined by the values of left, right, top, bottom.
3. fixed: This is similar to absolute except here the elements are positioned relative to the
<html> element.
4. relative: Here the element is positioned according to the normal flow of the document and
positioned relative to its original/ normal position.
5. initial: This resets the property to its default value.
6. inherit: Here the element inherits or takes the property of its parent.

30. In how many ways you can display HTML elements?

1. inline: Using this we can display any block-level element as an inline element. The height
and width attribute values of the element will not affect.
2. block: using this, we can display any inline element as a block-level element.
3. inline-block: This property is similar to inline, except by using the display as inline-block, we
can actually format the element using height and width values.
4. flex: It displays the container and element as a flexible structure. It follows flexbox property.
5. inline-flex: It displays the flex container as an inline element while its content follows the
flexbox properties.
6. grid: It displays the HTML elements as a grid container.
7. none: Using this property we can hide the HTML element.

Below are some of the display types which are rarely used:

1. table
2. inline-table
3. table-cell
4. table-column
5. table-row
6. inline-grid
7. list-item
8. inherit
9. initial
10. table-caption

31. What is the difference between “display: none” and “visibility: hidden”,
when used as attributes to the HTML element.

When we use the attribute “visibility: hidden” for an HTML element then that element will
be hidden from the webpage but still takes up space. Whereas, if we use the “display:
none” attribute for an HTML element then the element will be hidden, and also it won’t
take up any space on the webpage.
32. How to specify the link in HTML and explain the target attribute?

HTML provides a hyperlink - <a> tag to specify the links in a webpage. The ‘href’
attribute is used to specify the link and the ‘target’ attribute is used to specify, where do
we want to open the linked document. The ‘target’ attribute can have the following
values:

1. _self: This is a default value. It opens the document in the same window or tab as it
was clicked.
2. _blank: It opens the document in a new window or tab.
3. _parent: It opens the document in a parent frame.
4. _top: It opens the document in a full-body window.

33. Difference between link tag <link> and anchor tag <a>?

The anchor tag <a> is used to create a hyperlink to another webpage or to a certain part
of the webpage and these links are clickable, whereas, link tag <link> defines a link
between a document and an external resource and these are not clickable.

34. When to use scripts in the head and when to use scripts in the body?

If the scripts contain some event-triggered functions or jquery library then we should use
them in the head section. If the script writes the content on the page or is not inside a
function then it should be placed inside the body section at the bottom. In short, follow
below three points:

1. Place library scripts or event scripts in the head section.


2. Place normal scripts that do not write anything on the page, in the head section until
there is any performance issue.
3. Place scripts that render something on the web page at the bottom of the body section.

CSS 3

1. What is CSS?
Cascading Style Sheets fondly referred to as CSS, is a simply designed language intended
to simplify the process of making web pages presentable. CSS allows you to apply styles to
web pages

2. Why do we use CSS?


We use CSS because of the following reasons:
 CSS saves time: You can write CSS once and reuse the same sheet on multiple HTML
pages.
 Easy Maintenance: To make a global change simply change the style, and all elements
in all the webpages will be updated automatically.
 Search Engines: CSS is considered a clean coding technique, which means search
engines won’t have to struggle to “read” its content.
 Superior styles to HTML: CSS has a much wider array of attributes than HTML, so you
can give a far better look to your HTML page in comparison to HTML attributes.
 Offline Browsing: CSS can store web applications locally with the help of an offline
cache. Using of this we can view offline websites.

3. What is the syntax for CSS?

A CSS style rule consists of a selector, property, and its value. The selector points to the HTML
element where CSS style is to be applied. The CSS property is separated by semicolons.
Syntax:
selector {
Property: value;
}

4. In how many ways can we add CSS to our HTML file?


Cascading Style Sheet(CSS) is used to set the style in web pages that contain HTML
elements. It sets the background color, font size, font family, color, … etc properties
of elements on a web page.
There are three types of CSS which are given below:
 Inline CSS
 Internal or Embedded CSS
 External CSS
5. What are CSS Selectors?

CSS Selectors: CSS Selectors are used to selecting HTML elements based on their element
name, id, attributes, etc. It can select one or more elements simultaneously.
element selector: The element selector in CSS is used to select HTML elements which are
required to be styled. In a selector declaration, there is the name of the HTML element, and
the CSS properties which are to be applied to that element is written inside the brackets {}.
Syntax:
element_name {
// CSS Property
}
id selector: The #id selector is used to set the style of the given id. The id attribute is the
unique identifier in an HTML document. The id selector is used with a # character.
Syntax:
#id_name {
// CSS Property
}
class selector: The .class selector is used to select all elements which belong to a particular
class attribute. To select the elements with a particular class, use the (.) character with
specifying the class name. The class name is mostly used to set the CSS property to the given
class.
Syntax:
.class_name {
CSS
// Property
}
6. What are CSS HSL Colors?
 HSL: HSL stands for Hue, Saturation, and Lightness respectively. This format
uses the cylindrical coordinate system.
 Hue: Hue is the degree of the color wheel. Its value lies between 0 to 360 where 0
represents red, 120 represents green and 240 represents a blue color.
 Saturation: It takes a percentage value, where 100% represents completely
saturated, while 0% represents completely unsaturated (gray).
 Lightness: It takes a percentage value, where 100% represents white, while 0%
represents black.

7. What are CSS backgrounds, list the properties?


The CSS background properties are used to define the background effects for elements.
CSS background properties are as follows:
1. background-color: This property specifies the background color of an element.
2. background-image: This property specifies an image to use as the background of an
element. By default, the image is repeated so it covers the entire element.
3. background-repeat: By default, the background image property repeats the
image both horizontally and vertically.
4. background-attachment: This property is used to fix the background ground
image. The image will not scroll with the page.
5. background-position: This property is used to set the image to a particular
position.

8. What are the different CSS border properties?


CSS border properties allow us to set the style, color, and width of the border.
 Border Style: The border-style property specifies the type of border. None of the other
border properties will work without setting the border style.
 Border Width: Border width sets the width of the border. The width of the border can
be in px, pt, cm or thin, medium and thick.
 Border Color: This property is used to set the color of the border. Color can be set using
the color name, hex value, or RGB value. If the color is not specified border inherits the
color of the element itself.

9. What does margin: 40px 100px 120px 80px signify?


CSS margins are used to create space around the element. We can set the different sizes
of margins for individual sides (top, right, bottom, left).
Margin properties can have the following values:
1. Length in cm, px, pt, etc.
2. Width % of the element.
3. Margin calculated by the browser: auto. Therefore,
margin: 40px 100px 120px 80px signifies:
1. top = 40px
2. right = 100px
3. bottom = 120px
4. left = 80px

10. What is the difference between margin and padding?


 Margin is used to create space around elements and padding is used to create space
around elements inside the border.
 We can set the margin property to auto but we cannot set the padding property to
auto.
 In Margin property we can allow negative or float number but in padding we
cannot allow negative values.
 Margin and padding target all the 4 sides of the element. Margin and padding will work
without the border property also. The difference will be more clear with the following
example.
11. What is CSS Box Model?
The CSS box model is a container that contains multiple properties including borders,
margin, padding, and the content itself. It is used to create the design and layout of web
pages. It can be used as a toolkit for customizing the layout of different elements. The web
browser renders every element as a rectangular box according to the CSS box model.
Box-Model has multiple properties in CSS. Some of them are given below:
 borders
 margins
 padding
 Content
12. What is the difference between CSS border and outline?
 CSS border properties allow us to set the style, color, and width of the border.
 CSS outline property allows us to draw a line around the element, outside the
border.
13. How can we format text in CSS?
CSS text formatting properties are used to format text and style text. CSS text
formatting includes the following properties:
1. Text-color
2. Text-alignment
3. Text-decoration
4. Text-transformation
5. Text-indentation
6. Letter spacing
7. Line height
8. Text-direction
9. Text-shadow
10. Word spacing

14. Can we add an image as a list item marker?


To add an image as the list-item marker in a list, we use the list-style- image
property in CSS.
Syntax:
list-style-image: none | url | initial | inherit;

15. How can we hide an element in CSS?


The style display property is used to hide and show the content of HTML DOM by
accessing the DOM element using JavaScript/jQuery.
To hide an element, set the style display property to “none”.
display: "none";
To show an element, set the style display property to “block”.
display:"block";
16. Name some CSS frameworks.

CSS frameworks are libraries that make web page styling easier. Some of them are
Foundation, Bootstrap, Gumby, Ukit, Semantic UI, etc.

17. What do you understand by the universal sector?

A universal selector is a selector that matches any element type's name instead of selecting
elements of a particular type.

Example:

<style>

*{

color: blue;

font-size: 10px;

</style>

18. Tell us about the use of the ruleset.

The ruleset is used for the identification of selectors, which can be attached with other
selectors. The two parts of a ruleset are:

 Declaration block: contains one or more semicolon-separated declarations

 Sector: indicates the HTML element needed to be styled

19. What are the elements of the CSS Box Model?

The CSS box model defines the layout and design of CSS elements. The elements are
content (like text and images, padding (the area around content), border (the area around
padding), and margin (the area around the border).
20. Differentiate between CSS3 and CSS2.

The main difference between CSS3 and CSS2 is that CSS divides different sections into
modules and supports many browsers. It also contains new General Sibling Combinators
responsible for matching similar elements.

21. How can CSS be integrated into an HTML page?

There are three ways of integrating CSS into HTML: using style tags in the head section, using
inline-styling, writing CSS in a separate file, and linking into the HTML page by the link tag.

22. Explain a few advantages of CSS.

With CSS, different documents can be controlled using a single site, styles can be grouped
in complex situations using selectors and grouping methods, and multiple HTML elements
can have classes.

23. What is meant by RGB stream?

RGB represents colors in CSS. The three streams are namely Red, Green, and Blue. The
intensity of colors is represented using numbers 0 to 256. This allows CSS to have a
spectrum of visible colors.

24. What was the purpose of developing CSS?

CSS was developed to define the visual appearances of websites. It allows developers to
separate the structure and content of a website that was not possible before.

25. What is the difference between a class and an ID?

Ans. Class is a way of using HTML elements for styling. They are not unique and have
multiple elements. Whereas ID is unique and it can be assigned to a single element
26. How can you target h3 and h2 with the same styling?

Multiple elements can be targeted by separating with a comma: h2, h3

{color: red;}

27. How can you use CSS to control image repetition?

The background-repeat property is used to control the image. Example: h3 {

background-repeat: none;

28. How to include CSS in the webpage?

1. With the help of a link tag, you can include an external style sheet file as a CSS file into your
HTML file.

2. You can add CSS styles included within your HTML page and write it in the stand-alone
stylesheet form of CSS.

3. CSS can be included directly in the HTML tag by adding an inline style to HTML
elements.

4. One can import an external stylesheet file as a new CSS file by using the @import rule.

29. What is the difference between inline, inline-block, and block?

1. Block Elements are <div> and <p>. They usually start on a new line and can take space for an
entire row or width.

2. Inline elements are <a>, <span>, <strong>, and <img> tags. They don't start on a new line.
However, they appear on the same line as the content and tags beside them.

3. Inline block elements have padding and margins and set height and width values.
Though, they are similar to inline elements.
30. Does margin-top or margin-bottom have an effect on inline elements?

No, mMargin-top or margin-bottom does not have an effect on the inline elements.

31. What property is used for changing the font face?

The font-family property is used for changing the font face that is applied to the
element in the DOM.

32. What are the differences between adaptive design and responsive
design?

 Adaptive Design:

 Main focus is to develop a website in multiple fixed layout sizes.

 Offers good control over the design to develop variation in screens.

 It is very time-consuming and takes a lot of effort to build the best possible adaptive design
as examining it will need to go for many options with respect to the realities of the end user.

 There are six standard screen sizes for the appropriate layouts; they are 320px, 480px,
760px, 960px, 1200px, 1600px to design.

 Responsive Design

 Main focus is to show content with respect to browser space.

 Offers less control over the design.

 It takes less time to build the design and there is no screen size issue irrespective of
content.

 It uses CSS media queries to design the screen layouts with respect to specific devices and
property changes in the screen.

JAVASCRIPT

1. What do you understand about JavaScript?

JavaScript is a popular web scripting language used for client-side and server-side
development. Its code can be inserted into HTML pages and understood and
executed by web browsers. JavaScript also supports object-oriented programming
abilities.

2. What’s the difference between JavaScript and Java?

JavaScript Java

Java is an object-oriented
JavaScript is an object-oriented scripting language.
programming language.

Java applications are generally


JavaScript applications are meant to run inside a web
made for use in operating
browser.
systems and virtual machines.

Java source code needs a


JavaScript does not need compilation before running
compiler before it can be ready
the application code.
to run in realtime.

3. What are the various data types that exist in JavaScript?

These are the different types of data that JavaScript supports:

 Boolean - For true and false values

 Null - For empty or unknown values

 Undefined - For variables that are only declared and not defined or initialized
 Number - For integer and floating-point numbers

 String - For characters and alphanumeric values

 Object - For collections or complex values

 Symbols - For unique identifiers for objects

4. What are the features of JavaScript?

These are the features of JavaScript:

 Lightweight, interpreted programming language

 Cross-platform compatible

 Open-source

 Object-oriented

 Integration with other backend and frontend technologies

 Used especially for the development of network-based applications.

5. What are the advantages of JavaScript over other web technologies?

These are the advantages of JavaScript:

Enhanced Interaction

JavaScript adds interaction to otherwise static web pages and makes them react to
users’ inputs.

Quick Feedback

There is no need for a web page to reload when running JavaScript. For example,
form input validation.

Rich User Interface

JavaScript helps in making the UI of web applications look and feel much better.

Frameworks

JavaScript has countless frameworks and libraries that are extensively used for
developing web applications and games of all kinds.
6. How do you create an object in JavaScript?

Since JavaScript is essentially an object-oriented scripting language, it supports and


encourages the usage of objects while developing web applications.

const student = {

name: 'John',

age: 17

7. How do you create an array in JavaScript?

Here is a very simple way of creating arrays in JavaScript using the array literal:

var a = [];

var b = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’];

8. What are some of the built-in methods in JavaScript?

Built-in Method Values


Returns the present date and
Date()
time

Joins two strings and returns the


concat()
new string

push() Adds an item to an array

Removes and also returns the


pop()
last element of an array

Rounds of the value to the


round() nearest integer and then returns
it

length() Returns the length of a string

9.What are the scopes of a variable in JavaScript?

The scope of a variable implies where the variable has been declared or defined in a
JavaScript program. There are two scopes of a variable:
Global Scope

Global variables, having global scope are available everywhere in a JavaScript code.

Local Scope

Local variables are accessible only within a function in which they are defined.

10. What is the ‘this’ keyword in JavaScript?

The ‘this’ keyword in JavaScript refers to the currently calling object. It is commonly
used in constructors to assign values to object properties.

11. What are the conventions of naming a variable in JavaScript?

Following are the naming conventions for a variable in JavaScript:

 Variable names cannot be similar to that of reserved keywords. For example, var, let,
const, etc.

 Variable names cannot begin with a numeric value. They must only begin with a letter or
an underscore character.

 Variable names are case-sensitive.

12. What is Callback in JavaScript?

In JavaScript, functions are objects and therefore, functions can take other functions
as arguments and can also be returned by other functions.

Fig: Callback function

A callback is a JavaScript function that is passed to another function as an argument


or a parameter. This function is to be executed whenever the function that it is
passed to gets executed.
13. How do you debug a JavaScript code?

All modern web browsers, such as Chrome, Firefox, etc., have an inbuilt debugger
that can be accessed anytime by pressing the relevant key, usually the F12 key. The
debugging tools offer several features.

We can also debug JavaScript code inside a code editor that we use to develop a

14. What is the difference between Function declaration and Function expression?

Function declaration Function expression

Declared as a separate statement within the main JavaScript Created inside an expression or
code some other construct

Created when the execution point


Can be called before the function is defined reaches it; can be used only after
that

Used when there is a need for a


Offers better code readability and better code organization
conditional declaration of a function

Example: Example:

function abc() { var a = function abc() {


return 5; return 5;

} }

15. What are the ways of adding JavaScript code in an HTML file?

There are primarily two ways of embedding JavaScript code:

 We can write JavaScript code within the script tag in the same HTML file; this is suitable
when we need just a few lines of scripting within a web page.

 We can import a JavaScript source file into an HTML document; this adds all scripting
capabilities to a web page without cluttering the code.

16. What do you understand about cookies?

Fig: Browser cookies

A cookie is generally a small data that is sent from a website and stored on the
user’s machine by a web browser that was used to access the website. Cookies are
used to remember information for later use and also to record the browsing activity
on a website.

17. How would you create a cookie?

The simplest way of creating a cookie using JavaScript is as below:


document.cookie = "key1 = value1; key2 = value2; expires = date";

18. How would you read a cookie?

Reading a cookie using JavaScript is also very simple. We can use the
document.cookie string that contains the cookies that we just created using that
string.

The document.cookie string keeps a list of name-value pairs separated by


semicolons, where ‘name’ is the name of the cookie, and ‘value’ is its value. We can
also use the split() method to break the cookie value into keys and values.

19. How would you delete a cookie?

To delete a cookie, we can just set an expiration date and time. Specifying the
correct path of the cookie that we want to delete is a good practice since some
browsers won’t allow the deletion of cookies unless there is a clear path that tells
which cookie to delete from the user’s machine.

function delete_cookie(name) {

document.cookie = name + "=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;";

20. What are the different ways an HTML element can be accessed in a JavaScript
code?

Here are the ways an HTML element can be accessed in a JavaScript code:

 getElementByClass(‘classname’): Gets all the HTML elements that have the specified
classname.

 getElementById(‘idname’): Gets an HTML element by its ID name.

 getElementbyTagName(‘tagname’): Gets all the HTML elements that have the specified
tagname.

 querySelector(): Takes CSS style selector and returns the first selected HTML element.

21. What are the ways of defining a variable in JavaScript?

There are three ways of defining a variable in JavaScript:


Var

This is used to declare a variable and the value can be changed at a later time within
the JavaScript code.

Const

We can also use this to declare/define a variable but the value, as the name implies,
is constant throughout the JavaScript program and cannot be modified at a later
time.

Let

This mostly implies that the values can be changed at a later time within the
JavaScript code.

22. What are some of the JavaScript frameworks and their uses?

JavaScript has a collection of many frameworks that aim towards fulfilling the
different aspects of the web application development process. Some of the
prominent frameworks are:

 React - Frontend development of a web application

 Angular - Frontend development of a web application

 Node - Backend or server-side development of a web application

23. Why do we use the word “debugger” in javascript?

The debugger for the browser must be activated in order to debug the code. Built-in
debuggers may be switched on and off, requiring the user to report faults. The remaining
section of the code should stop execution before moving on to the next line while debugging.

24. Difference between “ == “ and “ === “ operators.

Both are comparison operators. The difference between both the operators is that “==” is
used to compare values whereas, “ === “ is used to compare both values and types.

Example:

var x = 2;
var y = "2";
(x == y) // Returns true since the value of both x and y is the same
(x === y) // Returns false since the typeof x is "number" and typeof y is
"string"
25. Difference between var and let keyword in javascript.

Some differences are

1. From the very beginning, the 'var' keyword was used in JavaScript programming whereas the
keyword 'let' was just added in 2015.
2. The keyword 'Var' has a function scope. Anywhere in the function, the variable specified
using var is accessible but in ‘let’ the scope of a variable declared with the 'let' keyword is
limited to the block in which it is declared. Let's start with a Block Scope.
3. In ECMAScript 2015, let and const are hoisted but not initialized. Referencing the variable in
the block before the variable declaration results in a ReferenceError because the variable is
in a "temporal dead zone" from the start of the block until the declaration is processed.

26. Is javascript a statically typed or a dynamically typed language?

JavaScript is a dynamically typed language. In a dynamically typed language, the type of a


variable is checked during run-time in contrast to a statically typed language, where the type
of a variable is checked during compile-time.

27.What is NaN property in JavaScript?

NaN property represents the “Not-a-Number” value. It indicates a value that is not a legal
number.

typeof of NaN will return a Number.

To check if a value is NaN, we use the isNaN() function,

Note- isNaN() function converts the given value to a Number type, and then equates to NaN.

28. Explain passed by value and passed by reference.

In JavaScript, primitive data types are passed by value and non-primitive data types
are passed by reference.

For understanding passed by value and passed by reference, we need to understand what
happens when we create a variable and assign a value to it,

var x = 2;
In the above example, we created a variable x and assigned it a value of “2”. In the
background, the “=” (assign operator) allocates some space in the memory, stores the value
“2” and returns the location of the allocated memory space. Therefore, the variable x in the
above code points to the location of the memory space instead of pointing to the value 2
directly.

Assign operator behaves differently when dealing with primitive and non-primitive data
types.

29. What do you mean by strict mode in javascript and characteristics of javascript strict-
mode?

In ECMAScript 5, a new feature called JavaScript Strict Mode allows you to write a code or a
function in a "strict" operational environment. In most cases, this language is 'not particularly
severe' when it comes to throwing errors. In 'Strict mode,' however, all forms of errors,
including silent errors, will be thrown. As a result, debugging becomes a lot simpler. Thus
programmer's chances of making an error are lowered.

Characteristics of strict mode in javascript

1. Duplicate arguments are not allowed by developers.


2. In strict mode, you won't be able to use the JavaScript keyword as a parameter or function
name.
3. The 'use strict' keyword is used to define strict mode at the start of the script. Strict mode is
supported by all browsers.
4. Engineers will not be allowed to create global variables in 'Strict Mode.

30. Explain Higher Order Functions in javascript.

Functions that operate on other functions, either by taking them as arguments or by


returning them, are called higher-order functions.

Higher-order functions are a result of functions being first-class citizens in javascript.

Examples of higher-order functions:

function higherOrder(fn) {
fn();
}

higherOrder(function() { console.log("Hello world") });


function higherOrder2() {
return function() {
return "Do something";
}
}
var x = higherOrder2();
x() // Returns "Do something"
31.What do you mean by Self Invoking Functions?

Without being requested, a self-invoking expression is automatically invoked (initiated). If a


function expression is followed by (), it will execute automatically. A function declaration
cannot be invoked by itself.

Normally, we declare a function and call it, however, anonymous functions may be used to
run a function automatically when it is described and will not be called again. And there is no
name for these kinds of functions.

32. What is currying in JavaScript?

Currying is an advanced technique to transform a function of arguments n, to n


functions of one or fewer arguments.

33. Explain Scope and Scope Chain in javascript.

Scope in JS determines the accessibility of variables and functions at various parts of one’s
code.

In general terms, the scope will let us know at a given part of code, what are variables and
functions we can or cannot access.

There are three types of scopes in JS:

 Global Scope
 Local or Function Scope
 Block Scope

Global Scope: Variables or functions declared in the global namespace have global scope,
which means all the variables and functions having global scope can be accessed from
anywhere inside the code.

Function Scope: Any variables or functions declared inside a function have


local/function scope, which means that all the variables and functions declared
inside a function, can be accessed from within the function and not outside of it.

Block Scope: Block scope is related to the variables declared using let and const.
Variables declared with var do not have block scope. Block scope tells us that any
variable declared inside a block { }, can be accessed only inside that block and
cannot be accessed outside of it.

Scope Chain: JavaScript engine also uses Scope to find variables

34. Mention some advantages of javascript.

There are many advantages of javascript. Some of them are


1. Javascript is executed on the client-side as well as server-side also. There are a variety of
Frontend Frameworks that you may study and utilize. However, if you want to use JavaScript
on the backend, you'll need to learn NodeJS. It is currently the only JavaScript framework
that may be used on the backend.
2. Javascript is a simple language to learn.
3. Web pages now have more functionality because of Javascript.
4. To the end-user, Javascript is quite quick

35. What are callbacks?

A callback is a function that will be executed after another function gets executed. In
javascript, functions are treated as first-class citizens, they can be used as an argument of
another function, can be returned by another function, and can be used as a property of an
object.

36.What is memoization?

Memoization is a form of caching where the return value of a function is cached based on its
parameters. If the parameter of that function is not changed, the cached version of the
function is returned.

37. What is the use of a constructor function in javascript?

Constructor functions are used to create objects in javascript.

When do we use constructor functions?

If we want to create multiple objects having similar properties and methods, constructor
functions are used.

Note- The name of a constructor function should always be written in Pascal Notation: every word
should start with a capital letter.

38. What is DOM?

 DOM stands for Document Object Model. DOM is a programming interface for HTML and XML
documents.
 When the browser tries to render an HTML document, it creates an object based on the HTML
document called DOM. Using this DOM, we can manipulate or change various elements inside the
HTML document.

39. Which method is used to retrieve a character from a certain index?

The charAt() function of the JavaScript string finds a char element at the supplied index. The
index number begins at 0 and continues up to n-1, Here n is the string length. The index value
must be positive, higher than, or the same as the string length.
40. What do you mean by BOM?

Browser Object Model is known as BOM. It allows users to interact with the browser. A
browser's initial object is a window. As a result, you may call all of the window's functions
directly or by referencing the window. The document, history, screen, navigator, location,
and other attributes are available in the window object.

41. What is the distinction between client-side and server-side JavaScript?

Client-side JavaScript is made up of two parts, a fundamental language and predefined


objects for performing JavaScript in a browser. JavaScript for the client is automatically
included in the HTML pages. At runtime, the browser understands this script.

42. What is the real name of JavaScript?


The original name was Mocha, a name chosen by Marc Andreessen, founder of Netscape. In
September of 1995, the name was changed to LiveScript. In December 1995, after receiving a
trademark license from Sun, the name JavaScript was adopted.

43. What is the difference between undefined value and null value?
Undefined value: A value that is not defined and has no keyword is known as undefined value.

Null value: A value that is explicitly specified by the keyword "null" is known as a null value.

You might also like