Java Full Stack Interview Questions
Java Full Stack Interview Questions
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.
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.
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.
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:
8. 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.
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.
In Java, command line arguments are passed to the `main` method as an array of `String` objects.
Here is an example:
```java
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:
To declare an array in Java, you specify the data type followed by square brackets. Here is an
example:
```java
```
You can find the length of an array using the `length` property. For example:
```java
```
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.
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
```
1. **Platform Independence**: Java programs can run on any platform with a JVM.
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.
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.
**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.
- 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.
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
// No fields
// No methods
- 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.
**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.
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() {
void bark() {
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
MyClass() {
}
public static void main(String[] args) {
new MyClass();
new MyClass();
**Example:**
```java
class BaseClass {
}
}
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
int value;
MyClass(int value) {
void display() {
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
class InnerClass {
void display() {
System.out.println("Outer value: " + outerValue); // Access outer class member
```
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() {
void makeSound() {
System.out.println("Dog barks");
```
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");
Dog() {
System.out.println("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.
39. Explain with an example how we can access a hidden base class variable.
**Example:**
```java
class BaseClass {
void display() {
```
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
void eat() {
void makeSound() {
System.out.println("Dog barks");
}
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
```
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
System.out.println(AbstractClass.staticVar); // Output: 10
```
**Example:**
```java
```
- 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
```
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.
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.
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.
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();
```
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.
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:**
- 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();
System.out.println("Method1 implementation");
System.out.println("Method2 implementation");
**Example:**
```java
- **Abstract Classes:**
- **Interfaces:**
- Can only have abstract methods (until Java 8, which introduced default and static methods).
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.
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;
```
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?
```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
```
Exceptions are events that disrupt the normal flow of a program's execution. They are objects that
represent errors and other exceptional conditions.
- **Exceptions:** Handled using try-catch blocks and can occur during runtime (e.g., `IOException`,
`SQLException`).
- **Compile-time Errors:** Errors detected by the compiler, such as syntax errors or missing classes.
61. What are the 2 types of exception classification? Explain its differences.
```java
```
```java
if (b == 0) {
throw new ArithmeticException("Division by zero");
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 {
} catch (Exception e) {
// handling exception
} finally {
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 {
} finally {
64. What is the difference between throw and throws keyword in Java?
```java
```
- **throws:** Used in the method signature to declare that the method might throw exceptions.
```java
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
User-defined exceptions are custom exceptions created by extending the `Exception` class or its
subclasses to handle specific application conditions.
**Example:**
```java
super(message);
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.
Custom messages can be provided by passing a string message to the constructor of the exception.
**Example:**
```java
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:**
- **Boxing:** Converting a primitive type into its corresponding wrapper class object.
```java
- **Unboxing:** Converting a wrapper class object back to its corresponding primitive type.
```java
The `Cloneable` interface does not contain any methods. It is a marker interface used to indicate that
a class supports cloning.
- **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.
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.
The `Serializable` interface does not contain any methods. It is a marker interface used to indicate
that a class can be serialized.
83. What are the static variables found in System Class in Java?
- **ArrayList:**
- **LinkedList:**
- **ListIterator:** Can iterate over lists in both forward and backward directions, and allows
modification of the list.
- **Set:** Does not allow duplicate elements, does not guarantee order (except for specific
implementations like `LinkedHashSet`).
- **HashMap:** Not synchronized, allows one `null` key and multiple `null` values.
- **Comparable:** Used to define natural ordering of objects, implemented by the class itself.
```java
// comparison logic
```
```java
// comparison logic
}
Properties files are used to store configuration data in a key-value format. They provide a simple way
to manage application settings and internationalization.
- `ArrayList`
- `LinkedList`
- `Vector`
- `Stack`
- Streams API
- Enhanced `Map` interface with methods like `forEach`, `compute`, `merge`, etc.
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:**
- Encourages software reuse with a well-designed set of interfaces and abstract classes.
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.add("Hello");
- `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.
- 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.
- 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.
```java
This ensures that all operations on the list are synchronized, making it thread-safe.
- 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.
- Iterators provide a way to traverse collections in a uniform manner without exposing the underlying
structure of the collection. Advantages include:
- Uniform access to elements across different types of collections (lists, sets, maps, etc.).
**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.
- `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`.
- 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.
- `Comparable` and `Comparator` are interfaces used for sorting objects in Java:
- **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:**
- **Differences:**
- **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:
- `entrySet()`: Returns a `Set` view of the key-value pairs (`Map.Entry` objects) contained in the map.
- `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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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?**
- Annotations (`@Test`, `@Before`, `@After`, etc.) for defining test methods and setup/teardown
operations.
- Assertion methods (`assertEquals()`, `assertTrue()`, etc.) for verifying expected outcomes.
- Integration with IDEs and build tools for seamless test execution.
- 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.
- 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.
- **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:
- `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.**
- `Before`, `After`, `BeforeClass`, `AfterClass`: Annotations for setup and teardown methods.
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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
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.
- 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.
- 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.
- **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).
- 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.
- 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.
- **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.
- **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.
- 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.
- 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.
- 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`.
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.
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.
- **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.
**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.
- 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.
**8. What is the difference between forwarding a request and redirecting a request?**
- **Translation:** JSP source code is translated into a servlet class by the JSP container.
- **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.
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.
- 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.
- **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.
- **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.
- **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.
- **Query:** Executes queries against the database, using HQL or native SQL.
- **`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.
- **`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.
- **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.
- 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?**
- **One-to-One:** Links one instance of an entity to another instance of the same entity.
- 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.
- 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.
- Elements must be properly nested and closed (either with a closing tag or self-closing tag for
empty elements).
- 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).
- 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.
- 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.
- 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.
- 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.
- Uses its own syntax to define document structure, elements, and attributes.
- Supports only basic data types and cannot define complex data structures easily.
- 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.
- **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?**
- 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.
- 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');
This CSS snippet sets an image as the background for the entire web page.
Yes, a data cell in an HTML table can contain images. Here is an example:
```html
<table>
<tr>
</tr>
</table>
- **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.
- 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?**
7. **Which tag tells the browser as to where the page starts and stops?**
- `<head>`
- `<body>`
10. **Which tag is used to insert images into your web page?**
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.
- 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.
- **ID selector**: Unique, can be used only once per page. Defined with `#`.
- **CLASS selector**: Can be used multiple times on a page. Defined with `.`.
No, CSS is not case-sensitive. However, HTML attributes (like class names) are case-sensitive in
XHTML.
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**:
- **Disadvantages**:
- **Advantages**:
- **Disadvantages**:
- Harder to maintain.
Style sheet properties are CSS properties used to apply styles to HTML elements, such as `color`,
`font-size`, `margin`, `padding`, `border`, etc.
- `font-family`
- `font-size`
- `font-weight`
- `font-style`
- `font-variant`
- `line-height`
- **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:
23. **What are some of the new features and properties in CSS3?**
JavaScript is a programming language used to create interactive effects within web browsers.
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.
The `isNaN` function is used to determine whether a value is an illegal number (Not-a-Number).
Yes, JavaScript code can be broken into several lines, typically using the `+` operator or proper
syntax conventions.
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.
Ajax applications are web applications that use Ajax techniques to provide a more dynamic and
responsive user experience.
- Complexity in implementation.
- XML/JSON
- XMLHttpRequest
- JavaScript
JavaScript is a programming language, while Ajax is a technique that uses JavaScript to perform
asynchronous HTTP requests.
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).
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?**
- 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.
A synchronous request blocks the execution of the script until the server responds, set by the
`async` parameter to `false`.
- Data exposure
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.
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.
The `XMLHttpRequest` object is used in JavaScript to interact with servers. It allows you to:
```javascript
xhr.onreadystatechange = function() {
console.log(xhr.responseText);
};
xhr.send();
- jQuery
- AngularJS
- React
- Vue.js
- Axios
- Prototype
- Dojo Toolkit
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?**
```html
<form id="myForm">
</form>
<script>
document.getElementById('myForm').onsubmit = function(e) {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function() {
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:**
```javascript
xhr.send();
```
- **POST request:**
```javascript
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('param1=value1¶m2=value2');
```
```javascript
formData.append('param1', 'value1');
formData.append('param2', 'value2');
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.
- **Data Redundancy and Inconsistency Control**: DBMS reduces data redundancy and ensures
data consistency.
- **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?**
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.
- **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.
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.
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.
- **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.
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).
Oracle is an RDBMS.
- **Relational Model**: Data is organized into tables with rows and columns.
Attributes are the properties or characteristics of an entity in a database. In a table, attributes are
the columns.
Tuples are rows in a table. Each tuple represents a single record in the table.
Keys are attributes or sets of attributes that uniquely identify tuples in a table. They ensure data
integrity and establish relationships between tables.
A primary key is a candidate key that is chosen to uniquely identify tuples in a table. It cannot have
null values.
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.
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.
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.
- **Primary Key**:
- **Unique Key**:
- **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.
- **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).
- **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`.
Projection operation in SQL is used to select certain columns from a table, effectively reducing the
number of columns.
Selection operation in SQL is used to select certain rows from a table based on a specified condition.
1. `SELECT`
2. `FROM`
3. `WHERE`
4. `GROUP BY`
5. `HAVING`
6. `ORDER BY`
The wild card character `*` in a `SELECT` statement selects all columns from the specified table.
No, `ORDER BY` clause does not accept negative values. It only accepts column names or positions,
and sorting order (ASC or DESC).
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
### 13. The Clause Restricts Rows Before Inclusion in a WHERE Group Calculation
True. The `WHERE` clause restricts rows before they are grouped.
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
Self Joins.
Equi Join.
- Equi Join
- Natural Join
- Cross Join (though usually considered separate, it’s often confused with Inner Join)
- Theta Join
Natural Join.
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.
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.
No. `UPDATE` modifies existing records, while `INSERT` adds new records.
No. `INSERT` adds new records, while `UPDATE` modifies existing records.
```sql
```
### 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.