CorejavaInterviewBooster13
CorejavaInterviewBooster13
only one thread to access a block of code or method at a time for a given object or
class. Here’s a detailed explanation of the three variations you mentioned:
---
#### **Example:**
```java
class Display {
public void displayNumbers() {
synchronized (this) {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " - " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
t1.start();
t2.start();
}
}
```
**Expected Output:**
```
Thread-1 - 1
Thread-1 - 2
Thread-1 - 3
Thread-1 - 4
Thread-1 - 5
Thread-2 - 1
Thread-2 - 2
Thread-2 - 3
Thread-2 - 4
Thread-2 - 5
```
---
#### **Example:**
```java
class Display {
private final Object lock = new Object();
t1.start();
t2.start();
}
}
```
---
#### **Example:**
```java
class Display {
public static void displayStaticNumbers() {
synchronized (Display.class) {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " - " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
t1.start();
t2.start();
}
}
```
**Expected Output:**
```
Thread-1 - 1
Thread-1 - 2
Thread-1 - 3
Thread-1 - 4
Thread-1 - 5
Thread-2 - 1
Thread-2 - 2
Thread-2 - 3
Thread-2 - 4
Thread-2 - 5
```
---
---
---
---
#### **Example**:
```java
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
try {
System.out.println("Doing something else while the task is
running...");
Integer result = future.get(); // Waits for the task to complete and
gets the result
System.out.println("Result of the task: " + result);
} catch (Exception e) {
e.printStackTrace();
} finally {
executor.shutdown();
}
}
}
```
**Output**:
```
Doing something else while the task is running...
Result of the task: 42
```
---
#### **Example**:
```java
import java.util.concurrent.Callable;
try {
System.out.println(task.call());
} catch (Exception e) {
System.out.println("Caught exception: " + e.getMessage());
}
}
}
```
**Output**:
```
Caught exception: Something went wrong!
```
---
#### **Example**:
```java
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.ArrayList;
import java.util.List;
try {
List<Future<Integer>> results = executor.invokeAll(tasks);
for (Future<Integer> result : results) {
System.out.println("Result: " + result.get());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
executor.shutdown();
}
}
}
```
**Output**:
```
Result: 1
Result: 4
Result: 9
Result: 16
Result: 25
```
---
---
---
**Example:**
```java
class Car {
String model;
int year;
**Explanation:**
- `Car myCar = new Car("Tesla", 2022);`: The `new` keyword creates a new
instance of the `Car` class and assigns it to the `myCar` reference variable.
- This is the most common and direct way to create objects.
**Example:**
```java
class Car {
String model;
Car(String model) {
this.model = model;
}
}
**Example:**
```java
class Car implements Cloneable {
String model;
Car(String model) {
this.model = model;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
**Explanation:**
- The `clone()` method creates a new object that is a copy of the original `Car`
object.
- This approach is useful for duplicating objects when deep cloning is not
required.
**Example:**
```java
import java.lang.reflect.Constructor;
class Car {
String model;
Car(String model) {
this.model = model;
}
}
**Explanation:**
- The `getConstructor()` method gets the constructor of the `Car` class that
takes a `String` parameter.
- `newInstance()` is used to create the object using the constructor.
**Example:**
```java
class Car {
String model;
Car(String model) {
this.model = model;
}
// Factory Method
public static Car createCar(String model) {
return new Car(model);
}
}
**Explanation:**
- The `createCar()` method is a static factory method that returns a new `Car`
object. This approach encapsulates object creation and can be extended to return
different subclasses or objects based on some logic.
**Example:**
```java
import java.io.*;
Car(String model) {
this.model = model;
}
}
**Explanation:**
- The object is serialized to a file using `ObjectOutputStream`.
- The object is deserialized using `ObjectInputStream`, creating a new instance
of the object.
- This is useful for object persistence.
**Example:**
```java
enum Car {
TESLA, BMW, AUDI;
}
**Explanation:**
- Enum constants like `Car.TESLA` are instances of the `Car` enum. These
instances are created automatically.
**Example:**
```java
import java.util.function.Supplier;
class Car {
String model;
Car(String model) {
this.model = model;
}
}
**Explanation:**
- A `Supplier<Car>` is created using a lambda expression, and the `get()` method
is called to create a new `Car` object.
---
Each method has its use cases and is suitable for different scenarios. The most
common way is using the `new` keyword, but others, like reflection or factory
methods, can be used depending on the design needs.
==================================
In Spring Data JPA, the `@Transactional` annotation provides declarative
transaction management. One of its key attributes is `rollbackFor` (commonly
misspelled as "roolbackon"), which specifies the exceptions that should cause the
transaction to roll back.
---
### Syntax
```java
@Transactional(rollbackFor = {ExceptionType1.class, ExceptionType2.class})
```
---
### Example
Suppose you have a service that processes orders and needs to ensure that any
exception, including checked exceptions, triggers a rollback.
```java
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String productName;
private int quantity;
```java
import org.springframework.data.jpa.repository.JpaRepository;
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class OrderService {
@Autowired
private OrderRepository orderRepository;
4. **Controller**: `OrderController`
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/orders")
public class OrderController {
@Autowired
private OrderService orderService;
@PostMapping
public String createOrder(@RequestBody Order order) {
try {
orderService.placeOrder(order);
return "Order placed successfully";
} catch (Exception e) {
return "Failed to place order: " + e.getMessage();
}
}
}
```
---
### Explanation
1. **Default Behavior**:
- Without `rollbackFor`, the transaction would not roll back for the `Exception`
(a checked exception), and the invalid order would remain in the database.
2. **Custom Behavior**:
- By specifying `rollbackFor = {Exception.class}`, the transaction rolls back
even for checked exceptions.
---
### Testing
**Input**:
```json
{
"productName": "Laptop",
"quantity": 150
}
```
**Output**:
```
Failed to place order: Quantity too large
```
- The database remains unchanged since the transaction was rolled back due to the
checked exception.
---
@Id
@GenericGenerator(name = "client_id", strategy =
"com.eframe.model.generator.ClientIdGenerator")
@GeneratedValue(generator = "client_id")
@Column(name="client_id")
private String clientId;
}
@Override
public Serializable generate(SessionImplementor session, Object object)
throws HibernateException {
return null;
}
}
@Override
public Object generate(SharedSessionContractImplementor session, Object object){
============================================================
The `Arrays.asList()` method in Java is part of the `java.util.Arrays` utility
class and is used to create a **fixed-size** list backed by the specified array. It
essentially provides a bridge between an array and the `List` interface, allowing
you to treat an array as a `List`.
---
### Syntax
```java
public static <T> List<T> asList(T... a)
```
- **Parameters**:
- `T... a`: The array elements to be converted into a list.
- **Returns**:
- A `List` containing the array elements.
---
1. **Fixed Size**:
- The returned list is **fixed-size**, meaning you cannot add or remove
elements, but you can modify existing elements.
2. **Backed by Array**:
- Changes to the list reflect in the original array and vice versa.
3. **When to Use**:
- When you need to quickly convert an array into a `List` for easier iteration
or use with methods that accept a `List`.
---
### Example 1: Basic Usage
```java
import java.util.Arrays;
import java.util.List;
// Access elements
System.out.println("List: " + list);
// Modify an element
list.set(1, "D");
System.out.println("Modified List: " + list);
System.out.println("Modified Array: " + Arrays.toString(array)); //
Reflects in the original array
}
}
```
**Output**:
```
List: [A, B, C]
Modified List: [A, D, C]
Modified Array: [A, D, C]
```
---
```java
import java.util.Arrays;
import java.util.List;
try {
list.remove(0); // UnsupportedOperationException
} catch (UnsupportedOperationException e) {
System.out.println("Cannot remove elements: " + e.getMessage());
}
}
}
```
**Output**:
```
Cannot add elements: null
Cannot remove elements: null
```
---
If you need a `List` where you can add or remove elements, wrap the result in a new
`ArrayList`:
```java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
**Output**:
```
Mutable List: [A, B, C, D]
```
---
1. **Quick Conversion**:
- When you need to quickly convert an array into a `List` for easier
manipulation or compatibility with APIs that accept lists.
2. **Iteration**:
- For iterating over array elements using a `List` interface.
---
### Limitations
1. **Fixed Size**:
- You cannot add or remove elements from the list.
2. **Mutability**:
- Changes to the list affect the backing array and vice versa.
3. **Generic Types**:
- Only works with arrays of objects; primitive arrays need to be converted using
boxed types (e.g., `Integer[]` for `int[]`).
---
### Summary
---
2. **Convenience**:
- Instead of setting the model and view separately, `ModelAndView` combines them
into a single object.
---
### Syntax
```java
public ModelAndView(String viewName)
public ModelAndView(String viewName, Map<String, ?> model)
public ModelAndView(String viewName, String modelName, Object modelObject)
```
---
```java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class GreetingController {
@RequestMapping("/greet")
public ModelAndView greet() {
ModelAndView mv = new ModelAndView("greeting"); // View name
mv.addObject("message", "Welcome to Spring MVC!"); // Adding model data
return mv;
}
}
```
- **Explanation**:
- `"greeting"`: The name of the view (e.g., `greeting.jsp` or `greeting.html`).
- `"message"`: A key-value pair added to the model.
---
```java
@RequestMapping("/userDetails")
public ModelAndView userDetails() {
ModelAndView mv = new ModelAndView("user");
mv.addObject("username", "JohnDoe");
mv.addObject("email", "[email protected]");
return mv;
}
```
---
```java
@RequestMapping("/product")
public ModelAndView productDetails() {
Map<String, Object> model = new HashMap<>();
model.put("id", 101);
model.put("name", "Laptop");
model.put("price", 75000);
- This approach is useful when you already have a `Map` of data to send to the
view.
---
If you use a `ViewResolver` (e.g., Thymeleaf or JSP), you can define logical view
names. For example:
```java
// In application.properties (for Thymeleaf):
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
```
```java
@RequestMapping("/dashboard")
public ModelAndView dashboard() {
ModelAndView mv = new ModelAndView("dashboard"); // Resolves to
/templates/dashboard.html
mv.addObject("title", "User Dashboard");
return mv;
}
```
---
2. **Legacy Code**:
- It is often used in legacy Spring MVC applications.
3. **Flexibility**:
- It gives you control to pass model attributes and specify view names
dynamically.
---
Modern Spring MVC applications often use the `Model` or `Map` interface instead of
`ModelAndView`. For example:
```java
@RequestMapping("/modernGreet")
public String modernGreet(Model model) {
model.addAttribute("message", "Welcome to Spring MVC with Model!");
return "greeting"; // View name
}
```
---
### Summary
```properties
spring.mvc.view.prefix=/views/
spring.mvc.view.suffix=.jsp
```
This setup will resolve view names dynamically based on the name returned by your
controller. Spring MVC will automatically append the prefix (`/views/`) and suffix
(`.jsp`) to the view name.
---
```
/views/home.jsp
/views/about.jsp
/views/contact.jsp
```
```java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class PageController {
@GetMapping("/home")
public String homePage() {
return "home"; // Resolves to /views/home.jsp
}
@GetMapping("/about")
public String aboutPage() {
return "about"; // Resolves to /views/about.jsp
}
@GetMapping("/contact")
public String contactPage() {
return "contact"; // Resolves to /views/contact.jsp
}
}
```
2. **How It Works**:
- When the `/home` endpoint is accessed, the `homePage()` method returns
`"home"`.
- Spring MVC adds the prefix (`/views/`) and suffix (`.jsp`) to form the full
path: `/views/home.jsp`.
---
If you have many JSP pages in the `/views/` folder, you can simply return the name
of the desired JSP page from your controller methods. The framework automatically
resolves the correct file path based on the `spring.mvc.view.prefix` and
`spring.mvc.view.suffix` properties.
---
### Dynamic Page Names
If you want to dynamically choose which JSP page to render based on some condition,
you can return the view name conditionally.
```java
@GetMapping("/page")
public String dynamicPage(@RequestParam String name) {
// Dynamically resolve the view based on the "name" parameter
return name; // Resolves to /views/{name}.jsp
}
```
For example:
- Access `/page?name=home` → Resolves to `/views/home.jsp`.
- Access `/page?name=about` → Resolves to `/views/about.jsp`.
---
If you want to organize your JSP files into subfolders within `/views/`, you can
include the subfolder name in the returned view string.
@GetMapping("/templates/contact")
public String contactPage() {
return "templates/contact"; // Resolves to /views/templates/contact.jsp
}
```
---
2. **Organizing Files**:
- You can group JSP files in subfolders and reference them with a path-like view
name (e.g., `subfolder/file`).
3. **Dynamic Selection**:
- Use parameters to dynamically determine which JSP page to render.
This setup makes it easy to manage and render multiple JSP pages without additional
configuration.
==========================================================
// while (num != 0) {
// rev = rev * 10 + num % 10;
// num = num / 10;
// }
=================================================
import java.util.Scanner;
}
if (original_num == rev) {
System.out.println("Entered number is a palindrome");
} else {
System.out.println("Entered number is Not a palindrome");
}
}
}
=================================================
The `@RequestBody` annotation in Spring MVC is used to bind the HTTP request body
to a Java object. It is typically used in RESTful APIs when handling HTTP POST,
PUT, or PATCH requests, where the data is sent in the body of the request (usually
in JSON or XML format).
---
---
**Controller:**
```java
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api")
public class UserController {
@PostMapping("/users")
public String createUser(@RequestBody User user) {
// Access the deserialized User object
return "User created: " + user.getName();
}
}
```
```java
public class User {
private String name;
private int age;
```json
{
"name": "John Doe",
"age": 25
}
```
**Output:**
```
User created: John Doe
```
---
Add validation annotations to the model class and use `@Valid` in the controller to
enforce constraints.
```java
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
```java
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import jakarta.validation.Valid;
@RestController
@RequestMapping("/api")
@Validated
public class UserController {
@PostMapping("/users")
public String createUser(@Valid @RequestBody User user) {
return "Validated user: " + user.getName();
}
}
```
```json
{
"name": "",
"age": 15
}
```
```json
{
"timestamp": "2024-11-27T12:00:00",
"status": 400,
"errors": [
"Name is mandatory",
"Age must be at least 18"
]
}
```
---
You can handle nested objects in the request body by defining them in your model
class.
```java
public class User {
private String name;
private Address address;
**JSON Payload:**
```json
{
"name": "Jane Doe",
"address": {
"street": "123 Main St",
"city": "Springfield"
}
}
```
Spring will automatically deserialize nested objects as well.
---
2. **Complex Input**:
- When handling complex input data structures with nested objects or arrays.
---
=============================================
In Spring MVC, **controller methods** can use different return types to handle
requests and responses. Two commonly used return types are:
1. **`ModelAndView`**
2. **`String`**
Both have distinct purposes and usage patterns. Let's break them down:
---
This allows you to set both the data and the view in a single object.
---
---
#### **Example**
```java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class DemoController {
@GetMapping("/greeting")
public ModelAndView greeting() {
ModelAndView mav = new ModelAndView("greeting"); // View name (e.g.,
greeting.jsp)
mav.addObject("message", "Hello, welcome to Spring MVC!"); // Data to the
view
mav.addObject("name", "John Doe"); // Additional data
#### **Explanation**:
- The `greeting` view will render, and it can use the `message` and `name` values.
- The view file could be `greeting.jsp` in this case.
#### **Advantages**:
- Combines data (`Model`) and view (`View`) in one return type.
- Explicitly specifies both the view and the data.
---
---
---
#### **Example**
```java
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class DemoController {
@GetMapping("/welcome")
public String welcome(Model model) {
model.addAttribute("message", "Welcome to Spring MVC!"); // Add data to the
model
return "welcome"; // View name (e.g., welcome.jsp)
}
}
```
#### **Explanation**:
- The `welcome` view will render, and it can access the `message` attribute via the
`Model`.
#### **Advantages**:
- Simpler and more concise when only the view name and a small amount of data are
needed.
---
| **Aspect** | **`ModelAndView`** |
**`String`** |
|-----------------------|---------------------------------------------|------------
---------------------------------|
| **Purpose** | Combines view name and data. | Represents
the view name only. |
| **Flexibility** | More flexible for complex scenarios. | Simpler for
straightforward cases. |
| **Data Passing** | Data is added via `addObject()`. | Data is
passed using the `Model` object. |
| **Dynamic View Name** | Easier to set dynamically. | Requires
additional logic for dynamic names.|
| **Code Style** | Slightly verbose. | Cleaner and
concise. |
---
- Use **`ModelAndView`**:
- If you need to set the view name dynamically.
- When working with complex data models.
- If combining data and view into one return type makes sense for your use case.
- Use **`String`**:
- If the view name is static.
- When the model data is simple.
- To keep the code concise and readable.
---
2. **`ResponseEntity`**:
- Used in RESTful APIs to return a response body with HTTP status codes.
---
============================================================
Securing REST APIs is essential to protect data, prevent unauthorized access, and
ensure the integrity of the system. Below are best practices and techniques to
secure REST APIs in Java-based projects, especially with frameworks like Spring
Boot:
---
## **1. Use HTTPS**
---
Authentication ensures only valid users can access the API. Common methods:
Example:
```java
Authorization: Bearer <your-token>
```
---
---
Example:
```java
@Valid
public ResponseEntity<?> createUser(@RequestBody @Valid UserDTO user) {
// Automatically validates fields
}
```
---
Example:
```yaml
spring:
cloud:
gateway:
routes:
- id: rate_limit_route
uri: http://your-api
predicates:
- Path=/api/**
filters:
- name: RequestRateLimiter
args:
redis-rate-limiter:
replenishRate: 10
burstCapacity: 20
```
---
Example Header:
```http
X-API-KEY: your-api-key
```
---
---
---
---
## **10. Secure Data**
---
---
- Set **Content Security Policies (CSP)** headers to mitigate XSS and data
injection attacks:
```java
http.headers().contentSecurityPolicy("script-src 'self'; object-src 'none';");
```
---
- Periodically review and test your APIs for vulnerabilities using tools like:
- OWASP ZAP
- Burp Suite
---
- API gateways like **Kong**, **Zuul**, or **AWS API Gateway** provide centralized
security features like:
- Authentication.
- Rate limiting.
- Logging.
---
```java
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/api/public/**").permitAll() // Public APIs
.antMatchers("/api/private/**").authenticated() // Secure APIs
.and()
.httpBasic(); // Or JWT Authentication
}
}
```
---
By combining these practices, you can build robust, secure REST APIs. Let me know
if you'd like examples for a specific method!
==============================================
To configure JWT (JSON Web Token) security in a Spring Boot application, you need
to implement the following components:
---
For **Gradle**:
```gradle
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'io.jsonwebtoken:jjwt-api:0.11.5'
runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.11.5'
runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.11.5'
```
---
import java.security.Key;
import java.util.Date;
import org.springframework.stereotype.Component;
@Component
public class JwtUtil {
Jwts.parserBuilder().setSigningKey(getSigningKey()).build().parseClaimsJws(token);
return true;
} catch (JwtException e) {
return false; // Invalid token
}
}
---
import java.io.IOException;
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
@Autowired
private JwtUtil jwtUtil;
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
response, FilterChain filterChain)
throws ServletException, IOException {
if (jwtUtil.validateToken(jwt)) {
UsernamePasswordAuthenticationToken authToken =
new UsernamePasswordAuthenticationToken(userDetails, null,
userDetails.getAuthorities());
authToken.setDetails(new
WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authToken);
}
}
filterChain.doFilter(request, response);
}
}
```
---
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http,
JwtAuthenticationFilter jwtAuthenticationFilter) throws Exception {
http
.csrf().disable()
.authorizeHttpRequests()
.requestMatchers("/auth/**").permitAll() // Open endpoints (e.g.,
login)
.anyRequest().authenticated() // Secure all other endpoints
.and()
.addFilterBefore(jwtAuthenticationFilter,
UsernamePasswordAuthenticationFilter.class);
return http.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration
configuration) throws Exception {
return configuration.getAuthenticationManager();
}
}
```
---
This controller handles login and generates JWT tokens for valid users.
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import
org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/auth")
public class AuthController {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private JwtUtil jwtUtil;
@PostMapping("/login")
public String login(@RequestBody AuthRequest authRequest) {
try {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(authRequest.getUsername(),
authRequest.getPassword())
);
return jwtUtil.generateToken(authentication.getName());
} catch (AuthenticationException e) {
throw new RuntimeException("Invalid username or password");
}
}
}
// Request DTO
class AuthRequest {
private String username;
private String password;
---
All endpoints, except `/auth/**`, are secured. Include the JWT token in the
`Authorization` header for authenticated requests.
---
This setup ensures your API is protected with JWT-based authentication. Let me know
if you need further clarification!
=============================================