🚀 Day 19 – Java Full Stack Journey | Arrays in Depth (1D, 2D, 3D + length Property) Today’s session was a complete deep dive into Arrays in Java — not just creating them, but truly understanding: • Memory behavior • Traversal logic • Why loops are mandatory • How length actually works • Regular vs Jagged arrays 🔹 What is an Array? 👉 Arrays are objects in Java 👉 Stored in the Heap memory 👉 Used to store homogeneous data 👉 Indexed starting from 0 When you print the array reference directly: System.out.println(a); You don’t get elements. You get the address reference — because arrays are objects. To access elements → Traversal using loops is mandatory. 🔹 1️⃣ One-Dimensional Array (1D) int[] a = new int[5]; ✔ Stored in Heap ✔ Default values → 0 ✔ Traversed using single loop Important rule: for(int i = 0; i < a.length; i++) Using a.length makes your code dynamic. Never hardcode size like i < 5. 🔹 2️⃣ Two-Dimensional Array (2D) int[][] a = new int[2][5]; Meaning: 2 rows 5 columns Traversal requires nested loops: for(int i = 0; i < a.length; i++) { for(int j = 0; j < a[i].length; j++) { // Access element } } Important Understanding: a.length → number of rows a[i].length → number of columns in that row This makes the code scalable and flexible. 🔹 3️⃣ Three-Dimensional Array (3D) int[][][] a = new int[2][3][5]; Meaning: 2 blocks 3 rows per block 5 columns per row Traversal requires 3 nested loops: for(int i = 0; i < a.length; i++) { for(int j = 0; j < a[i].length; j++) { for(int k = 0; k < a[i][j].length; k++) { // Access element } } } Understanding flow: Column moves fastest → Then row → Then block That’s how memory gets populated. 🔹 Regular Array vs Jagged Array ✔ Regular Array → All rows have equal number of columns ✔ Looks rectangular Tomorrow’s focus → Jagged Array (Where each row can have different column size) 🔹 Most Important Learning Today Arrays are not about syntax. They are about: • Understanding object behavior • Understanding memory (Heap & Stack) • Writing dynamic loops • Avoiding hardcoded logic • Thinking in dimensions 90% of array problems follow the same pattern: Create → Traverse → Process → Print Once traversal is clear, logic becomes easy. Consistency + Practice + Typing the code yourself = Mastery. Day 19 Complete ✔ #Day19 #Java #CoreJava #Arrays #DataStructures #JVM #FullStackJourney #LearningInPublic #JavaDeveloper #100DaysOfCode TAP Academy
Java Arrays in Depth: 1D, 2D, 3D & Length Property
More Relevant Posts
-
🚀 Day 10 — Restarting My Java Journey with Consistency How Arrays Actually Work in Java (Memory Level Understanding) Most of us write: int[] arr = new int[5]; But what really happens behind the scenes? 🔹 1️⃣ Stack vs Heap — What is Actually Stored? When we create an array: ->The array object is created in Heap memory ->The variable arr is stored in the Stack ->arr does NOT store the actual elements ->It stores a reference (address) pointing to the array in heap So internally: Stack → arr → (reference) → Heap → [10, 20, 30, 40, 50] This cleared a major misconception. 🔹 2️⃣ Why Array Access is O(1) — The Address Formula Arrays support random access because of direct memory calculation. Conceptually: arr[i] = base_address + (size_of_datatype × i) For int (4 bytes): arr[3] = 100 + (4 × 3) = 112 That’s why accessing any index takes constant time — No traversal needed. 🔹 3️⃣ Why Java Throws ArrayIndexOutOfBoundsException consider arr.length <=100 In languages like C, accessing arr[100] might give garbage value. But Java internally performs a bounds check: if( index < 0 || index >= arr.length ) throw ArrayIndexOutOfBoundsException; That’s one of the reasons Java is considered safer. 🔹 4️⃣ Boolean Size — Interesting JVM Detail Officially, Java does NOT define a fixed size for boolean. It depends on JVM implementation. In HotSpot (Oracle/OpenJDK): ->Boolean is typically stored as 1 byte ->Even though logically it needs only 1 bit Reason? modern CPUs are byte-addressable and optimized for byte-aligned memory access. 🔹5️⃣ 2D array - Array of Arrays The Array stores the refences of Arrays means the each element of the Array is a Reference variable What is the size of a reference in Java? It depends on the JVM and system architecture: On a 32-bit JVM → a reference is typically 4 bytes On a 64-bit JVM → a reference is typically 8 bytes However ⚠️ In modern 64-bit JVMs, Compressed OOPs (Ordinary Object Pointers) are enabled by default. With this optimization, object references are compressed and effectively use 4 bytes, even on a 64-bit system. 🔹 6️⃣ String Arrays — Important Concept When we write: String[] names = new String[3]; The array stores references, not actual String objects. Each names[i] holds a reference to a String object in heap. New insight for me today: Also interesting: ->Before JDK 9, String internally used a char[], meaning each character consumed 2 bytes (UTF-16), even for simple English text. ->From JDK 9 onwards, Java introduced Compact Strings, where String uses a byte[] plus a small encoding flag. ->If the text contains only Latin characters, it uses 1 byte per character otherwise, it switches to UTF-16 (2 or 4 bytes). ->This significantly reduces memory usage without changing the String API (String class method calls). Learning daily with Coder Army and Aditya Tandon Bhaiya and Rohit Negi Bhaiya #Day10 #Java #Consistency #BackendDevelopment #LearningJourney #SoftwareEngineering #CoderArmy
To view or add a comment, sign in
-
-
A Marker Interface 👇 A Marker Interface in Java is an interface that contains no methods or fields. It is used to mark a class so that the Java runtime or compiler can identify some special behavior or capability of that class. Example: Here, Serializable has no methods but if a class implements it, Java knows that objects of that class can be serialized. 🔹A Marker Interface (also known as a Tagging Interface) is a design pattern in Java where an interface contains no methods or constants. If you look at the source code of a marker interface, it’s just an empty shell: Java public interface MyMarkerInterface { // Absolutely nothing here } Why use an empty interface? The purpose isn't to define behavior (like a normal interface does), but to deliver a message to the JVM or a framework. It acts like a "stamp" or a "label" on a class. When a class implements a marker interface, it's telling the runtime: "I have a special property. You can treat me differently." 🌟 How It Works (The "Metadata" Approach) Since the interface is empty, the class implementing it doesn't have to write any new code. Instead, other parts of the system use the instanceof operator to check for the "stamp." 🔹The Logic: Class A implements Serializable. ✔ The JVM sees a request to save Class A to a file. ✔ The JVM checks: if (A instanceof Serializable). ✔ If True: The JVM proceeds with the specialized logic to save the data. ✔ If False: The JVM throws a NotSerializableException. Famous Examples in Java 🔹 Serializable: Tells the JVM that the object’s state can be converted into a byte stream (saved to a file or sent over a network). 🔹Cloneable: Tells the Object.clone() method that it is legal to make a field-for-field copy of instances of that class. 🔹Remote: Used in RMI (Remote Method Invocation) to identify interfaces whose methods may be invoked from a non-local virtual machine. I’m truly thankful to my mentor for their valuable guidance Anand Kumar Buddarapu Saketh Kallepu Uppugundla Sairam #Java #CoreJava #MarkerInterface #JavaProgramming #OOP #Serializable #Cloneable #JavaConcepts #Programming #Developers
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
-
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
-
-
Hello everyone! 👋 Day 5 of my deep dive into core Java fundamentals! ☕ Today, I explored Type Conversions, specifically answering a crucial question: What is the actual difference between Implicit and Explicit conversions in Java? 🤔 If you think of computer memory as physical boxes, it makes perfect sense! Here is how Java handles moving data between different sized containers: 🟢 1. Implicit Conversion (The Automatic Upgrade) This is also known as a "Widening Conversion". It happens when you move data from a smaller data type (like an 8-bit byte) into a wider/larger data type (like a 32-bit int). Because what fits in a small box will easily fit into a massive box, Java does this completely automatically. You just write int i = b; and the compiler handles it behind the scenes without complaining. 🔴 2. Explicit Conversion (The Manual Override) This is known as a "Narrowing Conversion". This happens when you try to go backwards—stuffing a large container into a smaller one. For example, trying to put a 32-bit int into an 8-bit byte. If you try to do this automatically, Java will throw a compile-time error. Why? Because the compiler is terrified that your data will get chopped off (truncated) during the squeeze! To make it happen, you have to use Type Casting. You have to manually write the target type in brackets, like b = (byte) i;, to explicitly tell Java: "I know the risks, do it anyway!". 🧠 The "Under the Hood" Mindblower: I ran an experiment today: what actually happens if you cast a massive int of 300 into a tiny byte container? Since a byte can only hold up to 127, it obviously overflows. But it doesn't crash! Instead, Java looks at the 32-bit binary representation of 300 and literally chops off the extra bits, keeping only the 8 bits that fit. A massive shortcut I learned: To figure out what number you will end up with, you can just take your number and use the modulo operator against the maximum range of a byte (256). So, 300 % 256 means our new byte will store exactly 44! Understanding how the JVM aggressively protects our memory from data loss makes its strict rules feel so much more logical. 🛡️ #Java #SoftwareEngineering #TypeCasting #TechFundamentals #StudentDeveloper #InterviewPrep #CodingJourney
To view or add a comment, sign in
-
-
Java 26 is officially here. Talk is cheap—let’s look at the code. 🚀 If you’re building scalable backend systems, Java 26 just shipped features that drastically reduce boilerplate and make massive concurrency safer. The ecosystem isn't just evolving; it's practically a new language compared to 5 years ago. Here are the 4 major upgrades every backend engineer needs to know: ⚡ 1. Primitive Types in Patterns Pattern matching finally supports primitives. No more clunky autoboxing or redundant casting. ❌ Old Way: if (obj instanceof Integer) { int i = (Integer) obj; // Unnecessary boxing overhead System.out.println(i * 2); } ✅ Java 26 Way: if (obj instanceof int i) { System.out.println(i * 2); // Clean, direct, fast } 🚀 2. Scoped Values > ThreadLocal If you use Virtual Threads, ThreadLocal is an expensive memory hazard. Scoped Values are immutable, safe, and built for millions of concurrent tasks. ❌ Old Way (Mutable & prone to memory leaks): public static final ThreadLocal<String> USER = new ThreadLocal<>(); ✅ Java 26 Way (Safe & Scope-bound): public static final ScopedValue<String> USER = ScopedValue.newInstance(); ScopedValue.where(USER, "Pondurai").run(() -> { // USER is securely available only inside this specific execution block processRequest(); }); 🧩 3. Structured Concurrency Managing multiple sub-tasks usually means risking orphaned threads. Now, you can treat concurrent threads as a single logical block. If one fails, the rest are cleanly canceled. ✅ Java 26 Way: try (var scope = new StructuredTaskScope.ShutdownOnFailure()) { Subtask<User> user = scope.fork(() -> fetchUser(id)); Subtask<Order> order = scope.fork(() -> fetchOrder(id)); scope.join() // Wait for both .throwIfFailed(); // Cleanly abort if either fails return new UserOrder(user.get(), order.get()); } Concurrency without the chaos. 🧠 4. The Vector API (Hardware-Accelerated Math) Java is aggressively optimizing for AI and data analytics. Instead of standard loops, your code can now tap directly into CPU SIMD instructions to process massive arrays in parallel. ✅ Java 26 Way: var species = FloatVector.SPECIES_256; var v1 = FloatVector.fromArray(species, arrayA, i); var v2 = FloatVector.fromArray(species, arrayB, i); var result = v1.mul(v2); // Executes massively faster at the hardware level 💡 The Takeaway Java doesn’t chase trends. It evolves systematically, making it faster, safer, and cleaner, which is exactly why banks, airlines, and Netflix-scale architectures still run on the JVM. Are you keeping your stack up to date? 📚 Reference Official OpenJdk:👇⬇️🎉💥 https://lnkd.in/gaFbaXpU ♻️ Repost if you believe Java is still one of the most powerful backend languages on the planet. Follow Pondurai Madheswaran for more deep dives into Java • Microservices • System Design. #Java #Java26 #BackendDevelopment #SoftwareEngineering #Microservices #JVM #SystemDesign #TechLeadership #PonduraiWrites
To view or add a comment, sign in
-
-
🚀 Day 15 – Java Full Stack Journey | Methods, Stack Frame & Garbage Collection Today’s session was a deep dive into one of the most important pillars of Java: 👉 Methods (Functions) 👉 Stack & Heap Memory Behavior 👉 Garbage Collection Not just writing code — but understanding what happens inside RAM during execution. 🔹 1️⃣ What is a Method? A method is simply: A block of code that performs a specific task. Basic structure: public int add() { int c = a + b; return c; } Every method has: Access Modifier (public) Return Type (int) Method Name (add) Parentheses (input parameters) Body (logic) 🔹 2️⃣ Types of Methods (Covered Today) ✅ Method with No Input & No Output public void add() { int c = a + b; System.out.println(c); } Doesn’t take parameters Doesn’t return anything Uses void ✅ Method with No Input but Returns Output public int add() { int c = a + b; return c; } Key difference: print → Displays value on console return → Sends value back to caller Understanding this difference is crucial. 🔹 3️⃣ What Happens in Memory? (Very Important) When a program runs: Java Runtime Environment (JRE) has: Code Segment Stack Segment Heap Segment Static Segment 🧠 Stack Segment Stores method stack frames Stores local variables Follows LIFO (Last In, First Out) When a method is called: A stack frame is pushed After execution, it is popped 🧠 Heap Segment Stores objects Stores instance variables Objects live here If an object has no reference: 👉 It becomes a Garbage Object Java’s Garbage Collector automatically cleans it. No manual memory deallocation needed (unlike C/C++). 🔹 4️⃣ Important Concept: Return Type & Type Casting Return type must match the returned value Implicit type casting works during return Example: int → float ✅ (Implicit) float → int ❌ (Needs explicit casting) Even during return, Java follows type promotion rules. 💡 Biggest Takeaway Today Understanding: Method execution flow Stack frame creation Heap memory allocation Garbage collection Return vs Print difference This is what separates: ❌ Syntax learners From ✅ Real Java developers Today wasn’t about output. It was about internal execution clarity. Day 15 Complete ✔ #Day15 #Java #CoreJava #Methods #JVM #StackAndHeap #GarbageCollection #OOPS #FullStackJourney #LearningInPublic TAP Academy
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
-
-
🌟 Day 5 of 10 – Core Java Recap: Arrays & Strings 🌟 Continuing my 10-day Java revision journey 🚀 Today I revised Arrays and Strings in Java, which are very important for programming and interviews. 📚 1️⃣ Arrays in Java An array is a container object that stores multiple values of the same data type in a fixed size. Java is not 100% object-oriented because it also supports primitive data types like int, char, etc. Example: int arr[] = new int[5]; Key Points: Stores fixed number of values Same data type elements Index starts from 0 Default values: int → 0, boolean → false, object → null 🔹 Types of Arrays ✔ Single Dimensional Array (1D) Used to store elements in a single row. Example: int arr[] = {1, 2, 3, 4, 5}; ✔ Multi-Dimensional Array (2D) Array of arrays (rows and columns). Example: int arr[][] = new int[2][3]; ✔ Jagged Array Array where each row can have different number of columns. Example: int arr[][] = new int[3][]; arr[0] = new int[2]; arr[1] = new int[3]; arr[2] = new int[1]; 🔁 Iterating Arrays Using for loop: for(int i = 0; i < arr.length; i++){ System.out.println(arr[i]); } Using for-each loop: for(int num : arr){ System.out.println(num); } 🧵 2️⃣ Strings in Java A String is a sequence of characters and is a class in Java. Strings are immutable (cannot be changed after creation). Example: String s1 = "Hello"; String s2 = new String("Hello"); ⚖ Difference Between == and equals() == → Compares memory address (reference) equals() → Compares actual content (value) Example: s1 == s2 // compares address s1.equals(s2) // compares value 🛠 Common String Methods length() → returns length of string charAt() → returns character at index indexOf() → finds position of character substring() → extracts part of string toUpperCase() → converts to uppercase toLowerCase() → converts to lowercase trim() → removes extra spaces split() → splits string into array replace() → replaces characters isEmpty() → checks if string is empty equalsIgnoreCase() → compares ignoring case 🔄 Conversion Array to String: Arrays.toString(arr); String to Array: String s = "Java"; char ch[] = s.toCharArray(); 💡 Key Learnings Today: Understood array types (1D, 2D, Jagged) Learned array traversal using loops Understood String as a class and immutability Learned important string methods used in real programs Building strong Java fundamentals step by step 💻🔥 #Java #CoreJava #Arrays #Strings #JavaLearning #CodingJourney
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