Day 25 of Sharing What I’ve Learned 🚀 Method Overloading in Java — Compile-Time Polymorphism Explained 🔥 When building real-world applications, flexibility in handling different inputs is essential… That’s where method overloading becomes powerful 💡 🔹 What Is Method Overloading? Method overloading is the process of defining multiple methods with the same name within the same class, but with different parameter lists. ✔ Same method name ✔ Different number or type of parameters ✔ Improves readability and usability 🔹 Simple Example — Calculator Add Method class Calculator { void add(int a, int b) { System.out.println(a + b); } void add(float a, float b) { System.out.println(a + b); } void add(int a, int b, int c) { System.out.println(a + b + c); } } Now you can call: calc.add(10, 20); calc.add(10.5f, 20.3f); calc.add(5, 6, 7); Same method name ➜ Different behavior ✔ 🔹 How Java Chooses the Correct Method The Java compiler follows 3 rules: 1️⃣ Method name 2️⃣ Number of parameters 3️⃣ Type of parameters This decision happens at compile time, not runtime. 👉 That’s why method overloading is called: ✔ Compile-time polymorphism ✔ Static binding ✔ Early binding ✔ (Also known as false polymorphism) 🔹 Type Promotion If an exact match isn’t found, Java promotes types to the closest compatible one. Example: void add(float a, float b) { } Calling: add(10, 20); ➡ int values are promoted to float ✔ 🔹 Ambiguity Problem Sometimes the compiler can’t decide which method to call ❌ void add(int a, float b) { } void add(float a, int b) { } add(10, 20); // ❌ ambiguous Both methods are equally valid ➜ Compile-time error 🧠 Key Takeaways ✔ Multiple methods can share the same name (within the same class) ✔ Differentiation is based on parameters, not return type ✔ Resolved at compile time ✔ Supports cleaner and more intuitive APIs ✔ Widely used in real-world Java libraries Method overloading makes code easier to use, easier to read, and more flexible — a fundamental concept for interviews and production code. #Java #CoreJava #MethodOverloading #Polymorphism #OOP #Programming #BackendDevelopment #InterviewPreparation #Day25 Grateful for the guidance from Sharath R, Harshit T, TAP Academy
Java Method Overloading Explained - Compile-Time Polymorphism
More Relevant Posts
-
Why Java Is Not a Pure Object-Oriented Language A pure object-oriented programming language is one where everything in the program is treated as an object. In such languages, even basic values like numbers, characters, and boolean values are represented as objects. There are no primitive data types. javava is a language that embraces many object-oriented concepts, yet it does not fully qualify as a purely object-oriented language. Here are the key reasons why: 1. Presence of Primitive Data Types Java includes several primitive data types, such as: - int - float - double - char - boolean - long - short - byte These types are not objects, which contradicts the principle that all values in a program should be objects. For example, in the code snippet below, `a` is a primitive value, not an object: ```java int a = 5; System.out.println(a); ``` In contrast, languages like Smalltalk treat even numbers and boolean values as objects. 2. Use of the static Keyword Java permits the declaration of methods and variables using the static keyword. Static members are associated with the class itself rather than with an instance of the class, allowing access without creating an object. This undermines the principle that all operations should occur through objects. For instance: ```java class Test { static int count = 0; static void show() { System.out.println("Hello"); } } ``` In this example, the method `show()` can be called without instantiating an object. 3. Wrapper Classes and Primitive Conversion Java offers wrapper classes such as: - Integer - Float - Double - Character - Boolean These classes enable primitive values to be treated as objects. However, Java still relies on primitive types through mechanisms like autoboxing and unboxing. For example: ```java public class BoxingExample { public static void main(String[] args) { Integer i = new Integer(10); Integer j = new Integer(20); Integer k = new Integer(i.intValue() + j.intValue()); System.out.println("Output: " + k); } } ``` In this case, primitive values #ProgrammingConcepts #SoftwareEngineering #Coding #BackendDevelopment #JavaInterview #TechLearning #ProgrammingEducation #CodeNewbie #DeveloperLife #ComputerScience #ProgrammingTips #JavaConcepts
To view or add a comment, sign in
-
-
The "11th Rule" Trap: Why Java’s Map.of() Might Be Misleading You ❌ Have you ever written perfectly logical, declarative code, only to be hit by a strange Compilation Error? You look at your IDE, and it insists on an "Incompatible Types" issue, even though your classes match perfectly. I recently hit a classic, but treacherous problem, using the Map.of() method. 📋 Dispatch Map Pattern I was implementing a "Type-to-Strategy Map" to replace a messy chain of if-else and instanceof blocks. The idea is clean: a map where the key is the Rule class and the value is the mapping function. Ten rules worked flawlessly. But as soon as I added the eleventh, everything broke. 🤯 A Misleading Hint Instead of a clear "Too many arguments" message, the compiler threw a confusing: "Incompatible types: expected... " I spent 15 minutes re-verifying my code, thinking I had made a mistake in the type system. I was convinced the problem was the type of the new rule, while the actual problem was simply the quantity. The compiler's "confused" hint led me down a rabbit hole, when I should have just been counting my arguments. 💡 Why is there a limit of 10? Why can't Map.of() just use varargs like List.of() to accept any number of elements? Varargs can only handle a single type. Type Mixing: In a Map, we have Keys (K) and Values (V). Java's varargs doesn't have a syntax to say "take arguments where every first is K and every second is V". Safety: Using Object... would lose type safety and risk an odd number of arguments, leading to runtime crashes. Performance: To keep Map.of() lightning-fast and "allocation-free" (avoiding temporary arrays), JDK developers manually overloaded it 11 times (from 0 to 10 pairs). Once you hit 11, you've run out of "pre-built" templates! ✅ The Fix: Map.ofEntries() To bypass the "one-type varargs" limit, Java uses Map.ofEntries(). It wraps each pair into a Map.Entry object. Since the type is now uniform (Entry), varargs works perfectly, allowing for any number of elements. 🛠 Lessons Learned: Source over Docs: When a standard method acts weird, Command(Ctrl for Windows) + Click into the JDK source. Don’t trust the error message 100%: The compiler often "guesses" the closest mismatch, leading you away from the actual fix. The Dispatch Map Pattern: Despite this hiccup, it’s a powerful way to keep your code Open/Closed compliant and maintainable. Have you ever been misled by a cryptic compiler error? Share your stories in the comments! 👇 #java #backend #programming #cleancode #softwaredevelopment #tips #generics #jvm
To view or add a comment, sign in
-
-
Method Overloading: More Than Just Same Method Names Just wrapped up a deep‑dive quiz session on Method Overloading in Java - scored 16.5 out of 18 While the overall result is solid, the half‑point deductions were a humbling reminder that method overloading - often considered a straightforward concept - has subtle intricacies that can trip up even experienced developers. The quiz covered a wide range of scenarios, and I’m sharing my takeaways because these details matter in everyday coding and design. What I explored: ✅ Core Rules - Method overloading is about same method name, different parameter lists (number, type, or order). ✅ Return Type - Alone, it’s "not" sufficient to overload a method. The compiler needs the parameter list to decide. ✅ Invalid Overloading - Understanding what doesn’t work (e.g., only changing return type) prevents subtle bugs. ✅ Differentiating Overloaded Methods - How Java resolves the correct method at compile time. ✅ Overloading and Polymorphism - Overloading is compile‑time (static) polymorphism, not runtime. ✅ Timing of Resolution - Confirmed: overloading is resolved at compile time based on reference type. ✅ Access Modifiers - They don’t affect overloading; you can overload with different access levels. ✅ Number of Parameters - A key dimension; varying the count is a primary way to overload. ✅ Benefits - Code readability, flexibility, and supporting multiple use cases with one method name. ✅ Constructor Overloading - Same rules apply; essential for providing multiple object initialization paths. ✅ Parameter Order - Changing order of parameters (of different types) is a valid overloading technique. 📉 Where I lost points (and learned the most): - Method Overloading and Polymorphism (0.5/1) – A reminder that overloading isn’t runtime polymorphic; that’s overriding’s job. - Method Overloading Timing (0.5/1) – Reinforced that binding happens at compile time. - Number of Parameters in Overloaded Methods (0.5/1 after 2 attempts) - Probably a trick question about ambiguity. - Constructor Overloading in Java (0.5/1 after 2 attempts) - Highlighted nuances like constructor chaining with "this()". - Parameter Order (0.5/1 after 2 attempts) - A valid but often overlooked way to overload. 💡Why this matters: Method overloading improves API usability and readability, but misusing it can lead to confusing code or unexpected method calls. Knowing the rules thoroughly helps you design cleaner interfaces and avoid common pitfalls - especially when working on libraries or frameworks where method names are exposed to other developers. If you’re a Java developer, I’d love to hear: What’s the most surprising overloading behaviour you’ve encountered? Or a trick question that stumped you? Drop it in the comments! 👇 #Java #MethodOverloading #Polymorphism #CleanCode #OOP #SoftwareEngineering #LearningInPublic TAP Academy
To view or add a comment, sign in
-
-
DAY 17: CORE JAVA TAP Academy 🚀 Understanding Mutable Strings in Java – StringBuffer, StringBuilder & StringTokenizer In Java, String objects are immutable. That means once a string is created, it cannot be changed. Every modification creates a new object in memory. But what if we need frequent modifications? 🤔 That’s where mutable strings come into play! 🔹 1️⃣ StringBuffer StringBuffer is a mutable, thread-safe class used to modify strings dynamically. ✅ Key Features: Thread-safe (synchronized) Slower than StringBuilder (due to synchronization) Ideal for multi-threaded environments 📌 Important Methods: append() → Adds data to the existing string capacity() → Returns current buffer capacity trimToSize() → Reduces capacity to match current string length 💻 Example: StringBuffer sb = new StringBuffer("Hello"); System.out.println("Capacity: " + sb.capacity()); // Default 16 + length sb.append(" World"); sb.trimToSize(); System.out.println("Updated Capacity: " + sb.capacity()); 🔹 2️⃣ StringBuilder StringBuilder is also mutable but not thread-safe. ✅ Key Features: Faster than StringBuffer Best for single-threaded applications Preferred in most cases 📌 Important Methods: append() capacity() trimToSize() 💻 Example: StringBuilder sb = new StringBuilder("Java"); System.out.println("Capacity: " + sb.capacity()); sb.append(" Programming"); sb.trimToSize(); System.out.println("Updated Capacity: " + sb.capacity()); 🔹 3️⃣ StringTokenizer StringTokenizer is used to break a string into tokens based on delimiters. 📌 Example: String str = "Java,Python,C++"; StringTokenizer st = new StringTokenizer(str, ","); while(st.hasMoreTokens()) { System.out.println(st.nextToken()); } ⚠ Note: StringTokenizer is considered a legacy class. Modern alternatives include: String.split() Pattern and Matcher classes 🎯 Quick Comparison Feature StringBuffer StringBuilder Mutable ✅ ✅ Thread-Safe ✅ ❌ Performance Slower Faster Recom mended Multi- Single- threaded threaded --- 💡 Key Takeaway: Use StringBuilder for better performance in most applications. Use StringBuffer when thread safety is required. Avoid StringTokenizer in modern development; prefer split() or regex. #Java #JavaProgramming #CoreJava #StringHandling #Programming #Developers
To view or add a comment, sign in
-
-
Want to Level Up Your Java Game? Let's Talk JVM! 🚀 Ever wondered what makes Java tick behind the scenes? 🧐 It’s not just a language; it's an entire ecosystem, and the heart of it all is the Java Virtual Machine (JVM). 💓 Understanding the JVM is like knowing how your car's engine works—it makes you a better driver, or in our case, a better developer! 👩💻👨💻 Think of the JVM as Java’s interpreter and bodyguard. It’s what gives Java its superpower: "Write Once, Run Anywhere." 🌍 Here's a quick, breakdown of how it pulls off the magic. ✨ Your Code's Epic Journey: 1️⃣ Class Loader Subsystem: This is the JVM's "receptionist." It reads your .class files (compiled Java bytecode) and loads them into memory. It also takes care of linking and initialising things so they're ready to go. 🧑✈️ 2️⃣ Runtime Data Areas (Memory): This is where all the action happens! 🏗️ It's divided into key zones: * Method Area: Stores class information and static variables. Think of it as the project blueprint repository. 📂 * Heap: The big arena where all your objects live. 🏟️ This is shared space, and it's where the Garbage Collector does its work. * JVM Stack: Per-thread, private storage for method calls and local variables. Think of it as a personal notebook for each process. 💪 * PC Register: Keeps track of exactly where each thread is in the execution process. The ultimate bookmark! 🔖 * Native Method Stack: Dedicated space for non-Java (native) code. 🌐 3️⃣ Execution Engine: The engine room! 🚂 It takes that bytecode and turns it into real, executable commands. This is where you find the performance boosters: * Interpreter: Executes bytecode line by line, fast for getting things started. ⚡️ * JIT (Just-In-Time) Compiler: The performance wizard. 🧙♂️ It finds the "hot spots" in your code and compiles them directly into native machine code for maximum speed. * Garbage Collector (GC): Your code's janitor. 🧹 It automatically finds and frees up memory occupied by objects you're no longer using, preventing memory leaks and keeping things running smoothly. So, next time you run a Java application, remember the incredibly sophisticated JVM working tirelessly to make it happen! ⚙️ What's your favourite part of JVM architecture? Let me know in the comments! 👇 #Java #JVM #SoftwareEngineering #TechInfluencer #CloudComputing #CodingLife #LearnToCode #JavaDeveloper #TechTutorials #ProgrammerInsights #JVMInternal #PerformanceOptimization
To view or add a comment, sign in
-
-
Day 28: Exploring Strings in Java Today I practiced some important concepts related to Strings in Java and how they behave in memory. One of the key characteristics of Java Strings is that they are "immutable". This means once a String object is created, its value cannot be changed. Any operation like replace() or concat() creates a new String object instead of modifying the existing one. For scenarios where frequent modifications are required, using StringBuilder or StringBuffer is recommended because they are mutable. 🔹 Ways to create Strings in Java String str1 = "java"; // String literal String str2 = new String("java"); // Using new operator When Strings are created using literals, they are stored in the String Constant Pool (SCP) inside the heap memory. The SCP avoids duplicate objects to save memory. Because of this: String str1 = "java"; String str3 = "java"; System.out.println(str1 == str3); // true "==" returns true because both references point to the same object in the String Constant Pool. But when we create a String using the new operator: String str3 = new String("java"); System.out.println(str1 == str3); // false System.out.println(str1.equals(str3)); // true == compares memory addresses, while .equals() compares actual values. 🔹 Immutability Example String str7 = "Hello "; str7.concat("Everyone"); System.out.println(str7); // Output: Hello The String is not modified because Strings are immutable. 🔹 Mutable Alternative StringBuilder sb = new StringBuilder("Hello "); sb.append("Everyone"); System.out.println(sb); //Output: Hello Everyone StringBuilder and StringBuffer allow modification without creating multiple objects, making them better for frequent string manipulations in problem solving. 📌 Key Takeaways • Strings are immutable in Java • == compares references, .equals() compares values • String literals use the String Constant Pool • Use StringBuilder/StringBuffer when frequent modifications are required Learning these concepts helped me better understand how Java manages memory and string operations internally. #Java #Programming #JavaDeveloper #CodingJourney #SoftwareDevelopment #LearningInPublic Raviteja T Mohammed Abdul Rahman 10000 Coders
To view or add a comment, sign in
-
-
DAY 18: CORE JAVA TAP Academy 🚀 Understanding Method Overloading in Java Method Overloading is one of the core concepts of Compile-Time Polymorphism in Java. It allows a class to have multiple methods with the same name but different parameter lists. Let’s break down how method overloading is observed and identified 👇 🔹 1. Method Name The method name must be the same. Example: add() can have multiple definitions within the same class. 🔹 2. Number of Parameters If the number of parameters is different, the method is overloaded. int add(int a, int b) int add(int a, int b, int c) 🔹 3. Type of Parameters Even if the number of parameters is the same, changing the data type makes it overloaded. int add(int a, int b) double add(double a, double b) 🔹 4. Order of Parameters If parameter types are the same but in a different order, it is still valid overloading. void display(int a, String b) void display(String b, int a) 🔹 5. Type Conversion (Implicit Casting) Java follows method matching rules: Exact match Widening (int → long → float → double) Autoboxing Varargs Example: void show(int a) void show(double a) If we call show(5), Java chooses the most specific match (int). 🔹 6. Ambiguity in Method Overloading Ambiguity occurs when Java cannot determine which method to call. Example: void test(int a, float b) void test(float a, int b) Calling test(10, 10) creates confusion because both methods are possible after type conversion. ⚠️ The compiler throws an error in such cases. 📌 Important Terms Related to Method Overloading ✔️ Compile-Time Polymorphism ✔️ Static Binding ✔️ Early Binding ✔️ Method Signature (method name + parameter list) ✔️ Implicit Type Promotion ✔️ Varargs ✔️ Autoboxing 💡 Key Rule to Remember Changing only the return type does NOT achieve method overloading. int sum(int a, int b) double sum(int a, int b) ❌ (Invalid) ✨ Method overloading improves code readability, flexibility, and reusability. It allows developers to perform similar operations in different ways without changing method names. Mastering this concept is essential for cracking Java interviews and writing clean object-oriented code. #Java #OOPS #Programming #SoftwareDevelopment #Coding #LearningJourney
To view or add a comment, sign in
-
-
𝗗𝗔𝗬 𝟯 – 𝗦𝘁𝗿𝘂𝗰𝘁𝘂𝗿𝗲 𝗼𝗳 𝗮 𝗝𝗮𝘃𝗮 𝗣𝗿𝗼𝗴𝗿𝗮𝗺 + 𝗝𝗮𝘃𝗮 𝗧𝗼𝗸𝗲𝗻𝘀 𝗜𝗻 𝘁𝗵𝗲 𝗹𝗮𝘀𝘁 𝘁𝘄𝗼 𝗽𝗼𝘀𝘁𝘀 𝘄𝗲 𝘂𝗻𝗱𝗲𝗿𝘀𝘁𝗼𝗼𝗱: • Why Java is Platform Independent • How JDK, JRE, and JVM work together to run a Java program Now it's time to move from 𝘁𝗵𝗲𝗼𝗿𝘆 → 𝗮𝗰𝘁𝘂𝗮𝗹 𝗰𝗼𝗱𝗲. 𝗟𝗲𝘁’𝘀 𝘄𝗿𝗶𝘁𝗲 𝗮 𝘀𝗶𝗺𝗽𝗹𝗲 𝗝𝗮𝘃𝗮 𝗽𝗿𝗼𝗴𝗿𝗮𝗺. ``` 𝚙𝚞𝚋𝚕𝚒𝚌 𝚌𝚕𝚊𝚜𝚜 𝙷𝚎𝚕𝚕𝚘𝚆𝚘𝚛𝚕𝚍 { 𝚙𝚞𝚋𝚕𝚒𝚌 𝚜𝚝𝚊𝚝𝚒𝚌 𝚟𝚘𝚒𝚍 𝚖𝚊𝚒𝚗(𝚂𝚝𝚛𝚒𝚗𝚐[] 𝚊𝚛𝚐𝚜) { 𝚂𝚢𝚜𝚝𝚎𝚖.𝚘𝚞𝚝.𝚙𝚛𝚒𝚗𝚝𝚕𝚗("𝙷𝚎𝚕𝚕𝚘 𝚆𝚘𝚛𝚕𝚍"); } } ``` At first glance this may look confusing. But if we break it down, the structure becomes very simple. 𝗦𝘁𝗿𝘂𝗰𝘁𝘂𝗿𝗲 𝗼𝗳 𝗮 𝗝𝗮𝘃𝗮 𝗣𝗿𝗼𝗴𝗿𝗮𝗺 Every Java program generally contains: 1️⃣ 𝗖𝗹𝗮𝘀𝘀 𝗗𝗲𝗰𝗹𝗮𝗿𝗮𝘁𝗶𝗼𝗻 𝚙𝚞𝚋𝚕𝚒𝚌 𝚌𝚕𝚊𝚜𝚜 𝙷𝚎𝚕𝚕𝚘𝚆𝚘𝚛𝚕𝚍 In Java, everything starts with a class. The filename must match the class name. Example: 𝙷𝚎𝚕𝚕𝚘𝚆𝚘𝚛𝚕𝚍.𝚓𝚊𝚟𝚊 2️⃣ 𝗠𝗮𝗶𝗻 𝗠𝗲𝘁𝗵𝗼𝗱 𝚙𝚞𝚋𝚕𝚒𝚌 𝚜𝚝𝚊𝚝𝚒𝚌 𝚟𝚘𝚒𝚍 𝚖𝚊𝚒𝚗(𝚂𝚝𝚛𝚒𝚗𝚐[] 𝚊𝚛𝚐𝚜) This is the entry point of every Java program. When we run a program, the JVM starts execution from the 𝗺𝗮𝗶𝗻() 𝗺𝗲𝘁𝗵𝗼𝗱. 3️⃣ 𝗦𝘁𝗮𝘁𝗲𝗺𝗲𝗻𝘁𝘀 𝚂𝚢𝚜𝚝𝚎𝚖.𝚘𝚞𝚝.𝚙𝚛𝚒𝚗𝚝𝚕𝚗("𝙷𝚎𝚕𝚕𝚘 𝚆𝚘𝚛𝚕𝚍"); This statement simply prints output on the console. 𝗡𝗼𝘄 𝗹𝗲𝘁’𝘀 𝘂𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱 𝘀𝗼𝗺𝗲𝘁𝗵𝗶𝗻𝗴 𝘃𝗲𝗿𝘆 𝗶𝗺𝗽𝗼𝗿𝘁𝗮𝗻𝘁 𝗶𝗻 𝗝𝗮𝘃𝗮. 𝗝𝗮𝘃𝗮 𝗧𝗼𝗸𝗲𝗻𝘀 Tokens are the smallest building blocks of a Java program. Java programs are basically made up of tokens. 𝗧𝗵𝗲𝗿𝗲 𝗮𝗿𝗲 𝗺𝗮𝗶𝗻𝗹𝘆 𝟱 𝘁𝘆𝗽𝗲𝘀: • 𝗞𝗲𝘆𝘄𝗼𝗿𝗱𝘀 → public, class, static, void • 𝗜𝗱𝗲𝗻𝘁𝗶𝗳𝗶𝗲𝗿𝘀 → names of variables, classes, methods • 𝗟𝗶𝘁𝗲𝗿𝗮𝗹𝘀 → actual values (10, "Hello", true) • 𝗦𝗲𝗽𝗮𝗿𝗮𝘁𝗼𝗿𝘀 → { } ( ) [ ] ; , • 𝗢𝗽𝗲𝗿𝗮𝘁𝗼𝗿𝘀 → + - * / = == Example identifier rules: ✔ Cannot start with a number ✔ Cannot use Java keywords ✔ No spaces allowed ✔ Can use letters, numbers, _ and $ Once you understand structure + tokens, reading Java code becomes much easier. If you look at the Java program again, you’ll now notice: It is simply a combination of tokens working together. Once you understand tokens and structure, reading Java code becomes much easier. 𝗧𝗼𝗺𝗼𝗿𝗿𝗼𝘄 (𝗗𝗮𝘆 𝟰) 𝗪𝗲’𝗹𝗹 𝗴𝗼 𝗱𝗲𝗲𝗽𝗲𝗿 𝗶𝗻𝘁𝗼 𝗼𝗻𝗲 𝗼𝗳 𝘁𝗵𝗲 𝗺𝗼𝘀𝘁 𝗶𝗺𝗽𝗼𝗿𝘁𝗮𝗻𝘁 𝘁𝗼𝗽𝗶𝗰𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮: • Data Types • Variables • Primitive vs Non-Primitive types • Memory basics behind variables Because before writing real programs, understanding how Java stores data is critical. 𝗦𝗲𝗲 𝘆𝗼𝘂 𝗶𝗻 𝗗𝗮𝘆 𝟰. #Java #BackendDevelopment #Programming #LearnInPublic #Day3
To view or add a comment, sign in
-
🚀 Day 124 of My Java Learning Journey Hi Guys, Today I practiced an important string logical problem — 👉 Finding the occurrence of each character in a String (including spaces) using Java Streams. This type of logic is very common in interviews and improves your understanding of Streams and Collections. ------------------------------------------------------------------------------------------- 💻 Code: -------------> import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; public class OccurrenceAndNonRepeatingChar { public static void main(String[] args) { String name = "yuvraj singh kushwah"; // Occurrence of all character with spaces Map<Character, Long> charCount = name.chars() .mapToObj(x -> (char) x) .collect(Collectors.groupingBy( Function.identity(), Collectors.counting() )); System.out.println("Occurrence of all characters with spaces: " + charCount); } } ------------------------------------------------------------------------------------------- 🖥 Output: -------------> Occurrence of all characters with spaces: { =2, a=2, g=1, h=2, i=1, j=1, k=1, n=1, r=1, s=2, u=2, v=1, w=1} 🔎 Output Explanation: • Space " " is counted → appears 2 times • Characters like g, i, j, k appear only 1 time • Characters like a, s, u appear 2 times Since we didn’t remove spaces, they are treated like normal characters. ⭐ Important Concept: ✔ chars() → Converts String into IntStream ✔ mapToObj() → Converts int to Character ✔ groupingBy() → Groups identical characters ✔ counting() → Counts frequency This is a clean Java 8+ approach instead of manually using loops and HashMap. 💡 Important Tip: If you don’t want to count spaces, add: .filter(ch -> ch != ' ') before collect(). 🔥 Why This Is Important? ✔ Frequently asked in interviews ✔ Builds strong Stream knowledge ✔ Improves logical thinking ✔ Real-world text processing use case Consistency > Motivation 💪 Day 124 done ✅ What should I practice tomorrow — more Stream problems or interview-based tricky logic? #Java #JavaDeveloper #JavaStreams #CodingPractice #ProblemSolving #InterviewPreparation #DevOps #LearningInPublic #124day #CodeWithYuvi
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
Great progress Mohammed Usman shaik! Love seeing people invest in learning Java and growing their skills. If you’re looking for structured practice, feel free to check out our free course: https://www.javapro.academy/bootcamp/the-complete-core-java-course-from-basics-to-advanced/ Keep up the awesome work!