Java Interview Questions(J2SE)
Java Interview Questions(J2SE)
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.
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.
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 Interpreted: Java uses the Just-in-time (JIT) interpreter along with the
compiler for the program execution.
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.
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:
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.
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.
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.
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.
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.
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?
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.
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 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.
There are the following basic differences between the object-oriented language
and object-based language.
21. What will be the initial value of an object reference which is defined
as an instance variable?
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.
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.
yes, The constructor implicitly returns the current instance of the class (You can't use an explicit
return type with the constructor)
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.
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 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.
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.
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.
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.
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. }
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?
2)We don't need to create the objects to call the The object is required to call
static methods. the instance methods.
4)For example: public static int cube(int n){ For example: public void
return n*n*n;} msg(){...}.
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.
o Single-level inheritance
o Multi-level inheritance
o Multiple Inheritance
o Hierarchical Inheritance
o Hybrid Inheritance
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.
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.
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.
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.
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.
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.
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.
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.
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:
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.
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
No, We cannot overload the methods by just applying the static keyword to
them(number of parameters and types are the same).
Yes, we can have any number of main methods in a Java program by using method
overloading.
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.
o No, you can't override the static method because they are the part of the class,
not the object.
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.
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.
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 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.
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.
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
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.
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.
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.
No, because methods of an interface are abstract by default, and we can not use static
and abstract together.
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?
An abstract class can have a method body The interface has only abstract methods.
(non-abstract methods).
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.
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();
} }
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?
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.
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.
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
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.
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.
There are the following differences between the process and thread.
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.
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.
Java supports primitive data types - byte, boolean, char, short, int,
float, long, and double and hence it is not a pure object oriented
language.
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.
The heap is created when the JVM starts up and may increase or decrease in size while the
application runs
2) The Iterator can be used in List, ListIterator can be used in List only.
Set, and Queue.
1) The Iterator can traverse legacy and Enumeration can traverse only
non-legacy elements. legacy elements.
4) The Iterator can perform remove The Enumeration can perform only
operation while traversing the traverse operation on the collection.
collection.
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.
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.
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.
2) HashMap can contain one null key Hashtable cannot contain any null
and multiple null values. key or null value.
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.
3 Arrays can store primitive data types ArrayList cannot store the primitive data
as well as objects. types it can only store the objects.
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()])
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:
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.
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.
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.
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:
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-
Yes! There can be two or more static methods in a class with the same name but differing
input parameters.
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;
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.
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.
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.
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.
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.
‘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.
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.
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.
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.
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.
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.
That is, the same entity (method or operator or object) can perform different operations in
different scenarios.
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).
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.
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.
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().
Method
Defined in the Object class Defined in the Thread class
Location
Also
Throws InterruptedException when
Interruption throws InterruptedException when
interrupted
interrupted
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.
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 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.
2) The Iterator can be used in List, ListIterator can be used in List only.
Set, and Queue.
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.
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."
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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).
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
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.
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.
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.
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.
However, a class can implement one or more interfaces, which has helped Java get rid of the
impossibility of multiple inheritances.
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.
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.
• 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.
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).
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.
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.
Access modifiers are keywords that determine the visibility of a class, method, or variable in
Java.
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.
12) What are the main differences between the Linked List and
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.
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.
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:
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:
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:
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
import java.util.List;
list.add("Dhanbad");
list.add("Mumbai");
list.add(3, "Sydney");
System.out.println(list);
import java.util.List;
list.add(0, "Banana");
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.
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);
arr = numbers.toArray(arr);
– 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.
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.
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).
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 ).
4)Dequeue(Q): removes the element pointed to by the front end of the queue.
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.
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).
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.
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.
Hash Map
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.
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.
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.
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.
Syntax:
Syntax:
HashMap<String, Integer> InterviewBIt_map2 = new HashMap<String, Integer>(50);
Syntax:
Syntax:
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.
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.
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.
map.put("One", 1);
map.put("Two", 2);
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;
map.put("One", 1);
map.put("Two", 2);
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.
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:
if(map.containsKey(key)) {
} else {
map.put(key, value);
System.out.println("Inserted successfully");
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.
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.
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.
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.
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.
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.
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.
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.
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:
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
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.
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.
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.
1. Insertion
2. Deletion
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.
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.
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.
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.
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.
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.
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:
TreeSet:
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.
Decision Making
Genetics
Image Processing
Blockchain
Numerical and Statistical Analysis
Compiler Design
Database Design and many more
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.
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.
Serializable
Queue
List
Cloneable
Collection
Deque
Iterable
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
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:
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.
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.
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.
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?
Stack:
Queue:
Here are simple example programs in Java for a Stack and a Queue:
Stack Example:
import java.util.Stack;
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;
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.
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.
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.
Empty the ArrayList using clear() method, which will remove all the elements from the list.
Now copy all the elements of LinkedHashset to ArrayList.
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.
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.
A stack can be implemented using an array by maintaining a pointer to the top of the stack.
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.
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:
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
- 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:
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.
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)
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.
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.
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:
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Explanation:
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.
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.
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.
Merge sort
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
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.
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.
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 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.
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.
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.
test(s1);
System.out.println(s1);
Ans. BuggyBread
test(s1);
System.out.println(s1);
test(s1);
System.out.println(s1);
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;
Example:
int *a[5];
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.
#include <stdio.h>
int main() {
ptr++;
return 0;
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.
Arrays and pointers are closely related, as an array name acts like a constant pointer to th
e first element of the array.
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;
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.
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.
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.
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.
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.
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.
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.
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.
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?
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.
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.
15. What are the different environments related to development 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.
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.
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.
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.
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.
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.
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.
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?
<br> tag – It separates the line of text. It breaks the current line and shifts the flow of
the text to a new line.
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.
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.
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>
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
<ol>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
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.
HTML elements which do not have closing tags or do not need to be closed are Void
elements. For Example <br />, <img />, <hr />, etc.
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.
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.
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.
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:
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?
Strict Doctype
Transitional Doctype
Frameset Doctype
22. Please explain how to indicate the character set being used by a
document in HTML?
<!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.
<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.
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.
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.
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:
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
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;
}
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.
CSS frameworks are libraries that make web page styling easier. Some of them are
Foundation, Bootstrap, Gumby, Ukit, Semantic UI, etc.
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>
The ruleset is used for the identification of selectors, which can be attached with other
selectors. The two parts of a ruleset are:
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.
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.
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.
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.
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.
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?
{color: red;}
background-repeat: none;
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.
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.
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:
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
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
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.
JavaScript Java
Java is an object-oriented
JavaScript is an object-oriented scripting language.
programming language.
Undefined - For variables that are only declared and not defined or initialized
Number - For integer and floating-point numbers
Cross-platform compatible
Open-source
Object-oriented
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.
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?
const student = {
name: 'John',
age: 17
Here is a very simple way of creating arrays in JavaScript using the array literal:
var a = [];
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.
The ‘this’ keyword in JavaScript refers to the currently calling object. It is commonly
used in constructors to assign values to object properties.
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.
In JavaScript, functions are objects and therefore, functions can take other functions
as arguments and can also be returned by other functions.
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?
Declared as a separate statement within the main JavaScript Created inside an expression or
code some other construct
Example: Example:
} }
15. What are the ways of adding JavaScript code in an HTML file?
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.
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.
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.
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) {
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.
getElementbyTagName(‘tagname’): Gets all the HTML elements that have the specified
tagname.
querySelector(): Takes CSS style selector and returns the first selected HTML element.
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:
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.
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.
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.
NaN property represents the “Not-a-Number” value. It indicates a value that is not a legal
number.
Note- isNaN() function converts the given value to a Number type, and then equates to NaN.
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.
function higherOrder(fn) {
fn();
}
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.
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.
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.
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.
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.
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.
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.
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.
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.