Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
45 views

Java Full Stack Interview Questions

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views

Java Full Stack Interview Questions

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 61

JAVA FULL STACK INTERVIEW

1. JDK (Java Development Kit):

 The JDK is a software development kit required to develop Java applications and
applets. It includes the JRE (Java Runtime Environment), an interpreter/loader (Java),
a compiler (javac), an archiver (jar), a documentation generator (Javadoc), and other
tools needed for Java development.

2. JRE (Java Runtime Environment):

 The JRE provides libraries, Java Virtual Machine (JVM), and other components to
run applications written in Java. It is the runtime part of the JDK but does not include
development tools such as compilers and debuggers.

3. JIT Compiler (Just-In-Time Compiler):

 The JIT compiler is a part of the JVM that improves the performance of Java
applications by compiling bytecodes into native machine code at runtime. This allows
Java programs to run faster because the code that is executed frequently is compiled
into native code, which is faster to execute than interpreting bytecode.

4.Adaptive Optimizer:

 The adaptive optimizer is a feature of the JVM that dynamically optimizes the
performance of Java applications during runtime. It collects statistics about the
running application and uses this information to make decisions about which parts of
the code to compile and how to optimize them for better performance.

5. Class Loader:

 A class loader in Java is a part of the Java Runtime Environment that dynamically
loads Java classes into the JVM. It is responsible for finding and loading class files
into memory, verifying their bytecode, and preparing them for execution. Java has a
hierarchical class loader architecture, starting with the bootstrap class loader, followed
by the system (application) class loader, and then the user-defined class loaders.

6. Byte Code Verifier:

 The bytecode verifier is a part of the JVM that checks the validity of bytecode before
it is executed. It ensures that the code adheres to Java's security constraints and does
not violate access rights. This verification process helps in maintaining the security
and integrity of the Java runtime environment by preventing malicious or malformed
code from being executed.
7. Compiler:

 A compiler is a software tool that translates code written in a high-level programming


language into machine code or intermediate bytecode. The resulting code is then
executed by a computer's CPU or a virtual machine. In Java, the compiler (javac)
converts Java source code into bytecode, which can be executed by the JVM.

8. Interpreter:

 An interpreter is a software tool that reads and executes code line-by-line or


statement-by-statement. Unlike a compiler, which translates the entire code before
execution, an interpreter translates and executes the code simultaneously. In the
context of Java, the JVM initially interprets bytecode, but frequently executed code
can be compiled into native code by the JIT compiler for better performance.

9. Difference between a Compiler and Interpreter:

 Compiler:
o Translates the entire source code into machine code before execution.
o Generates an executable file (e.g., bytecode in Java).
o Typically faster execution since the code is already translated.
o Examples: C, C++, Java (javac).
 Interpreter:
o Translates and executes code line-by-line or statement-by-statement.
o No intermediate executable file is generated.
o Generally slower execution due to on-the-fly translation.
o Examples: Python, Ruby, JavaScript.

10. Components of JVM (Java Virtual Machine):

 Class Loader: Loads class files into the JVM.


 Bytecode Verifier: Ensures that the bytecode is correct and adheres to security
constraints.
 Interpreter: Interprets the bytecode and executes it.
 JIT Compiler: Compiles frequently executed bytecode into native machine code for
better performance.
 Garbage Collector: Manages memory by reclaiming memory occupied by objects
that are no longer in use.
 Runtime Data Areas: Includes method area, heap, stack, program counter registers,
and native method stack.

11. What is Platform Independence?

Platform independence means that software can run on any computer system, regardless of the
operating system or hardware. Java achieves platform independence by compiling code into
bytecode, which can be executed on any system with a Java Virtual Machine (JVM).
12. How does Java achieve Platform Independence?

Java achieves platform independence through the Java Virtual Machine (JVM). Java code is compiled
into an intermediate form called bytecode, which is the same on all platforms. The JVM interprets
this bytecode and executes it on the underlying hardware, allowing the same Java program to run on
any platform with a JVM.

13. How to Access Command Line Arguments?

In Java, command line arguments are passed to the `main` method as an array of `String` objects.
Here is an example:

```java

public class CommandLineExample {

public static void main(String[] args) {

for (String arg : args) {

System.out.println(arg);

```

14. What are the Data Types in Java and What are Their Sizes?

Java has both primitive data types and reference data types. Here are the primitive data types and
their sizes:

- `byte` (8-bit): -128 to 127

- `short` (16-bit): -32,768 to 32,767

- `int` (32-bit): -2^31 to 2^31-1

- `long` (64-bit): -2^63 to 2^63-1

- `float` (32-bit): approximately ±3.40282347E+38F

- `double` (64-bit): approximately ±1.79769313486231570E+308


- `char` (16-bit): '\u0000' to '\uffff'

- `boolean`: true or false (size is JVM dependent)

15. How Do You Declare an Array in Java?

To declare an array in Java, you specify the data type followed by square brackets. Here is an
example:

```java

int[] array = new int[10];

```

16. How Do You Find the Length of an Array in Java?

You can find the length of an array using the `length` property. For example:

```java

int[] array = {1, 2, 3, 4, 5};

int length = array.length; // length is 5

```

17. What is the Use of PATH Variable?

The `PATH` variable is an environment variable that tells the operating system where to look for
executable files. When you run a command from the command line, the system searches for the
executable file in the directories listed in the `PATH` variable.

18. What is the Use of CLASSPATH Variable?

The `CLASSPATH` variable is an environment variable that tells the Java Virtual Machine and Java
compiler where to look for user-defined classes and packages in Java programs. It can include
directories, JAR files, and ZIP files.
19. How Do You Assign Values for PATH and CLASSPATH Variable?

To assign values to the `PATH` and `CLASSPATH` variables, you can use the following syntax depending
on your operating system:

#### On Windows:

```cmd

set PATH=C:\path\to\directory;%PATH%

set CLASSPATH=C:\path\to\classes;%CLASSPATH%

```

#### On Unix/Linux/Mac:

```sh

export PATH=/path/to/directory:$PATH

export CLASSPATH=/path/to/classes:$CLASSPATH

```

20. What are the Characteristic Features of Java Programming Language?

Java has several characteristic features:

1. **Platform Independence**: Java programs can run on any platform with a JVM.

2. **Object-Oriented**: Java follows the object-oriented programming paradigm, promoting


reusable and modular code.

3. **Simple and Familiar**: Java's syntax is simple and easy to learn, especially for those with
experience in C or C++.

4. **Secure**: Java provides a secure environment through features like bytecode verification and a
security manager.

5. **Robust**: Java emphasizes early error checking, runtime checking, and exception handling to
create reliable programs.

6. **Multithreaded**: Java supports multithreading, allowing concurrent execution of two or more


threads for maximum CPU utilization.

7. **High Performance**: Java achieves high performance with its Just-In-Time (JIT) compiler.
8. **Distributed**: Java has a strong networking capability, allowing programs to be distributed over
the network.

9. **Dynamic**: Java can dynamically link new class libraries, methods, and objects.

21. Object-oriented programming uses classes and objects.

Object-oriented programming (OOP) is a programming paradigm that uses "objects" and


their interactions to design and program applications. This paradigm is based on several key
concepts:

1. Classes and Objects:


o Classes: These are blueprints for creating objects. They define a datatype by
bundling data (attributes) and methods (functions or procedures) that work on
the data into one single unit.
o Objects: These are instances of classes. Objects represent real-world entities
and have states and behaviors defined by their class.
2. Encapsulation:
o This concept involves bundling the data (variables) and methods (functions)
that operate on the data into a single unit or class. It also restricts direct access
to some of an object's components, which is a means of preventing accidental
interference and misuse of the methods and data.
3. Inheritance:
o Inheritance is a mechanism where one class inherits the properties and
behaviors (methods) of another class. This helps in reusability and can lead to
a hierarchical classification.
4. Polymorphism:
o Polymorphism allows methods to do different things based on the object it is
acting upon, even though they share the same name. This is typically achieved
via method overloading (compile-time polymorphism) and method overriding
(runtime polymorphism).
5. Abstraction:
o Abstraction means hiding the complex implementation details and showing
only the necessary features of an object. This simplifies the user interaction
with the complex system.

22. What are classes and what are objects?

**Classes:**

- A class is a blueprint for creating objects. It defines a datatype by bundling data and methods that
work on the data into one single unit.

- In Java, a class contains fields (variables) and methods to define the behaviors of an object.

**Objects:**

- An object is an instance of a class. When a class is defined, no memory is allocated until an object of
that class is created.
- Objects hold specific values for the fields defined in the class and can invoke methods defined in the
class.

23. What is the relationship between classes and objects?

- A class is a template or blueprint for objects, defining the structure and behavior (via methods) that
the objects created from the class will have.

- An object is a specific instance of a class with actual values and state. Multiple objects can be
created from the same class, each having its own unique state.

24. Explain carefully what `null` means in Java, and why this special value is necessary.

- `null` in Java is a special value that indicates that a reference variable does not point to any object
or data. It is the default value for uninitialized object references.

- This special value is necessary to represent the absence of a value or the non-existence of an
object. It allows for conditional checks to ensure that operations are only performed on valid objects.

25. What are the three parts of a simple empty class? Explain with an example.

The three parts of a simple empty class are:

1. **Class Name:** The name of the class.

2. **Fields (Variables):** Data members of the class (though an empty class will have none).

3. **Methods:** Functions or procedures that define behaviors (though an empty class will have
none).

**Example:**

```java

public class MyClass {

// Class name: MyClass

// No fields

// No methods

26. What is a constructor? What is the purpose of a constructor in a class?

- A constructor is a special method that is called when an object of a class is instantiated. It has the
same name as the class and does not have a return type.

- The purpose of a constructor is to initialize the new object. It sets initial values for fields and
performs any setup or configuration required for the object.

27. What is meant by the terms instance variable and instance method?

**Instance Variable:**
- An instance variable is a variable that is defined in a class and each object of that class has its own
copy of that variable.

**Instance Method:**

- An instance method is a method defined in a class that operates on instance variables. It can be
called on an object of the class.

28. Explain what is meant by the terms subclass and superclass.

**Subclass:**

- A subclass is a class that inherits from another class (the superclass). It can add its own fields and
methods in addition to those inherited from the superclass.

**Superclass:**

- A superclass is a class that is extended by another class (the subclass). It provides common behavior
and structure that can be inherited by subclasses.

29. Explain the term polymorphism.

Polymorphism is the ability of a single function or method to operate in different ways on different
data types or the ability of objects to be treated as instances of their parent class rather than their
actual class. In Java, it allows methods to be overridden and provides flexibility and integration
between different classes.

30. Java uses "garbage collection" for memory management. Explain what is meant here by
garbage collection. What is the alternative to garbage collection?

**Garbage Collection:**

- Garbage collection is the process of automatically identifying and reclaiming memory that is no
longer in use by the program. In Java, the garbage collector runs in the background to free up
memory by destroying objects that are no longer reachable.

**Alternative:**

- The alternative to garbage collection is manual memory management, where the programmer
explicitly allocates and deallocates memory (as seen in languages like C/C++).

31. Bring out the importance of inheritance with the help of an example.

Inheritance allows a class to inherit properties and behaviors from another class, promoting code
reusability and hierarchical classification.

**Example:**

```java

class Animal {

void eat() {

System.out.println("This animal eats food.");


}

class Dog extends Animal {

void bark() {

System.out.println("The dog barks.");

public class Main {

public static void main(String[] args) {

Dog myDog = new Dog();

myDog.eat(); // Inherited method

myDog.bark(); // Subclass method

32. When do we declare the members of the class as static? Explain with example.

- We declare the members of a class as static when the member is shared among all instances of the
class rather than belonging to any one instance. Static members are associated with the class itself
rather than an instance.

**Example:**

```java

public class MyClass {

static int count = 0; // Static variable

MyClass() {

count++; // Increment count whenever an object is created

static void displayCount() { // Static method

System.out.println("Count: " + count);

}
public static void main(String[] args) {

new MyClass();

new MyClass();

MyClass.displayCount(); // Output: Count: 2

33. When do we declare a method or class as final? Explain with example.

- A method is declared as `final` to prevent it from being overridden by subclasses.

- A class is declared as `final` to prevent it from being subclassed.

**Example:**

```java

final class FinalClass {

// Class cannot be subclassed

class BaseClass {

final void finalMethod() {

// Method cannot be overridden

class SubClass extends BaseClass {

// Cannot override finalMethod()

public class Main {

public static void main(String[] args) {

SubClass obj = new SubClass();

obj.finalMethod(); // Calls the final method

}
}

34. What is the advantage of using the `this` keyword? Explain.

The `this` keyword is used to refer to the current instance of the class. It helps in differentiating
between instance variables and parameters with the same name.

**Example:**

```java

public class MyClass {

int value;

MyClass(int value) {

this.value = value; // 'this.value' refers to the instance variable

void display() {

System.out.println("Value: " + this.value); // 'this.value' refers to the instance variable

public static void main(String[] args) {

MyClass obj = new MyClass(10);

obj.display(); // Output: Value: 10

35. Explain about inner classes with an example.

Inner classes are classes defined within another class. They can access members of the outer class
and are used to logically group classes that are only used in one place.

**Example:**

```java

public class OuterClass {

private int outerValue = 10;

class InnerClass {

void display() {
System.out.println("Outer value: " + outerValue); // Access outer class member

public static void main(String[] args) {

OuterClass outer = new OuterClass();

OuterClass.InnerClass inner = outer.new InnerClass();

inner.display(); // Output: Outer value: 10

```

36. Explain how the `super` keyword is used in overriding methods.

The `super` keyword is used to call methods of the superclass from a subclass, typically when
overriding a method and wanting to call the superclass version.

**Example:**

```java

class Animal {

void makeSound() {

System.out.println("Animal makes a sound");

class Dog extends Animal {

void makeSound() {

super.makeSound(); // Call superclass method

System.out.println("Dog barks");

public class Main {


public static void main(String[] args) {

Dog myDog = new Dog();

myDog.makeSound(); // Output: Animal makes a sound \n Dog barks

```

37. Explain the use of `super()` method in invoking a constructor.

The `super()` method is used to call the constructor of the superclass from a subclass. It helps in
initializing the superclass part of the object.

**Example:**

```java

class Animal {

Animal() {

System.out.println("Animal constructor");

class Dog extends Animal {

Dog() {

super(); // Call superclass constructor

System.out.println("Dog constructor");

public class Main {

public static void main(String[] args) {

Dog myDog = new Dog(); // Output: Animal constructor \n Dog constructor

```
38. When does a base class variable get hidden? Give reasons.

A base class variable gets hidden when a subclass defines a variable with the same name as the
variable in the base class. The subclass variable hides the base class variable.

**Reasons:**

- The variable in the subclass has the same name as the variable in the base class.

- The subclass variable shadows the base class variable.

39. Explain with an example how we can access a hidden base class variable.

To access a hidden base class variable, we use the `super` keyword.

**Example:**

```java

class BaseClass {

int value =10;

class SubClass extends BaseClass {

int value = 20; // Hidden variable

void display() {

System.out.println("Base class value: " + super.value);

System.out.println("Subclass value: " + value);

public class Main {

public static void main(String[] args) {

SubClass obj = new SubClass();

obj.display(); // Output: Base class value: 10 \n Subclass value: 20

```
40. What are called Abstract classes?

Abstract classes are classes that cannot be instantiated and are meant to be subclassed. They can
contain abstract methods (methods without implementation) that must be implemented by
subclasses.

**Example:**

```java

abstract class Animal {

abstract void makeSound(); // Abstract method

void eat() {

System.out.println("This animal eats food.");

class Dog extends Animal {

void makeSound() {

System.out.println("Dog barks");

public class Main {

public static void main(String[] args) {

Dog myDog = new Dog();

myDog.makeSound(); // Output: Dog barks

myDog.eat(); // Output: This animal eats food.

}
41. Can abstract classes have static methods?

Yes, abstract classes can have static methods. Since static methods belong to the class itself rather
than to any specific instance, they can be defined in abstract classes to provide utility functions or
common functionality that does not depend on instance variables.

**Example:**
```java

abstract class AbstractClass {

static void staticMethod() {

System.out.println("Static method in abstract class");

public class Main {

public static void main(String[] args) {

AbstractClass.staticMethod(); // Output: Static method in abstract class

```

42. Can abstract classes have static variables?

Yes, abstract classes can have static variables. Static variables are shared among all instances of the
class and belong to the class itself rather than any specific instance.

**Example:**

```java

abstract class AbstractClass {

static int staticVar = 10;

public class Main {

public static void main(String[] args) {

System.out.println(AbstractClass.staticVar); // Output: 10

```

43. Can abstract classes have static and final variables?


Yes, abstract classes can have both static and final variables. Static variables are associated with the
class, and final variables cannot be modified once assigned.

**Example:**

```java

abstract class AbstractClass {

static final int CONSTANT = 100;

public class Main {

public static void main(String[] args) {

System.out.println(AbstractClass.CONSTANT); // Output: 100

```

44. Can abstract classes have static and final methods?

- Abstract classes can have static methods.

- Abstract classes can have final methods.

- However, abstract methods cannot be static or final because:

- Abstract methods need to be overridden in subclasses, and final methods cannot be overridden.

- Static methods belong to the class, not to an instance, and cannot be abstract because abstract
methods are meant to be implemented in subclasses.

**Example:**

```java

abstract class AbstractClass {

static void staticMethod() {

System.out.println("Static method in abstract class");

final void finalMethod() {

System.out.println("Final method in abstract class");


}

```

45. Can a subclass directly use the abstract method of the base class without overriding it?

No, a subclass cannot directly use the abstract method of the base class without overriding it.
Abstract methods do not have implementations, so the subclass must provide an implementation for
the abstract methods inherited from the abstract base class.

46. Can we instantiate an abstract class?

No, we cannot instantiate an abstract class directly. Abstract classes are meant to be subclassed, and
their purpose is to provide a base for other classes to extend and implement the abstract methods.

47. Can we create a final and abstract method in a class?

No, we cannot create a method that is both final and abstract. Final methods cannot be overridden
by subclasses, while abstract methods must be overridden in subclasses. These two concepts are
contradictory.

48. Can an abstract class implement interfaces?

Yes, an abstract class can implement interfaces. When an abstract class implements an interface, it
can provide implementations for some or all of the interface's methods. Any methods not
implemented by the abstract class must be implemented by its concrete subclasses.

**Example:**

```java

interface MyInterface {

void interfaceMethod();

abstract class AbstractClass implements MyInterface {

// Optional: provide implementation for interface methods

public void interfaceMethod() {

System.out.println("Interface method in abstract class");

class ConcreteClass extends AbstractClass {


// If not implemented in abstract class, must be implemented here

public class Main {

public static void main(String[] args) {

ConcreteClass obj = new ConcreteClass();

obj.interfaceMethod(); // Output: Interface method in abstract class

```

49. Can an abstract class extend a final class?

No, an abstract class cannot extend a final class. Final classes cannot be subclassed, so it is not
possible to extend a final class with any other class, including an abstract class.

50. What are interfaces?

Interfaces are a reference type in Java, similar to a class, but they are a collection of abstract
methods that a class can implement. An interface can also contain constants, default methods, static
methods, and nested types.

**Key Points:**

- Interfaces cannot have instance variables.

- All methods in an interface are implicitly public and abstract (except for default and static methods).

- A class implements an interface by providing implementations for all of its abstract methods.

- A class can implement multiple interfaces, providing a way to achieve multiple inheritance in Java.

**Example:**

```java

interface MyInterface {

void method1();

void method2();

class MyClass implements MyInterface {


public void method1() {

System.out.println("Method1 implementation");

public void method2() {

System.out.println("Method2 implementation");

public static void main(String[] args) {

MyClass obj = new MyClass();

obj.method1(); // Output: Method1 implementation

obj.method2(); // Output: Method2 implementation

51. How to create an interface?


To create an interface in Java, you use the `interface` keyword. An interface can include abstract
methods, default methods, static methods, and constants.

**Example:**

```java

public interface MyInterface {

void method1(); // Abstract method

void method2(); // Abstract method

52. Difference between abstract classes and interfaces

- **Abstract Classes:**

- Can have both abstract and concrete methods.

- Can have instance variables.

- Can have constructors.

- A class can extend only one abstract class.

- **Interfaces:**

- Can only have abstract methods (until Java 8, which introduced default and static methods).

- Cannot have instance variables, only constants.


- Cannot have constructors.

- A class can implement multiple interfaces.

53. What are called Marker Interfaces and why do we use Marker Interface?

- **Marker Interfaces:** Interfaces with no methods or fields, used to signal to the JVM or compiler
that the class implementing the interface has a specific property.

- **Usage:** For example, `Serializable` and `Cloneable` are marker interfaces. They are used to
indicate that a class can be serialized or cloned, respectively.

54. What are packages?

Packages are namespaces that organize classes and interfaces by grouping them together. This helps
to avoid name conflicts and to control access.

**Example:**

```java

package com.example.myapp;

public class MyClass {

// Class code here

```

55. What are the benefits of creating programs using packaging?

- Avoiding name conflicts.

- Controlled access using access modifiers.

- Easier to locate and manage classes.

- Improved modularity and maintainability.

- Enhanced reusability of code.

56. Inside a package can we create private classes?

No, top-level classes cannot be private. They can only be public or package-private (default, no
modifier). However, nested classes within a class can be private.

57. What is the difference between import and import static statements?

- **import:** Used to import classes or entire packages.

```java

import java.util.List;

```
- **import static:** Used to import static members (fields and methods) of a class so they can be
accessed without class qualification.

```java

import static java.lang.Math.PI;

import static java.lang.Math.max;

```

58. What are Exceptions?

Exceptions are events that disrupt the normal flow of a program's execution. They are objects that
represent errors and other exceptional conditions.

59. Differentiate between exceptions, runtime errors, and compile-time errors

- **Exceptions:** Handled using try-catch blocks and can occur during runtime (e.g., `IOException`,
`SQLException`).

- **Runtime Errors:** Subclass of `Exception`, not checked at compile-time (e.g.,


`NullPointerException`, `ArrayIndexOutOfBoundsException`).

- **Compile-time Errors:** Errors detected by the compiler, such as syntax errors or missing classes.

60. Throwable class belongs to which package in Java API?


The `Throwable` class belongs to the `java.lang` package.

61. What are the 2 types of exception classification? Explain its differences.

- **Checked Exceptions:** Checked at compile-time. Subclasses of `Exception` (excluding


`RuntimeException`). Must be either caught or declared in the method signature.

```java

public void readFile() throws IOException {

// code that might throw IOException

```

- **Unchecked Exceptions:** Not checked at compile-time. Subclasses of `RuntimeException`. Not


required to be caught or declared.

```java

public void divide(int a, int b) {

if (b == 0) {
throw new ArithmeticException("Division by zero");

62. What is a finally block?

A `finally` block contains code that is always executed after the try block, regardless of whether an
exception was thrown or caught. It's typically used for cleanup code.

**Example:**

```java

try {

// code that may throw an exception

} catch (Exception e) {

// handling exception

} finally {

// cleanup code, always executed

63. Can we have try followed by only a finally block without a catch block?

Yes, we can have a `try` block followed by only a `finally` block without a `catch` block.

**Example:**

```java

try {

// code that may throw an exception

} finally {

// cleanup code, always executed

64. What is the difference between throw and throws keyword in Java?

- **throw:** Used to explicitly throw an exception.

```java

throw new IllegalArgumentException("Invalid argument");

```
- **throws:** Used in the method signature to declare that the method might throw exceptions.

```java

public void method() throws IOException, SQLException {

// code that may throw IOException or SQLException

65. Can the same exception be declared to be thrown many times by the method?

No, you cannot declare the same exception multiple times in the `throws` clause.

**Incorrect Example:**

```java

public void sample() throws IOException, IOException, SQLException {

// Incorrect: IOException declared twice

66. What are user-defined exceptions?

User-defined exceptions are custom exceptions created by extending the `Exception` class or its
subclasses to handle specific application conditions.

**Example:**

```java

class MyException extends Exception {

public MyException(String message) {

super(message);

67. Why do we need user-defined exceptions?

User-defined exceptions provide a way to handle specific error conditions in an application, making
the code more readable and maintainable by clearly indicating what went wrong.

68. How to give custom messages while throwing predefined exceptions?

Custom messages can be provided by passing a string message to the constructor of the exception.

**Example:**

```java

public void validateAge(int age) {

if (age < 18) {


throw new IllegalArgumentException("Age must be 18 or older");

69. What are wrapper classes? Describe the wrapper classes in Java?

Wrapper classes provide a way to use primitive data types as objects. Each primitive type has a
corresponding wrapper class in Java.

**Wrapper Classes:**

- `byte` -> `Byte`

- `short` -> `Short`

- `int` -> `Integer`

- `long` -> `Long`

- `float` -> `Float`

- `double` -> `Double`

- `char` -> `Character`

- `boolean` -> `Boolean`

70. What do you mean by Boxing and Unboxing in Java?

- **Boxing:** Converting a primitive type into its corresponding wrapper class object.

```java

int num = 10;

Integer boxedNum = Integer.valueOf(num); // Boxing

- **Unboxing:** Converting a wrapper class object back to its corresponding primitive type.

```java

Integer boxedNum = Integer.valueOf(10);

int num = boxedNum.intValue(); // Unboxing

71. Why do we need Wrapper Classes?

Wrapper classes are needed for:

- Treating primitives as objects.

- Using primitives in collections (like `ArrayList`).

- Providing utility methods (e.g., `Integer.parseInt()`).

- Supporting generic programming.

72. In which Package are all Wrapper Classes in Java found?


All wrapper classes in Java are found in the `java.lang` package.

73. How many methods are present in Cloneable Interface?

The `Cloneable` interface does not contain any methods. It is a marker interface used to indicate that
a class supports cloning.

74. In which package is Cloneable interface found?

The `Cloneable` interface is found in the `java.lang` package.

75. In which Class of Java is the clone method found?

The `clone` method is found in the `Object` class.

76. What are the two types of I/O available in Java?

The two types of I/O in Java are:

- **Character I/O:** Uses `Reader` and `Writer` classes to handle character data.

- **Byte I/O:** Uses `InputStream` and `OutputStream` classes to handle byte data.

77. What is the difference between the Reader/Writer class hierarchy and the
InputStream/OutputStream class hierarchy?

- **Reader/Writer:** Handles character data and is used for text files. They are part of the `java.io`
package.

- **InputStream/OutputStream:** Handles byte data and is used for binary data, like images and
videos. They are also part of the `java.io` package.

78. What value does readLine method return when it reaches end of the file?

The `readLine` method returns `null` when it reaches the end of the file.

79. What value does read method return when it reaches end of file?

The `read` method returns `-1` when it reaches the end of the file.

80. What is serialization in Java?

Serialization is the process of converting an object into a byte stream so that it can be easily saved to
a file or transmitted over a network.

81. How many methods are found in Serializable interface?

The `Serializable` interface does not contain any methods. It is a marker interface used to indicate
that a class can be serialized.

82. In which Java Package is the Serializable interface found?


The `Serializable` interface is found in the `java.io` package.

83. What are the static variables found in System Class in Java?

The `System` class has several static variables, including:

- `System.in` (standard input stream)

- `System.out` (standard output stream)

- `System.err` (standard error stream)

84. What is the difference between ArrayList and Vector?

- **ArrayList:** Not synchronized, not thread-safe, better performance for single-threaded


applications.

- **Vector:** Synchronized, thread-safe, slower performance due to synchronization overhead.

85. What is the difference between ArrayList and LinkedList?

- **ArrayList:**

- Uses dynamic arrays.

- Fast random access, slow insertion/deletion (except at the end).

- **LinkedList:**

- Uses doubly-linked lists.

- Slow random access, fast insertion/deletion.

86. What is the difference between Iterator and ListIterator?

- **Iterator:** Can iterate over collections in a forward direction.

- **ListIterator:** Can iterate over lists in both forward and backward directions, and allows
modification of the list.

87. What is the difference between Iterator and Enumeration?

- **Iterator:** Allows removal of elements during iteration, has more functionality.

- **Enumeration:** Only allows reading elements, is an older interface.

88. What is the difference between List and Set?

- **List:** Allows duplicate elements, maintains insertion order.

- **Set:** Does not allow duplicate elements, does not guarantee order (except for specific
implementations like `LinkedHashSet`).

89. What is the difference between HashSet and TreeSet?

- **HashSet:** Unordered, faster due to hashing.


- **TreeSet:** Ordered (sorted), slower due to tree structure.

90. What is the difference between Set and Map?

- **Set:** A collection that does not allow duplicate elements.

- **Map:** A collection of key-value pairs, where keys are unique.

91. What is the difference between HashSet and HashMap?

- **HashSet:** Implements the `Set` interface, stores only elements.

- **HashMap:** Implements the `Map` interface, stores key-value pairs.

92. What is the difference between HashMap and TreeMap?

- **HashMap:** Unordered, faster due to hashing.

- **TreeMap:** Ordered (sorted by keys), slower due to tree structure.

93. What is the difference between HashMap and Hashtable?

- **HashMap:** Not synchronized, allows one `null` key and multiple `null` values.

- **Hashtable:** Synchronized, does not allow `null` keys or values.

94. What is the difference between Collection and Collections?

- **Collection:** An interface representing a group of objects.

- **Collections:** A utility class that provides static methods to operate on collections.

95. What is the difference between Comparable and Comparator?

- **Comparable:** Used to define natural ordering of objects, implemented by the class itself.

```java

public class MyClass implements Comparable<MyClass> {

public int compareTo(MyClass other) {

// comparison logic

```

- **Comparator:** Used to define custom ordering, implemented by a separate class.

```java

public class MyComparator implements Comparator<MyClass> {

public int compare(MyClass obj1, MyClass obj2) {

// comparison logic
}

96. What is the advantage of Properties file?

Properties files are used to store configuration data in a key-value format. They provide a simple way
to manage application settings and internationalization.

97. What are the classes implementing List interface?

Classes implementing the `List` interface include:

- `ArrayList`

- `LinkedList`

- `Vector`

- `Stack`

98. What are Collection related features in Java 8?

Java 8 introduced several features to the Collections framework:

- Streams API

- Enhanced `Map` interface with methods like `forEach`, `compute`, `merge`, etc.

- `default` and `static` methods in interfaces.

99. What is Java Collections Framework? List out some benefits of Collections framework?

The Java Collections Framework is a set of classes and interfaces that implement commonly reusable
collection data structures.

**Benefits:**

- Reduces programming effort by providing data structures and algorithms.

- Increases performance by providing high-performance implementations.

- Encourages software reuse with a well-designed set of interfaces and abstract classes.

100. What is the benefit of Generics in Collections Framework?

Generics provide type safety, allowing compile-time checking of types and reducing the risk of
`ClassCastException`. They also make the code more readable and maintainable.

**Example:**

```java

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

list.add("Hello");

// list.add(123); // Compile-time error


**102. Why doesn’t Collection extend Cloneable and Serializable interfaces?**

- `Cloneable` and `Serializable` are marker interfaces that don't define any methods. They serve as
markers to indicate that a class supports cloning or serialization, respectively. Not all collections may
support cloning or serialization due to various reasons such as internal data structures or
complexities in the implementation. Therefore, making `Cloneable` and `Serializable` optional allows
collections to choose whether or not to support these features.

**103. Why doesn’t Map interface extend Collection interface?**

- Maps and collections serve different purposes: collections store a group of elements, while maps
store key-value pairs. Extending `Collection` would imply that maps should support operations like
adding individual elements, which is not applicable to maps (you add key-value pairs, not individual
elements). Thus, they are distinct interfaces to reflect these different behaviors.

**104. What is an Iterator?**

- An `Iterator` is an interface in Java that allows you to iterate (loop) through elements in a collection
sequentially. It provides methods like `hasNext()` to check if there are more elements and `next()` to
retrieve the next element in the iteration sequence.

**105. How can ArrayList be synchronized without using Vector?**

- You can synchronize an `ArrayList` by using the `Collections.synchronizedList()` method, which


wraps your `ArrayList` with a synchronized wrapper. For example:

```java

List<String> synchronizedList = Collections.synchronizedList(new ArrayList<>());

This ensures that all operations on the list are synchronized, making it thread-safe.

**106. When to use ArrayList or LinkedList?**

- Use `ArrayList` when you need fast iteration and random access to elements, but can tolerate
slower insertions and deletions. Use `LinkedList` when you frequently need to add or remove
elements from the middle of the list and can tolerate slower iteration times.

**107. What are the advantages of iterating a collection using iterator?**

- Iterators provide a way to traverse collections in a uniform manner without exposing the underlying
structure of the collection. Advantages include:

- Ability to remove elements safely during iteration using `Iterator.remove()`.

- Uniform access to elements across different types of collections (lists, sets, maps, etc.).

- Allows for fail-fast behavior, detecting concurrent modifications.

**108. Why can’t we create a generic array or write code like `List[] array = new ArrayList[10];`?**

- Arrays in Java have a fixed type at runtime. Since generics in Java use type erasure (where generic
type information is removed at runtime), creating a generic array like `List<String>[]` is not allowed
because it would not be type-safe. Instead, you can use a list of lists or a similar data structure.
**109. Why can’t we write code like `List numbers = new ArrayList();` without generics?**

- Without generics, the compiler cannot enforce type safety at compile-time. Using raw types (`List`
instead of `List<Integer>` for example) can lead to runtime errors or unexpected behavior when
types are mixed incorrectly. Generics provide compile-time type checking and avoid such issues.

**110. What is the difference between Comparable and Comparator interface?**

- `Comparable` is a functional interface that defines a method `compareTo()` to impose a natural


ordering on the objects of the class that implements it. It's used for objects that have a natural
ordering, such as numbers or strings.

- `Comparator` is also a functional interface with a method `compare()` that allows for comparing
objects of a specific class. It's typically used when you want to define a different way to compare
objects or when the objects themselves do not implement `Comparable`.

**111. What is Collections Class?**

- The `Collections` class in Java is a utility class that contains static methods for operating on
collections like `List`, `Set`, and `Map`. It provides methods for sorting, searching, synchronizing, and
manipulating collections in various ways.

**112. What is Comparable and Comparator interface?**

- `Comparable` and `Comparator` are interfaces used for sorting objects in Java:

- **Comparable**: Objects that implement `Comparable` can be compared to other instances of


the same class using the `compareTo()` method. It provides a natural ordering for objects of that
class.

- **Comparator**: Objects that implement `Comparator` can be used to define a custom way of
comparing objects. It's useful when you want to sort objects based on criteria other than their
natural ordering or when the objects themselves do not implement `Comparable`.

**113. What are the similarities and differences between ArrayList and Vector?**

- **Similarities:**

- Both `ArrayList` and `Vector` are implementations of the `List` interface.

- They both maintain the order of elements and allow duplicates.

- **Differences:**

- **Synchronization:** `Vector` is synchronized, meaning it is thread-safe out of the box. `ArrayList`


is not synchronized but can be synchronized using `Collections.synchronizedList(new ArrayList<>())`.

- **Performance:** `ArrayList` is generally faster than `Vector` because `Vector` incurs overhead
due to synchronization.

- **Growth:** `ArrayList` increases its size by 50% when it reaches its capacity, whereas `Vector`
doubles its size when it exceeds its capacity.
**114. How to decide between HashMap and TreeMap?**

- **HashMap:** Use `HashMap` when you need fast lookup times (average O(1) complexity for
`get()` and `put()` operations) and do not need to maintain the order of keys.

- **TreeMap:** Use `TreeMap` when you need the keys to be sorted in a natural order or a custom
order defined by a `Comparator`. It offers O(log n) time complexity for `get()`, `put()`, and `remove()`
operations.

**115. What are the different Collection views provided by the Map interface?**

- The `Map` interface provides three collection views through its methods:

- `keySet()`: Returns a `Set` view of the keys contained in the map.

- `values()`: Returns a `Collection` view of the values contained in the map.

- `entrySet()`: Returns a `Set` view of the key-value pairs (`Map.Entry` objects) contained in the map.

**116. What is the importance of hashCode() and equals() methods?**

- `hashCode()`: This method returns a hash code value for the object. It's used by hash-based data
structures like `HashMap` and `HashSet` to quickly locate objects in collections. It's important that if
two objects are equal according to `equals()`, their `hashCode()` method should return the same
value.

- `equals()`: This method determines if two objects are meaningfully equivalent. It's used to compare
the actual contents or fields of objects. If you override `equals()`, you should also override
`hashCode()` consistently.

**117. What is testing?**

- Testing is the process of evaluating a software application or system to find defects, bugs, or other
issues before it is deployed to production. It involves executing the software with the intent of
finding errors and verifying that the software meets specified requirements.

**118. What is unit testing?**

- Unit testing is a type of testing where individual units or components of a software application are
tested in isolation. The goal is to validate that each unit of the software performs as expected. Unit
tests are typically automated and are executed during the development phase.

**119. What is Manual testing?**

- Manual testing is a type of testing where tests are executed manually by a human tester without
using any automation tools. Test cases are executed step-by-step to find defects, ensure functionality,
and verify the user experience.

**120. What is Automated testing?**

- Automated testing is a type of testing where tests are executed using automated testing tools and
scripts. It involves writing scripts that automate the execution of test cases, comparing actual
outcomes with expected outcomes, and generating detailed test reports.

**121. Out of Manual and Automated testing, which one is better and why?**

- Both manual and automated testing have their own advantages and limitations:
- **Manual Testing:** Provides flexibility to explore the application, especially for UI/UX testing and
ad-hoc testing. It requires less upfront investment in tools and scripting but can be time-consuming
and error-prone for repetitive tests.

- **Automated Testing:** Offers faster test execution, repeatability, and coverage of a large number
of test cases. It's particularly useful for regression testing and when frequent testing is required.
However, it requires initial setup time, technical expertise, and may not be suitable for all types of
testing (like exploratory testing).

The choice between manual and automated testing depends on factors such as project
requirements, budget, timeline, and the nature of the application being tested.

**122. What is meant by White Box testing?**

- White Box testing, also known as clear box testing, glass box testing, or structural testing, is a
testing technique where the internal structure, design, and implementation of the software being
tested are known to the tester. It involves testing based on the internal logic, code paths, and
structure of the application.

**123. What is meant by Black Box testing?**

- Black Box testing is a testing technique where the internal structure, design, and implementation
details of the software being tested are not known to the tester. Test cases are derived from the
external specifications or requirements of the software, focusing on input-output behavior without
considering how the system processes inputs.

**124. What is JUnit?**

- JUnit is a popular open-source testing framework for Java programming language. It provides
annotations and assertion methods to write and run repeatable unit tests. JUnit is widely used for
unit testing and is supported by various IDEs and build tools.

**125. Is JUnit used for White Box testing or Black Box testing?**

- JUnit is primarily used for White Box testing, as it focuses on testing individual units or components
of code with known internal structure and logic. It's designed to facilitate testing at the code level,
validating internal behavior and logic.

**126. What are the advantages a testing framework like JUnit offers?**

- Advantages of JUnit and similar testing frameworks include:

- Simplified test creation with annotations (`@Test`, `@Before`, `@After`, etc.).

- Assertion methods (`assertEquals()`, `assertTrue()`, etc.) for verifying expected outcomes.

- Integration with build tools and continuous integration pipelines.

- Facilitation of automated testing practices, improving test efficiency and reliability.

**127. What are the important features of JUnit?**

- Key features of JUnit include:

- Annotations (`@Test`, `@Before`, `@After`, etc.) for defining test methods and setup/teardown
operations.
- Assertion methods (`assertEquals()`, `assertTrue()`, etc.) for verifying expected outcomes.

- Parameterized tests to run the same test with different inputs.

- Exception testing to verify expected exceptions in methods.

- Integration with IDEs and build tools for seamless test execution.

**128. What is a Unit Test Case?**

- A Unit Test Case is a specific test designed to verify the functionality of a single unit or component
of software in isolation. It typically focuses on testing a small piece of code, such as a method or
function, with specific inputs and expected outputs.

**129. When are Unit Tests written in the Development Cycle?**

- Unit Tests are typically written during the development phase, alongside the implementation of
code units or components. They are often created before or concurrently with the code to ensure
that each unit behaves as expected and meets its requirements.

**130. What is meant by expected output and actual output?**

- **Expected Output:** The output that is anticipated or predicted based on the input or test
conditions specified in a test case. It represents the correct or desired outcome of executing a piece
of code or a test scenario.

- **Actual Output:** The output produced by executing the code or running the test case under
consideration. It is compared against the expected output to determine whether the code behaves
as intended and to identify any discrepancies or errors.

Let's delve into your questions about Java threads, JUnit testing, and related concepts:

**131. Why not just use System.out.println() for testing?**

- `System.out.println()` is a basic mechanism for outputting messages to the console. While it can be
used for basic inspection of outputs during testing, it lacks structured assertion capabilities provided
by testing frameworks like JUnit. Assertions (like `assertEquals()`, `assertTrue()`, etc.) in JUnit allow
you to programmatically verify expected outcomes, automate test execution, and integrate with
build processes for continuous testing.

**132. Why does JUnit only report the first failure in a single test?**

- JUnit stops executing further assertions in a test method once it encounters the first failure. This
behavior helps focus on diagnosing and fixing one issue at a time, improving clarity in identifying the
cause of failures. If multiple failures occur, fixing them one by one ensures a stepwise approach to
achieving a passing test.

**133. In Java, assert is a keyword. Won't this conflict with JUnit's assert() method?**

- JUnit provides its own `assertXXX()` methods for assertions, such as `assertEquals()`, `assertTrue()`,
etc. These methods are static and do not conflict with Java's `assert` keyword because JUnit's
methods are called using class-level invocation (`Assertions.assertEquals()`), while Java's `assert`
keyword is used at the statement level (`assert condition;`).
**134. What are JUnit classes? List some of them.**

- JUnit provides several classes to facilitate unit testing:

- `Assert`: Contains assertion methods like `assertEquals()`, `assertTrue()`, etc.

- `Test`: Annotates a method as a test method.

- `TestSuite`: Groups related test cases.

- `Before`, `After`, `BeforeClass`, `AfterClass`: Annotations for setup and teardown methods.

- `Parameterized`: Annotation for parameterized tests.

- `Ignore`: Annotation to ignore a test method.

These classes help in organizing, running, and reporting test cases effectively.

**135. What are annotations and how are they useful in JUnit?**

- Annotations in Java provide metadata that can be used by the compiler or runtime to process
classes more effectively. In JUnit, annotations such as `@Test`, `@Before`, `@After`, `@BeforeClass`,
`@AfterClass`, `@Ignore`, and `@RunWith` are used to define and configure test methods and
classes. They make it easier to write and manage tests by providing structure and automating
repetitive tasks like setup, teardown, and test execution.

**136. What is a Test suite?**

- A Test suite in JUnit is a collection of test cases that can be executed together. It allows grouping of
related tests, facilitating batch execution and reporting. Test suites are typically defined using the
`@RunWith` annotation with `Suite.class` or by creating a suite manually.

**137. What is @Ignore annotation and how is this useful?**

- The `@Ignore` annotation in JUnit is used to temporarily disable a test method or test class from
being executed. It's useful when a test is known to fail or when you want to exclude certain tests
from a test run, such as during development or when debugging other parts of the codebase.

**138. What are Parameterized tests?**

- Parameterized tests in JUnit allow you to run the same test method multiple times with different
sets of parameters. It's useful when you need to test a method with various inputs or edge cases.
They are defined using the `@Parameterized` annotation and require a static method to provide
parameters.

**139. What happens if a JUnit Test Method is Declared as "private"?**

- JUnit requires test methods to be declared as `public` because it needs to invoke these methods
from outside the class for testing purposes. If a test method is declared as `private`, JUnit won't be
able to access and execute it, resulting in an error or warning.

**140. How do you test a "protected" method?**

- To test a `protected` method in JUnit, you can create a subclass (usually within the same package or
using reflection) and expose the method for testing purposes. Alternatively, you can refactor the
method as `protected` instead of private to make it accessible to subclasses.
**141. How do you test a "private" method?**

- Testing `private` methods directly in JUnit is discouraged because they are encapsulated and not
intended for direct testing. Instead, you can refactor the method as `protected` or package-private
(default access) if possible, or test it indirectly through public methods that call the private method.

**142. What happens if a JUnit test method is declared to return "String"?**

- JUnit test methods should not return any value (`void`), as they are not expected to return data. If a
test method is declared to return `String`, it will result in a compilation error because JUnit expects
test methods to return `void`.

**143. How can you use JUnit to test that the code throws a desired exception?**

- In JUnit, you can use the `@Test` annotation along with `expected` parameter to specify the
expected exception that a test method should throw. Alternatively, you can use `assertThrows()`
method introduced in JUnit 4 to assert that a specific exception is thrown by the tested code.

**144. How to create Parameterized tests in JUnit?**

- To create Parameterized tests in JUnit, you typically follow these steps:

1. Annotate your test class with `@RunWith(Parameterized.class)`.

2. Create a `public static` method annotated with `@Parameters` that returns a collection of arrays
or an `Iterable<Object[]>` containing parameter sets.

3. Create a constructor in your test class that accepts parameters matching those in your parameter
sets.

4. Write your test methods using the constructor parameters.

**145. Can you use a main() Method for Unit Testing?**

- While you can use a `main()` method for testing purposes, it's not recommended for unit testing in
Java. Unit testing frameworks like JUnit provide a structured approach, assertions, and integration
with build tools that streamline testing. Using `main()` for unit testing lacks automation, reporting,
and the benefits of isolation and repeatability that frameworks offer.

**146. When are tests garbage collected?**

- Tests are garbage collected like any other Java objects when they are no longer referenced and
become eligible for garbage collection. However, in practice, unit tests are often executed in short-
lived processes or environments where garbage collection is less of a concern compared to long-
running applications.

**147. What is Thread in Java?**

- A Thread in Java represents an independent path of execution within a program. It allows


concurrent execution of tasks, enabling multitasking and handling multiple operations
simultaneously.

**148. Difference between Thread and Process in Java?**


- **Thread:** A Thread is a lightweight unit of execution within a process. Multiple threads within
the same process share the same memory space and resources.

- **Process:** A Process is a standalone program or application that runs independently and has its
own memory space. Processes are heavier than threads and do not share memory unless explicitly
facilitated (e.g., inter-process communication).

**149. How do you implement Thread in Java?**

- You can implement a Thread in Java by extending the `Thread` class or implementing the `Runnable`
interface. Extending `Thread` directly defines the `run()` method, while implementing `Runnable`
requires you to implement the `run()` method yourself.

**150. When to use Runnable vs Thread in Java?**

- Use `Runnable` when you want to separate the task's code from the threading mechanism,
promoting better code structure and reusability. Use extending `Thread` when you need to customize
thread behavior or if the class represents a thread of execution itself.

**151. Difference between start() and run() method of Thread class?**

- **start():** Invokes the thread's `run()` method asynchronously, starting a new thread of execution.

- **run():** Defines the actual task or job that the thread will execute. It's the entry point for thread
execution but does not start a new thread. Calling `run()` directly runs the method in the current
thread context without creating a new thread.

**152. How to stop a thread in Java?**

- Threads in Java can be stopped using various mechanisms:

- **Thread interruption:** Use `thread.interrupt()` to interrupt a thread. The thread being


interrupted should handle `InterruptedException` appropriately.

- **Flag-based approach:** Use a `volatile boolean` flag to signal the thread to stop gracefully.

- **`stop()` method (deprecated):** Avoid using `stop()` as it forcefully terminates a thread and can
lead to inconsistent state.

**153. Explain the different priorities of Threads.**

- Threads in Java have priorities ranging from `Thread.MIN_PRIORITY` (1) to `Thread.MAX_PRIORITY`


(10), with `Thread.NORM_PRIORITY` (5) as the default. Higher priority threads are scheduled to run
before lower priority threads, but the actual behavior depends on the underlying operating system's
thread scheduler.

**154. What if we call run() method directly instead of start() method?**

- Calling `run()` directly instead of `start()` does not start a new thread of execution. It simply
executes the `run()` method in the current thread context, without the benefits of multithreading. To
achieve concurrent execution and thread management, always call `start()` to start a new thread.

**155. What is the primary drawback of using synchronized methods?**

- The primary drawback of using synchronized methods is potential performance degradation due to
the overhead of acquiring and releasing locks. When multiple threads contend for access to
synchronized methods or blocks, they may experience contention, leading to reduced concurrency
and increased thread waiting time.

**156. Is it possible to start a thread twice?**

- No, it's not possible to start a thread more than once. Once a thread has completed its execution
(either naturally by reaching the end of its `run()` method or forcibly by an exception or manual
interruption), it cannot be started again. Attempting to call `start()` on a thread that has already
completed its execution will result in an `IllegalThreadStateException`.

**157. What are the different states of a thread?**

- Threads in Java can be in different states throughout their lifecycle:

1. **New:** When a thread is created but not yet started using the `start()` method.

2. **Runnable:** When a thread is ready to run and waiting for CPU time. It can be executing or
waiting for execution.

3. **Blocked/Waiting:** When a thread is waiting for a monitor lock (synchronized block/method)


or for another thread to perform an action.

4. **Timed Waiting:** When a thread is waiting for a specified amount of time. Examples include
waiting on `sleep()` or `join()` methods with timeouts.

5. **Terminated:** When a thread has completed its execution either by finishing its `run()`
method or due to an exception.

**158. What are the different ways in which a thread can enter the waiting stage?**

- Threads can enter the waiting stage (`BLOCKED`, `WAITING`, or `TIMED_WAITING` states) through
various mechanisms:

- **`wait()` and `notify()/notifyAll()`:** Used for inter-thread communication using object monitors.

- **`sleep(long millis)` and `sleep(long millis, int nanos)`:** Causes the thread to temporarily pause
execution for a specified amount of time.

- **`join()` and `join(long millis)`:** Waits for another thread to complete its execution.

- **Synchronization:** When a thread attempts to enter a synchronized block or method that is


already locked by another thread.
**1. Explain MVC architecture relating to J2EE**

- MVC (Model-View-Controller) architecture in J2EE separates an application into three


interconnected components:

- **Model:** Represents the application's data and business logic. It manages the data, responds to
queries about the state of the data, and responds to instructions to change the state of the data.

- **View:** Represents the presentation layer or user interface. It displays the data from the model
to the user and sends user input to the controller.

- **Controller:** Acts as an intermediary between the model and the view. It processes user input,
performs operations on the model, and updates the view accordingly.

In J2EE, servlets or controllers manage requests, JSPs or views handle presentation logic, and
JavaBeans or models manage data and business logic. This separation enhances modularity,
maintainability, and scalability of applications.

**2. What is the difference between a Web server and an application server**

- **Web Server:** A web server handles HTTP requests from clients (like browsers) and serves static
content (HTML, images, etc.). It supports basic servlet execution and handles web-related protocols.
Examples include Apache HTTP Server, Nginx.

- **Application Server:** An application server provides a comprehensive environment for deploying


and managing enterprise applications. It supports various protocols (HTTP, IIOP, etc.), executes
business logic, manages transactions, and offers services like security, database connectivity,
messaging, etc. Examples include Apache Tomcat (with additional features), IBM WebSphere, Oracle
WebLogic.

**3. What are ear, war, and jar files? What are J2EE Deployment Descriptors?**

- **EAR (Enterprise ARchive):** A packaged file format used for deploying enterprise applications. It
may contain multiple modules (like EJBs, WARs) and resources (like XML files, libraries). EAR files
have a `.ear` extension.

- **WAR (Web ARchive):** A packaged file format used for deploying web applications. It contains
servlets, JSPs, HTML, JavaScript, and other resources needed for web applications. WAR files have a
`.war` extension.

- **JAR (Java ARchive):** A packaged file format used for aggregating Java class files, associated
metadata, and resources (like XML files, properties). JAR files have a `.jar` extension and are
commonly used for libraries and standalone Java applications.

- **J2EE Deployment Descriptors:** XML files (like `web.xml` for servlets) used to configure and
customize the deployment of J2EE applications. They specify information like servlet mappings,
initialization parameters, security configurations, etc.

**4. HTTP is a stateless protocol, so how do you maintain state? How do you store user data
between requests?**

- Stateless nature of HTTP means each request is independent, and the server does not retain
information between requests. To maintain state and store user data:
- **Cookies:** Small pieces of data stored on the client's machine and sent with each request. They
can store session IDs or small amounts of user-specific data.

- **Session Management:** Server-side mechanisms (like HttpSession in Java) store user data on
the server. A session ID is sent to the client, typically via a cookie, and used to retrieve session data
from the server on subsequent requests.

**5. Explain the life cycle methods of a servlet?**

- Servlets in J2EE have a life cycle managed by the servlet container (like Apache Tomcat):

- **Initialization (`init()`):** Called by the container when the servlet is first loaded into memory. It
initializes resources and performs one-time setup tasks.

- **Request handling (`service()`):** Called for each client request. It handles the request (GET,
POST, etc.) and generates the response.

- **Destruction (`destroy()`):** Called by the container when the servlet is being removed from
memory. It performs cleanup tasks and releases resources.

**6. What is the difference between `doGet()` and `doPost()` or GET and POST?**

- **GET:** Used to request data from a specified resource. Parameters are appended to the URL,
visible in the browser's address bar. Limited amount of data can be sent.

- **POST:** Used to send data to a server to create/update a resource. Parameters are sent in the
request body, not visible in the URL. It can handle large amounts of data and is more secure than GET
for sensitive data.

- **`doGet()` and `doPost()`:** These are methods defined in the `HttpServlet` class used for
handling GET and POST requests, respectively. They are overridden in servlets to implement specific
request handling logic for each HTTP method.

**7. What are the ServletContext and ServletConfig objects? What are Servlet environment
objects?**

- **ServletContext:** Represents the servlet container and provides information about the web
application. It's shared among all servlets in a web application and is used for configuration, logging,
and sharing data across servlets.

- **ServletConfig:** Provides configuration information to a servlet instance. It's specific to each


servlet and is used to initialize servlet parameters defined in deployment descriptors (like `web.xml`).

- **Servlet Environment Objects:** These include `HttpServletRequest` and `HttpServletResponse`


objects, which represent the client's request and the servlet's response, respectively. They provide
methods to access request parameters, headers, and to generate response content.

**8. What is the difference between forwarding a request and redirecting a request?**

- **Forwarding (`RequestDispatcher.forward()`):** It's performed on the server-side. The original


request is sent to another resource (like another servlet or JSP) within the same server, and the client
is unaware of the forwarded request. It's faster and allows sharing of request attributes.

- **Redirecting (`HttpServletResponse.sendRedirect()`):** It's performed on the client-side. The


server sends a response to the client with a new URL. The client then sends a new request to this
URL. It's slower as it involves an additional round-trip to the client but is useful for directing to
external resources or different domains.

**9. What is a filter, and how does it work?**

- A filter in J2EE intercepts requests and responses to perform pre-processing or post-processing


tasks. It's configured in `web.xml` and executed before or after servlet processing. Filters can modify
request parameters, headers, and responses, enforce security, logging, or perform
encryption/decryption tasks.

**10. Explain the life cycle methods of a JSP?**

- JSPs in J2EE have a life cycle managed by the JSP container:

- **Translation:** JSP source code is translated into a servlet class by the JSP container.

- **Compilation:** The translated servlet class is compiled into bytecode.

- **Initialization (`jspInit()`):** Called by the container when the JSP is initialized.

- **Request handling (`_jspService()`):** Called for each client request. It handles the request and
generates the response.

- **Destruction (`jspDestroy()`):** Called by the container when the JSP is being removed from
memory.

**11. What are the main elements of JSP? What are scriplets? What are expressions?**

- **Main elements of JSP:** Include HTML tags for markup, JSP directives (`<%@ ... %>`) for
configuring JSP pages, JSP actions (`<jsp:...>`) for dynamic content generation, and Java code
fragments (`<%! ... %>`, `<%= ... %>`) for embedding Java code within JSP.

- **Scriptlets (`<% ... %>`):** Embeds Java code snippets within JSP pages. It's used for tasks like
variable declarations, conditional statements, loops, etc.

- **Expressions (`<%= ... %>`):** Evaluates and outputs the result of a Java expression within the
HTML content of a JSP page. It's shorthand for printing Java variables or method calls directly into the
response.

**12. What are the different scope values or what are the different scope values for
`<jsp:useBean>`?**

- The `<jsp:useBean>` standard action in JSP creates or reuses a JavaBean instance. It supports
different scopes:

- **`page`:** The bean is accessible only within the current JSP page.

- **`request`:** The bean is accessible within the current HTTP request.

- **`session`:** The bean is accessible throughout the user's session.

- **`application`:** The bean is accessible throughout the web application's lifetime.

These scopes control the lifespan and accessibility of JavaBeans instantiated using `<jsp:useBean>`.
**1. What is Hibernate?**

- Hibernate is an open-source Java framework used for object-relational mapping (ORM). It simplifies
database programming by mapping Java objects to database tables and vice versa. It provides data
query and retrieval facilities, significantly reducing the development time for interacting with
databases.

**2. What is ORM?**

- ORM (Object-Relational Mapping) is a programming technique that maps objects from an object-
oriented domain model to a relational database model and vice versa. It allows developers to work
with objects and classes instead of SQL to interact with databases, thus bridging the gap between
object-oriented programming and relational databases.

**3. Explain Hibernate Architecture?**

- Hibernate architecture consists of several key components:

- **Hibernate Configuration:** XML or Java-based configuration that specifies database connection


details, mapping information, and other settings.

- **SessionFactory:** A factory class that produces Session objects. It's a thread-safe singleton and
initializes once per application.

- **Session:** Represents a single-threaded unit of work with the database. It provides methods to
perform CRUD operations and manages transaction boundaries.

- **Transaction:** Manages ACID properties (Atomicity, Consistency, Isolation, Durability) and


demarcates boundaries for database operations.

- **Persistent Objects:** Plain Java objects annotated or configured for persistence using Hibernate
mapping.

- **Mapping Metadata:** XML or annotations that define how Java classes and objects map to
database tables and columns.

**4. What are the core interfaces of Hibernate?**

- The core interfaces of Hibernate include:

- **SessionFactory:** Creates and manages Session objects. It's typically instantiated once per
application.

- **Session:** Represents a single-threaded unit of work with the database. It's used to perform
database operations.

- **Transaction:** Manages transaction boundaries, committing or rolling back changes.

- **Query:** Executes queries against the database, using HQL or native SQL.

**5. What is Session Factory?**


- SessionFactory in Hibernate is a thread-safe factory class that produces Session objects. It's
responsible for initializing Hibernate configuration, mapping metadata, and caching information. It's
typically instantiated once during application startup and shared across the application.

**6. What is the difference between Session.save() and Session.persist()?**

- **`Session.save()`:** Saves an object into the database. It assigns an identifier to the object
immediately and returns the generated identifier.

- **`Session.persist()`:** Similar to `save()`, but it does not guarantee immediate execution of SQL
INSERT. It may postpone the SQL INSERT until the transaction commit, especially when used with
auto-generated keys or sequences.

**7. What is the difference between get() and load() method?**

- **`session.get()`:** Retrieves an object from the database based on its identifier. It returns `null` if
no matching object is found in the database.

- **`session.load()`:** Retrieves an object from the database based on its identifier. It returns a proxy
object without hitting the database immediately. It throws an `ObjectNotFoundException` when the
proxy is accessed and the actual object does not exist in the database.

**8. What are the states of objects in Hibernate?**

- **Transient:** An object is transient if it's just created using the `new` operator and is not
associated with any Hibernate `Session`.

- **Persistent:** An object is persistent if it's associated with a Hibernate `Session`. Changes made to
persistent objects are synchronized with the database upon transaction commit.

- **Detached:** An object becomes detached if it was previously associated with a Hibernate


`Session` but the session is closed or the object is explicitly detached. Detached objects can still be
modified, but changes are not automatically synchronized with the database.

**9. What is HQL?**

- HQL (Hibernate Query Language) is an object-oriented query language similar to SQL but operates
on Hibernate persistent objects. It allows developers to perform database operations using entity
objects and their properties rather than database tables and columns.

**10. Differentiate between Criteria Query and HQL and its Advantages**

- **Criteria Query:** Uses criteria objects and methods to dynamically build queries at runtime. It's
type-safe and allows dynamic query composition based on conditions.

- **HQL (Hibernate Query Language):** Uses a syntax similar to SQL but operates on Hibernate
persistent objects. It's more powerful for complex queries involving multiple entities and
relationships.

**Advantages:**

- **HQL:** Provides flexibility and power, especially for complex queries involving associations and
joins.

- **Criteria Query:** Offers type-safety, dynamic query composition, and avoids string-based query
construction, reducing SQL injection risks.
**11. How many types of association mapping are possible in Hibernate?**

- Hibernate supports four types of association mappings:

- **One-to-One:** Links one instance of an entity to another instance of the same entity.

- **One-to-Many:** Links one instance of an entity to a collection of instances of another entity.

- **Many-to-One:** Links many instances of an entity to one instance of another entity.

- **Many-to-Many:** Links many instances of an entity to many instances of another entity.

**12. What is bidirectional mapping?**

- Bidirectional mapping in Hibernate involves defining associations between two entities in both
directions. Each entity can access and navigate the associated entities. It requires maintaining
references in both entities using appropriate mapping annotations or XML configurations.

**13. How to enable one-to-many mapping in Hibernate using XML elements and Annotations?**

- **Using XML:**

- Define `<set>` or `<list>` elements within the `<class>` mapping of the parent entity, specifying the
child entity type and mapping details.

- Use `<key>` and `<one-to-many>` elements to establish the foreign key relationship.

- **Using Annotations:**

- Annotate a collection attribute (`Set`, `List`, etc.) in the parent entity with `@OneToMany`.

- Use `@JoinColumn` or `@JoinTable` annotations to specify the foreign key column or join table
details.

**1. What is XML?**

- XML (eXtensible Markup Language) is a markup language that defines a set of rules for encoding
documents in a format that is both human-readable and machine-readable. It's designed to store
and transport data, and widely used for data interchange between systems over the internet.

**2. List the rules to be followed by an XML document.**

- An XML document must adhere to these basic rules:

- Begins with an XML declaration `<?xml version="1.0"?>`.

- Contains one root element that encloses all other elements.

- Elements must be properly nested and closed (either with a closing tag or self-closing tag for
empty elements).

- Attribute values must be quoted (either with single or double quotes).

- XML is case-sensitive, so `<element>` is different from `<Element>`.


**3. Define DTD (Document Type Definition).**

- DTD is a formal definition of the structure, elements, and attributes of an XML document. It
specifies the rules that XML documents must follow to be considered valid within a specific
document type. DTDs can be internal (declared within the XML document) or external (referenced
from an external file).

**4. What is a CDATA section in XML?**

- CDATA (Character Data) section in XML is used to include blocks of text that should not be parsed by
the XML parser. It's enclosed within `<![CDATA[ ... ]]>` and is often used to include characters that are
otherwise reserved in XML (like `<`, `>`, `&`) without escaping them.

**5. What is XSL?**

- XSL (eXtensible Stylesheet Language) is a language used for expressing stylesheets to transform
XML documents into other formats like HTML, XHTML, or even another XML document. XSL consists
of two parts: XSLT (XSL Transformations) for transforming XML documents and XPath for navigating
XML documents.

**6. What is XML Namespace?**

- XML Namespace is a mechanism used to avoid element name conflicts in XML documents by
providing a way to uniquely identify elements and attributes. It uses a URI (Uniform Resource
Identifier) to define a namespace, typically in the form of a URL. Elements and attributes can then be
prefixed with a namespace prefix to differentiate them.

**7. How do we create the XSD schema?**

- XSD (XML Schema Definition) is a more powerful and flexible way to define the structure and
constraints of XML documents compared to DTDs. To create an XSD schema:

- Define complex types, simple types, elements, and attributes using XML Schema elements
(`<xs:element>`, `<xs:complexType>`, `<xs:simpleType>`, `<xs:attribute>`, etc.).

- Specify data types, minOccurs, maxOccurs, default values, and other constraints using XSD
elements and attributes.

**8. What is the difference between Schema and DTD?**

- **DTD (Document Type Definition):**

- Older, simpler, and less expressive than XML Schema.

- Uses its own syntax to define document structure, elements, and attributes.

- Supports only basic data types and cannot define complex data structures easily.

- DTDs can be included directly within XML documents.

- **XSD (XML Schema Definition):**

- XML-based and more expressive than DTDs.

- Provides a richer set of data types and allows more detailed definition of complex data structures.
- XSDs are themselves XML documents and are separate from the XML documents they validate.-
XSDs are preferred for validating XML documents due to their flexibility and extensibility.

**9. How do you parse/validate the XML document?**

- Parsing and validating XML documents can be done using:

- **DOM (Document Object Model)**: Loads the entire XML document into memory as a tree
structure. It allows traversal and manipulation of the document.

- **SAX (Simple API for XML)**: Event-driven parsing where the parser notifies the application
about XML document structure and content as it reads.

- **StAX (Streaming API for XML)**: Pull-based parsing similar to SAX but with a more intuitive
programming model.

Validation involves using a validating XML parser (like Xerces) that checks the XML document
against its associated DTD or XSD schema to ensure it conforms to the specified rules.

**10. What are the steps to transform XML into HTML using XSL?**

- Transforming XML into HTML using XSL involves:

- Writing an XSLT stylesheet that defines rules for transforming XML elements and attributes into
HTML elements and attributes.

- Applying the XSLT stylesheet to the XML document using a processor (like Xalan or Saxon) to
produce an HTML output.

- The XSLT stylesheet uses templates, XPath expressions, and built-in functions to map XML data to
HTML presentation.

**11. How do I control formatting and appearance?**

- Formatting and appearance in XML and XSLT transformations can be controlled using:

- **CSS (Cascading Style Sheets)**: Apply CSS styles to the HTML output generated from XSLT to
control fonts, colors, layout, etc.

- **XSL-FO (Formatting Objects)**: For precise control over the layout and formatting of XML
documents, especially for printing or PDF generation.

- **XSLT Templates and Attributes**: Use XSLT templates to define output formatting, attributes,
and structure. XPath expressions can dynamically select content and apply formatting based on
conditions.
1. **How do I make a picture as a background on my web pages?**

```css

body {

background-image: url('path/to/image.jpg');

background-size: cover; /* or contain, depending on your preference */

This CSS snippet sets an image as the background for the entire web page.

2. **Can a data cell contain images?**

Yes, a data cell in an HTML table can contain images. Here is an example:

```html

<table>

<tr>

<td><img src="path/to/image.jpg" alt="Image description"></td>

</tr>

</table>

3. **What is the difference between XML and HTML?**

- **XML (eXtensible Markup Language)** is used to transport and store data, with a focus on what
data is.

- **HTML (HyperText Markup Language)** is used to display data, with a focus on how data looks.

4. **What is the language of the Web?**

HTML is considered the primary language of the web.

5. **What are the tags `<head>` and `<body>` used for?**

- The `<head>` tag contains meta-information about the HTML document, such as title, links to CSS,
and meta tags.

- The `<body>` tag contains the content of the HTML document, such as text, images, links, and
other elements displayed on the web page.

6. **Which section is used for text and tags that are shown directly on your web page?**

The `<body>` section.

7. **Which tag tells the browser as to where the page starts and stops?**

The `<html>` tag.

8. **Which tag adds a paragraph break after the text?**

The `<p>` tag.


9. **Which are the two parts that all normal webpages consist of?**

- `<head>`

- `<body>`

10. **Which tag is used to insert images into your web page?**

The `<img>` tag.

11. **What is CSS?**

CSS (Cascading Style Sheets) is a language used to describe the presentation of a document written
in HTML or XML, including layout, colors, and fonts.

12. **What is a class? What is an ID?**

- A **class** is a reusable style that can be applied to multiple elements. Defined with a `.` in CSS.

- An **ID** is a unique style that applies to only one element. Defined with a `#` in CSS.

13. **What is the difference between an ID selector and CLASS?**

- **ID selector**: Unique, can be used only once per page. Defined with `#`.

- **CLASS selector**: Can be used multiple times on a page. Defined with `.`.

14. **What are different ways to apply styles to a Web page?**

- Inline styles (using the `style` attribute within HTML elements)

- Embedded styles (within a `<style>` tag in the HTML document)

- External styles (linking to a CSS file)

15. **Is CSS case-sensitive?**

No, CSS is not case-sensitive. However, HTML attributes (like class names) are case-sensitive in
XHTML.

16. **What is grouping in CSS?**

Grouping allows multiple selectors to share the same styles. For example:

```css

h1, h2, h3 {

color: blue;

17. **What are the advantages and disadvantages of External Style Sheets?**

- **Advantages**:

- Separation of content and presentation.

- Reusability across multiple pages.


- Easier maintenance.

- **Disadvantages**:

- Extra HTTP request (can be mitigated with caching).

- May not work if the external file is unavailable.

18. **What are the advantages and disadvantages of Inline Styles?**

- **Advantages**:

- Specific to a single element.

- No need for external resources.

- **Disadvantages**:

- Poor separation of content and presentation.

- Harder to maintain.

19. **What are style sheet properties?**

Style sheet properties are CSS properties used to apply styles to HTML elements, such as `color`,
`font-size`, `margin`, `padding`, `border`, etc.

20. **List various font attributes used in style sheet.**

- `font-family`

- `font-size`

- `font-weight`

- `font-style`

- `font-variant`

- `line-height`

21. **Explain inline, embedded, and external style sheets.**

- **Inline style sheets**: Styles applied directly within HTML tags using the `style` attribute.

- **Embedded style sheets**: Styles included within the `<style>` tag in the HTML document's
`<head>`.

- **External style sheets**: Styles defined in a separate `.css` file and linked to the HTML
document using the `<link>` tag.

22. **What is the CSS Box Model used for? What are the elements that it includes?**

The CSS Box Model is used to define the design and layout of elements. It includes:

- `content`: The actual content of the box.

- `padding`: Space between the content and the border.


- `border`: A border surrounding the padding (if any) and content. - `margin`: Space outside the
border.

23. **What are some of the new features and properties in CSS3?**

- Rounded corners with `border-radius`

- Shadows with `box-shadow` and `text-shadow`

- Gradients with `linear-gradient` and `radial-gradient`

- Transitions and animations

- Flexbox and Grid layout systems

24. **What is JavaScript?**

JavaScript is a programming language used to create interactive effects within web browsers.

25. **What is JRE?**

JRE (Java Runtime Environment) is a software package that provides the libraries, Java Virtual
Machine (JVM), and other components to run applications written in Java.

26. **What is the use of `isNaN` function?**

The `isNaN` function is used to determine whether a value is an illegal number (Not-a-Number).

27. **Is it possible to break JavaScript Code into several lines?**

Yes, JavaScript code can be broken into several lines, typically using the `+` operator or proper
syntax conventions.

28. **What is AJAX? Is it a programming language?**

AJAX (Asynchronous JavaScript and XML) is a technique for creating fast and dynamic web pages
by exchanging small amounts of data with the server behind the scenes. It is not a programming
language but a combination of technologies.

29. **What are Ajax applications?**

Ajax applications are web applications that use Ajax techniques to provide a more dynamic and
responsive user experience.

30. **What are the advantages of Ajax?**

- Improved user experience with faster page updates.

- Reduced server load by sending only necessary data.

- Asynchronous data loading.

31. **What are the disadvantages of Ajax?**

- Complexity in implementation.

- Increased dependency on JavaScript.

- Potential security risks.


32. **What are all the technologies used by Ajax?**

- HTML/XHTML and CSS

- DOM (Document Object Model)

- XML/JSON

- XMLHttpRequest

- JavaScript

33. **What are the differences between Ajax and JavaScript?**

JavaScript is a programming language, while Ajax is a technique that uses JavaScript to perform
asynchronous HTTP requests.

34. **Where Ajax cannot be used?**

Ajax cannot be used to fetch data from a different domain due to the same-origin policy (this can
be bypassed using CORS).

35. **How can you find out that an Ajax request has been completed?**

By using the `readyState` and `status` properties of the `XMLHttpRequest` object and checking if
`readyState` is 4 (completed) and `status` is 200 (OK).

36. **Is JavaScript knowledge required to do Ajax?**

Yes, a good understanding of JavaScript is essential to implement Ajax.

37. **Is Ajax said to be a technology platform or is it an architectural style?**

Ajax is considered an architectural style rather than a technology platform.

38. **Is Ajax code cross-browser compatible?**

Most modern browsers support Ajax, but care must be taken to handle browser-specific issues.

39. **What is the name of the object used for Ajax request?**

The `XMLHttpRequest` object.

40. **How many types of ready states are available in Ajax?**

There are 5 ready states:

- 0: Uninitialized

- 1: Loading

- 2: Loaded

- 3: Interactive

- 4: Complete
41. **How is asynchronous processing handled using Ajax?**

By setting the `async` parameter to `true` in the `open` method of `XMLHttpRequest`, allowing the
script to continue executing while the request is being processed.

42. **What is a synchronous request in Ajax?**

A synchronous request blocks the execution of the script until the server responds, set by the
`async` parameter to `false`.

43. **List some common security issues with Ajax.**

- Cross-Site Scripting (XSS)

- Cross-Site Request Forgery (CSRF)

- Data exposure

44. **Does server-side control Ajax interaction? Or Client side?**

Both server-side and client-side can control Ajax interaction. The client-side initiates the request
using JavaScript, and the server-side processes the request and sends a response back to the client.

45. **What is an Ajax Framework?**

An Ajax framework is a library or set of libraries that simplifies the use of Ajax by providing pre-
built functions and methods for making asynchronous HTTP requests and handling responses. These
frameworks help developers avoid the complexities of directly using the `XMLHttpRequest` object
and dealing with cross-browser compatibility issues.

46. **Explain in brief about XMLHttpRequest object.**

The `XMLHttpRequest` object is used in JavaScript to interact with servers. It allows you to:

- Retrieve data from a URL without having to do a full page refresh.

- Send data to a server in the background.

- Update a web page without reloading it.

Example of basic usage:

```javascript

var xhr = new XMLHttpRequest();

xhr.open('GET', 'url/to/resource', true);

xhr.onreadystatechange = function() {

if (xhr.readyState == 4 && xhr.status == 200) {

// Process the response

console.log(xhr.responseText);

};
xhr.send();

47. **List some commonly used Ajax Frameworks.**

- jQuery

- AngularJS

- React

- Vue.js

- Axios

- Prototype

- Dojo Toolkit

48. **Is it possible to set session variables from JavaScript?**

No, JavaScript running in the browser cannot directly set session variables on the server. However,
JavaScript can make an Ajax request to a server-side script (written in PHP, ASP.NET, etc.) that sets the
session variables.

49. **How can we submit a form or a part of a form without a page refresh?**

By using Ajax to submit the form data:

```html

<form id="myForm">

<input type="text" name="name">

<input type="submit" value="Submit">

</form>

<script>

document.getElementById('myForm').onsubmit = function(e) {

e.preventDefault(); // Prevent the default form submission

var xhr = new XMLHttpRequest();

xhr.open('POST', 'url/to/submit', true);

xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

xhr.onreadystatechange = function() {

if (xhr.readyState == 4 && xhr.status == 200) {

// Handle the response

console.log(xhr.responseText);

};
var formData = new FormData(document.getElementById('myForm'));

xhr.send(new URLSearchParams(formData).toString());

};

</script>

50. **How do we pass parameters to the server using GET and POST requests?**

- **GET request:**

Parameters are appended to the URL.

```javascript

var xhr = new XMLHttpRequest();

xhr.open('GET', 'url/to/resource?param1=value1&param2=value2', true);

xhr.send();

```

- **POST request:**

Parameters are sent in the request body.

```javascript

var xhr = new XMLHttpRequest();

xhr.open('POST', 'url/to/resource', true);

xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

xhr.send('param1=value1&param2=value2');

```

Using the `FormData` object for `POST` requests:

```javascript

var formData = new FormData();

formData.append('param1', 'value1');

formData.append('param2', 'value2');

var xhr = new XMLHttpRequest();

xhr.open('POST', 'url/to/resource', true);

xhr.send(formData);
1. **What is DBMS?**

DBMS (Database Management System) is a software system that provides a way to store, retrieve,
and manage data in databases. It ensures data integrity, security, and consistency.

2. **What are advantages of DBMS over traditional file-based systems?**

- **Data Redundancy and Inconsistency Control**: DBMS reduces data redundancy and ensures
data consistency.

- **Data Sharing**: Multiple users can access the database simultaneously.

- **Data Security**: Access control mechanisms ensure that only authorized users can access the
data.

- **Data Integrity**: Constraints can be applied to maintain data accuracy and consistency.

- **Backup and Recovery**: Automated backup and recovery processes ensure data is safe and
recoverable.

3. **What is a Database?**

A database is an organized collection of structured information or data, typically stored


electronically in a computer system. A DBMS manages the database.

4. **What is the Role of Query Processor?**

The query processor translates user queries into a series of low-level instructions that the DBMS
can understand and execute to retrieve the desired data. It optimizes query execution and ensures
efficient data retrieval.

5. **What is the Role of Database Manager and File Manager?**

- **Database Manager**: Manages the database structure, enforces constraints, and ensures data
integrity, security, and concurrency control.

- **File Manager**: Manages the allocation of space on the storage device, and handles reading
and writing of data to and from the disk.

6. **What are called as Metadata?**

Metadata is data about data. It describes the structure, operations, constraints, and semantics of
the data in the database. Examples include table definitions, data types, and index information.

7. **What is conceptual level in database architecture?**

The conceptual level provides a unified view of the entire database, independent of how data is
physically stored. It describes what data is stored, the relationships among the data, and constraints
on the data.

8. **With example explain internal level and external level**

- **Internal Level**: Describes the physical storage of the database. It deals with data storage and
access methods.
- Example: The way a DBMS stores data in files and indexes on disk.

- **External Level**: Describes how users view the data. It involves user interfaces and application
programs.

- Example: A web application displaying user information from the database.

9. **What is RDBMS?**

RDBMS (Relational Database Management System) is a type of DBMS that uses the relational
model to manage data. Data is organized into tables (relations) with rows (tuples) and columns
(attributes).

10. **Is Oracle a DBMS or RDBMS?**

Oracle is an RDBMS.

11. **Define some DBMS models used with example.**

- **Hierarchical Model**: Data is organized in a tree-like structure.

- Example: IBM's Information Management System (IMS).

- **Network Model**: Data is organized in a graph, allowing many-to-many relationships.

- Example: Integrated Data Store (IDS).

- **Relational Model**: Data is organized into tables with rows and columns.

- Example: Oracle, MySQL, SQL Server.

- **Object-Oriented Model**: Data is stored as objects, similar to object-oriented programming.

- Example: db4o, ObjectDB.

12. **What are attributes?**

Attributes are the properties or characteristics of an entity in a database. In a table, attributes are
the columns.

13. **What are tuples?**

Tuples are rows in a table. Each tuple represents a single record in the table.

14. **What is degree?**

The degree of a relation (table) is the number of attributes (columns) it contains.

15. **What is cardinality?**

The cardinality of a relation (table) is the number of tuples (rows) it contains.

16. **What are Keys in a table?**

Keys are attributes or sets of attributes that uniquely identify tuples in a table. They ensure data
integrity and establish relationships between tables.

17. **What is a candidate Key?**


A candidate key is an attribute or a set of attributes that can uniquely identify a tuple in a table. A
table can have multiple candidate keys.

18. **What is a Primary Key?**

A primary key is a candidate key that is chosen to uniquely identify tuples in a table. It cannot have
null values.

19. **What is a Super Key?**

A super key is a set of one or more attributes that can uniquely identify a tuple in a table. It can
include extra attributes that are not necessary for unique identification.

20. **What is a Foreign Key?**

A foreign key is an attribute or a set of attributes in one table that refers to the primary key in
another table. It establishes a relationship between the two tables.

21. **What is a surrogate Key?**

A surrogate key is an artificial key used to uniquely identify tuples in a table. It is usually a
sequential number and has no business meaning.

22. **Differentiate between Primary Key and Unique Key.**

- **Primary Key**:

- Uniquely identifies tuples in a table.

- Cannot have null values.

- Only one primary key is allowed per table.

- **Unique Key**:

- Ensures all values in a column or set of columns are unique.

- Can have a single null value (depending on the DBMS).

- Multiple unique keys are allowed per table.


1. Oracle DB Features

- **Oracle Real Application Clusters (RAC)**: Enables a single database to run across multiple
servers, providing high availability and scalability.

- **Data Guard**: Provides disaster recovery and data protection through primary and standby
databases.

- **Automatic Storage Management (ASM)**: Simplifies database storage management by


integrating file system and volume manager capabilities.

- **Advanced Security**: Ensures data security through encryption, data masking, and redaction.

- **Oracle Data Pump**: Offers fast data import and export capabilities with features like parallel
processing and fine-grained object selection.

2. What is SQL?

SQL (Structured Query Language) is a standardized programming language used to manage and
manipulate relational databases. It is used for querying, updating, and managing data within a
database.

3. Is SQL an ANSI Standard Language or EBCDIC Standard Language for Operating RDBMS?

SQL is an ANSI (American National Standards Institute) standard language for operating RDBMS
(Relational Database Management Systems).

4. Define and Differentiate Between DDL, DML, and DCL

- **DDL (Data Definition Language)**: Used to define and modify database structures. Examples
include `CREATE`, `ALTER`, `DROP`.

- **DML (Data Manipulation Language)**: Used for data manipulation. Examples include `INSERT`,
`UPDATE`, `DELETE`, `SELECT`.

- **DCL (Data Control Language)**: Used to control access to data. Examples include `GRANT`,
`REVOKE`.

5. What is Projection Operation?

Projection operation in SQL is used to select certain columns from a table, effectively reducing the
number of columns.

6. What is Selection Operation?

Selection operation in SQL is used to select certain rows from a table based on a specified condition.

7. Order of Clauses in Select Statement

The order of various clauses in a `SELECT` statement is:

1. `SELECT`

2. `FROM`

3. `WHERE`
4. `GROUP BY`

5. `HAVING`

6. `ORDER BY`

8. Behavior of Wild Card Character `*` in Select Statement

The wild card character `*` in a `SELECT` statement selects all columns from the specified table.

9. Can We Give Negative Values in Order By Clause?

No, `ORDER BY` clause does not accept negative values. It only accepts column names or positions,
and sorting order (ASC or DESC).

### 10. Use of HAVING Clause Over WHERE Clause

The `HAVING` clause is used to filter groups of rows after the `GROUP BY` clause has been applied,
while the `WHERE` clause is used to filter rows before grouping.

### 11. Group Functions Return Result for Each and Every Row in the Table

False. Group functions return a single result for a group of rows.

### 12. Group Functions Include Nulls in Calculations

False. Group functions ignore `NULL` values in their calculations.

### 13. The Clause Restricts Rows Before Inclusion in a WHERE Group Calculation

True. The `WHERE` clause restricts rows before they are grouped.

### 14. The Join Which Does Cartesian Product is Called

Cross Join.

### 15. Are Full Outer Join and Cross Join Same?

No. A Cross Join produces a Cartesian product of two tables, while a Full Outer Join returns all rows
when there is a match in one of the tables.

### 16. Join Which Returns All Records from Right Table with Matching Records from Left Table, and
NULL for Non-Matching Left Table Values

Right Outer Join.


### 17. What are Also Called Self Joins?

Self Joins.

### 18. Other Name of Inner Join

Equi Join.

### 19. Types of Inner Joins

- Equi Join

- Natural Join

- Cross Join (though usually considered separate, it’s often confused with Inner Join)

- Theta Join

### 20. Type of Inner Join Restricting Fetching of Redundant Data

Natural Join.

### 21. Type Used for Joining Table to Itself

Self Join.

### 22. Can Sequence and Number of Columns and Values be Different in an Insert Statement?

No. The number and sequence of columns and values must match in an `INSERT` statement.

### 23. Column-wise Insertion of Data vs. Simply Passing Values

Column-wise insertion specifies the columns in which values are to be inserted, which ensures that
data is inserted into the correct columns even if the table structure changes.

### 24. Update Statement is Used to Insert Values in a Table and Thus a Replacement of Insert
Statement

False. The `UPDATE` statement modifies existing records, while `INSERT` adds new records.

### 25. Is Mentioning Column Name Corresponding to Its Value Mandatory in Update Statement?

Yes. It is mandatory to specify the column name with its corresponding value in an `UPDATE`
statement.
### 26. Consequence of Omitting “Where” Clause in Update Statement

Omitting the `WHERE` clause in an `UPDATE` statement updates all rows in the table.

### 27. Can Update Statement be Used in Place of Insert Statement?

No. `UPDATE` modifies existing records, while `INSERT` adds new records.

### 28. Can an Insert be Used in Place of Update?

No. `INSERT` adds new records, while `UPDATE` modifies existing records.

### 29. Can We Use “Where” Clause in Insert Statement?

No. The `INSERT` statement does not support a `WHERE` clause.

### 30. Basic Syntax for Delete Query

```sql

DELETE FROM table_name WHERE condition;

```

### 31. Clause in Delete Statement Leading to Delete with Certain Criteria

`WHERE` clause.

### 32. Delete Statement Locks Whole Table or Single Row at a Time

It depends on the database system and isolation level, but typically it locks the rows affected by the
`DELETE` statement.

### 33. Can Delete be Used in Views?

Yes, if the view is updatable, `DELETE` can be used on it.

You might also like