𝗝𝗮𝘃𝗮 𝟵 𝗦𝘁𝗿𝗲𝗮𝗺 𝗔𝗣𝗜 𝗘𝗻𝗵𝗮𝗻𝗰𝗲𝗺𝗲𝗻𝘁𝘀 — What's New Beyond Java 8 The Stream API was one of the most significant additions in Java 8, enabling functional-style processing of collections using Lambda Expressions. Java 9 took it further by introducing four powerful enhancements to the Stream interface. ────────────────────────── 𝟭. 𝘁𝗮𝗸𝗲𝗪𝗵𝗶𝗹𝗲() A default method that takes elements from the stream as long as the given predicate holds true. The moment the predicate returns false, processing stops and the rest of the stream is discarded. 🔑 Key distinction from filter(): → filter() scans every element in the stream. → takeWhile() short-circuits as soon as the condition fails. Example: list.stream().takeWhile(i -> i % 2 == 0).collect(Collectors.toList()); Input: [2, 4, 1, 3, 6, 5, 8] Output: [2, 4] ← stops at first odd number ────────────────────────── 𝟮. 𝗱𝗿𝗼𝗽𝗪𝗵𝗶𝗹𝗲() The complement of takeWhile(). It drops elements as long as the predicate is true, then returns the remainder of the stream once the predicate fails. Example: list.stream().dropWhile(i -> i % 2 == 0).collect(Collectors.toList()); Input: [2, 4, 1, 3, 6, 5, 8] Output: [1, 3, 6, 5, 8] ← drops until first odd number ────────────────────────── 𝟯. 𝗦𝘁𝗿𝗲𝗮𝗺.𝗶𝘁𝗲𝗿𝗮𝘁𝗲() — Enhanced with a 3-Argument Form Java 8 introduced a 2-argument iterate() that could run infinitely: Stream.iterate(1, x -> x + 1) // infinite — needs .limit() Java 9 introduced a 3-argument form with a built-in termination predicate — analogous to a traditional for loop: Stream.iterate(1, x -> x < 5, x -> x + 1).forEach(System.out::println); Output: 1 2 3 4 This eliminates the risk of accidental infinite loops and makes the intent explicit. ────────────────────────── 𝟰. 𝗦𝘁𝗿𝗲𝗮𝗺.𝗼𝗳𝗡𝘂𝗹𝗹𝗮𝗯𝗹𝗲() A static method that wraps a value in a single-element stream if non-null, or returns an empty stream if null. Particularly useful inside flatMap() to handle null values gracefully without explicit null checks. Stream.ofNullable(null) → [] Stream.ofNullable(100) → [100] Practical use: list.stream() .flatMap(o -> Stream.ofNullable(o)) .collect(Collectors.toList()); // Null elements are silently skipped — no NullPointerException ────────────────────────── 𝗞𝗲𝘆 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆𝘀 ✅ takeWhile() and dropWhile() enable positional, predicate-driven slicing of streams. ✅ The 3-arg iterate() provides a safe, bounded alternative to infinite stream generation. ✅ ofNullable() promotes null-safe stream pipelines without boilerplate null checks. These enhancements make stream pipelines more expressive, safer, and efficient. If you are working with Java 9+, these additions are well worth incorporating into your day-to-day code. 💬 Which of these do you find most useful in practice? Share your thoughts in the comments. #Java #Java9 #StreamAPI #FunctionalProgramming #BackendDevelopment #SoftwareEngineering #CleanCode
Java 9 Stream API Enhancements: takeWhile(), dropWhile(), iterate(), ofNullable()
More Relevant Posts
-
Stream API Stream API is one of the powerful features introduced in Java 8. It works like a pipeline that processes data in a sequence without storing it. ** Streams do not store data; they are used to process and iterate collections in a functional style. Stream syntax it is simple way to understand and apply the inputs. collection. Stream().intermediateOperation1().intermediateOperation2().terminal Operation(); After using terminal operation the stream will be end does not pass any value. Stream Method's List : Two types we are using. 1) Intermediate Operation's 1).filter() 2).map() 3).sorted() 4).distinct() 5).limit() 2) Terminal Operation's; 1).forEach() 2).collect() 3).toList() 4).reduce() 5).count() Here will show the example Stream API please look into below example this is you will understand easy and quickly. Filter : filter is an operation that selects elements from a stream based on a condition. import java.util.*; public class Main { public static void main(String[] args) { List<Integer> list = Arrays.asList(2,4,6,3,8,9,5,7); list.stream().filter(n->n%2==0).forEach(System.out::println); } } Map : map is used to transform each element in a stream into another form but map which elements we passed each and every elements is return. Example List<Integer> list = Arrays.asList(2,4,6,3,8,9,5,7); list.stream().map(n->n*2).forEach(System.out::println); * Sorted() : sorting is used to arrange elements in a specific order. Example List<Integer> list = Arrays.asList(2,4,6,3,8,9,5,7); List<Integer>result= list.stream().sorted().toList(); System.out.println("print the list:"+result); Distinct() : Distinct method is used remove the duplicates. List<Integer> list = Arrays.asList(2,4,6,4,8,6,5,8); List<Integer> result= list.stream().distinct().toList(); System.out.println("print the list:"+result); Long count = list.stream().distinct().count(); System.out.println("print the list:"+count); Note: We can use count() method does not pass any terminal operation method. Limit() : Limit method is used to restrict the number of elements in list Example: List<Integer> list = Arrays.asList(2,4,6,4,8,6,5,8); list.stream().limit(5).forEach(System.out::println); Reduce() : Reduce() is used to combine all elements of a stream into a single result (like sum, product, etc.). Example: List<Integer> list = Arrays.asList(2,4,6,4,8,6,5,8); int num=list.stream().reduce(0, (a, b) -> a + b); System.out.println("print the list:"+num); Collect : collect() is used to gather stream elements into a collection (like List, Set, etc.). Example: List<Integer> list = Arrays.asList(2,4,6,4,8,6,5,8); List<Integer>result=list.stream().filter(n -> n > 5).collect(Collectors.toList()); System.out.println("collect the stream elements:"+result); ## Please Maintain consistency #☺️☺️
To view or add a comment, sign in
-
⏳Day 31 – 1 Minute Java Clarity – Iterator vs for-each in Collections Both loop. But one gives you control the other doesn't! ⚡ 📌 What's the difference? for-each = cleaner syntax, limited control. Iterator = explicit control, supports safe removal. 📌 Code Comparison: import java.util.*; public class IteratorVsForEach { public static void main(String[] args) { List<String> names = new ArrayList<>( Arrays.asList("Alice", "Bob", "Charlie", "David") ); // for-each loop for (String name : names) { System.out.println(name); } // Iterator – safe removal during iteration Iterator<String> iterator = names.iterator(); while (iterator.hasNext()) { String name = iterator.next(); if (name.equals("Bob")) { iterator.remove(); // ✅ Safe! } } System.out.println(names); // [Alice, Charlie, David] // ❌ ConcurrentModificationException – wrong way! // for (String name : names) { // if (name.equals("Alice")) names.remove(name); // DANGER! // } } } 📌 Head-to-Head Comparison: | Feature | for-each | Iterator | |---|---|---| | Syntax | Clean & simple | Verbose | | Remove during loop | ❌ Unsafe | ✅ Safe | | Index access | ❌ No | ❌ No | | Fail-fast behavior | ✅ Yes | ✅ Yes | | Best for | Read-only loops | Conditional removal | 💡 Real-time Example: 🛒 Shopping Cart: for-each→ Display all cart items to user Iterator → Remove out-of-stock items while scanning cart ⚠️ Interview Trap: What is ConcurrentModificationException? 👉 Thrown when you modify a collection while iterating with for-each. 👉 Fix → use Iterator.remove() instead. 📌 Pro Tip: // Java 8+ cleaner way to remove conditionally: names.removeIf(name -> name.equals("Bob")); // ✅ Clean & safe 💡 Quick Summary: ✔ for-each → clean syntax, read-only loops ✔ Iterator → safe element removal during loop ✔ Never remove from collection inside for-each ✔ Java 8+ → prefer removeIf() for cleaner code ✔ Both are fail-fast on structural modification ✅ 🔹 Next Topic → Comparable vs Comparator Did you know modifying a list inside for-each throws ConcurrentModificationException at runtime? Drop 🔥 if this was new to you! #Java #Iterator #ForEach #JavaCollections #CoreJava #1MinuteJavaClarity #JavaDeveloper #BackendDeveloper #100DaysOfCode
To view or add a comment, sign in
-
-
Java Is Not As Simple As We Think. We’re taught that Java is predictable and straightforward. But does it always behave the way we expect? Here are 3 subtle behaviors that might surprise you. Q1: Which method gets called? You have a method overloaded with int and long. What happens when you pass a literal? public void print(int i) { System.out.println("int"); } public void print(long l) { System.out.println("long"); } print(10); It prints "int". But what if you comment out the int version? You might expect an error, but Java automatically "widens" the int to a long. However, if you change them to Integer and Long (objects), Java will not automatically widen them. The rules for primitives vs. objects are completely different. Q2: Is 0.1 + 0.2 really 0.3? In a financial application, you might try this: double a = 0.1; double b = 0.2; System.out.println(a + b == 0.3); // true or false? It prints false. In fact, it prints 0.30000000000000004. The Reason: Java (and most languages) uses IEEE 754 floating-point math, which cannot represent certain decimals precisely in binary. This is why for any precise calculation, BigDecimal is the only safe choice. Q3: Can a static variable "see" the future? Look at the order of initialization here: public class Mystery { public static int X = Y + 1; public static int Y = 10; public static void main(String[] args) { System.out.println(X); // 11 or 1? } } It prints 1. The Reason: Java initializes static variables in the order they appear. When X is calculated, Y hasn't been assigned 10 yet, so it uses its default value of 0. A simple reordering of lines changes your entire business logic. The takeaway: Java is not a simple language. Even professionals with years of experience get tripped up by its subtle behaviors and exceptions to the rules. The language rewards curiosity and continuous learning — no matter how senior you are. Keep revisiting the fundamentals. They have more depth than you remember. #Java #SoftwareEngineering #Coding #JVM #ProgrammingTips
To view or add a comment, sign in
-
💬✨ STRING.INDENT() AND TRANSFORM(): SMALL JAVA APIS, BIGGER CLEAN CODE 🔸 TLDR Since Java 12, String.indent() and String.transform() make text processing much cleaner. Instead of manually splitting lines, looping, and rebuilding strings with StringBuilder, you can express the same idea in one fluent and readable pipeline. ☕✨ 🔸 WHY THIS MATTERS A lot of Java codebases still contain old-school string manipulation logic that feels heavier than the real intent. When your goal is simply: ▪️ indent some text ▪️ trim it ▪️ reformat it ▪️ chain a few transformations …you do not need ceremony anymore. Java already gives you elegant tools for that. ✅ 🔸 THE OLD WAY String[] lines = text.split("\n"); StringBuilder sb = new StringBuilder(); for (String line : lines) { sb.append(" ").append(line) .append("\n"); } String indented = sb.toString(); This works. But it is verbose, mechanical, and hides the real intention behind implementation details. 😅 🔸 THE MODERN WAY String indented = text.indent(4); String result = text .transform(String::strip) .transform(s -> s.replace(" ", "-")); Now the code says exactly what it does: ▪️ indent the text ▪️ strip extra outer spaces ▪️ replace spaces with dashes That is much easier to read at a glance. 👀 🔸 WHY THE MODERN WAY WINS ▪️ BUILT-IN Indentation is a common need, and indent() turns it into a direct API call. ▪️ CHAINABLE transform() lets you build a fluent pipeline instead of scattering temporary variables everywhere. ▪️ CLEANER INTENT The reader sees the purpose immediately, not the plumbing. ▪️ LESS BOILERPLATE No manual line splitting. No explicit loop. No StringBuilder dance. ▪️ BETTER TEACHING VALUE This is the kind of API that helps newer developers write code that looks modern and expressive from day one. 🔸 HOW IT WORKS ▪️ indent(n) adds indentation to each line of the string ▪️ transform(fn) applies a function to the string and returns the result ▪️ together, they help create readable string-processing pipelines 🔸 WHEN TO USE IT Use these APIs when: ▪️ formatting multiline text ▪️ preparing console output ▪️ adjusting generated content ▪️ applying several string operations in sequence ▪️ improving readability of utility code 🔸 TAKEAWAYS ▪️ String.indent() and String.transform() are available since Java 12 ▪️ they reduce boilerplate for common text operations ▪️ transform() is especially useful for fluent string pipelines ▪️ the biggest win is readability, not just fewer lines of code ▪️ small modern APIs can make everyday Java feel much cleaner #Java #Java12 #JDK #StringAPI #CleanCode #JavaDeveloper #SoftwareEngineering #Programming #BackendDevelopment #CodeQuality #DeveloperTips #ModernJava Go further with Java certification: Java👇 https://bit.ly/javaOCP Spring👇 https://bit.ly/2v7222 SpringBook👇 https://bit.ly/springtify JavaBook👇 https://bit.ly/jroadmap
To view or add a comment, sign in
-
-
🚀Wrapper Classes, Autoboxing & Unboxing (Explained Internally) If you're serious about Java, understanding Wrapper Classes is not optional — it's foundational. Let’s break it down clearly and professionally 👇 🔹 What is a Wrapper Class? In Java, wrapper classes are object representations of primitive data types. PrimitiveWrapper ClassintIntegerdoubleDoublecharCharacterbooleanBoolean 👉 Why do we need them? Because Java is object-oriented, and many frameworks (Collections, Generics, APIs) work only with objects, not primitives. 🔹 What is Autoboxing? Autoboxing = Automatic conversion of primitive → object int num = 10; Integer obj = num; // Autoboxing 💡 Internally, the compiler converts this into: Integer obj = Integer.valueOf(10); 🔹 What is Unboxing? Unboxing = Automatic conversion of object → primitive Integer obj = 20; int num = obj; // Unboxing 💡 Internally, it becomes: int num = obj.intValue(); 🔹 How It Works Internally ⚙️ Autoboxing uses valueOf() Java does NOT always create new objects. It uses Integer Cache (-128 to 127) for performance. Integer a = 100; Integer b = 100; System.out.println(a == b); // true (cached) Integer x = 200; Integer y = 200; System.out.println(x == y); // false (new objects) 👉 This optimization reduces memory usage and improves performance. Unboxing uses xxxValue() methods Each wrapper class has methods like: intValue() doubleValue() NullPointerException Risk ⚠️ Integer obj = null; int num = obj; // ❌ Runtime error 👉 Why? Because Java tries: obj.intValue(); // Null → Crash Performance Consideration ⚡ Autoboxing creates objects → more memory + slower Avoid in loops or performance-critical code 🔹 Real Use Case ArrayList<Integer> list = new ArrayList<>(); list.add(10); // Autoboxing int value = list.get(0); // Unboxing 👉 Collections only work with objects, so wrapper classes are essential. 🔹 Key Takeaways 🧠 ✔ Wrapper classes convert primitives into objects ✔ Autoboxing = primitive → object ✔ Unboxing = object → primitive ✔ Internally uses valueOf() & xxxValue() ✔ Integer caching improves performance ✔ Beware of NullPointerException 💬 Pro Tip: Understanding this deeply helps in interviews, performance optimization, and writing cleaner Java code. #Java #Programming #OOP #BackendDevelopment #JavaDeveloper #CodingInterview #SoftwareEngineering
To view or add a comment, sign in
-
-
Stop writing Java Switch statements like it’s 2004! If you are still writing switch statements with break; at the end of every line, you are living in the past! Java has transformed the humble switch from a clunky branching tool into a powerful, functional expression. Here is the evolution of how we control logic in Java: 1️⃣ The "Classic" Era (Java 1.0 - 6) * Syntax: case X: ... break; * Limitation: Only primitives (int, char) and Enums. * The Risk: "Fall-through" bugs. Forget one break and your logic cascades into chaos. 2️⃣ The "Modern Expression" (Java 14) Java 14 turned the Switch into an Expression. It can now return a value! * Arrow Syntax (->): No more break. It’s cleaner and safer. * Assignment: var result = switch(val) { ... }; * Yield: Use yield to return values from complex multi-line blocks. 3️⃣ The "Pattern Matching" Powerhouse (Java 21) This is the game changer. Switch is no longer just for values; it’s for Types. * Case Patterns: Switch directly on an Object. * Automatic Casting: No more instanceof followed by manual casting. * Guarded Patterns: Use the when keyword to add logic filters directly into the case. * Null Safety: Explicitly handle case null without crashing. Sample : /** * SCENARIO: Processing a result object that could be * a String, an Integer, or a custom Status record. */ // 🛑 THE OLD WAY (Java 8) - Verbose and manual public String handleResultOld(Object result) { if (result == null) { return "Unknown"; } if (result instanceof String) { String s = (String) result; // Manual casting return "Message: " + s; } else if (result instanceof Integer) { Integer i = (Integer) result; return "Code: " + i; } return "Unsupported"; } // ✅ THE MODERN WAY (Java 21) - Concise and Type-Safe public String handleResultModern(Object result) { return switch (result) { case null -> "Unknown"; case String s when s.isBlank() -> "Empty Message"; case String s -> "Message: " + s; // Automatic casting case Integer i -> "Code: " + i; default -> "Unsupported"; }; } #Java21 #ModernJava #BackendDevelopment #Coding #TechCommunity #Developers #LearningToCode
To view or add a comment, sign in
-
🚨 Java Records: Core Mechanics Most Developers Miss After understanding why records exist, the next step is more important: How do records actually behave under the hood? Because this is where most misconceptions start. 🧠 First: Records are NOT just “shorter classes.” They are a language-level construct with strict rules. When you write: public record User(Long id, String name) {} Java doesn’t “reduce boilerplate”… 👉 It generates a fully-defined, immutable data structure 🔍 What the compiler actually creates Behind the scenes, this becomes: private final fields A canonical constructor (all fields required) Accessor methods equals(), hashCode(), toString() Everything is tied to the data itself, not object identity. ⚠️ Common mistake: “Records don’t have getters.” Not true. They DO have accessors — just not JavaBean style. Instead of: getId() You get: id() 👉 This follows a different philosophy: “State is the API” 🔒 Immutability is enforced — not optional In a record: Fields are always final No setters allowed Object must be fully initialized There is no way to create a “half-filled” object. 🚫 No default constructor (and that’s intentional) Unlike normal classes: ❌ No no-arg constructor ✅ Only canonical constructor (all fields) This enforces: Every record instance is valid at creation time 🔥 Constructor behavior (important) You can customize construction — but with rules. Example: public record User(Long id, String name) { public User { if (id == null) { throw new IllegalArgumentException("id cannot be null"); } } } 👉 This is a compact constructor You can: ✔ Add validation ✔ Normalize data ✔ Add logic But you cannot: ❌ Skip field initialization ❌ Break immutability ⚖️ Records vs Lombok (under the hood mindset) Lombok → generates code you could have written Records → enforce rules you cannot bypass That’s a huge difference. 🧩 Subtle but critical behavior Records use: Value-based equality That means: new User(1L, "A").equals(new User(1L, "A")) // true 👉 Equality is based on data, not memory reference. 🧠 Why this matters in real systems Because records eliminate: Partial object states Hidden mutations Inconsistent equality logic They give you: ✔ Predictable behavior ✔ Safer concurrency ✔ Cleaner APIs 🚨 One key takeaway Records don’t just reduce code… They change how objects behave fundamentally If you still treat records like normal POJOs, You’ll miss the guarantees they provide. #Java #JavaRecords #BackendDevelopment #SpringBoot #SystemDesign #SoftwareEngineering #JavaDeveloper #CleanCode #Concurrency #Programming
To view or add a comment, sign in
-
Java- Automatic Type Promotion of Primitives I am trying to explore and explain the concept of automatic type promotion of primitives using a simple code in java using two byte values: class TestAutomatictypepromotion{ public static void main(String[] ar){ byte a=10; byte b=20; int sum=a+b; System.out.println(sum); }} Perfect! Let me prove the byte → int promotion step by step through actual bytecode analysis.We have the real bytecode. Now let me build the full visual explanation. javac your souce code javap -c TestAutomatictypepromotion.class (we will get the vyte code) The 3 smoking-gun proofs from the actual bytecode Here is the raw javap -c output from your exact code, with the proof highlighted: 0: bipush 10 ← pushes 10 as INT (not byte) 2: istore_1 ← "i" = integer store (no bstore exists!) 3: bipush 20 ← pushes 20 as INT 5: istore_2 ← integer store 6: iload_1 ← "i" = integer load (no bload exists!) 7: iload_2 ← integer load 8: iadd ← "i" = INTEGER add ← THE KEY PROOF 9: istore_3 Proof 1 — iload, not bload: When a and b are loaded from local variable slots, the opcode is iload_1 and iload_2. The i prefix means integer. There is literally no bload instruction in the entire JVM specification. Proof 2 — iadd, not badd: The addition uses iadd. There is no badd opcode. The JVM arithmetic instruction set only has iadd, ladd, fadd, dadd (int, long, float, double). Bytes have no dedicated add — they must become ints first. Proof 3 — println:(I)V: The method descriptor in constant pool entry #13 is println:(I)V. The I is the JVM type descriptor for int. So even println receives an int, not a byte. Why does Java do this? The JVM's operand stack and local variable slots work natively in 32-bit units. Byte, short, char, and boolean values are all widened to int the moment they enter the stack — this is called numeric promotion. It's defined in the JLS §5.6.1 (Unary Numeric Promotion) and §5.6.2 (Binary Numeric Promotion). The JVM spec simply has no byte-level arithmetic opcodes — they were intentionally omitted to keep the instruction set small and the stack 32-bit aligned. Want me to show what happens when the result overflows a byte, or demonstrate why byte c = a + b causes a compile-time error without an explicit cast: Let me cover both — byte overflow AND the compile-time error proof through actual bytecode! byte data type has a range: -128 to 127 Assume we declare the variables llike : byte b=100.byte b=100; then try to add both (byte values) like byte c=a+b; The result :200 is not in byte range. So overflow happens. Compiler will not allow. The compiled and interpreted way in Java is the base for such standard code. Most developers fear the JVM. Java developers understand it. Codeest Software Factory Anirudh Mangore Sandip Magdum Mehvish Fansopkar Mitali Dere Sakshi Randive Shruti Chavan NILESH GHAVATE Shaikh Abdulkhadir Java Recruiting Group,OpenJDK
To view or add a comment, sign in
-
Small concept. Big impact. In Java: byte + byte = int That’s automatic type promotion — and it’s one of those things that silently causes bugs if you don’t fully understand it. Back to basics = better code.
Java- Automatic Type Promotion of Primitives I am trying to explore and explain the concept of automatic type promotion of primitives using a simple code in java using two byte values: class TestAutomatictypepromotion{ public static void main(String[] ar){ byte a=10; byte b=20; int sum=a+b; System.out.println(sum); }} Perfect! Let me prove the byte → int promotion step by step through actual bytecode analysis.We have the real bytecode. Now let me build the full visual explanation. javac your souce code javap -c TestAutomatictypepromotion.class (we will get the vyte code) The 3 smoking-gun proofs from the actual bytecode Here is the raw javap -c output from your exact code, with the proof highlighted: 0: bipush 10 ← pushes 10 as INT (not byte) 2: istore_1 ← "i" = integer store (no bstore exists!) 3: bipush 20 ← pushes 20 as INT 5: istore_2 ← integer store 6: iload_1 ← "i" = integer load (no bload exists!) 7: iload_2 ← integer load 8: iadd ← "i" = INTEGER add ← THE KEY PROOF 9: istore_3 Proof 1 — iload, not bload: When a and b are loaded from local variable slots, the opcode is iload_1 and iload_2. The i prefix means integer. There is literally no bload instruction in the entire JVM specification. Proof 2 — iadd, not badd: The addition uses iadd. There is no badd opcode. The JVM arithmetic instruction set only has iadd, ladd, fadd, dadd (int, long, float, double). Bytes have no dedicated add — they must become ints first. Proof 3 — println:(I)V: The method descriptor in constant pool entry #13 is println:(I)V. The I is the JVM type descriptor for int. So even println receives an int, not a byte. Why does Java do this? The JVM's operand stack and local variable slots work natively in 32-bit units. Byte, short, char, and boolean values are all widened to int the moment they enter the stack — this is called numeric promotion. It's defined in the JLS §5.6.1 (Unary Numeric Promotion) and §5.6.2 (Binary Numeric Promotion). The JVM spec simply has no byte-level arithmetic opcodes — they were intentionally omitted to keep the instruction set small and the stack 32-bit aligned. Want me to show what happens when the result overflows a byte, or demonstrate why byte c = a + b causes a compile-time error without an explicit cast: Let me cover both — byte overflow AND the compile-time error proof through actual bytecode! byte data type has a range: -128 to 127 Assume we declare the variables llike : byte b=100.byte b=100; then try to add both (byte values) like byte c=a+b; The result :200 is not in byte range. So overflow happens. Compiler will not allow. The compiled and interpreted way in Java is the base for such standard code. Most developers fear the JVM. Java developers understand it. Codeest Software Factory Anirudh Mangore Sandip Magdum Mehvish Fansopkar Mitali Dere Sakshi Randive Shruti Chavan NILESH GHAVATE Shaikh Abdulkhadir Java Recruiting Group,OpenJDK
To view or add a comment, sign in
-
🚀 Java Revision Journey – Day 29 Today I revised TreeSet in Java, an important Set implementation used when sorted data is required. 📝 TreeSet Overview TreeSet is a class in java.util that implements the SortedSet and NavigableSet interfaces. It stores elements in a sorted order using a Red-Black Tree internally. 📌 Key Characteristics: • Stores unique elements only (no duplicates) • Maintains sorted order (ascending by default) • Does not allow null values (throws NullPointerException) • Provides navigation methods like higher(), lower(), ceiling(), floor() • Not thread-safe (can be synchronized using Collections.synchronizedSet()) 💻 Example TreeSet<Integer> set = new TreeSet<>(); set.add(30); set.add(10); set.add(20); System.out.println(set); // Output: [10, 20, 30] 🏗️ Constructors Default Constructor TreeSet<Integer> set = new TreeSet<>(); With Comparator TreeSet<Integer> set = new TreeSet<>(Comparator.reverseOrder()); From Collection TreeSet<Integer> set = new TreeSet<>(list); From SortedSet TreeSet<Integer> set = new TreeSet<>(sortedSet); 🔑 Basic Operations Adding Elements: • add() → Adds element in sorted order (duplicates ignored) Accessing Elements: • contains() → Checks existence • first() → Returns smallest element • last() → Returns largest element Removing Elements: • remove() → Removes specific element • pollFirst() / pollLast() → Removes first/last element 🔁 Iteration • Using enhanced for-loop • Using Iterator for (Integer num : set) { System.out.println(num); } ⚙️ Custom Sorting (Important) 👉 If objects don’t implement Comparable, use a Comparator: TreeSet<Integer> set = new TreeSet<>((a, b) -> b - a); 💡 Key Insight TreeSet is widely used when you need: • Automatically sorted data (no need to sort manually) • Fast search operations (O(log n)) • Range-based operations like finding closest elements • Implementing features like leaderboards, rankings, etc. 📌 Understanding TreeSet is essential for handling sorted and navigable data efficiently, especially in DSA and backend logic. Continuing to strengthen my Java fundamentals step by step 💪🔥 #Java #JavaLearning #TreeSet #DataStructures #JavaDeveloper #BackendDevelopment #Programming #JavaRevisionJourney 🚀
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