🚀 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
Java Full Stack: Methods, Stack Frame & Garbage Collection
More Relevant Posts
-
🚀 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
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
-
-
🧩☕ GUESS THE JAVA VERSION: SWITCH EXPRESSION EDITION 🔸 THE QUESTION Can you identify the first Java version that supports this code as a standard feature? 👇 class Example { public int test(String s) { return switch (s) { case "a" -> 1; case "b" -> 2; default -> 0; }; } } Which Java version is it? ▪️ Java 1.4 ▪️ Java 7 ▪️ Java 14 ▪️ Java 16 ▪️ Java 21 ▪️ Java 25 🔸 TRY BEFORE CHECKING THE ANSWER 🤔 Take a moment before reading further. This code is using a modern switch style: ▪️ the switch returns a value ▪️ the cases use -> ▪️ there is no fall-through like in the old switch form Do you have your answer? 👀 🔸 TLDR If a switch returns a value directly and uses case ->, think Java 14 ☕ 🔸 THE ANSWER ✅ The correct answer is: Java 14 This code uses a switch expression. That means the switch does not only execute code: it also produces a value that can be returned directly. The case -> syntax is part of that feature, and switch expressions became a standard Java feature in Java 14 with JEP 361. A related detail: yield is only needed when a case uses a block and must explicitly return a value from that block. In your example, each case already returns a simple value, so yield is not necessary. 🔸 WHY THIS MATTERS This is a good example of how Java became more expressive over time. With switch expressions, code is: ▪️ shorter ▪️ clearer ▪️ safer against accidental fall-through ▪️ closer to an expression-oriented style That is why this feature is easy to recognize once you know what to look for. 🔸 TAKEAWAYS ▪️ switch expressions became standard in Java 14 ▪️ case -> is a strong visual clue ▪️ yield is used only for block-style cases ▪️ This feature helps write cleaner and safer Java code #Java #OpenJDK #Java14 #Programming #SoftwareDevelopment #CleanCode #Coding #Developers #Backend #TechQuiz Go further with Java certification: Java👇 https://lnkd.in/eZKYX5hP Spring👇 https://lnkd.in/eADWYpfx SpringBook👇 https://bit.ly/springtify JavaBook👇 https://bit.ly/jroadmap
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 35 – Core Java | Super Keyword, Method Types in Inheritance & Access Modifiers Today’s session connected multiple important concepts in Java Inheritance and clarified how classes interact with each other in real programs. 🔹 Super Keyword When both parent and child classes have the same variable or method, Java gives priority to the child class. To access the parent class version, Java provides the super keyword. Example: super.variableName super.methodName() ✔ Used to access parent variables ✔ Used to call parent methods Important difference: super() → used for constructor chaining super keyword → used to access parent properties and behaviors 🔹 Constructor Chaining Recap Constructor chaining can happen in two ways: 1️⃣ Within the same class this() 2️⃣ Between parent and child classes super() Important rule: Both this() and super() must be the first line of a constructor, so they cannot be used together in the same constructor. 🔹 Types of Methods in Inheritance In inheritance, methods fall into three categories: 1️⃣ Inherited Methods Methods that the child class directly acquires from the parent without any modification. Example: takeoff() land() 2️⃣ Overridden Methods Methods that the child class inherits and then modifies. Example: fly() Each plane type flies differently. Java uses: @Override This annotation helps: Documentation Detecting coding mistakes 3️⃣ Specialized Methods Methods created only in the child class. Example: carryCargo() carryPassengers() carryWeapons() These methods do not exist in the parent class. 🔹 Real Example Used in Class We designed a Plane system using inheritance. Parent Class: Plane Methods: takeoff() fly() land() Child Classes: CargoPlane PassengerPlane FighterPlane Each child: inherits takeoff() and land() overrides fly() adds specialized methods This demonstrated how code reuse reduces development effort. 🔹 Access Modifiers in Java To understand inheritance properly, we also explored Access Modifiers. Key observation: Public → Maximum visibility Private → Minimum visibility Visibility decreases in this order: public → protected → package access → private 💡 Biggest Takeaway Understanding inheritance is not just about writing extends. It requires clarity about: Constructor chaining Method overriding Code reuse Access control Class relationships These concepts are fundamental before moving to the next pillar of OOP – Polymorphism. #Day35 #CoreJava #Inheritance #SuperKeyword #MethodOverriding #JavaOOP #AccessModifiers #DeveloperJourney
To view or add a comment, sign in
-
-
🚀 Day 26 – Java Full Stack Journey | Method Overloading (Deep Dive) + Command Line Arguments + Encapsulation Begins Today’s session was powerful. We moved from understanding how Java compiler thinks to stepping into the first pillar of OOPS – Encapsulation. 🔹 1️⃣ Method Overloading – Compiler Logic (Advanced Understanding) We revised that: Method Overloading = Multiple methods with same name inside the same class. 🔹 2️⃣ Command Line Arguments We understood: public static void main(String[] args) args is a 1D String array It is dynamically sized Values are passed from Command Prompt Example: java Demo ABC 123 Inside program: args[0] → "ABC" args[1] → "123" Important realization: Even if you pass numbers, 👉 They are still stored as Strings + operator → Concatenation Not arithmetic addition. 🔥 3️⃣ OOPS Begins – Encapsulation (First Pillar) Today we officially stepped into Object-Oriented Programming System (OOPS). OOPS is built on 4 pillars: 1️⃣ Encapsulation 2️⃣ Inheritance 3️⃣ Polymorphism 4️⃣ Abstraction And today we started with Encapsulation. 🔹 What is Encapsulation? Encapsulation is the process of providing security to the most important data and giving controlled access. Not just wrapping data. Not just hiding variables. It means: ✔ Protect critical data ✔ Allow controlled access ✔ Prevent direct manipulation 🔹 How Do We Achieve Encapsulation in Java? Step 1️⃣ → Make variable private Step 2️⃣ → Provide public setter and getter Example: class Bank { private int balance; public void setData(int x) { if(x >= 0) balance = x; else System.out.println("Invalid input"); } public int getData() { return balance; } } Now: ✔ Direct access → ❌ Not allowed ✔ Controlled access → ✅ Through methods This is real-world security logic. 🔹 Real-World Understanding Brain protected by skull Coolant protected inside AC Lens protected inside camera Balance protected inside Bank object Protection + Controlled Access = Encapsulation 💡 Biggest Learning Today Java is not just syntax. It’s: Understanding compiler behavior Understanding JVM execution Understanding memory Writing secure code Thinking like a software engineer We are no longer learning “Java basics”. We have officially entered serious OOPS architecture. Day 26 Complete ✅ #Day26 #Java #CoreJava #MethodOverloading #CommandLineArguments #OOPS #Encapsulation #FullStackJourney #LearningInPublic #SoftwareEngineer TAP Academy
To view or add a comment, sign in
-
-
📌Headline: Stop manually setting data! Let Java Constructors do the heavy lifting. 🏗️☕ I’ve been brushing up on my Java fundamentals, specifically focusing on Constructors. Think of a constructor as the "birth certificate" of an object. 📜 The moment you use the new keyword, the constructor kicks in to initialize your object. Whether it’s a Default Constructor (which Java kindly provides if you forget) or a Parameterized Constructor (where you pass specific data right at the start), they are the backbone of clean, efficient code. Key takeaways from my study session: ✅ No return type—not even void! ✅ Always shares the exact same name as the Class. ✅ Perfect for setting initial state through the this keyword. It’s the difference between buying a plain "Default" car or ordering one "Parameterized" with your favorite color and engine type. 🚗💨 #JavaProgramming 💡 Important Points to Remember Based on your notes, here are the "Must-Knows": 📍Implicit vs. Explicit: If you don't write a constructor, Java provides a Default Constructor (no-args) automatically. However, the moment you write any constructor yourself, Java stops providing the default one. 📍The this Keyword: Used to distinguish between class variables (instance variables) and parameters when they have the same name (e.g., this.cid = cid;). 📍Memory Execution: When new Customer(...) is called, memory is allocated in the Heap, and the constructor immediately fills those memory slots with your data. Constructor vs. Method: Constructor: Purpose is Initialization. Called once at "birth." Method: Purpose is Behavior. Called anytime during the object's life. 🌍 Real-Time Example: The "Smart Home Account" Imagine you are signing up for a new Music Streaming App. The Class: UserAccount The Constructor (Parameterized): When you click "Sign Up," you provide your email, username, and planType. The app uses a constructor to create your account object with those specific details immediately. You wouldn't want an account with "null" values that you have to fix later! The Method: playSong() or changePassword(). These are actions you take after the account is already created and initialized. TAP Academy #Java #Constructor #Programming #SoftwareDevelopment #InterviewPreparation
To view or add a comment, sign in
-
-
🚀 Day 13 of Java – Static Keyword & Wrapper Classes Today I learned some very important core concepts in Java — Static keyword and Wrapper Classes. 🔹 Static in Java The static keyword is used for memory management and belongs to the class, not to objects. ✔ Static Variable – Shared among all objects, only one copy exists. ✔ Static Method – Called using ClassName.method(), cannot access non-static data directly. ✔ Static Block – Executes once when the class is loaded into memory. 💡 Static members are stored in the Method Area (Class Area) and are allocated only once per class. 🔹 Wrapper Classes Wrapper classes provide an object representation of primitive data types. PrimitiveWrapperintIntegerdoubleDoublecharCharacterbooleanBoolean Why Wrapper Classes? ✔ Collections work only with objects ✔ Allow null values ✔ Provide utility methods like parseInt() ✔ Required for Generics 🔹 Autoboxing & Unboxing 🔸 Autoboxing → int → Integer 🔸 Unboxing → Integer → int Example: int a = 10; Integer obj = a; // Autoboxing int value = obj; // Unboxing 🔹 Parsing Wrapper classes help convert String to primitive: String s = "100"; int num = Integer.parseInt(s); 🎯 Key Takeaway: Understanding static improves OOP clarity and memory concepts, while wrapper classes are essential for collections and real-world Java applications. Consistency is building confidence day by day 💪 #Day13 #30DaysOfJava #JavaLearning #StaticKeyword #WrapperClasses #Autoboxing #JavaDeveloper #CodingJourney #FutureSoftwareEngineer 🚀 100DAYS OF CODE ALSO Perfect 🔥 Here’s your updated Day 13 description with #100DaysOfCode included 👇 🚀 Day 13 of Java | Static Keyword & Wrapper Classes On Day 13 of my Java learning journey, I explored two important core concepts — Static keyword and Wrapper Classes. 🔹 Static in Java The static keyword belongs to the class, not the object. ✔ Static Variable – Shared among all objects (single copy per class) ✔ Static Method – Called using ClassName.method() ✔ Static Block – Executes once when the class is loaded 💡 Static members are stored in the Method Area and help in efficient memory usage. 🔹 Wrapper Classes Wrapper classes provide an object representation of primitive data types. Examples: int → Integer double → Double char → Character boolean → Boolean Why Wrapper Classes? ✔ Needed for Collections ✔ Allow null values ✔ Provide utility methods like parseInt() ✔ Used in Generics 🔹 Autoboxing & Unboxing Autoboxing → Primitive to Object Unboxing → Object to Primitive int a = 10; Integer obj = a; // Autoboxing int value = obj; // Unboxing 🔹 Parsing Example String s = "100"; int num = Integer.parseInt(s); Every day I’m strengthening my Java fundamentals step by step 💪 Consistency > Motivation 🚀 #Day13 #30DaysOfJava #100DaysOfCode #Java #JavaLearning #StaticKeyword #WrapperClasses #Autoboxing #CodingJourney #FutureDeveloper
To view or add a comment, sign in
-
-
🚀 Java 8 Features 📅 Day 13 ForEach Loop in Java 8 Why Do We Need It? Even though Java already has two looping mechanisms, Normal for loop and Enhanced for-each loop, Java 8 introduced forEach() to support functional programming and stream processing. 1️⃣ Normal for Loop for(int i = 0; i < arr.length; i++){ System.out.println(arr[i]); } ✅ Access elements using index ✅ Can traverse forward and reverse ✅ Can skip elements using conditions ✅ Can remove elements ⚠️ Issue: If the index exceeds array size → ArrayIndexOutOfBoundsException 2️⃣ Enhanced For-Each Loop for(int num : numbers){ System.out.println(num); } ✅ No need for index ✅ Simple syntax ⚠️ Limitation: Only forward traversal No direct index access 🔹 3️⃣ Java 8 forEach() Introduced to support Functional Programming. int[] numbers = {43, 743, 7, 2, 90}; Arrays.stream(numbers) .forEach(num -> System.out.println(num)); 💡 Even simpler: Arrays.stream(numbers) .forEach(num -> System.out::println); ✅ Functional style coding ✅ Works with Streams API ✅ Concise and readable code ✅ Supports parallel processing 🔹 Behind the scenes default method foreach available in iterable interface forEach() accepts a Consumer Functional Interface void accept(T t); The lambda expression you pass is internally executed by the Consumer's accept() method. ♻️Repost so others can learn and grow together. 🔔 Follow Hariprasath V for daily Java, DSA, and System Design,Springboot,Microservices,Devops,Full Stack resources. =============================================== #Java #Java8 #Streams #Programming #Developers #Coding #SoftwareEngineering #Git #GitHub #VersionControl #SoftwareDevelopment #BackendDevelopment #JavaDeveloper #Coding #DeveloperCommunity #TechLearning #DevOps #LearnInPublic #DeveloperCommunity #Developer #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 #FunctionalProgramming #Lambda #MethodReference #ConstructorReference #Programming #Coding #Java #Java8 #StringJoiner #JavaProgramming #Developers #Coding
To view or add a comment, sign in
-
-
Most Java Docker Images in Production Are Bigger, Slower, and Less Secure Than They Need to Be. I have reviewed a lot of Dockerfiles across enterprise Java projects. The same pattern shows up every time. One stage. JDK base image. Source code copied in. Maven runs inside the container. Everything ships together. It works. Until it doesn't. A container is a runtime artifact. Not a build environment. When you run mvn package inside your final image you are shipping Maven, the JDK compiler toolchain, your source code, and every build-time dependency alongside your application. None of that belongs in production. It inflates your image, widens your attack surface, and gives anyone who gets a shell inside that container far more capability than they should have. A proper multi-stage Dockerfile fixes this cleanly. dockerfile # Stage 1 - Builder FROM eclipse-temurin:21-jdk-alpine AS builder WORKDIR /app COPY .mvn/ .mvn/ COPY mvnw pom.xml ./ RUN ./mvnw dependency:go-offline COPY src ./src RUN ./mvnw package -DskipTests # Stage 2 - Runtime FROM eclipse-temurin:21-jre-alpine WORKDIR /app COPY --from=builder /app/target/*.jar app.jar ENTRYPOINT ["java", "-jar", "app.jar"] The runtime image never saw Maven. Never saw your source. Never saw the JDK compiler. Layer caching is where you recover real build time. Dependencies are resolved before source code is copied. Your pom.xml changes far less frequently than your src directory. Flip the order and your incremental builds drop from three minutes to under thirty seconds because the dependency layer is already cached. Your base image choice is a security decision. Eclipse Temurin on Alpine gives you a minimal JRE with a small footprint. Distroless Java images go further by stripping the shell entirely. No bash, no package manager, nothing for an attacker to work with. Your image size drops from 600MB to under 150MB. In regulated environments like healthcare or banking this matters beyond convenience. Being precise about what a container is actually for is not exotic engineering. It is just discipline. What does your current Java Dockerfile look like? #Java #Docker #SpringBoot #DevOps #Kubernetes #ContainerSecurity #CloudNative #Java21 #Microservices #BackendEngineering #PlatformEngineering #DockerBestPractices #JVM #EnterpriseJava #CI_CD #SoftwareEngineering #EclipseTemurin #SoftwareArchitecture #SiteReliabilityEngineering #InfrastructureAsCode
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