📘 Java Learning – Multithreading (Part 1: Multitasking & Thread Creation) 🚀🎯 Starting my learning journey into Java Multithreading, one of the most powerful features of Java used for executing multiple tasks simultaneously. 🔰 Multitasking Executing several tasks simultaneously is called Multitasking. There are two types of multitasking: 👉 Process Based Multitasking 👉 Thread Based Multitasking 1️⃣ Process Based Multitasking Executing several tasks simultaneously where each task is a separate independent process. Example: Running multiple applications at the same time: • Browser • Music Player • Code Editor ✔ Best suited at Operating System level 2️⃣ Thread Based Multitasking (Multithreading) Executing several tasks simultaneously where each task is an independent part of the same program. Each independent path of execution is called a Thread. ✔ Best suited for Programmatic level 🎯 Objective of Multitasking • Improve system performance • Reduce response time 📌 Applications of Multithreading Multithreading is widely used in: • Video games • Multimedia graphics • Animations • High performance applications 🔰 Multithreading Support in Java Java provides rich API support for multithreading through: • Thread • Runnable • ThreadGroup • ThreadLocal ✔ Java provides built-in APIs for multithreading, and programmers use these APIs to create and manage threads. This makes multithreading easier in Java compared to C++. 🔰 Ways to Create a Thread A thread can be defined in two ways: 1️⃣ Extending Thread class 2️⃣ Implementing Runnable interface 📌 Example – Extending Thread Class class MyThread extends Thread { public void run() { for(int i=0;i<5;i++){ System.out.println("Child Thread"); } } } public class ThreadDemo { public static void main(String[] args) { MyThread t = new MyThread(); // instantiation of thread t.start(); // starting of a thread for(int i=0;i<5;i++){ System.out.println("Main Thread"); } } } 📌 start() does NOT directly execute run(). It does: start() ↓ JVM asks Thread Scheduler ↓ New Thread Created ↓ run() executes in new thread ⭐ Key Points • start() method creates a new thread • run() contains the task executed by thread • Multiple threads execute simultaneously More concepts like Thread Scheduler, start() vs run(), Thread Lifecycle in the next post. #Java #CoreJava #Multithreading #JavaDeveloper #Concurrency #LearningJourney
Java Multithreading Basics: Multitasking & Thread Creation
More Relevant Posts
-
🚀 Day 25 | Core Java Learning Journey 📌 Topic: ArrayList & LinkedList in Java Today I learned about ArrayList and LinkedList, two important classes in the Java Collections Framework that implement the Java List Interface. Both are used to store ordered collections of elements, but they use different internal data structures and have different performance characteristics. 🔹 ArrayList ✔ ArrayList is a dynamic (growable) array implementation of the List interface. ✔ It automatically resizes when elements are added or removed. ✔ It allows duplicate elements and maintains insertion order. ✔ Elements can be accessed quickly using an index. Internal Data Structure: • Uses a resizable array. 📌Key Features: ✔ Fast random access using index (get, set operations) ✔ Allows null values and duplicate elements ✔ Maintains insertion order ✔ Automatically increases capacity when needed Best Use Case: ✔ When frequent data access (reading) is required. Example Implementation: • ArrayList 🔹 LinkedList ✔ LinkedList is another implementation of the List interface. ✔ It stores elements using nodes connected through links. ✔ Each node contains data and references to other nodes. ✔ It also implements Deque, so it can be used as a queue or stack. Internal Data Structure: • Doubly Linked List Each node contains: • Data • Reference to the previous node • Reference to the next node 📌Key Features : ✔ Efficient insertion and deletion of elements ✔ Allows duplicate elements ✔ Maintains insertion order ✔ Can be used as List, Queue, or Deque 🔹Types of Linked Lists (Conceptually): • Singly Linked List – Node points to next node • Doubly Linked List – Node points to both previous and next node • Circular Linked List – Last node connects back to the first node In Java, LinkedList is implemented as a Doubly Linked List. Example Implementation: • LinkedList 📌 Key Differences ✔ ArrayList uses a dynamic array ✔ LinkedList uses a doubly linked list structure ✔ ArrayList provides faster element access ✔ LinkedList provides faster insertion and deletion 📌 Key Takeaways ✔ Both ArrayList and LinkedList implement the List interface ✔ ArrayList is best for fast access and reading data ✔ LinkedList is better for frequent insertions and deletions ✔ Choosing the right data structure improves performance and efficiency Understanding these implementations helps developers select the most suitable data structure when working with collections in Java 💻⚡ Special thanks to Vaibhav Barde Sir for explaining these concepts clearly. #CoreJava #JavaLearning #ArrayList #LinkedList #JavaCollections #JavaDeveloper #Programming #LearningJourney
To view or add a comment, sign in
-
-
🚀 Day 22 | Core Java Learning Journey 📌 Topic: Multithreading in Java Today I learned an important concept in Java — Multithreading. It helps programs perform multiple tasks simultaneously, improving performance and CPU utilization. 🔹 What is a Thread? ✔ A Thread is the smallest unit of execution within a process ✔ Multiple threads can run inside a single program ✔ Threads share the same memory but execute independently 🔹 Definition of Multithreading ✔ Multithreading is the process of executing multiple threads concurrently within a single program ✔ It improves application performance and responsiveness 🔹 Two Ways to Create Threads in Java 1️⃣ By Extending Thread Class ✔ Create a class that extends Thread ✔ Override the run() method ✔ Start execution using start() Syntax: class MyThread extends Thread { public void run() { // task } } 2️⃣ By Implementing Runnable Interface ✔ Create a class that implements Runnable ✔ Override the run() method ✔ Pass object to Thread class Syntax: class MyRunnable implements Runnable { public void run() { // task } } ✔ Runnable approach is preferred because it supports better design and flexibility. 🔹 Thread Priorities Java provides three important priority constants: ✔ MIN_PRIORITY → 1 ✔ NORM_PRIORITY → 5 (Default) ✔ MAX_PRIORITY → 10 Higher priority threads may get more CPU time, but execution order is not guaranteed. 🔹 Methods that Control / Prevent Thread Execution ✔ sleep() → Pauses thread for a specified time ✔ yield() → Temporarily pauses current thread to give chance to others ✔ join() → Makes one thread wait until another thread finishes ✔ wait() → Makes thread wait until another thread notifies it (used in synchronization) ⚠ suspend() method is deprecated because it may cause deadlocks. 🔹 Synchronization ✔ Synchronization controls access to shared resources when multiple threads run simultaneously ✔ Prevents race conditions and data inconsistency ✔ Implemented using the synchronized keyword 📌 Key Takeaways ✔ Thread → Smallest unit of execution ✔ Multithreading → Multiple threads running concurrently ✔ Threads can be created using Thread class or Runnable interface ✔ Priority affects scheduling but not guaranteed execution order ✔ Methods like sleep(), yield(), join(), wait() help manage threads ✔ Synchronization ensures safe access to shared resources Multithreading is essential for building efficient and high-performance Java applications 💻⚡ Special thanks to Vaibhav Barde Sir. #CoreJava #JavaLearning #Multithreading #JavaDeveloper #Concurrency #OOP #LearningJourney
To view or add a comment, sign in
-
-
Understanding Multithreading in Java 🔹 In this example, I explored two approaches for creating threads: • Extending the Thread class • Implementing the Runnable interface package multithreading; /* 1️⃣ Extending Thread Class When a class extends the Thread class, it becomes a thread class. Objects of this class can run in a separate thread. However, the actual task that the thread executes must be written inside the run() method. When start() is called, the JVM creates a new thread and internally invokes the run() method. */ class CommonResource extends Thread { public void commonResource(String t){ System.out.println("common resources " + t); } @Override synchronized public void run() { String currT = Thread.currentThread().getName(); if(currT.equals("bheem")){ System.out.println("bheem thread"); } else if(currT.equals("kalia")){ System.out.println("kalia thread"); } else{ System.out.println("raju thread"); } try{ Thread.sleep(5000); } catch(Exception e){ e.printStackTrace(); } commonResource(currT); } } /* 2️⃣ Creating a Common Resource using the Runnable interface. Instead of extending Thread, it is generally recommended to implement the Runnable interface. Advantages: • The task is separated from the thread. • The class can still extend another class (Java doesn't support multiple inheritance). • This approach is widely used in industry (especially with thread pools). */ class CommonResource1 implements Runnable { public void commonResource(String t){ System.out.println("common resources " + t); } /* Multiple threads will share the same object of this class. Because the run() method is synchronized, only one thread can execute it at a time for this shared object. */ @Override synchronized public void run() { String currT = Thread.currentThread().getName(); if(currT.equals("bheem")){ System.out.println("bheem thread"); } else if(currT.equals("kalia")){ System.out.println("kalia thread"); } else{ System.out.println("raju thread"); } try{ Thread.sleep(5000); } catch(Exception e){ e.printStackTrace(); } commonResource(currT); } } public class ThreadsUsesCommonResource { public static void main(String[] args){ // Creating a shared resource object CommonResource1 commonResource1 = new CommonResource1(); // Creating multiple threads that use the same resource Thread t1 = new Thread(commonResource1); t1.setName("kalia"); Thread t2 = new Thread(commonResource1); t2.setName("bheem"); Thread t3 = new Thread(commonResource1); t3.setName("raju"); // start() → JVM creates a new thread → run() method executes t1.start(); t2.start(); t3.start(); } } #Java #Multithreading #Synchronized #BackendDevelopment #LearningInPublic
To view or add a comment, sign in
-
🚀 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
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
-
-
🚀 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 135 of My Java Learning Journey 🤩 Respected connections, Today I explored how to rotate elements of a list in Java using the Collections.rotate() method. List rotation means shifting elements either left or right by a certain number of positions. Java provides a simple built-in method to do this without writing manual logic. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 💻 Java Code: -----------------> public class ListRotation { public static void main(String[] args) { List<Integer> list = Arrays.asList(10, 20, 30, 40, 50); System.out.println("Original List: " + list); // Left Side Rotation Collections.rotate(list, -3); System.out.println("After three time left rotation: " + list); // Right Side Rotation Collections.rotate(list, +3); System.out.println("After three time right rotation: " + list); } } ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 🖥 Output: --------------> Original List: [10, 20, 30, 40, 50] After three time left rotation: [40, 50, 10, 20, 30] After three time right rotation: [10, 20, 30, 40, 50] 📌 Output Explanation Collections.rotate(list, distance) shifts elements in the list. If the distance is positive, elements rotate to the right. If the distance is negative, elements rotate to the left. In this example: rotate(list, -3) moves the list 3 positions to the left. rotate(list, +3) moves the list 3 positions to the right, restoring the original list. ⭐ Important Concept Collections.rotate() is a utility method from the Collections framework that simplifies list manipulation operations such as circular shifting of elements. 💡 Important Tip Instead of writing complex loops for shifting elements, using Collections.rotate() keeps your code clean, readable, and efficient. 🤔 Question for Developers Can you modify this program to rotate the list based on user input instead of a fixed number like 3? Small Java concepts like this help improve problem-solving and understanding of the Collections framework. 🚀 Follow my journey as I continue exploring Java every day. #Java #JavaProgramming #JavaDeveloper #CollectionsFramework #Coding #Programming #Developers #TechLearning #ProblemSolving #LearningInPublic #100DaysOfCode #DevOps #Logical #day135 #CodeWithYuvi
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
-
-
🚀 Day 26 | Core Java Learning Journey 📌 Topic: Legacy Classes in Java & Iteration Interfaces Today I learned about Legacy Classes in Java and the iteration mechanisms used to traverse elements in collections. These concepts were introduced in early versions of Java and later became compatible with the Java Collections Framework. Understanding them helps in learning how Java collections evolved over time. 🔹 What are Legacy Classes in Java? ✔ Legacy Classes are the classes that were introduced before Java 1.2, when the Java Collections Framework did not exist. ✔ These classes were part of the original Java library. ✔ Later, they were updated to work with the Collections Framework, but modern alternatives are usually preferred today. 📌 Five Important Legacy Classes 1️⃣ Vector ✔ Dynamic array similar to ArrayList ✔ Synchronized (thread-safe) by default ✔ Allows duplicate elements ✔ Maintains insertion order 2️⃣ Stack ✔ Subclass of Vector ✔ Follows LIFO (Last In First Out) principle ✔ Common methods: • push() – add element • pop() – remove top element • peek() – view top element 3️⃣ Hashtable ✔ Stores key–value pairs ✔ Synchronized (thread-safe) ✔ Does not allow null key or null value ✔ Considered the older version of HashMap 4️⃣ Dictionary ✔ Abstract class used for storing key–value pairs ✔ Parent class of Hashtable ✔ Rarely used in modern Java 5️⃣ Properties ✔ Subclass of Hashtable ✔ Stores configuration data as String key–value pairs ✔ Commonly used in .properties files 🔹 Iteration Interfaces in Java To traverse elements in collections, Java provides different iteration mechanisms. 📌 Enumeration ✔ One of the oldest iteration interfaces ✔ Mainly used with legacy classes like Vector and Hashtable ✔ Supports read-only traversal Methods: • hasMoreElements() • nextElement() 📌 Iterator ✔ Introduced with the Java Collections Framework ✔ Used to iterate over most collection classes Methods: • hasNext() • next() • remove() 📌 ListIterator ✔ Advanced version of Iterator used with List implementations ✔ Supports bidirectional traversal Additional Methods: • hasPrevious() • previous() • nextIndex() • previousIndex() • add() • set() 📌 Difference: Enumeration vs Iterator vs ListIterator ✔ Enumeration → Used with legacy classes, forward traversal only, no modification ✔ Iterator → Works with most collections, forward traversal, supports remove() ✔ ListIterator → Used with lists, supports forward & backward traversal, allows modification of elements Learning these concepts improves understanding of how Java collections work internally and how iteration mechanisms evolved in Java 💻⚡ Special thanks to Vaibhav Barde Sir for explaining these concepts clearly. #CoreJava #JavaLearning #LegacyClasses #Iterator #ListIterator #Enumeration #JavaCollections #JavaDeveloper #Programming #LearningJourney
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
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