🚀 Java 8 Features Day 4 What is Bi Functional Interfaces in Java? 1️⃣ BiPredicate<T, U> 👉 Takes two input arguments 👉 Returns a boolean value Example Code: import java.util.function.BiPredicate; class Main { public static void main(String[] args) { BiPredicate<Float, Float> isValidWeight = (height, weight) -> weight == height - 100; if (isValidWeight.test(174.5f, 74.5f)) { System.out.println("Congrats! You are in correct weight."); } else { System.out.println("Sorry! You are not in correct weight."); } } } 👉 Use case: Validations involving two values. 2️⃣ BiFunction<T, U, R> 👉 Takes two input arguments 👉 Returns any type (R) Example Code: import java.util.function.BiFunction; import java.util.Base64; class Main { public static void main(String[] args) { BiFunction<Long, String, String> tempPassword = (phoneNumber, email) -> Base64.getEncoder() .encodeToString((email + phoneNumber).getBytes()); System.out.println( tempPassword.apply(9080555678L, "hariv6@gmail") ); } } 👉 Use case: Transforming two inputs into one result ✅ 3️⃣ BiConsumer<T, U> 👉 Takes two input arguments 👉 Returns nothing (void) 👉 Only consumes data Example Code: import java.util.function.BiConsumer; class Main { public static void main(String[] args) { BiConsumer<Float, Double> bonusCalculation = (experience, salary) -> { if (experience < 5 && salary <= 100000.0) { System.out.println("Your bonus is 20%"); } else { System.out.println("Your bonus is 10%"); } }; bonusCalculation.accept(4.3f, 70000.0); } } 👉 Use case: Performing operations like logging, printing, updating records. ❓ Why is there no BiSupplier? Because: 👉 Supplier<T> does not take any input. 👉 It only supplies (returns) a value. 👉 So logically, BiSupplier is not required. ♻️Repost so others can learn and grow together. 🔔 Follow Hariprasath V for daily Java, DSA, and System Design,Springboot,Microservices,Devops,Full Stack resources. ================================================ #java8Features #java8 #LambdaExpressions #Java #SystemDesign #DataStructures #Algorithms #JavaDeveloper #DSA #CodingInterview #TechInterview #SystemDesignInterview #DSAChallenge #60DaysOfDSA #ProblemSolving #CodingJourney #Consistency #LearnByDoing #DataStructures #Algorithms #InterviewPrep #KeepCoding #Productivity #Focus #DreamBig #BackendDevelopment #SoftwareEngineering #JavaInterview #LeetCode #InterviewPrep #DataStructureAndAlgorithms #DesignPatterns #LowLevelDesign #Multithreading #SOLIDPrinciples #RESTAPI #BackendEngineer #CodeInterview #interviewtips #interviewexperience
Java 8 Features: Bi Functional Interfaces Explained
More Relevant Posts
-
🚀 Day 6/100 — Methods in Java 🔧 As programs grow bigger, repeating the same code again and again becomes messy. This is where methods help. A method is a reusable block of code that performs a specific task. Instead of rewriting logic multiple times, you write it once and call it whenever needed. This follows the DRY principle — Don't Repeat Yourself. 🔹 Basic Method Syntax returnType methodName(parameters){ // method body } Example: public static void greet(){ System.out.println("Hello Java!"); } Calling the method: greet(); Output: Hello Java! 🔹 Method with Parameters Parameters allow methods to work with different inputs. Example: public static void add(int a, int b){ int sum = a + b; System.out.println(sum); } add(5, 3); Output: 8 🔹 Method with Return Value Sometimes a method needs to return a result. Example: public static int square(int num){ return num * num; } int result = square(4); System.out.println(result); Output: 16 🔹 Method Overloading Java allows multiple methods with the same name but different parameters. This is called method overloading. Java automatically chooses the correct method based on the arguments. Example: public static int add(int a, int b){ return a + b; } public static int add(int a, int b, int c){ return a + b + c; } Usage: System.out.println(add(5,3)); // calls first method System.out.println(add(5,3,2)); // calls second method 🔴 Live Example — Max of 3 Numbers public static int max(int a, int b, int c){ if(a >= b && a >= c){ return a; } else if(b >= a && b >= c){ return b; } else{ return c; } } public static void main(String[] args){ int result = max(10, 25, 15); System.out.println("Maximum number is: " + result); } Output: Maximum number is: 25 🎯 Challenge: Write a method to find the maximum of 3 numbers and test it with different inputs. Drop your solution in the comments 👇 #Java #CoreJava #100DaysOfCode #JavaMethods #ProgrammingJourney
To view or add a comment, sign in
-
-
🚀 Day 4/100 — If-Else & Switch in Java 🚦 Conditions are the brain of a program. They help your program make decisions based on different situations. In Java, the most common decision-making statements are if, else if, else, and switch. 🔹 If-Else Statement Used when a program needs to execute code based on a condition. Example: int age = 20; if(age >= 18){ System.out.println("Eligible to vote"); }else{ System.out.println("Not eligible to vote"); } ✔ If the condition is true, the first block runs. ✔ If it's false, the else block runs. 🔹 Else If Ladder Used when there are multiple conditions. ⚠️ Important: Java checks conditions top to bottom, and once one condition becomes true, the rest are skipped. Example: int marks = 85; if(marks >= 90){ System.out.println("Grade A"); } else if(marks >= 75){ System.out.println("Grade B"); } else if(marks >= 60){ System.out.println("Grade C"); } else{ System.out.println("Grade D"); } 🔹 Switch Statement Used when comparing one variable with multiple values. Example: int day = 3; switch(day){ case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; default: System.out.println("Invalid day"); } ⚠️ Important: If you forget break, Java will execute all cases after that one (called fall-through). Example without break: int num = 1; switch(num){ case 1: System.out.println("One"); case 2: System.out.println("Two"); case 3: System.out.println("Three"); } Output: One Two Three 🔴 Mini Example — Pass or Fail int marks = 40; if(marks >= 35){ System.out.println("Pass"); }else{ System.out.println("Fail"); } 🎯 Challenge: Build a Grade Calculator using if-else. Example logic: 90+ → Grade A 75–89 → Grade B 60–74 → Grade C Below 60 → Grade D Drop your solution in the comments 👇 #Java #CoreJava #100DaysOfCode #JavaLearning #ProgrammingJourney
To view or add a comment, sign in
-
-
🚀 Day 40 of #100DaysOfCode – Understanding LinkedList in Java Today I learned about LinkedList, another important class in the Java Collection Framework. While ArrayList stores elements in a dynamic array, LinkedList stores elements as nodes connected by links. This makes LinkedList very powerful for operations like frequent insertions and deletions. Here’s a quick LinkedList guide you can learn in 60 seconds 👇 🔹 What is LinkedList? LinkedList is a collection that stores elements in nodes where each node contains: [ Previous | Data | Next ] This structure is called a Doubly Linked List. Each node keeps: • Reference to the previous node • The actual data • Reference to the next node 🔹 Package LinkedList belongs to the package: java.util Import example: import java.util.LinkedList; 🔹 Creating a LinkedList import java.util.LinkedList; public class LinkedListExample { public static void main(String[] args) { LinkedList<String> fruits = new LinkedList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Mango"); System.out.println(fruits); } } Output [Apple, Banana, Mango] 🔹 Basic Operations in LinkedList 1️⃣ Insertion fruits.add("Orange"); fruits.addFirst("Grapes"); fruits.addLast("Pineapple"); Output [Grapes, Apple, Banana, Mango, Orange, Pineapple] 2️⃣ Access Element System.out.println(fruits.get(2)); Output Banana 3️⃣ Update Element fruits.set(1, "Kiwi"); 4️⃣ Deletion fruits.remove("Apple"); fruits.removeFirst(); fruits.removeLast(); 5️⃣ Size of LinkedList System.out.println(fruits.size()); 🔹 Time Complexity OperationTime ComplexityAdd First / LastO(1)Insert MiddleO(n)Access ElementO(n)Update ElementO(n)Delete FirstO(1)Delete MiddleO(n)🔹 Key Features of LinkedList ✔ Dynamic size ✔ Maintains insertion order ✔ Allows duplicate elements ✔ Allows null values ✔ Efficient insertion and deletion ✔ Implements List and Deque interfaces 🔹 Internal Structure Visualization null <- [Apple] <-> [Banana] <-> [Mango] <-> [Orange] -> null Each element is connected using references instead of indexes. 🔹 When Should We Use LinkedList? LinkedList is useful when: ✔ Frequent insertions ✔ Frequent deletions ✔ Less random access For fast element access, ArrayList is usually better. 💡 Key Takeaway ArrayList is better for fast access, while LinkedList is better for frequent insertions and deletions. Understanding when to use each data structure is an important skill for Java Backend Development and Technical Interviews. 🙏 Grateful to my mentor Suresh Bishnoi from Kodewala Academy for guiding me step by step in my Java Backend Developer journey. #Java #LinkedList #JavaCollections #BackendDevelopment #JavaDeveloper #100DaysOfCode #LearningInPublic
To view or add a comment, sign in
-
-
🚀 Java Collections: Why your "Set" might be broken (and how it's actually a Map) ➡️ If you’ve ever had a "Unique List" that somehow ended up with duplicate data, this post is for you. In Java, the Set Interface is your best friend for handling uniqueness—but only if you know which "flavor" to pick. 🏠 The Analogy: The Guest List ➡️ Imagine you are hosting a high-end tech gala. ✔️HashSet: You have a guest list, but people are standing anywhere they want in the room. It’s messy, but you can find anyone instantly. ✔️LinkedHashSet: Guests are standing in a line based on when they arrived. You know exactly who came first. ✔️TreeSet: You’ve asked everyone to stand in alphabetical order by their last name. It takes a moment to organize, but it’s perfectly sorted. 🛠️ The Developer’s Toolbox (Top Methods) ➡️ To master Sets, you only need these core commands: ✅ add(element): Tries to add an item. Returns false if it’s already there (No duplicates allowed!). 🔎 contains(element): The fastest way to check if someone is "on the list." ❌ remove(element): Kicks an item out of the Set. 📏 size(): Tells you exactly how many unique items you have. 🧠 The "Secret" Internal Mechanism ❓Did you know a Set is actually a Map in disguise? ➡️ Inside a HashSet, Java actually creates a HashMap. When you "add" a value to a Set, Java puts that value as a Key in the Map and attaches a useless "dummy" object as the Value. ➡️ Since a Map cannot have duplicate keys, your Set stays unique. It’s one of the cleverest "hacks" in the Java source code! ⚠️ The hashCode() & equals() Trap ➡️ This is the #1 reason for bugs. If you create a custom User object: 🔸Without overriding these methods: Java looks at the memory address. Two users with the same ID will stay in the Set as duplicates. 🔸 With these methods: Java looks at the data (like ID or Email) to decide if the person is already there. 💡The Golden Rule: If you change how you compare two objects (equals), you must change how Java calculates their "ID" (hashCode). 💡 My Takeaway ✔️ Don't just default to HashSet. 🔸Need a Leaderboard? Use TreeSet. 🔸 Need a Recent Search History? Use LinkedHashSet. 🔸Need Raw Performance? Stick with HashSet. #Java #BackendDevelopment #CodingTips #SoftwareEngineering #JavaCollections #TechSimplified
To view or add a comment, sign in
-
💡 A Small Java Feature That Can Make Your APIs Much Cleaner: Varargs (...) While working on a file upload utility recently, I wanted a clean way to build file paths dynamically. Something like this: uploads/category/file.png uploads/company/apple/logo.png uploads/company/apple/products/iphone.png At first, I considered writing multiple overloaded methods for each case. But that quickly felt messy. Then I remembered a small Java feature that often goes unnoticed: varargs (...). The Idea Instead of forcing callers to pass arrays or creating multiple methods, Java allows a method to accept a variable number of arguments. Example: public String buildPath(String... segments) { return String.join("/", segments); } Now the method becomes very flexible. buildPath("category", "electronics"); buildPath("company", "apple", "logo.png"); buildPath("company", "apple", "products", "iphone.png"); Under the hood, Java simply converts the arguments into an array. String... segments → String[] segments So inside the method, you can treat segments exactly like a normal array. Why This Feature Is So Useful Using varargs can make APIs cleaner because it removes the need for rigid parameter lists. Instead of something like: buildPath(String folder, String subFolder, String fileName) You can support any depth of path structure with a single method. Where You’ve Already Seen This Many core Java APIs rely on this feature: Arrays.asList("A", "B", "C"); System.out.printf("Name: %s Age: %d", name, age); Both use varargs internally. A Few Rules About Varargs There are some constraints to remember: • The varargs parameter must be the last parameter in the method • Only one varargs parameter is allowed • Java creates an array internally every time the method is called Example: public void log(int level, String... messages) This is valid because the varargs parameter comes last. Final Thought Varargs is a small feature in Java, but it can make utility methods and APIs significantly more flexible and expressive. Sometimes the best improvements in code don’t come from new frameworks or libraries, but from using the language features we already have more effectively. #Java #BackendDevelopment #SoftwareEngineering #CleanCode #Programming
To view or add a comment, sign in
-
-
Java 26 just dropped! But most developers have not even adopted Java 21 features yet. Here are 5 modern Java features you should be using every single day. —— 1. Switch Expressions: clean and exhaustive (Java 14+) // Before: verbose, fall-through prone String label; switch (status) { case ACTIVE: label = "Active"; break; case PENDING: label = "Pending"; break; default: label = "Unknown"; } // After: String label = switch (status) { case ACTIVE -> "Active"; case PENDING -> "Pending"; default -> "Unknown"; }; No fall-through bugs. Compiler ensures all cases are handled. —— 2. Text Blocks: readable multiline strings (Java 15+) // Before: String json = "{\n \"name\": \"Alice\",\n \"role\": \"admin\"\n}"; // After: String json = """ { "name": "Alice", "role": "admin" } """; Clean SQL, JSON, HTML — no escape characters. Just readable strings. —— 3. Optional: use it properly (Java 8+, daily practice) // Bad: Optional user = userRepo.findById(id); if (user.isPresent()) { return user.get(); } return null; // Good: return userRepo.findById(id) .orElseThrow(() -> new UserNotFoundException("User not found: " + id)); Optional exists to eliminate null checks — not to wrap them. Never use .get() alone. Always orElseThrow() or orElse(). —— 4. Pattern Matching for Switch: Java 21 flagship (Java 21) // Before: fragile instanceof chain if (obj instanceof Integer i) return "int: " + i; if (obj instanceof String s) return "str: " + s; // After: clean, compiler-verified return switch (obj) { case Integer i -> "int: " + i; case String s -> "str: " + s; default -> "unknown"; }; // Even better with guards: return switch (order) { case Order o when o.isPaid() -> "Paid"; case Order o when o.isPending() -> "Pending"; default -> "Unknown"; }; Replaces entire if-instanceof chains. Safe, readable, exhaustive. —— 5. New String methods: small but mighty (Java 11–17) input.strip(); // Unicode-aware trim() input.isBlank(); // true if empty or whitespace input.repeat(3); // repeats string N times "line1\nline2".lines(); // Stream by line "hello %s".formatted("world"); // cleaner than String.format() No libraries needed. Used constantly. Zero excuses not to. ---------------------------------------------------------------- Java is not the verbose language it used to be. Pick one feature. Use it in your next PR. Then the next one. Java 26 post coming next. Stay tuned! Which one are you already using daily? Drop a number below.. #Java #Java17 #Java21 #BackendDevelopment #SpringBoot #SoftwareEngineering #CleanCode
To view or add a comment, sign in
-
Two threads. One shared resource. What could possibly go wrong? In Java, when multiple threads try to access or modify the same resource at the same time, the result can be data inconsistency. This situation is known as a race condition, and it is one of the most common problems in multithreaded systems. To control this behavior, Java provides the "synchronized" keyword. The synchronized keyword ensures that only one thread can execute a critical section of code at a time. It works using a mechanism called locks. Where can we apply synchronized? The synchronized keyword can be applied in two places: • Synchronized Method • Synchronized Block I. Synchronized Method When a method is declared as synchronized, the entire method becomes a critical section. Example concept: public synchronized void display() { // critical section } Before executing this method, a thread must acquire the lock of the object. If another thread already holds that lock, the remaining threads must wait until the lock is released. Once execution finishes, the JVM automatically releases the lock. However, synchronizing the entire method is not always efficient. Sometimes only a small portion of the method needs protection. Synchronizing the whole method can increase waiting time for other threads, which affects performance. II. Synchronized Block To avoid unnecessary waiting, Java allows us to synchronize only a specific part of the code. Example concept: synchronized(object) { // critical section } Here, only the code inside the block is synchronized. III. Advantages of synchronized blocks: • Improves performance • Reduces thread waiting time • Allows better control over critical sections Note: The lock mechanism in Java works only with objects and classes, not with primitive data types. This means we cannot pass primitive values like: int, float, double, boolean to a synchronized block. Locks must always be associated with an object reference. In Interview, we may asked questions on: 1. Race Condition When multiple threads operate simultaneously on the same object and cause data inconsistency, it is called a race condition. 2. Object-Level Lock Every object in Java has a unique lock. When a thread executes a synchronized instance method, it must acquire the lock of that object. Different objects → different locks → threads can run simultaneously. 3. Class-Level Lock Every class in Java also has a single class-level lock. This lock is used when a thread executes a static synchronized method. Before executing the method, the thread must acquire the class lock. 4. Can a thread acquire multiple locks simultaneously? Yes. A thread can hold multiple locks at the same time, as long as they belong to different objects. #Day10 #Java #Multithreading #SoftwareEngineering
To view or add a comment, sign in
-
🚀Day 20 of #75DaysOfLeetCode LeetCode 2215 – Find the Difference of Two Arrays | Java | HashSet Approach Today I solved an interesting array + hashing problem that focuses on finding distinct elements between two arrays. 🔹 Problem Statement Given two integer arrays nums1 and nums2, return: answer[0] → all distinct integers in nums1 not present in nums2 answer[1] → all distinct integers in nums2 not present in nums1 The order of elements in the result does not matter. 📌 Example Input: nums1 = [1,2,3] nums2 = [2,4,6] Output: [[1,3], [4,6]] ✔️ 1 and 3 are in nums1 but not in nums2 ✔️ 4 and 6 are in nums2 but not in nums1 💡 Approach Instead of using nested loops (which would be inefficient), we can use HashSet: 1️⃣ Convert both arrays into sets to remove duplicates. 2️⃣ Check elements of set1 that are not in set2. 3️⃣ Check elements of set2 that are not in set1. 4️⃣ Store results in a list of lists. ⏱ Time Complexity: O(n + m) 📦 Space Complexity: O(n + m) 💻 Java Solution import java.util.*; class Solution { public List<List<Integer>> findDifference(int[] nums1, int[] nums2) { Set<Integer> set1 = new HashSet<>(); Set<Integer> set2 = new HashSet<>(); for(int n : nums1) set1.add(n); for(int n : nums2) set2.add(n); List<Integer> list1 = new ArrayList<>(); List<Integer> list2 = new ArrayList<>(); for(int n : set1){ if(!set2.contains(n)){ list1.add(n); } } for(int n : set2){ if(!set1.contains(n)){ list2.add(n); } } List<List<Integer>> result = new ArrayList<>(); result.add(list1); result.add(list2); return result; } } 🔑 Key Takeaway: Using HashSet simplifies the problem by removing duplicates and providing O(1) lookup time. #LeetCode #Java #DSA #CodingPractice #HashSet #Arrays #ProblemSolving #SoftwareDevelopment
To view or add a comment, sign in
-
-
Day 49 – Java 2026: Smart, Stable & Still the Future Difference Between Static and Non-Static Initializers in Java In Java, initializer blocks are used to initialize variables during the class loading or object creation phase. There are two types: Static Initializer Non-Static (Instance) Initializer Understanding their difference helps in learning how JVM memory management and class loading work. 1. Static Initializer A static initializer block is used to initialize static variables of a class. It executes only once when the class is loaded into memory by the ClassLoader. class Example { static int a; static { a = 10; System.out.println("Static initializer executed"); } public static void main(String[] args) { System.out.println(a); } } Key idea: It runs once during class loading. 2. Non-Static Initializer A non-static initializer block is used to initialize instance variables. It executes every time an object is created. class Example { int b; { b = 20; System.out.println("Non-static initializer executed"); } Example() { System.out.println("Constructor executed"); } public static void main(String[] args) { new Example(); new Example(); } } Key idea: It runs every time an object is created. 3. Key Differences FeatureStatic InitializerNon-Static InitializerKeywordUses staticNo keywordExecution timeWhen class loadsWhen object is createdRuns how many timesOnce per classEvery object creationVariables initializedStatic variablesInstance variablesMemory areaMethod AreaHeapExecution orderBefore main()Before constructor4. Execution Flow in JVM When a Java program runs: ClassLoader loads the class Static initializer executes main() method starts Object is created Non-static initializer executes Constructor executes Flow: Program Start ↓ Class Loaded ↓ Static Initializer ↓ Main Method ↓ Object Creation ↓ Non-Static Initializer ↓ Constructor Key Insight Static initializer → class-level initialization (runs once) Non-static initializer → object-level initialization (runs every object creation) Understanding these concepts helps developers clearly see how JVM manages class loading, memory, and object initialization. #Java #JavaDeveloper #JVM #OOP #Programming #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