Tuesday, March 31, 2026

Method Overloading vs Method Overriding in Java

1. Introduction

In Java, method overloading and method overriding are key concepts of polymorphism.

  • Overloading → Same method name, different parameters (Compile-time polymorphism)

  • Overriding → Same method, same parameters, different implementation (Runtime polymorphism)




2. Method Overloading

Explanation

  • Multiple methods with the same name but different parameter lists

  • Occurs within the same class

  • Decision is made at compile-time

Rules

  • Method name must be same

  • Parameters must differ (type, number, or order)

  • Return type alone is NOT enough


3. Example of Method Overloading

class Calculator {

    int add(int a, int b) {
        return a + b;
    }

    int add(int a, int b, int c) {
        return a + b + c;
    }

    double add(double a, double b) {
        return a + b;
    }
}

public class OverloadingExample {
    public static void main(String[] args) {
        Calculator c = new Calculator();

        System.out.println(c.add(10, 20));
        System.out.println(c.add(10, 20, 30));
        System.out.println(c.add(10.5, 20.5));
    }
}

4. Explanation of Code

  • Same method add() used in different ways

  • Compiler decides which method to call based on arguments

Output:

30
60
31.0

5. Method Overriding

Explanation

  • Subclass provides a specific implementation of a method already defined in parent class

  • Occurs between parent and child classes

  • Decision is made at runtime

Rules

  • Method name must be same

  • Parameters must be same

  • Must have inheritance

  • Cannot reduce access level


6. Example of Method Overriding

class Animal {
    void sound() {
        System.out.println("Animal makes sound");
    }
}

class Dog extends Animal {
    void sound() {
        System.out.println("Dog barks");
    }
}

public class OverridingExample {
    public static void main(String[] args) {
        Animal a = new Dog();
        a.sound();
    }
}

7. Explanation of Code

  • Dog overrides sound() method

  • Method call is decided at runtime → dynamic binding

Output:

Dog barks

8. Key Differences Table




9. Real-Time Example

  • Overloading → Calculator methods (add, multiply with different inputs)

  • Overriding → Payment system:

    • Parent: pay()

    • Child: UPI, Card → different implementations


10. Summary

  • Overloading → Same name, different parameters (Compile-time)

  • Overriding → Same method, different behavior (Runtime)

  • Overloading improves readability

  • Overriding supports runtime flexibility


Java Full Stack Developer Roadmap

To master OOP concepts like polymorphism:

๐Ÿ‘‰ https://www.ashokit.in/java-full-stack-developer-roadmap


Promotional Content

Want to master Java OOP concepts like Overloading and Overriding?

Best Core JAVA Online Training in ameerpet

Monday, March 30, 2026

What is Synchronization and Why is it Needed in Java?

1. Introduction

Synchronization in Java is a mechanism used to control multiple threads accessing shared resources.

It ensures that:

  • Only one thread executes a critical section at a time

  • Data remains consistent and accurate

Without synchronization, multithreaded programs can produce unexpected results.




2. Why Synchronization is Needed

Explanation

When multiple threads access and modify the same data simultaneously, it leads to problems like:

  • Race Condition

  • Data Inconsistency

  • Thread Interference

Synchronization solves these issues by controlling thread access.


3. Race Condition Example (Without Synchronization)

class Counter {
    int count = 0;

    void increment() {
        count++;
    }
}

public class Test {
    public static void main(String[] args) {
        Counter c = new Counter();

        Runnable task = () -> {
            for (int i = 0; i < 1000; i++) {
                c.increment();
            }
        };

        Thread t1 = new Thread(task);
        Thread t2 = new Thread(task);

        t1.start();
        t2.start();
    }
}

Explanation of Code

  • Two threads increment the same variable count

  • Expected result: 2000

  • Actual result: unpredictable (less than 2000)

Why?

Because count++ is not atomic:

  • Read → Modify → Write (3 steps)

  • Threads interfere with each other


4. Synchronization Solution

class Counter {
    int count = 0;

    synchronized void increment() {
        count++;
    }
}

public class Test {
    public static void main(String[] args) throws InterruptedException {
        Counter c = new Counter();

        Runnable task = () -> {
            for (int i = 0; i < 1000; i++) {
                c.increment();
            }
        };

        Thread t1 = new Thread(task);
        Thread t2 = new Thread(task);

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.println(c.count);
    }
}

Explanation of Code

  • synchronized keyword ensures:

    • Only one thread can execute increment() at a time

  • join() ensures main thread waits for others

Output:

2000

5. Types of Synchronization

1. Method Level Synchronization

synchronized void method() {
    // critical section
}
  • Locks the entire method


2. Block Level Synchronization

void method() {
    synchronized(this) {
        // critical section
    }
}
  • Locks only a specific block → better performance


3. Static Synchronization

synchronized static void method() {
}
  • Locks the class-level lock


6. How Synchronization Works Internally

  • Every object in Java has a monitor (lock)

  • When a thread enters a synchronized block:

    • It acquires the lock

  • Other threads must wait until:

    • Lock is released


7. Advantages

  • Prevents race conditions

  • Ensures data consistency

  • Provides thread safety


8. Disadvantages

  • Performance overhead (due to locking)

  • Can lead to deadlocks if not used carefully


9. When to Use Synchronization

Use synchronization when:

  • Multiple threads access shared data

  • At least one thread modifies the data


10. Summary

  • Synchronization controls thread access to shared resources

  • Prevents data inconsistency and race conditions

  • Achieved using synchronized keyword

  • Essential for multithreaded applications


Java Full Stack Developer Roadmap

To master multithreading and synchronization concepts:

๐Ÿ‘‰ https://www.ashokit.in/java-full-stack-developer-roadmap


Promotional Content

Want to master Java Multithreading and Synchronization concepts?

Top Core JAVA Online Training in 2026

Saturday, March 28, 2026

How to Design a URL Shortener (like bit.ly)

Designing a URL shortener is a classic system design problem that helps you understand how real-world scalable systems are built. It involves concepts like unique ID generation, database design, caching, and handling large traffic efficiently.




1. Basic Explanation

A URL shortener converts a long URL into a shorter, manageable link.

Example:

Long URL
https://www.example.com/blog/how-to-learn-java-step-by-step

Short URL
https://short.ly/abc123

When a user clicks the short URL, the system redirects them to the original long URL.

The core idea is simple:

  • Generate a unique short code for every long URL

  • Store the mapping between short code and long URL

  • Redirect users when the short URL is accessed


2. How It Works (Step-by-Step Flow)

Step 1: User submits a long URL
Step 2: System generates a unique identifier (ID or hash)
Step 3: Convert that ID into a short code (using Base62 encoding)
Step 4: Store mapping in database (shortCode → longURL)
Step 5: Return short URL to user

When user accesses the short URL:

  • Extract short code

  • Look up database

  • Redirect to original URL using HTTP 301/302


3. Detailed Design Components
3.1 API Design

POST /shorten
Input: Long URL
Output: Short URL

GET /{shortCode}
Output: Redirect to original URL


3.2 Database Design

A simple table structure:

Table: URL_MAPPING

  • id (Primary Key)

  • short_code (Unique)

  • long_url

  • created_at

  • expiry_date (optional)

Indexes:

  • Index on short_code for fast lookup


3.3 Short Code Generation Strategies
Option 1: Auto-increment ID + Base62 Encoding

  • Generate ID (1, 2, 3...)

  • Convert to Base62 (a-z, A-Z, 0-9)

Example:
1 → a
2 → b
61 → Z
62 → ba

Advantages:

  • Simple

  • Predictable

Disadvantages:

  • Sequential (not secure)


Option 2: Hashing (MD5/SHA)

  • Hash the long URL

  • Take first few characters

Problem:

  • Collisions possible


Option 3: Random String

  • Generate random 6–8 character string

Problem:

  • Need collision handling


3.4 Redirect Mechanism

When user hits short URL:

  1. Extract short code

  2. Query database

  3. If found → return HTTP redirect

  4. If not → return 404


3.5 Caching (Important for Performance)

Use caching (like Redis):

  • Store frequently accessed URLs

  • Reduce database load

Flow:

  • Check cache first

  • If not found → query DB → update cache


3.6 Scalability Considerations

To handle millions of users:

  • Use load balancers

  • Use distributed databases

  • Use caching layers

  • Use CDN for faster access


3.7 High Availability

  • Replicate database

  • Use failover systems

  • Avoid single point of failure


4. Real-Time Example

User input:
https://ashokitech.com/core-java-online-training/

System process:

  • ID generated: 125

  • Base62 encoded: cb

  • Short URL: short.ly/cb

Database:
cb → original URL


5. Java Implementation (Simple Version)
5.1 Base62 Encoder

class Base62 {
    private static final String CHARSET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    public String encode(int num) {
        StringBuilder sb = new StringBuilder();

        while (num > 0) {
            sb.append(CHARSET.charAt(num % 62));
            num /= 62;
        }

        return sb.reverse().toString();
    }
}

5.2 URL Service

import java.util.HashMap;
import java.util.Map;

class URLShortenerService {

    private Map<String, String> db = new HashMap<>();
    private int counter = 1;
    private Base62 encoder = new Base62();

    public String shortenURL(String longURL) {
        String shortCode = encoder.encode(counter++);
        db.put(shortCode, longURL);
        return "http://short.ly/" + shortCode;
    }

    public String getOriginalURL(String shortCode) {
        return db.get(shortCode);
    }
}

5.3 Main Class

public class Main {
    public static void main(String[] args) {
        URLShortenerService service = new URLShortenerService();

        String shortUrl = service.shortenURL("https://ashokitech.com");
        System.out.println("Short URL: " + shortUrl);

        String code = shortUrl.substring(shortUrl.lastIndexOf("/") + 1);
        System.out.println("Original URL: " + service.getOriginalURL(code));
    }
}

6. Advanced Real-World Improvements

In production systems like bit.ly:

  • Use distributed ID generators (Snowflake)

  • Store data in NoSQL databases

  • Add analytics (click tracking)

  • Support custom aliases

  • Add expiration for links

  • Implement rate limiting


7. Java Learning Roadmap

To build systems like this, follow a structured path:



8. Learn Core Java

If you want to master concepts like system design, backend development, and real-time projects.


Final Thoughts

A URL shortener may look simple, but it involves many important backend concepts:

  • Database design

  • Scalability

  • Caching

  • System reliability

Friday, March 27, 2026

What is caching in Java?

Caching in Java is a technique used to store frequently accessed data in memory so that future requests can be served faster.

๐Ÿ‘‰ In simple terms:
Caching = Save data temporarily to improve performance




 Why Do We Use Caching?

In real-world applications, fetching data from:

  • Databases

  • External APIs

  • File systems

⏳ can be slow and expensive.

 Solution:

๐Ÿ‘‰ Store the result in a cache and reuse it instead of fetching again.


 Example

Without Caching ❌

public User getUser(int id) {
    return userRepository.findById(id); // DB call every time
}

With Caching 

@Cacheable("users")
public User getUser(int id) {
    return userRepository.findById(id); // Called only once
}

๐Ÿ‘‰ Next time:

  • Data comes from cache ⚡

  • No DB call


 How Caching Works

  1. First request → Data fetched from DB

  2. Data stored in cache

  3. Next request → Data returned from cache


 Types of Caching in Java

1. In-Memory Cache

  • Stored inside application memory

  • Very fast

Examples:

  • HashMap

  • Caffeine

  • EhCache


2. Distributed Cache

  • Shared across multiple servers

Examples:

  • Redis

  • Memcached


 Spring Boot Caching Annotations

1. @Cacheable

  • Stores result in cache

@Cacheable("users")

2. @CachePut

  • Updates cache

@CachePut("users")

3. @CacheEvict

  • Removes data from cache

@CacheEvict("users")

 Real-Time Example

Imagine an e-commerce app:

  • Product details fetched from DB (slow)

  • Cached in memory

  • Next user gets data instantly ⚡


 Cache Challenges

  • Data may become outdated (stale data)

  • Cache invalidation is tricky

  • Memory usage increases


 Benefits of Caching

  • Faster response time ⚡

  • Reduced database load

  • Improved scalability

  • Better user experience


 Without vs With Caching




 Conclusion

Caching is a powerful technique in Java that helps improve performance and scalability by reducing repeated data fetching.

It is widely used in Spring Boot applications and is a must-know concept for backend developers.


 Learn More

Want to master Java performance optimization, Spring Boot, and real-time projects?

๐Ÿ‘‰ No 1 Core JAVA Online Training in 2026



Thursday, March 26, 2026

What is JUnit?

JUnit is an open-source framework used to test Java applications. It allows developers to write and run repeatable tests to verify that individual components (units) of the code work as expected.

๐Ÿ‘‰ In simple terms, JUnit helps you test your code automatically.




 What is Unit Testing?

Unit testing is the process of testing small parts (methods or classes) of an application in isolation.

๐Ÿ‘‰ Example:

  • Testing a method that calculates total price

  • Testing a login validation function


 Key Features of JUnit

 1. Test Annotations

JUnit uses annotations to define test methods.

๐Ÿ“Œ Example:

import org.junit.Test;

public class CalculatorTest {

    @Test
    public void testAddition() {
        int result = 2 + 3;
        assert result == 5;
    }
}

 2. Assertions

Assertions are used to validate expected results.

๐Ÿ“Œ Example:

assertEquals(5, result);
assertTrue(condition);
assertFalse(condition);

๐Ÿ‘‰ If the condition fails, the test fails.


 3. Test Runner

JUnit automatically runs all test cases and provides results:

  • Passed ✅

  • Failed ❌


 4. Test Suites

You can group multiple test cases together and run them as a suite.


 Why Use JUnit?

  • ๐Ÿงช Ensures code correctness

  • ๐Ÿ”„ Helps in regression testing

  • ⚡ Detects bugs early

  • ๐Ÿงฉ Improves code quality

  • ๐Ÿš€ Supports automation and CI/CD


 Real-Time Example

Imagine you are building a banking application:

  • You write a method to transfer money

  • Using JUnit → You test different scenarios (success, failure, insufficient balance)

๐Ÿ‘‰ This ensures your application behaves correctly before deployment.


 JUnit with Build Tools

JUnit integrates easily with tools like:

  • Apache Maven

  • Gradle

๐Ÿ‘‰ Tests can be executed automatically during the build process.


 Conclusion

JUnit is a powerful and essential tool for Java developers to perform unit testing. It ensures that your code is reliable, maintainable, and production-ready. Learning JUnit is a key step toward writing high-quality and bug-free applications.


 Promotional Content

Want to master JUnit, testing frameworks, and real-time Java development?

๐Ÿ‘‰ Join the Best Core JAVA Online Training in 2026

Wednesday, March 25, 2026

What is OAuth 2.0?

OAuth 2.0 is an authorization framework that allows applications to access user data from another service without sharing the user’s password.






๐Ÿ“Œ Why Do We Use OAuth 2.0?

  • Avoid sharing user credentials

  • Secure third-party access

  • Used in social logins (Google, GitHub, etc.)

  • Works well with APIs and microservices


๐Ÿ“Œ Key Roles in OAuth 2.0


๐Ÿ“Œ How OAuth 2.0 Works

  1. User tries to log in via third-party (e.g., Google)

  2. User is redirected to Authorization Server

  3. User grants permission

  4. Authorization Server returns an Authorization Code

  5. Client exchanges code for Access Token

  6. Client uses token to access protected resources


๐Ÿ”น Example Flow (Google Login)

  • Click “Login with Google”

  • Redirect to Google login page

  • User approves access

  • App receives access token

  • App fetches user profile data


๐Ÿ“Œ Important Concepts

๐Ÿ”‘ Access Token

  • Used to access APIs

  • Short-lived

๐Ÿ”„ Refresh Token

  • Used to generate new access tokens

  • Long-lived


๐Ÿ“Œ OAuth 2.0 Grant Types



๐Ÿš€ Advantages

  • ✔️ Secure (no password sharing)

  • ✔️ Scalable for modern apps

  • ✔️ Widely adopted standard

  • ✔️ Works with APIs & mobile apps


⚠️ Disadvantages

  • ❌ Complex to implement

  • ❌ Requires proper token management

  • ❌ Misconfiguration can lead to vulnerabilities


๐ŸŽฏ OAuth 2.0 vs JWT

  • OAuth 2.0 → Authorization framework

  • JWT → Token format used inside OAuth

๐Ÿ‘‰ They are often used together in real-world applications.


⚡ Real-Time Use Cases

  • Social login (Google, Facebook, GitHub)

  • API authorization

  • Microservices security

  • Single Sign-On (SSO)


๐Ÿ”ฅ OAuth 2.0 in Java

In Java (Spring Boot), OAuth 2.0 is implemented using:

  • Spring Security OAuth

  • Keycloak / Auth0 integration


✅ Conclusion

OAuth 2.0 is a powerful and secure way to allow third-party access to user data without exposing credentials. It is widely used in modern applications and is a must-know concept for backend developers.

Mastering OAuth 2.0 is essential if you're preparing for real-world projects and interviews through Top Core JAVA Online Training in Hyderabad.

Tuesday, March 24, 2026

What is Serialization in Java (with File Handling)?

Serialization in Java is the process of converting an object into a byte stream so that it can be stored in a file, sent over a network, or saved in a database.

๐Ÿ‘‰ When we use file handling, serialization helps us persist object data into a file and later retrieve it.




๐Ÿ”น Why Serialization is Used?

In real-world applications, we often need to:

  • Save object data permanently

  • Transfer objects between systems

  • Cache objects for faster access

Serialization makes all of this possible.


๐Ÿ”น How Serialization Works

Java provides built-in support using:

  • Serializable (marker interface)

  • ObjectOutputStream → to write object to file

  • ObjectInputStream → to read object from file


๐Ÿ”น Step 1: Make Class Serializable

import java.io.Serializable;

class Student implements Serializable {
    int id;
    String name;

    Student(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

๐Ÿ‘‰ Serializable is a marker interface (no methods)


๐Ÿ”น Step 2: Serialize Object (Write to File)

import java.io.*;

public class SerializeDemo {
    public static void main(String[] args) throws Exception {
        Student s = new Student(101, "John");

        FileOutputStream fos = new FileOutputStream("student.ser");
        ObjectOutputStream oos = new ObjectOutputStream(fos);

        oos.writeObject(s);
        oos.close();
        fos.close();

        System.out.println("Object Serialized");
    }
}

๐Ÿ”น Step 3: Deserialize Object (Read from File)

import java.io.*;

public class DeserializeDemo {
    public static void main(String[] args) throws Exception {
        FileInputStream fis = new FileInputStream("student.ser");
        ObjectInputStream ois = new ObjectInputStream(fis);

        Student s = (Student) ois.readObject();

        ois.close();
        fis.close();

        System.out.println(s.id + " " + s.name);
    }
}

๐Ÿ”น Key Points to Remember

✔ Object is converted into byte stream
✔ Stored in file (like .ser file)
✔ Must implement Serializable
✔ Used with file handling streams


๐Ÿ”น Important Concepts

๐Ÿ”ธ transient Keyword

  • Prevents a variable from being serialized

transient int password;

๐Ÿ”ธ serialVersionUID

  • Used to maintain version control during serialization

private static final long serialVersionUID = 1L;

๐Ÿ”น Real-Time Use Cases

  • Saving user session data

  • Storing objects in files

  • Sending objects over network (RMI, APIs)

  • Caching data in applications


๐Ÿ”น Serialization vs File Handling


๐Ÿš€ Final Thoughts

Serialization is a powerful feature that combines object-oriented programming with file handling, allowing you to store and retrieve complete objects easily.

If you want to master Core Java concepts like Serialization with real-time projects, check out:
๐Ÿ‘‰ No 1 Core JAVA Online Training in Hyderabad



Thread vs Runnable in Java: Key Differences, Best Practices & Which One to Use (2026 Guide)

Multithreading is a core part of Java —but one of the most common interview questions is: Should you use Thread or Runnable ? Thread is a ...