🚀 Day 39 – Core Java | Polymorphism, Upcasting & Downcasting Today’s session focused on understanding the third pillar of Object-Oriented Programming — Polymorphism and how it works internally in Java. 🔹 What is Polymorphism? The word Polymorphism comes from Greek: Poly → Many Morph → Forms Meaning: One entity behaving in multiple forms. In Java, this is achieved mainly using method overriding and inheritance. 🔹 Example Used A Plane parent class with a method: fly() Three child classes: CargoPlane PassengerPlane FighterPlane Each class overrides the fly() method and behaves differently. Example: Cargo Plane → flies at low height Passenger Plane → flies at medium height Fighter Plane → flies at high altitude This demonstrates one method → multiple behaviors. 🔹 Tight Coupling vs Loose Coupling Tight Coupling Child reference → Child object CargoPlane cp = new CargoPlane(); cp.fly(); Here both reference and object are child type. Loose Coupling (Used for Polymorphism) Parent reference → Child object Plane ref = new CargoPlane(); ref.fly(); Here: Parent reference Child object This allows polymorphic behavior. 🔹 Types of Methods in Inheritance 1️⃣ Inherited Method Method comes directly from parent. 2️⃣ Overridden Method Child modifies the parent method. 3️⃣ Specialized Method Method exists only in child class. Example: carryCargo() carryPassengers() carryWeapons() 🔹 Important Rule Using parent reference, we can access: ✔ Inherited methods ✔ Overridden methods ❌ Cannot access specialized methods. 🔹 Downcasting To access child-specific methods: Parent reference must behave like a child. Example: ((CargoPlane) (ref)).carryCargo(); This process is called Downcasting. 🔹 Upcasting Plane ref = new CargoPlane(); Child object assigned to parent reference. This is called Upcasting and it happens automatically in Java. 🔹 Advantages of Polymorphism 1️⃣ Code Reduction Common logic can be reused instead of repeating code. 2️⃣ Code Flexibility One method can handle multiple object types. Example: airport.permit(plane) The same method can accept: CargoPlane PassengerPlane FighterPlane 💡 Key Takeaway Polymorphism allows one interface to perform multiple behaviors, making Java programs: More flexible Easier to maintain Less repetitive It is one of the most powerful concepts used in real-world Java applications and interviews. #CoreJava #Polymorphism #JavaOOP #MethodOverriding #Upcasting #Downcasting #JavaLearning #DeveloperJourney #InterviewPreparation
Java Polymorphism, Upcasting & Downcasting Explained
More Relevant Posts
-
🚀 Mastering Java Stream API – Write Cleaner, Smarter Code If you're still writing verbose loops in Java, it's time to rethink your approach. The Stream API (introduced in Java 8) is not just a feature—it’s a paradigm shift toward functional-style programming in Java. It allows you to process collections of data in a declarative, concise, and efficient way. 🔍 What is Stream API? A Stream is a sequence of elements that supports various operations to perform computations. Unlike collections, streams: Don’t store data Are immutable (operations don’t modify the source) Support lazy evaluation Enable parallel processing effortlessly ⚙️ Core Concepts 1. Stream Creation List<String> names = Arrays.asList("John", "Jane", "Jack"); Stream<String> stream = names.stream(); 2. Intermediate Operations (Lazy) filter() map() sorted() These return another stream and are not executed until a terminal operation is invoked. names.stream() .filter(name -> name.startsWith("J")) .map(String::toUpperCase); 3. Terminal Operations (Trigger Execution) forEach() collect() count() List<String> result = names.stream() .filter(name -> name.length() > 3) .collect(Collectors.toList()); 💡 Why Use Stream API? ✅ Readable & Declarative Code Focus on what to do, not how to do it ✅ Less Boilerplate Goodbye nested loops ✅ Parallel Processing names.parallelStream().forEach(System.out::println); ✅ Functional Programming Power Lambdas + Streams = Clean pipelines 🔥 Real-World Example Traditional Approach List<String> filtered = new ArrayList<>(); for (String name : names) { if (name.length() > 3) { filtered.add(name.toUpperCase()); } } Stream API Approach List<String> filtered = names.stream() .filter(name -> name.length() > 3) .map(String::toUpperCase) .collect(Collectors.toList()); 👉 Less code. More clarity. Better maintainability. ⚠️ Common Pitfalls Overusing streams can hurt readability Avoid complex nested streams Be cautious with parallel streams (thread-safety matters) 🧠 Pro Tip Think of streams as a data pipeline: Source → Intermediate Operations → Terminal Operation 📌 Final Thoughts The Stream API is a must-have skill for modern Java developers. It helps you write clean, scalable, and expressive code, especially in microservices and data-heavy applications. If you're building backend systems with Java, mastering streams is not optional—it's essential. 💬 How often do you use Stream API in your projects? Any advanced patterns you rely on? #Java #StreamAPI #BackendDevelopment #Java8 #CleanCode #FunctionalProgramming #SoftwareEngineering
To view or add a comment, sign in
-
🚀 Day 40 – Core Java | Abstraction & Abstract Classes Today’s session focused on the fourth pillar of Object-Oriented Programming — Abstraction and how it works in Java. 🔹 What is Abstraction? Abstraction means: 👉 Hiding the implementation details and showing only the essential features. Real-world example When you drive a car: You press the accelerator You use the steering You apply brakes But you don’t know the internal engine mechanism. The internal working is hidden — this is Abstraction. Another example: Using Instagram / WhatsApp You swipe or send a message But you don’t know the internal code. You only see the features, not the implementation. 🔹 Abstract Method in Java An abstract method is an incomplete method. It contains only the method signature, not the body. Example: abstract void calculateArea(); Here: Method name → calculateArea No implementation The implementation will be provided by child classes. 🔹 Abstract Class If a class contains at least one abstract method, the class must be declared as abstract. Example: abstract class Shape { abstract void calculateArea(); } Important rule: 👉 Abstract class cannot be instantiated (object cannot be created). ❌ Not allowed Shape s = new Shape(); Because the class contains incomplete methods. 🔹 Example Used in Class We implemented Shapes example using abstraction. Parent class: Shape Child classes: Square Rectangle Circle Common behavior: acceptInput() calculateArea() displayArea() Design Shape (Abstract Class) abstract class Shape { float area; abstract void acceptInput(); abstract void calculateArea(); void displayArea() { System.out.println(area); } } Child classes override the abstract methods. Example: class Square extends Shape Each class calculates area differently. 🔹 Advantages 1️⃣ Code Reusability Common methods like displayArea() written once in parent class. 2️⃣ Better Design Abstract class defines common structure. 3️⃣ Cleaner Code Child classes implement only required logic. 🔹 Important Rules of Abstraction ✔ Abstract method → no body ✔ Class with abstract method → must be abstract ✔ Abstract class cannot create object ✔ Abstract class can contain normal methods also ✔ Abstract keyword cannot be used with variables ❌ Not allowed abstract int a; 🔹 Abstract vs Final abstract and final cannot be used together. Reason: abstract → method must be overridden final → method cannot be overridden So they contradict each other. 🔹 Key Insight Abstraction works like a hierarchy: Top level → more abstract Lower level → more concrete Example: Bird (abstract) ↓ Eagle (partially abstract) ↓ GoldenEagle / SerpentEagle (concrete) As we move down the hierarchy, abstract behavior becomes fully implemented. #Java #CoreJava #OOPS #Abstraction #AbstractClass #JavaDeveloper #ProgrammingJourney #SoftwareEngineering #LearningInPublic
To view or add a comment, sign in
-
Day 39 of Learning Java: Downcasting & instanceof Explained Clearly 1. What is Downcasting? Downcasting is the process of converting a parent class reference → child class reference. It is the opposite of Upcasting. 👉 Key Points: Requires explicit casting Used to access child-specific methods Only works if the object is actually of the child class Example: class A {} class B extends A {} A ref = new B(); // Upcasting B obj = (B) ref; // Downcasting 💡 Here, ref actually holds a B object, so downcasting is safe. 2. When Downcasting Fails If the object is NOT of the target subclass → it throws: ClassCastException 📌 Example: A ref = new A(); B obj = (B) ref; // Runtime Error 👉 This is why we need a safety check! 3. instanceof Keyword (Safety Check ) The instanceof keyword is used to check whether an object belongs to a particular class before casting. 📌 Syntax: if (ref instanceof B) { B obj = (B) ref; } 💡 Prevents runtime errors and ensures safe downcasting. 4. Real-World Example class SoftwareEngineer { void meeting() { System.out.println("Attending meeting"); } } class Developer extends SoftwareEngineer { void coding() { System.out.println("Writing code"); } } class Tester extends SoftwareEngineer { void testing() { System.out.println("Testing application"); } } 📌 Manager Logic using instanceof: void review(SoftwareEngineer se) { if (se instanceof Developer) { Developer dev = (Developer) se; dev.coding(); } else if (se instanceof Tester) { Tester t = (Tester) se; t.testing(); } } 💡 This is a real use of polymorphism + safe downcasting 5. Key Rules to Remember ✔ Downcasting requires upcasting first ✔ Always use instanceof before downcasting ✔ Helps access child-specific behavior ✔ Wrong casting leads to runtime exceptions 💡 My Key Takeaways: Upcasting gives flexibility, Downcasting gives specificity instanceof is essential for writing safe and robust code This concept is widely used in real-world applications, frameworks, and APIs #Java #OOP #LearningInPublic #100DaysOfCode #Programming #Developers #JavaDeveloper #CodingJourney
To view or add a comment, sign in
-
-
DAY 27: CORE JAVA 🚀 Understanding Inheritance in Java and Its Types Inheritance is one of the fundamental pillars of Object-Oriented Programming (OOP). It allows one class to acquire the properties (variables) and behaviors (methods) of another class. 📌 Definition: Inheritance is the process where a child class (subclass) acquires the properties and behaviors of a parent class (superclass) using the "extends" keyword in Java. 💡 Advantages of Inheritance ♻️ Code Reusability – Existing code can be reused in new classes ⏱️ Reduced Development Time & Effort 📈 Improved Maintainability and Productivity 🔹 Types of Inheritance in Java 1️⃣ Single Inheritance A class inherits from only one parent class. Example structure: Parent → Child 2️⃣ Multilevel Inheritance Inheritance happens in multiple levels, where a class becomes both a child and a parent. Example structure: Grandparent → Parent → Child This allows properties and methods to pass through multiple generations of classes. 3️⃣ Hierarchical Inheritance Multiple child classes inherit from one parent class. Example structure: Parent → Child1 Parent → Child2 Parent → Child3 4️⃣ Hybrid Inheritance A combination of two or more types of inheritance, such as multilevel + hierarchical. ⚠️ Multiple Inheritance and Diamond Problem Multiple Inheritance means a class inherits from more than one parent class. Example idea: Parent1 Parent2 ↓ Child However, Java does NOT allow multiple inheritance using classes. ❓ Why? Because of the Diamond Problem. In this situation: - Two parent classes inherit from the same grandparent class. - The child class inherits from both parents. - If both parents contain the same method, the child class cannot decide which method to use. This creates ambiguity in method resolution, which is known as the Diamond Problem. Therefore, Java avoids this complexity by not allowing multiple inheritance with classes. Instead, Java uses interfaces to achieve similar behavior safely. ⚠️ Cyclic Inheritance Cyclic inheritance occurs when a class tries to inherit from itself directly or indirectly. Example idea: Class A → inherits from B Class B → inherits from A This creates an infinite inheritance loop, so Java does not allow cyclic inheritance. 💻 Simple Example class Parent { void readBooks() { System.out.println("Read Books"); } } class Child extends Parent { } public class Main { public static void main(String[] args) { Child c = new Child(); c.readBooks(); } } Here, the Child class inherits the method from the Parent class, demonstrating Single Inheritance. ✨ Understanding inheritance helps developers design clean, reusable, and scalable object-oriented systems. TAP Academy #Java #OOP #Inheritance #Programming #SoftwareDevelopment #JavaDeveloper #Coding
To view or add a comment, sign in
-
-
Standard Signature of main() Method in Java In every programming language there must be an entry point of execution from where program execution begins. In C/C++, the entry point is the main() function, which is invoked by the Operating System. OS expects 0 as exit status indicating successful program execution so the return type of main is commonly int. In Java, the entry point is also the main() method, but it is invoked by the Java Virtual Machine (JVM) instead of the OS. Since the JVM handles execution internally, there is no need to return a status code, therefore the return type of the main method is always void. In Java, every method belongs to a class, so the main method must be defined inside a class. Example: class Main { void main() { // code } } However, this method cannot be executed by the JVM because it is not accessible outside the class. To allow the JVM to access it, the method must be declared public. class Main { public void main() { // code } } In Java, methods normally belong to objects and are invoked using an object reference. If the main method were not static, the JVM would have to create an object of the class before calling it. Since main is the entry point of every program, this would add unnecessary overhead. To allow the JVM to invoke the method without creating an object, the main method is declared static. class Main { public static void main() { // code } } But this method still cannot receive data from the command line arguments. To accept input from the command line during program execution, the main method takes a parameter which is an array of strings. Each element of this array represents one argument passed from the command line. Final standard signature of the main method: class Main { public static void main(String[] args) { // code } } Here: public → allows the JVM to access the method static → allows the JVM to call the method without creating an object void → no return value required String[] args → receives command line arguments However, for a beginner writing "public static void main(String[] args)" is overwhelming. So Java developer decided to introduce simplified syntax for new comer to maintain language acceptance and popularity among all. In newer Java versions, we can write a simpler program like: void main() { System.out.println("Hello"); } Introduced in JDK 21 and finally accepted in JDK 25 (2025). The compiler automatically wraps this into a class behind the scenes. However, this feature is mainly designed for learning and small scripts, while the traditional main method remains the standard approach used in real applications. Grateful to my mentor Syed Zabi Ulla for explaining these concepts so clearly and helping me build a strong foundation in programming. #OOP #Java #Programming #ComputerScience #LearningJourney #SoftwareDevelopment
To view or add a comment, sign in
-
Basic Java Interview Q&A ✅ 1. What is Java? Java is a high-level, object-oriented, platform-independent programming language. Its “Write Once, Run Anywhere” principle is powered by the Java Virtual Machine (JVM). ✅ 2. Key Features of Java Simple & Secure Object-Oriented Platform Independent (via JVM) Robust & Multithreaded High Performance (with JIT Compiler) ✅ 3. Difference Between JDK, JRE, and JVM JDK (Java Development Kit) → Includes compiler, tools, and JRE. JRE (Java Runtime Environment) → Contains JVM + core libraries. JVM (Java Virtual Machine) → Executes bytecode, platform-dependent. ✅ 4. Four OOP Principles in Java Encapsulation → Data hiding through classes. Inheritance → Reuse properties and methods. Polymorphism → One interface, multiple implementations. Abstraction → Hide implementation details, expose essential features. ✅ 5. Difference Between == and .equals() == → Compares memory references. .equals() → Compares actual values or content. ✅ 6. What is String Immutability? Strings in Java are immutable, meaning once created, they cannot be changed. Any modification results in a new String object in the memory pool. ✅ 7. What is the difference between Array and ArrayList? Array → Fixed size, can store primitives & objects ArrayList → Dynamic size, only stores objects, part of Collections framework ✅ 8. Types of Access Modifiers public → Accessible from anywhere. protected → Accessible within the same package and subclasses. default → Accessible only within the package. private → Accessible only within the same class. ✅ 9. What is Exception Handling? A mechanism to handle runtime errors using keywords: try, catch, finally, throw, and throws. ✅ 10. Checked vs. Unchecked Exceptions Checked → Compile-time (e.g., IOException, SQLException). Unchecked → Runtime (e.g., NullPointerException, ArithmeticException). ✅ 11. What is Garbage Collection? Automatic memory management that removes unused objects from the heap to free memory space. ✅ 12. What is the difference between Overloading and Overriding? Overloading → Same method name, different parameters (Compile-time polymorphism) Overriding → Subclass redefines parent class method (Runtime polymorphism) Follow Programming [Assignment-Project-Coursework-Exam-Report] Helper For Students | Agencies | Companies for more #Java #JavaInterview #CoreJava #OOP #BackendDevelopment #JavaProgramming #CodingInterview #100DaysOfCode
To view or add a comment, sign in
-
Hello Connections, Post 17 — Java Fundamentals A-Z ☕ Java Streams have completely transformed coding approach. 🚀 However, many developers still have misconceptions about what a Stream truly is. Let's clear the air! 💡 🚫 What a Stream is NOT: ❌ A data structure ❌ A place to store data ❌ Anything like an ArrayList ✅ What a Stream actually IS: 🌊 A pipeline that processes data 📖 Reads from a source ⚙️ Transforms it step by step 🏁 Produces a result Example in Action: 💻 List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David"); long count = names.stream() // 1. SOURCE 📥 .filter(n -> n.length() > 3) // 2. INTERMEDIATE ⚙️ .count(); // 3. TERMINAL 🏁 System.out.println(count); // Output: 3 ⚠️ The Golden Rule: Streams are LAZY! 😴 Stream<String> stream = names.stream() .filter(n -> { System.out.println("Checking: " + n); return n.length() > 3; }); // 🤫 Nothing happens yet! stream.count(); // 🔥 NOW it runs! This laziness is a superpower—it avoids unnecessary processing, even in pipelines with millions of records! ⚡ 🧠 Quick Quiz — Test Your Knowledge! Problem 1 — What is the output? 🔢 List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5); long result = nums.stream().filter(n -> n > 2).count(); System.out.println(result); 👉 Answer: 3 (Numbers 3, 4, and 5 pass the filter!) Problem 2 — How many times does filter run? ⏱️ List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); Optional<String> result = names.stream() .filter(n -> n.startsWith("C")) .findFirst(); 👉 Answer: 3 times (Alice ❌, Bob ❌, Charlie ✅... then it stops!) Problem 3 — Will this print anything? 🙊 List<Integer> nums = Arrays.asList(1, 2, 3); Stream<Integer> stream = nums.stream() .filter(n -> n > 1) .map(n -> n * 2); 👉 Answer: Nothing! Remember: No terminal operation = No execution! 🚫 Post 17 Summary: 📝 🔴 Unlearned → "Stream is just another collection." 🟢 Relearned → "Stream is a lazy processing pipeline." 🤯 Biggest surprise → filter() does NOTHING without a terminal operation! Follow along for more👇 #Java #JavaFundamentals #BackendDevelopment #LearningInPublic #SDE2 #CodingTips #SoftwareEngineering
To view or add a comment, sign in
-
-
Let’s talk about Optional in Java. ☕ When should you use it, and when should you avoid it? Recently, I saw a post suggesting using Optional as a method parameter to simulate Kotlin's Elvis operator (?:). This is actually an anti-pattern! Let's review when to use it and when to avoid it, inspired by Stuart Marks’s famous talk on the topic. What’s the actual problem with null in Java? It’s semantic ambiguity: is it an error, an uninitialized variable, or a legitimate absence of a value? This forces us into defensive coding (if (obj != null)) to avoid the dreaded NPEs. Java introduced Optional<T> to declare a clear API contract: "This value might not be present; it's your responsibility to decide how to handle its absence." ✅ WHERE TO USE OPTIONAL: 👉 Method Return Types: This is its primary design purpose. It clearly communicates that a result might be empty: Optional<SaleEntity> findSaleById(Long id) 👉 Safe Transformations: Extract nested data without breaking your flow with intermediate null checks: var city = Optional.ofNullable(client) .map(Client::getAddress) .map(Address::getCity) .orElse("Unknown"); 👉 Stream Pipelines: Using flatMap(Optional::stream) elegantly filters a stream, leaving only the present values without cluttering your code. ❌ WHERE NOT TO USE OPTIONAL (ANTI-PATTERNS): 👉 Method Parameters: Never do this. It complicates the signature, creates unnecessary object allocation, and doesn't even prevent someone from passing a null instead of an Optional! Use internal validations (Objects.requireNonNull). 👉 Calling .get() without checking: Never call Optional.get() unless you can mathematically prove it contains a value. Prefer alternatives like .orElse(), .orElseGet(), or .ifPresent(). 👉 Returning Null for an Optional: If your method returns an Optional, returning a literal null defeats the entire purpose and will cause unexpected NPEs downstream. Always return Optional.empty(). 👉 Class Fields (Attributes): Optional is not Serializable. Use a documented null or the "Null Object Pattern". 👉 Collections: Never return Optional<List<T>>. Just return an empty list (Collections.emptyList()). It's semantically correct and saves memory. Optional doesn't eradicate null, but it helps us design more honest APIs. Let's use it responsibly. 🛠️ To dive deeper, I've attached a PDF summary of the core rules for Optionals. 📄👇 What other anti-patterns have you seen when using Optionals? Let me know below! (PS: I'll leave the link to Stuart Marks's full video breakdown in the first comment). #Java #SoftwareEngineering #CleanCode #Backend #JavaDeveloper #Optional
To view or add a comment, sign in
-
📌 Java 8 Functional Interfaces — Explained with Use Cases Java provides built-in functional interfaces to support lambda expressions and functional programming. Here are the most important ones every Java developer should know: --- 1️⃣ Runnable @FunctionalInterface public interface Runnable { void run(); } ✔ Takes: No input ✔ Returns: Nothing Use Case: • Multithreading tasks Example: Runnable r = () -> System.out.println("Task running"); --- 2️⃣ Callable @FunctionalInterface public interface Callable<V> { V call() throws Exception; } ✔ Takes: No input ✔ Returns: Result Use Case: • Tasks that return values (ExecutorService) Example: Callable<Integer> c = () -> 10; --- 3️⃣ Comparator @FunctionalInterface public interface Comparator<T> { int compare(T o1, T o2); } ✔ Takes: Two inputs ✔ Returns: int Use Case: • Sorting collections Example: list.sort((a, b) -> a - b); --- 4️⃣ Function<T, R> ✔ Takes: One input ✔ Returns: One output Use Case: • Transforming data Example: Function<String, Integer> f = s -> s.length(); --- 5️⃣ Predicate<T> ✔ Takes: One input ✔ Returns: boolean Use Case: • Filtering conditions Example: Predicate<Integer> p = x -> x > 10; --- 6️⃣ Consumer<T> ✔ Takes: One input ✔ Returns: Nothing Use Case: • Performing actions (printing, logging) Example: Consumer<String> c = s -> System.out.println(s); --- 7️⃣ Supplier<T> ✔ Takes: No input ✔ Returns: Value Use Case: • Lazy value generation Example: Supplier<Double> s = () -> Math.random(); --- 🧠 Quick Summary Runnable → No input, no output Callable → No input, returns output Function → Input → Output Predicate → Input → boolean Consumer → Input → action Supplier → No input → output --- 💡 Key Takeaway These interfaces form the backbone of Java 8 features like Streams and Lambdas. Mastering them helps write clean, functional, and expressive code. #Java #Java8 #FunctionalInterfaces #Lambda #BackendDevelopment
To view or add a comment, sign in
-
Asynchronous Programming in Java Java Level Async (Core Concepts) ✅ Runnable vs Callable At the very basic level, when you create a task: Runnable → Just runs something, doesn’t return anything Callable → Runs something and gives you a result back In real projects: Use Runnable for things like logging, background audit, notifications Use Callable when you’re calling a DB or another API and need a response Example: Runnable r = () -> System.out.println("Logging task"); Callable<String> c = () -> { return "DB Data"; }; ✅ Executor This is a very simple interface — just executes a task. In reality, you won’t use this directly much. It’s more like a base concept behind everything else. Example: Executor ex = Runnable::run; ex.execute(() -> System.out.println("Task executed")); ✅ ExecutorService (Very Important) This is where real-world usage starts. Instead of creating threads manually (which is costly), we use a thread pool. Why? Thread creation is expensive Reusing threads improves performance You get control over how many tasks run in parallel Typical scenarios: Processing thousands of records Calling multiple APIs in parallel Running batch jobs Example: ExecutorService ex = Executors.newFixedThreadPool(3); ex.submit(() -> { System.out.println(Thread.currentThread().getName()); }); ✅ Executors (Factory Class) 👉 Utility class to create thread pools Types: Fixed → Controlled threads Cached → Dynamic threads Single → Sequential execution Executors.newFixedThreadPool(5); Executors.newCachedThreadPool(); ->Quick setup (POC / small apps) ->Avoid direct use in production → use custom thread pool ✅ Future (Old Approach) ->Represents async result ->get() blocks the thread Future<String> f = ex.submit(() -> "Hello"); String res = f.get(); // blocks ->Blocking → reduces performance ->Legacy systems only ✅ CompletableFuture ⭐⭐⭐ (MOST IMPORTANT) ->Modern async API (Java 8+) Supports: Non-blocking execution Chaining Combining multiple tasks Exception handling CompletableFuture.supplyAsync(() -> "User") .thenApply(name -> name + " Data") .thenAccept(System.out::println); ->Parallel Calls Example CompletableFuture<String> f1 = CompletableFuture.supplyAsync(() -> "Orders"); CompletableFuture<String> f2 = CompletableFuture.supplyAsync(() -> "Payments"); CompletableFuture.allOf(f1, f2).join(); =>Real Scenarios: Aggregating microservice responses Calling multiple APIs in parallel Building dashboards =>Why it's powerful? Non-blocking → better performance Functional style → clean code ✅ ForkJoinPool -> Uses divide & conquer approach ForkJoinPool pool = new ForkJoinPool(); ->When to use? Large computations Recursive parallel processing ->Example: File parsing Data splitting tasks Spring level async techniques are upcoming post. #java #springboot #javadevelopement #spring #springboot #programming #coding
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development