Wednesday, October 15, 2025

Java Questions

 How exceptions are handled in applications

Exception handling is a mechanism to handle runtime errors, so the normal flow of the application can be maintained instead of crashing.

Java uses a structured approach with five main keywords:
try, catch, finally, throw, and throws.


Throwable

├── Exception

│   ├── Checked Exceptions (e.g., IOException, SQLException)

│   └── Unchecked Exceptions (RuntimeException and its subclasses)

│       ├── NullPointerException

│       ├── ArithmeticException

│       └── IllegalArgumentException

└── Error (e.g., OutOfMemoryError, StackOverflowError)

Checked exceptions:
Must be either handled with try-catch or declared using throws.
Unchecked exceptions: Occur at runtime; not required to be declared or caught.
Errors: Usually not handled — they indicate serious system issues.


3. How Exceptions Are Handled in Applications

A. Using try-catch-finally

You wrap risky code in a try block and handle specific exceptions in catch blocks.

B. Using throws in Method Signatures

If a method can’t handle an exception, it can declare it and let the caller handle it.

C. Using throw to Manually Raise Exceptions

You can create and throw exceptions explicitly.



Global Exception Handlers

Frameworks use centralized exception handling via annotations like:


@RestControllerAdvice

public class GlobalExceptionHandler {

    

    @ExceptionHandler(ResourceNotFoundException.class)

    public ResponseEntity<String> handleNotFound(ResourceNotFoundException ex) {

        return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);

    }


    @ExceptionHandler(Exception.class)

    public ResponseEntity<String> handleGeneric(Exception ex) {

        return new ResponseEntity<>("Something went wrong", HttpStatus.INTERNAL_SERVER_ERROR);

    }

}


Best Practices

  • Catch only what you can handle meaningfully.

  • Use custom exceptions for domain-specific errors.

  • Never swallow exceptions silently (catch (Exception e) {} is bad).

  • Log exceptions with meaningful messages.

  • Always release resources (use finally or try-with-resources).



Excellent question ๐Ÿ‘ — this is a common Java interview question that tests your understanding of serialization and the transient keyword.

Let’s go step by step ๐Ÿ‘‡


๐Ÿงฉ 1. What is Serialization?

Serialization in Java is the process of converting an object into a byte stream so it can be:

  • Saved to a file

  • Sent over a network

  • Stored in memory or cache

This is done using the Serializable interface.

import java.io.Serializable;

class Employee implements Serializable {
    private int id;
    private String name;
}

When you serialize such an object, all its non-static, non-transient fields are saved.


⚙️ 2. How to Avoid a Variable from Being Serialized

Use the transient keyword

When you mark a variable as transient, Java skips it during serialization.

import java.io.Serializable;

class Employee implements Serializable {
    private int id;
    private String name;
    private transient String password; // ๐Ÿšซ will not be serialized

    public Employee(int id, String name, String password) {
        this.id = id;
        this.name = name;
        this.password = password;
    }
}

๐Ÿงช 3. Example

import java.io.*;

class Employee implements Serializable {
    private static final long serialVersionUID = 1L;

    int id;
    String name;
    transient String password;

    public Employee(int id, String name, String password) {
        this.id = id;
        this.name = name;
        this.password = password;
    }
}

public class TestSerialization {
    public static void main(String[] args) throws Exception {
        Employee e = new Employee(1, "John", "secret123");

        // Serialize
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("emp.ser"));
        out.writeObject(e);
        out.close();

        // Deserialize
        ObjectInputStream in = new ObjectInputStream(new FileInputStream("emp.ser"));
        Employee emp = (Employee) in.readObject();
        in.close();

        System.out.println("ID: " + emp.id);
        System.out.println("Name: " + emp.name);
        System.out.println("Password: " + emp.password); // will print null
    }
}

๐ŸŸข Output:

ID: 1
Name: John
Password: null

๐Ÿ’ก 4. Alternative Ways (Advanced)

In some advanced scenarios, you can customize serialization without transient, for example:

a. Override writeObject() and readObject()

You can manually control which fields to serialize.

private void writeObject(ObjectOutputStream oos) throws IOException {
    oos.defaultWriteObject();  // write normal fields
    // don't write sensitive fields
}

private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
    ois.defaultReadObject();
    // reinitialize transient/sensitive fields if needed
}

b. Use Externalizable

Implement Externalizable instead of Serializable, and explicitly write/read the desired fields.

class Employee implements Externalizable {
    int id;
    String name;
    String password;

    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeInt(id);
        out.writeObject(name);
        // skip password
    }

    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        id = in.readInt();
        name = (String) in.readObject();
    }
}

๐Ÿง  5. Common Interview Follow-ups

Question Short Answer
What happens to a transient variable after deserialization? It becomes null (for objects) or 0 / false for primitives.
Can static variables be serialized? No — because they belong to the class, not the object.
Can you serialize a non-serializable object inside a serializable class? Only if that field is marked transient, otherwise NotSerializableException will occur.



Excellent — this is a core Spring Boot interview question ๐Ÿ’ก
Let’s break it down clearly and completely ๐Ÿ‘‡


⚙️ What is @SpringBootApplication?

@SpringBootApplication is a convenience annotation that marks the main class of a Spring Boot application.

It tells Spring Boot to:

  • Auto-configure the application,

  • Scan for components (like @Controller, @Service, @Repository), and

  • Enable configuration support.


๐Ÿงฉ 1. Defined As a Combination of Three Annotations

Internally, @SpringBootApplication is a shorthand for:

@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan
public @interface SpringBootApplication {
}

Let’s see what each does ๐Ÿ‘‡


๐Ÿ”น A. @SpringBootConfiguration

  • It’s itself a specialization of @Configuration.

  • Marks the class as a source of bean definitions.

  • You can define beans using @Bean methods inside it.

@SpringBootConfiguration
public class MyAppConfig {
    @Bean
    public DataSource dataSource() {
        return new HikariDataSource();
    }
}

✅ Essentially: Tells Spring “This class can define beans.”


๐Ÿ”น B. @EnableAutoConfiguration

  • Tells Spring Boot to automatically configure the application based on the dependencies present in the classpath.

Example:

  • If you have spring-boot-starter-web, it auto-configures:

    • DispatcherServlet

    • Embedded Tomcat

    • JSON converters, etc.

✅ It reads META-INF/spring.factories to find configuration classes and auto-wire them.


๐Ÿ”น C. @ComponentScan

  • Tells Spring where to look for beans/components.

By default, it scans the package of the class where @SpringBootApplication is declared and all subpackages.

Example:

@SpringBootApplication  // scans com.example and below
public class MyApp {
    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }
}

If your components are outside that package, you can specify base packages:

@SpringBootApplication(scanBasePackages = "com.mycompany.project")

๐Ÿง  2. How It Works in the Main Class

@SpringBootApplication
public class MySpringBootApp {
    public static void main(String[] args) {
        SpringApplication.run(MySpringBootApp.class, args);
    }
}

✅ What happens here:

  1. Spring Boot starts.

  2. Performs component scanning.

  3. Applies auto-configuration.

  4. Starts the embedded server (if it’s a web app).


๐Ÿงฐ 3. Equivalent Code Without It

If you didn’t use @SpringBootApplication, you’d need to write:

@Configuration
@EnableAutoConfiguration
@ComponentScan(basePackages = "com.example")
public class MyApp {
    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }
}

So @SpringBootApplication is just a shortcut that makes configuration cleaner.


๐Ÿ’ก 4. Common Interview Follow-Ups

Question Short Answer
What does @SpringBootApplication do internally? It combines @Configuration, @EnableAutoConfiguration, and @ComponentScan.
Can we control which packages to scan? Yes — @SpringBootApplication(scanBasePackages = {"com.example", "org.demo"}).
How does auto-configuration work? Through @EnableAutoConfiguration, which loads config classes from spring.factories.
What if we don’t want certain auto-configurations? Use @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}).
Where should this annotation be placed? On the main class in the root package of your project.

5. Summary

Purpose Annotation Description
Declare configuration class @SpringBootConfiguration Allows defining beans
Enable auto configuration @EnableAutoConfiguration Configures app based on dependencies
Scan for beans @ComponentScan Finds @Component, @Service, etc.
Shortcut for all above @SpringBootApplication Cleaner and simpler main entry point

Excellent — another must-know Spring Boot interview question ๐Ÿ‘

Let’s break down Spring Boot Actuator in simple, clear terms — with examples and interview-style insights ๐Ÿ‘‡


⚙️ What is Spring Boot Actuator?

Spring Boot Actuator is a built-in feature that provides production-ready monitoring and management endpoints for your Spring Boot application — without writing extra code.

It gives you insights into your application’s:

  • Health

  • Metrics

  • Environment

  • Configuration

  • Thread dumps

  • HTTP requests, and more.


๐Ÿงฉ 1. Why Actuator Is Needed

In real-world (production) systems, you need to:

  • Know if the app is running (health checks),

  • Monitor performance (memory, CPU, request count),

  • Expose metrics to tools like Prometheus, Grafana, or New Relic,

  • Dynamically change logging levels or configurations.

➡️ Actuator makes all that easy — automatically.


⚙️ 2. How to Enable It

Just add this dependency in your pom.xml (for Maven):

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Or in Gradle:

implementation 'org.springframework.boot:spring-boot-starter-actuator'

Then start your Spring Boot app — done ✅


๐Ÿงญ 3. Common Actuator Endpoints

By default, actuator endpoints are available under /actuator.

Some important ones:

Endpoint Description
/actuator/health Shows application health status
/actuator/info Displays custom info about the app
/actuator/metrics Shows system and app metrics (CPU, memory, etc.)
/actuator/env Shows environment properties
/actuator/beans Shows all Spring beans
/actuator/mappings Shows all URL mappings
/actuator/threaddump Shows thread info
/actuator/loggers View/change log levels dynamically

Example:

http://localhost:8080/actuator/health

๐ŸŸข Response:

{
  "status": "UP"
}

๐Ÿ” 4. Security Configuration

By default, only /actuator/health and /actuator/info are public.
Others are restricted — you must enable them in application.properties:

management.endpoints.web.exposure.include=*

Or to enable only specific endpoints:

management.endpoints.web.exposure.include=health,info,metrics

If you use Spring Security, you can also secure actuator endpoints with roles.


๐Ÿง  5. Customize Health and Info

Add custom info:

management.info.env.enabled=true
info.app.name=Payment Service
info.app.version=1.0.3

Endpoint:

/actuator/info

Response:

{
  "app": {
    "name": "Payment Service",
    "version": "1.0.3"
  }
}

Add custom health indicator:

@Component
public class CustomHealthIndicator implements HealthIndicator {
    @Override
    public Health health() {
        boolean healthy = checkExternalService();
        if (healthy) return Health.up().build();
        return Health.down().withDetail("Error", "External service not reachable").build();
    }
}

๐Ÿ“Š 6. Integration with Monitoring Tools

Actuator can expose metrics in formats compatible with:

  • Prometheus

  • Grafana

  • Micrometer (built-in metrics system)

Just add the relevant dependency:

<dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-registry-prometheus</artifactId>
</dependency>

Then you get metrics at:

/actuator/prometheus

๐Ÿงฉ 7. Example Output (Metrics)

/actuator/metrics/jvm.memory.used

Response:

{
  "name": "jvm.memory.used",
  "measurements": [
    { "statistic": "VALUE", "value": 23456789.0 }
  ],
  "availableTags": [
    { "tag": "area", "values": ["heap", "nonheap"] }
  ]
}

๐Ÿ’ก 8. Common Interview Follow-Ups

Question Answer
What is the use of Actuator? Provides endpoints for monitoring, health checks, metrics, etc.
How do you expose all actuator endpoints? management.endpoints.web.exposure.include=*
How to restrict access to actuator endpoints? Use Spring Security roles or configure management port separately.
How to add custom health checks? Implement HealthIndicator interface.
How to monitor your app with Prometheus/Grafana? Use micrometer-registry-prometheus and /actuator/prometheus.

9. Summary

Feature Description
Purpose Monitor and manage Spring Boot apps
Enabled by spring-boot-starter-actuator
Endpoints /actuator/*
Common Uses Health, Metrics, Info, Logging
Integration Prometheus, Grafana, Micrometer
Customizable? Yes (health, info, metrics)
 

Excellent question ๐Ÿ‘ — default methods are one of the most important features introduced in Java 8, and they often come up in interviews because they show your understanding of interfaces and backward compatibility.

Let’s go step by step ๐Ÿ‘‡


⚙️ 1. What is a Default Method in Java?

A default method is a method with a body (implementation) inside an interface.
It’s defined using the default keyword.

✅ Syntax:

public interface MyInterface {
    default void show() {
        System.out.println("Default method implementation");
    }
}

This means any class implementing this interface automatically inherits this method — unless it overrides it.


๐Ÿง  2. Why Were Default Methods Introduced?

Before Java 8, interfaces could only have abstract methods — no implementations allowed.

If you added a new method to an interface, all implementing classes would break (you’d have to modify all of them).

To solve this, Java 8 introduced default methods, allowing you to:

  • Add new functionality to existing interfaces

  • Maintain backward compatibility

Purpose:

To evolve interfaces without breaking existing code.


๐Ÿงฉ Example

Before Java 8:

interface Vehicle {
    void start();
}

If you add a new method later:

void stop();

Every class that implements Vehicle must implement stop() — or else it breaks.


After Java 8:

You can give it a default implementation:

interface Vehicle {
    void start();

    default void stop() {
        System.out.println("Vehicle stopped");
    }
}

Now old classes still compile fine — and can override stop() if needed.


Usage Example

interface Vehicle {
    void start();

    default void stop() {
        System.out.println("Vehicle stopped");
    }
}

class Car implements Vehicle {
    public void start() {
        System.out.println("Car started");
    }
}

public class Demo {
    public static void main(String[] args) {
        Vehicle car = new Car();
        car.start();
        car.stop();  // uses default method
    }
}

๐ŸŸข Output:

Car started
Vehicle stopped

⚙️ 3. Overriding Default Methods

A class can override the default method if it wants custom behavior.

class Bike implements Vehicle {
    public void start() {
        System.out.println("Bike started");
    }

    @Override
    public void stop() {
        System.out.println("Bike stopped safely");
    }
}

⚔️ 4. What If Two Interfaces Have the Same Default Method?

If a class implements two interfaces that define the same default method, there’s a conflict — the class must override it and decide which one to use.

Example:

interface A {
    default void show() { System.out.println("From A"); }
}

interface B {
    default void show() { System.out.println("From B"); }
}

class C implements A, B {
    @Override
    public void show() {
        A.super.show(); // or B.super.show()
    }
}

public class Test {
    public static void main(String[] args) {
        new C().show(); // prints "From A"
    }
}

Rule:

If multiple inherited default methods conflict, you must override and explicitly resolve which one to call.


๐Ÿงฉ 5. Default Methods vs Static Methods in Interfaces

Feature Default Method Static Method
Can have body? ✅ Yes ✅ Yes
Can be overridden? ✅ Yes ❌ No
Called using Object reference Interface name
Introduced in Java 8 Java 8

Example:

interface Utils {
    static void print() { System.out.println("Static method"); }
    default void log() { System.out.println("Default method"); }
}

Usage:

Utils.print();  // static
new MyClass().log();  // default

๐Ÿ’ก 6. Benefits of Default Methods

Benefit Description
Backward compatibility You can add new methods to interfaces without breaking old implementations.
Code reuse Common behavior shared across multiple classes can live in one interface.
Multiple inheritance of behavior A class can implement multiple interfaces that have reusable method logic.

๐Ÿšซ 7. Limitations

Limitation Description
⚠️ Multiple inheritance conflicts You must resolve method conflicts manually.
⚠️ Can’t override Object methods e.g., you can’t define a default toString() in an interface.
⚠️ Still not a replacement for abstract classes No state (fields) or constructors allowed.

8. Real-World Example

Default methods are widely used in Java libraries — e.g., Collections API:

List<String> list = Arrays.asList("A", "B", "C");
list.forEach(System.out::println);  // forEach() is a default method

forEach() was added to Iterable in Java 8 as a default method — so all existing collections automatically got the feature.


๐Ÿงพ Summary

Feature Description
Keyword default
Location Inside interfaces
Purpose Add method implementations without breaking existing code
Introduced in Java 8
Overridable? ✅ Yes
Key Use Interface evolution, shared behavior



Cache aside :

Purchase through Bncloud : Device details - > check in cache first : if not from DB





Excellent, Mishal ๐Ÿ‘ — here’s your 3-week senior/lead interview preparation schedule, with daily goals, exercises, and practice questions. It blends system design, Java & Spring technical review, and hands-on practice so that by the end of 3 weeks, you’ll be interview-ready for any senior backend or architect-level round.


๐Ÿ—“️ 3-Week Senior Java Backend Interview Preparation Plan


๐Ÿงฉ Week 1 – System Design Fundamentals

Day Topic Study Focus Hands-on / Practice Deliverable
1 Caching Concepts Cache types (in-memory, distributed), cache eviction, cache-aside vs write-through Implement Redis caching in a sample Spring Boot app Diagram: Cache + DB data flow
2 Load Balancing Load balancers, sticky sessions, reverse proxy, failover Draw Nginx/HAProxy setup for load balancing 3 microservices Architecture diagram
3 Sharding Horizontal vs Vertical sharding, consistent hashing Design DB shard strategy by region for “Inventory Service” DB schema split plan
4 Distributed Transactions 2PC, Saga pattern, event choreography Design an “Order → Payment → Inventory” workflow using Saga Sequence diagram
5 Event-driven Design Kafka vs RabbitMQ, async processing Implement a producer-consumer demo in Spring Boot using Kafka Kafka microservice
6 High-level System Design Scalability, bottlenecks, CAP theorem, eventual consistency Revisit all concepts and summarize tradeoffs System design notes
7 Design #1: Order Tracking System REST API + cache + queue + DB Draw architecture + write data flow for tracking shipments Design doc + diagram

⚙️ Week 2 – Complex System Design & Architecture

Day Topic Study Focus Hands-on / Practice Deliverable
8 Design #2: Inventory Management System Handle concurrent stock updates, optimistic/pessimistic locks Implement API with concurrency handling Spring Boot mini-project
9 Design #3: Payment Gateway Idempotency, retries, security, distributed transactions Write pseudo-code for payment retries & rollback Design flow document
10 Design #4: Product Recommendation System Event-driven + async updates Design Kafka-based recommendation flow Architecture diagram
11 Scaling Techniques Horizontal vs vertical scaling, caching, DB replication Identify bottlenecks in your earlier designs and fix them Updated architecture diagrams
12 Monitoring & Observability Logging, metrics, tracing (Zipkin, Prometheus, Grafana) Add actuator endpoints to a microservice Demo project
13 Practice Mock Design Round Pick one: “E-commerce order system” or “Ride booking system” Present 15-min explanation aloud Self-record or review notes
14 Review & Consolidation Summarize key design patterns + your 3–4 system designs Create 2-page cheat sheet System Design Summary Sheet

๐Ÿ’ป Week 3 – Java, Spring, and Database Mastery

Day Topic Study Focus Hands-on / Practice Deliverable
15 Concurrency & Multithreading Threads, ExecutorService, Locks, ThreadLocal Implement producer-consumer + thread-safe singleton Java code examples
16 JVM & Garbage Collection Memory areas, GC algorithms (G1, ZGC), tuning Analyze heap dump of a Spring app using VisualVM Notes on GC optimization
17 Spring Boot Internals Bean lifecycle, dependency injection, auto-configuration Debug app startup with custom BeanPostProcessor Small demo project
18 Spring Security JWT, OAuth2, filters, roles Add JWT-based security to your REST API Secured API example
19 REST API Design & Error Handling Best practices, status codes, @ControllerAdvice Implement global exception handler + versioned API REST API project
20 Database Design & Optimization Indexing, query plans, transactions Optimize a few SQL queries; analyze EXPLAIN PLAN SQL optimization notes
21 Final Review & Mock Interview Combine Java + Spring + System Design Conduct a mock interview (self or peer) Confidence checklist

๐Ÿง  Daily Study Routine (2–3 hours suggested)

Time Activity
30 min Theory reading (concepts, notes, or video lecture)
1 hr Hands-on coding / system design sketching
30 min Review + write key takeaways in notes
30 min Practice 2–3 interview questions aloud

๐Ÿ’ฌ Sample Practice Questions (Use Throughout)

System Design

  • Design an order tracking system that supports millions of users.

  • How would you scale a payment gateway that handles 10K TPS?

  • How to ensure data consistency between Order and Inventory services?

Core Java

  • Explain the difference between synchronized and ReentrantLock.

  • How does CompletableFuture improve async programming?

  • How does G1 GC differ from Parallel GC?

Spring

  • How does Spring Boot auto-configuration work internally?

  • How would you secure microservices using JWT tokens?

  • What are @Transactional pitfalls in microservices?

Database

  • Explain deadlock detection and prevention.

  • How would you design a DB for order and payment relationships?

  • What indexing strategy would you use for frequent order lookups?


๐ŸŽฏ End Goal by Week 3

✅ You can design and explain at least 3 production-grade systems
✅ You can answer deep Java & Spring questions confidently
✅ You have working demos & architecture diagrams ready to discuss in interviews
✅ You’ve practiced mock interviews and identified weak spots


 


 

Tuesday, September 30, 2025

 Key Java 17 Features


1. Records

  • Introduced in Java 14 (preview), finalized in Java 16.

  • Purpose: A concise way to create immutable data classes.


Before : 

class User {
    private final String name;
    private final int age;

    User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String name() { return name; }
    public int age() { return age; }
    @Override public String toString() { return name + " (" + age + ")"; }
}


with Records : 

record User(String name, int age) {}


2) Sealed Classes
    • Introduced in Java 15 (preview), finalized in Java 17.

    • Purpose: Restrict which classes can extend or implement a type.

    • Provides more control over inheritance.

  • sealed interface Shape permits Circle, Rectangle {}


    final class Circle implements Shape {

        double radius;

    }


    final class Rectangle implements Shape {

        double length, width;

    }



    3. Enhanced Switch (Switch Expressions + Pattern Matching)

    • Modernized since Java 12 → finalized in Java 17.

    • Switch can return a value and use arrow syntax.

    Old :
    String dayType;
    switch (day) {
        case "MONDAY": case "TUESDAY": case "WEDNESDAY":
            dayType = "Weekday";
            break;
        default:
            dayType = "Weekend";
    }

    NEW : 
    String dayType = switch (day) {
        case "MONDAY", "TUESDAY", "WEDNESDAY" -> "Weekday";
        default -> "Weekend";
    };


    Also supports pattern matching (useful with sealed classes):

    static String describeShape(Shape shape) {
        return switch (shape) {
            case Circle c -> "Circle with radius " + c.radius;
            case Rectangle r -> "Rectangle " + r.length + " x " + r.width;
        };
    }


    Quick Practice Checklist

    • Convert an old POJO (like User) → record.

    • Create a sealed interface Vehicle with Car, Bike, Truck.

    • Write a switch expression that works with the Vehicle hierarchy.

    • Notice how exhaustiveness is enforced (compiler warns if you miss a case).


    4)  Pattern Matching for instanceof
    • Simplifies type checks + casting.

      if (obj instanceof String) {

          String s = (String) obj;

          System.out.println(s.length());

      }

      NOW : 

      if (obj instanceof String s) {

          System.out.println(s.length());

      }


    5) 

     Text Blocks (Multi-line Strings)

    • Introduced earlier (Java 13+), standard in Java 15+.

    • Makes multi-line strings easier (useful for JSON, SQL, XML in code).

    • String json = """

      {

        "name": "Alice",

        "age": 30

      }

      """;


    Stream.toList() and Collection Factory Methods

    • Instead of .collect(Collectors.toList()), use:

    List<String> list = Stream.of("a","b","c").toList();
    • Immutable by default.

    • Collection factory methods:

    Set<String> s = Set.of("a", "b", "c"); Map<String, Integer> m = Map.of("a",1,"b",2);

    Monday, June 30, 2025

    MapReduce

     


    2004 -> GMR - MR

    200 -> GFS - HDFS


    Hadoop
    |
    |--> MR

    |--> HDFS 

    What is MR

    Batch processing framework 

    Spark also processing framework 



    Language used in Mapreduce : Java by default 

    Advantages  of MR : 

    >  Framework : : Like gated community where all other things will be managed by the admin team 
    > Cluster monitoring 

    >Resource allocation 

    >Cluster management 

    >Scheduling 

    >Execution 

    >Speculative execution


    Aim of  MR: 
    data locality 


    Use of MR:

    Parallel processing 


    Abstraction of MR : 
    Hive ,Pig,Scoopy ,oozie will work only when MR is running 


    Alternate of MR : 
    Spark 



    Daemons in MR: 

    JobTracker and TaskTracker-V1

    Resource Manager & Node Manager -V2 


    MAP 


    REDUCE 

    Inputs for Mapper : Blocks 

    Inpu





    Hadoop Commands

    Hadoop Commands


    To find the quotas allocated :

    hadoop fs -count -q -h -v /foldName



    To set quota : 

    hadoop dfsadmin -setQuota 10 /foldName



    How to Automatically Post Daily Using Zapier and OpenAI (GPT-3.5)#AI

     How to Automatically Post Daily Using Zapier and OpenAI (GPT-3.5)

    A Zapier account: https://zapier.com
    An OpenAI API key: https://platform.openai.com/account/api-keys
    A platform to post to (e.g., WordPress, Twitter/X, LinkedIn, Notion, etc.)


    Step 1: Get Your OpenAI API Key

    1. Sign up or log in at https://platform.openai.com

    2. Visit: https://platform.openai.com/account/api-keys

    3. Click “+ Create new secret key”

    4. Copy the API key — you’ll need this in Zapier

    Step 2: Create a Zap in Zapier

    1. Go to https://zapier.com/app/zaps

    2. Click “Create Zap”


    Step 3: Set the Trigger – Schedule Daily

    1. Choose App: Schedule by Zapier

    2. Trigger Event: Every Day

    3. Choose time (e.g., 9:00 AM)

    This sets your zap to run daily.


     Step 4: Generate Content Using OpenAI

    1. Action App: OpenAI (GPT-3, DALL·E)

    2. Event: Send Prompt

    3. Connect your OpenAI account using the API key

    4. Prompt Example:

      txt
      Write a motivational blog post about productivity in under 150 words.
    5. Set model to gpt-3.5-turbo

    6. Choose text output field for later steps


    Step 5: Post the Content

    Example: Post to WordPress

    1. Action App: WordPress

    2. Event: Create Post

    3. Fill in:

      • Title: “{{today’s date}} – Your Daily Productivity Boost”

      • Content: Use OpenAI response output

      • Status: Published or Draft

    Example: Tweet It

    1. Action App: Twitter (X)

    2. Event: Create Tweet

    3. Content: Output from OpenAI (trimmed to 280 chars)


     Optional: Customize It More

    • Add filters to skip weekends

    • Randomize topics from a list

    • Store generated posts in Google Sheets


     That’s It!

    Now, every day, Zapier will trigger OpenAI to generate content and post it where you want — no manual input needed. This is great for:

    • Bloggers automating daily posts

    • Social media managers posting regular updates

    • Productivity nerds who want content on autopilot

    Wednesday, August 7, 2024

    Java lernings

    For biggners :

    http://theopentutorials.com/examples/java-ee/jax-ws/create-and-consume-web-service-using-jax-ws/
    http://javapostsforlearning.blogspot.in/2013/03/jaxws-web-service-eclipse-tutorial.html


    http://javapostsforlearning.blogspot.in/2013/03/jaxws-webservice-deployement-on-tomcat.html

    <c:set var="myTest" value="testValue"/>
    #1:<c:out value="${myTest}" />
    #2:<%=pageContext.getAttribute("myTest") %>




    Please ensure that you are providing a xml input in the UTF 8 format .
    If you creating XML dynamically and provide this for parsing then please ensure you write the content in xml as follows :

     File tempXML = File.createTempFile("xmlfile", "tmp", new File("/tmp"));
     tempXML.deleteOnExit();
        
    OutputStream os = new FileOutputStream(tempXML);
    OutputStreamWriter bufferedWriter = new OutputStreamWriter(os, "UTF8");

    bufferedWriter.write(xmlData);
    bufferedWriter.flush();
    bufferedWriter.close();    

    XSLTInputHandler input = new XSLTInputHandler(tempXML, xslFile);




    Logback natively implements the SLF4J API. This means that if you are using logback, you are actually using the SLF4J API. You could theoretically use the internals of the logback API directly for logging, but that is highly discouraged. All logback documentation and examples on loggers are written in terms of the SLF4J API.


    http://logback.qos.ch/reasonsToSwitch.html

    SLF4J is basically an abstraction layer. It is not a logging implementation. It means that if you're writing a library and you use SLF4J, you can give that library to someone else to use and they can choose which logging implementation to use with SLF4J e.g. log4j or the Java logging API. It helps prevent projects from being dependent on lots of logging APIs just because they use libraries that are dependent on them.
    So, to summarise: SLF4J does not replace log4j, they work together. It removes the dependency on log4j from your library/app.

    if a project is already using log4j, and you included a library say Apache Active MQ, which has dependency on logback, another logging library, then you need to include them as well, but if Apache Active MQ uses SL4J, you can continue with your logging library, without pain of adding and maintaining new logging framework

    Read more: http://javarevisited.blogspot.com/2013/08/why-use-sl4j-over-log4j-for-logging-in.html#ixzz49qnR9Y4v

    Take a look here: http://www.slf4j.org/, or even here: http://commons.apache.org/logging/ (Apache Commons Logging is similar to SLF4J) for more info on this concept.

    SSE -Java/J2ee Interview questions

     

    1.ArrayList vs LinkedList

    First of all, you should be aware that they both implement the List interface, an abstract structure built to maintain the ordering of the elements inserted. The main difference is that LinkedList additionally implements the Deque interface, so developers can use it as a standard FIFO-like structure.

    The internals of the two collections differ a lot. While ArrayList is based on an auto-resizable array, LinkedList uses pointers to the next and previous elements, building a chain of elements to grant access to data. This means that choosing the correct structure depends on the use case, as the performance may vary greatly depending on this.


    2. REST vs SOAP 

    The theoretical differences, such as “SOAP is a protocol and REST is not,” . Something that is usually not mentioned during comparisons and that can help detect if the candidate has real experience with both, is the use of Web Service Definition Language (WSDL) files.

    WSDL files are usually used to generate communication STUBs in Java. Is there any tool or technology that helps us do the same with REST endpoints? The answer is yes, and it’s called OpenAPI. Documenting web services is one of the most important things to do when providing functionality.  

    3. Merge vs rebase

     

    When it’s not possible to merge two branches because of conflicts, developers have two options: merging or rebasing. A rebase may be needed when reserving a clean Git history is important. Rebasing means to move the base of a branch on top of the leaf of another. Instead of having branches intersect multiple times, you can have a clean Git history, as long as everyone follows the golden rule of rebasing: never rebase a public branch.

    Stashing is a powerful tool to put aside code that you just wrote, without pushing it to any remote tracked branch. While it’s possible to create multiple stashes at once by giving them different names, it’s usually better to not have more than one stash, as things can become complex to restore. 

    4. Define the testing pyramid and its layers

     Being able to identify all the layers (unit testing, integration testing, UI testing) should be enough for a junior developer, but for more experienced candidates, it’s better to make sure they have also implemented some of those using different tools or technologies. 

    5. How to sort HashSet of integers?

     Set is by default an unordered structure. So the answer is simply no unless we use an additional data structure.

    Starting from this question, it’s possible to:

    1. Investigate the candidate's knowledge of Java collections. TreeSet, LinkedHashSet, and List are only some of the possible solutions.

    6. Describe an exception hierarchy 

    This abstraction is useful in several ways: first, it’s possible to catch exceptions at various levels of the hierarchy, and second, it’s possible to further extend the family of exceptions with peculiar and ad-hoc use cases.

    A further related question to ask regards the concept of “fault barriers,” which I encourage every senior Java developer to understand if they aren’t already familiar with the construct.

    7. How to identify performance issues in an application?

     The first step in identifying and resolving a performance issue is measuring the actual performance of the behavior. Only then can an optimization make any sense, otherwise the enhancement cannot be measured.

    Identification of the precise piece of the business logic to optimize may occur manually by inserting logs measuring time, or by using profiling tools that automatically decouple the various pieces of the flow measuring time spent in the execution.

    When asked this senior Java developer interview question, experienced candidates may also want to describe one of the hardest performance issues they have faced, or trivial issues that can be easily avoided by adopting a series of good practices and keeping an eye on performance during the whole development lifecycle.

    8. How to handle huge data on Redis cache?

    The candidate’s first reaction to this question should be, “Does it make sense to have huge data on Redis?” A distributed cache is built primarily to enhance the performance of a distributed microservice application. Together with the physical limit of the RAM available for the Redis host, there is a software limit on a single item of 512MB. To store a huge data load, we should be able to split it into chunks and retrieve results, for example by using the HGETALL command. Compression before storing the data might also be an option.

    Generally speaking, Redis was not built to achieve this. Retrieving vast chunks of data has been indicated as one of the worst practices. A way better solution could be to store the data object in a standard NoSQL database.

    The goal of this interview question is to check the previous experience of senior Java developer candidates, with a focus on how they propose new solutions instead of sticking to the plan.

    9. Define AOP and its biggest pitfall

    Aspect-oriented programming (AOP) is a powerful feature implemented in the Spring framework. Its most common use cases are logging, authorization, and caching.

    The most common pitfall that the candidate should be aware of is the probable performance drop when using AOP, as it uses reflection under the hood, and Java reflection isn’t free (direct call to methods is way faster). This can make business logic a little difficult to read to someone who’s skilled in this way of programming.

    10. What are the limitations of GET?

    The GET method in HTTP should be used only to retrieve resources from a web server, without altering the state of the application in any way. An exception to this is when we have caching. In this case, a slight modification to the state of the application might be tolerable.

    Limitations of GET usually regard the fact that the method cannot theoretically have a request body, so every parameter should be included in the URL, and the URL has a limited length (~2K characters). In practice, it is possible to send a body with the GET method even if this is not a good practice and should be avoided.

    With 2K characters available, we are certain to have all the input needed to retrieve a resource from a web server.



    Topic 1: Project flow and architecture


    inquire about its functionality, flow, and architecture. I’ll also ask about the tech stack and how it is deployed in production, as well as their role and contributions.




    Topic 2: Core Java

    • String Concepts/Hashcode-Equal Methods

          String Concepts

    1. Immutability:

      • Definition: Once a String object is created, it cannot be changed.
      • Reason: Immutability ensures thread safety and enables the string pool mechanism.
    2. String Pool:

      • Definition: A special memory region where Java stores String literals.
      • Benefit: It saves memory by reusing instances of String literals.
    3. String Methods:

      • Common methods include length(), charAt(int index), substring(int beginIndex, int endIndex), toUpperCase(), toLowerCase(), concat(String str), replace(char oldChar, char newChar), etc.
    4. Creating Strings:

      • Using literals: String str = "Hello";
      • Using new keyword: String str = new String("Hello");

        hashCode() and equals() Methods

                These methods are essential for the correct functioning of collections like HashSet, HashMap, HashTable, etc.

            equals() Method

    • Purpose: To check if two objects are logically equal.
    • Default Implementation: Inherited from Object class, which compares memory addresses.
    • Override: Override this method to compare the values of the objects.

       hashCode() Method

    • Purpose: To return an integer representation of the object’s memory address.
    • Contract with equals():
      • If two objects are equal (equals() returns true), they must have the same hash code.
      • If two objects have the same hash code, they are not necessarily equal.
    • Immutability(custom immutable class and example in JDK)


                 Immutability means that once an object is created, its state cannot be modified. Immutable objects are inherently thread-safe and have several benefits, including simplicity, safety, and ease of maintenance.

                 Creating a Custom Immutable Class

                    To create an immutable class, follow these principles:

      1. Declare the class as final so it cannot be subclassed.
      2. Declare all fields as private and final so they cannot be modified after initial assignment.
      3. Do not provide setter methods.
      4. Initialize all fields via the constructor.
      5. Ensure that mutable fields are not exposed (e.g., by returning copies instead of direct references).

        Benefits of Immutability

        1. Thread Safety: Immutable objects can be shared freely between threads without synchronization.
        2. Simplicity: Immutable objects are easier to understand and reason about since their state cannot change after construction.
        3. Security: Immutable objects are inherently more secure since their state cannot be altered, reducing the risk of unintended side effects.
        4. Cache-Friendly: Immutable objects can be cached or used as keys in hash-based collections without the risk of their state changing, ensuring consistency
    • OOPS concepts(all four pillars and solid principle)

                    Object-Oriented Programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code to manipulate that data. The four main pillars of OOP are encapsulation, abstraction, inheritance, and polymorphism. Additionally, the SOLID principles are a set of guidelines that can help improve object-oriented design.

    ### Four Pillars of OOP

    1. **Encapsulation**
       - **Definition**: Encapsulation is the bundling of data (attributes) and methods (functions) that operate on the data into a single unit or class. It restricts direct access to some of the object's components, which can protect the object's internal state from unintended interference and misuse.
       - **Example**:
         ```java
         public class Person {
             private String name;
             private int age;

             public String getName() {
                 return name;
             }

             public void setName(String name) {
                 this.name = name;
             }

             public int getAge() {
                 return age;
             }

             public void setAge(int age) {
                 this.age = age;
             }
         }
         ```

    2. **Abstraction**
       - **Definition**: Abstraction is the concept of hiding the complex implementation details and showing only the essential features of the object. It helps in reducing programming complexity and effort.
       - **Example**:
         ```java
         public abstract class Animal {
             public abstract void makeSound();
         }

         public class Dog extends Animal {
             @Override
             public void makeSound() {
                 System.out.println("Bark");
             }
         }
         ```

    3. **Inheritance**
       - **Definition**: Inheritance is the mechanism by which one class (child or subclass) can inherit the properties and behaviors (methods) of another class (parent or superclass). This promotes code reuse and establishes a natural hierarchy.
       - **Example**:
         ```java
         public class Vehicle {
             protected String brand;

             public void honk() {
                 System.out.println("Beep Beep!");
             }
         }

         public class Car extends Vehicle {
             private String modelName;

             public Car(String brand, String modelName) {
                 this.brand = brand;
                 this.modelName = modelName;
             }

             public String getModelName() {
                 return modelName;
             }
         }
         ```

    4. **Polymorphism**
       - **Definition**: Polymorphism allows objects to be treated as instances of their parent class rather than their actual class. The two types of polymorphism are compile-time (method overloading) and runtime (method overriding).
       - **Example**:
         ```java
         public class Animal {
             public void makeSound() {
                 System.out.println("Some sound");
             }
         }

         public class Cat extends Animal {
             @Override
             public void makeSound() {
                 System.out.println("Meow");
             }
         }

         public class Main {
             public static void main(String[] args) {
                 Animal myCat = new Cat();
                 myCat.makeSound();  // Outputs "Meow"
             }
         }
         ```

    ### SOLID Principles

    1. **Single Responsibility Principle (SRP)**
       - **Definition**: A class should have only one reason to change, meaning it should have only one job or responsibility.
       - **Example**:
         ```java
         public class Invoice {
             private final Order order;

             public Invoice(Order order) {
                 this.order = order;
             }

             public void printInvoice() {
                 // Print the invoice
             }

             public void saveToFile() {
                 // Save the invoice to a file
             }
         }
         ```
         To adhere to SRP, the printing and saving functionality should be moved to separate classes.

    2. **Open/Closed Principle (OCP)**
       - **Definition**: Software entities (classes, modules, functions, etc.) should be open for extension but closed for modification.
       - **Example**:
         ```java
         public abstract class Shape {
             public abstract double calculateArea();
         }

         public class Rectangle extends Shape {
             private final double length;
             private final double width;

             public Rectangle(double length, double width) {
                 this.length = length;
                 this.width = width;
             }

             @Override
             public double calculateArea() {
                 return length * width;
             }
         }

         public class Circle extends Shape {
             private final double radius;

             public Circle(double radius) {
                 this.radius = radius;
             }

             @Override
             public double calculateArea() {
                 return Math.PI * radius * radius;
             }
         }
         ```

    3. **Liskov Substitution Principle (LSP)**
       - **Definition**: Objects of a superclass should be replaceable with objects of a subclass without affecting the correctness of the program.
       - **Example**:
         ```java
         public class Bird {
             public void fly() {
                 System.out.println("Flying");
             }
         }

         public class Ostrich extends Bird {
             @Override
             public void fly() {
                 // Ostriches can't fly
                 throw new UnsupportedOperationException("Ostriches can't fly");
             }
         }
         ```
         The `Ostrich` class violates LSP. It should not be a subclass of `Bird` if it cannot perform the `fly` operation.

    4. **Interface Segregation Principle (ISP)**
       - **Definition**: Clients should not be forced to depend on interfaces they do not use. It’s better to have many small, specific interfaces rather than a single, general-purpose interface.
       - **Example**:
         ```java
         public interface Workable {
             void work();
         }

         public interface Eatable {
             void eat();
         }

         public class Worker implements Workable, Eatable {
             @Override
             public void work() {
                 // working
             }

             @Override
             public void eat() {
                 // eating
             }
         }
         ```

    5. **Dependency Inversion Principle (DIP)**
       - **Definition**: High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details. Details should depend on abstractions.
       - **Example**:
         ```java
         public interface Keyboard {
         }

         public interface Monitor {
         }

         public class StandardKeyboard implements Keyboard {
         }

         public class StandardMonitor implements Monitor {
         }

         public class Computer {
             private final Keyboard keyboard;
             private final Monitor monitor;

             public Computer(Keyboard keyboard, Monitor monitor) {
                 this.keyboard = keyboard;
                 this.monitor = monitor;
             }
         }
         ```

                        By adhering to the four pillars of OOP and the SOLID principles, you can create software that is modular, maintainable, and scalable. These principles help manage complexity and ensure that your codebase can evolve over time without becoming unmanageable.
    • Serialization (serialversionUUID)
    • Collection Framework/concurrent collection(they Hashamap, concurrent hashmap, ArrayList,HashSet)
    • Exception Handling(especially Runtime exception)
    • Multithreading especially Executor Framework which includes ThreadPool(deadlock, Thread-dump)
    • Java Memory Model(how objects, methods, and variable gets stored in each area of Java memory)
    • Garbage collection(working of it, how it garbage collects the object, algorithm used while doing it)




    Question:

    How does ThreadPoolExecutor work?
    How do you create a custom immutable class? What are examples of immutable classes in Java?
    What are hashCode() and equals()? If you have Object as a custom key in a map, what will happen? How to use it correctly?
    What are deep copy and shallow copy?
    What is CompletableFuture?
    What is the Java Memory Model as per the latest Java version?
    What is a concurrent collection?
    What are the time/space complexities of HashMap, ArrayList, and LinkedList?
    What algorithm is used by these Java APIs Arrays.sort() and Collections.sort()?
    How do you create a custom annotation in Java?
    What is CompletableFuture?
    What are deep copy and shallow copy?
    How do HashMap and HashSet work internally?
    What is the use of String’s join() method?



    Topic 3: Java-8/Java-11/Java17

    Topics:

    • Java 8 features
    • Default/Static methods
    • Lambda expression
    • Functional interfaces
    • optional API
    • stream API
    • pattern matching
    • text block
    • modules






    Questions:

    What is new in Java 8/Java11/Java17?
    What is a parallel stream in Java and how does it work?
    What is the new improvement in the Java memory model, improvement in Java 8 hashmap?



    Topic 4: Spring Framework, Spring-Boot, Microservice, and Rest API


    Topics:

    • Dependency Injection/IOC, Spring MVC
    • configuration, Annotations, CRUD operations
    • Bean, Scopes, Profiles, Bean lifecycle
    • App context/Bean context
    • AOP, Exception Handler, Control Advice
    • Security(JWT,Oauth)
    • Actuators
    • WebFlux and Mono Framework
    • HTTP methods
    • Microservice concepts
    • Spring Cloud
    • JPA

    Questions:

    What is the use of these annotations — @RequestMapping @RestController @Serivice @Repository @entity

    What is an Actuator and its uses?
    How do you make your application fault-tolerant and resilient?
    What is distributed tracing? What is the use of traceId and spanId in a Spring Boot application?
    What is WebFlux and Mono Framework in Spring Boot?
    What is a cyclic dependency in Spring, and how do you prevent it?
    How to secure REST APIs?
    What is distributed tracing? What is the use of traceId and spanId in a Spring Boot application?
    What is WebFlux and Mono Framework in Spring Boot?
    How to make your application fault-tolerant and resilient?
    How do you disable auto-configuration in a Spring Boot application?



    Topic 5: Hibernate/Spring-data Jpa/Database(SQL or NoSQL)

    Topics You should be aware are,

    • JPA Repositories
    • Relationship with Entities
    • SQL queries on Employee department queries, Highest Nth salary queries
    • Relational and No-Relational DB concepts
    • CRUD operations in DB
    • joins, indexing, procs, functions,

    Questions

    What is the Difference between SQL and NoSQL?
    What is sharding in databases?
    What is JPA?
    What is the Parent-Child Relationship?
    What are joins?


    Topic 6: Coding


    Topics:

    • Stream API coding Questions
    • Normal Coding questions related to String and Array
    • Sorting and searching using Java API.

    Questions

    Write a program to find the second-highest element from an array. The array can contain duplicate elements. Solve it using Java 8 streams.

    Find the duplicate element and its occurrence in a given string using the Stream API.

    Write a program to find the first non-repeating element from a given string using Java Streams.

    Write a program to find unique elements in a given string using Java streams.

    Write a program to find the longest string in a given array.

    Write a program to sort two types of numbers to the left and right in an array. Example: Integer array[] = [5, 5, 0, 5, 0] -> output: [0, 0, 5, 5, 5]

    Write a program to find the first repeating element/character from a given string using Java Streams.

    Write a program for valid parenthesis.

    WAP to find the duplicate characters in a list of strings using the Stream API?

    Topic 7: Devops questions on deployment Tools(Kubernetes,Cloud,Kafka,cache)



    Questions:

    What are POD, Configmap, Node, and cluster in Kubernetes?

    What is a Hybrid cloud?
    What is Apache Spark? Can you give me a use case using a Spring Boot application?
    What is Kafka? How does it work? What are offset and consumer groups?



    Topics 8: Best practice(Design pattern/Microservice pattern)



    Microservice is heavily used nowadays, and with that different types of patterns also come into the picture like,

    Circuit Breaker
    SAGA
    CQRS
    Two-phase commit, BFF, API Gateway,

     

    Question:

    What is a Singleton design pattern, builder design pattern, or facade design pattern?
    What are the common microservice patterns we should be using? Tell me about any two.
    These topics always get repeated so by preparing them you can crack the final part of it.



    https://rathod-ajay.medium.com/your-guide-to-clear-java-developer-interview-in-2024-36a926ec6719