Hii Connection's 👋 🚀 𝐉𝐚𝐯𝐚 𝐕𝐚𝐫𝐚𝐫𝐠𝐬: 𝐒𝐭𝐨𝐩 𝐂𝐫𝐞𝐚𝐭𝐢𝐧𝐠 𝐌𝐚𝐧𝐮𝐚𝐥 𝐀𝐫𝐫𝐚𝐲𝐬! Ever found yourself writing extra code just to pass multiple values into a method? 💡 𝐇𝐨𝐰 𝐖𝐞 𝐇𝐚𝐧𝐝𝐥𝐞𝐝 𝐌𝐮𝐥𝐭𝐢𝐩𝐥𝐞 𝐀𝐫𝐠𝐮𝐦𝐞𝐧𝐭𝐬 𝐁𝐞𝐟𝐨𝐫𝐞 𝐉𝐚𝐯𝐚 𝟓 (𝐍𝐨 𝐕𝐚𝐫𝐚𝐫𝐠𝐬!) Before Java 5 introduced Varargs, developers had limited options to handle multiple inputs. 🚫 𝐏𝐫𝐨𝐛𝐥𝐞𝐦: We couldn’t pass variable number of arguments directly to a method. 👉 𝐄𝐱𝐚𝐦𝐩𝐥𝐞 𝟏: Method Overloading class Demo { static void add(int a, int b) { System.out.println(a + b); } static void add(int a, int b, int c) { System.out.println(a + b + c); } static void add(int a, int b, int c, int d) { System.out.println(a + b + c + d); } } Drawback: Too many methods - Code duplication - Hard to maintain 👉 𝐄𝐱𝐚𝐦𝐩𝐥𝐞 𝟐: Using Arrays class Demo { static void add(int[] numbers) { int sum = 0; for (int n : numbers) { sum += n; } System.out.println(sum); } public static void main(String[] args) { add(new int[]{10, 20}); add(new int[]{5, 10, 15}); } } Drawback: Need to manually create arrays every time - Not user - friendly Conclusion: Before Java 5, handling dynamic arguments was complex and less flexible. Varargs solved this problem by making code clean, readable, and efficient. 🚀 𝐓𝐡𝐚𝐭’𝐬 𝐰𝐡𝐲 𝐕𝐚𝐫𝐚𝐫𝐠𝐬 𝐢𝐬 𝐚 𝐠𝐚𝐦𝐞 𝐜𝐡𝐚𝐧𝐠𝐞𝐫 𝐢𝐧 𝐉𝐚𝐯𝐚! 💡 𝐀𝐟𝐭𝐞𝐫 𝐉𝐚𝐯𝐚 𝟓 – 𝐕𝐚𝐫𝐚𝐫𝐠𝐬 (𝐕𝐚𝐫𝐢𝐚𝐛𝐥𝐞 𝐀𝐫𝐠𝐮𝐦𝐞𝐧𝐭𝐬) 𝐌𝐚𝐝𝐞 𝐋𝐢𝐟𝐞 𝐄𝐚𝐬𝐲! With the release of Java 5, Varargs was introduced to simplify handling multiple arguments. 🚀 What changed? No more multiple overloaded methods or manual array creation! 👉 Varargs allows passing any number of arguments directly to a method. 📌 Syntax: 𝐫𝐞𝐭𝐮𝐫𝐧𝐓𝐲𝐩𝐞 𝐦𝐞𝐭𝐡𝐨𝐝𝐍𝐚𝐦𝐞(𝐝𝐚𝐭𝐚𝐓𝐲𝐩𝐞... 𝐯𝐚𝐫𝐢𝐚𝐛𝐥𝐞𝐍𝐚𝐦𝐞) 👉 𝐄𝐱𝐚𝐦𝐩𝐥𝐞 1: class Demo { static void add(int... numbers) { int sum = 0; for (int n : numbers) { sum += n; } System.out.println("Sum: " + sum); } public static void main(String[] args) { add(10, 20); // 2 arguments add(5, 10, 15); // 3 arguments add(); // no arguments (Valid) } } Advantages: ✔ Reduces method overloading ✔ Improves readability 𝐍𝐨𝐭𝐞: ⚠𝐑𝐮𝐥𝐞𝐬 𝐭𝐨 𝐑𝐞𝐦𝐞𝐦𝐛𝐞𝐫: ✔ 𝐎𝐧𝐥𝐲 𝐨𝐧𝐞 𝐯𝐚𝐫𝐚𝐫𝐠𝐬 𝐩𝐚𝐫𝐚𝐦𝐞𝐭𝐞𝐫 𝐚𝐥𝐥𝐨𝐰𝐞𝐝 ✔ 𝐌𝐮𝐬𝐭 𝐛𝐞 𝐭𝐡𝐞 𝐥𝐚𝐬𝐭 𝐩𝐚𝐫𝐚𝐦𝐞𝐭𝐞𝐫 𝐢𝐧 𝐭𝐡𝐞 𝐦𝐞𝐭𝐡𝐨𝐝 🔥 Behind the Scenes: Varargs is converted into an 𝐚𝐫𝐫𝐚𝐲 𝐢𝐧𝐭𝐞𝐫𝐧𝐚𝐥𝐥𝐲 by the compiler. 💬 Example Real Usage: -> System.out.printf() -> Arrays.asList() 🚀 Conclusion: Varargs made Java code cleaner, shorter, and more powerful compared to pre-Java 5 approaches. #Java #Programming #Coding #Developers #Java #Varargs #Learning
Java Varargs: Simplifying Multiple Argument Handling
More Relevant Posts
-
💡 Why do we need forEach() in Java 8 when we already have loops? Java has always supported iteration using traditional loops. But with Java 8, forEach() was introduced to align with functional programming and stream processing. Let’s break it down 👇 🔹 1. Traditional for Loop for(int i = 0; i < arr.length; i++){ System.out.println(arr[i]); } ✅ Gives full control using index ✅ Supports forward & backward traversal ✅ Easy to skip elements or modify logic ⚠️ Downside: You must manage indexes manually, which can lead to errors like ArrayIndexOutOfBoundsException ------------------------------------------------------------------------------ 🔹 2. Enhanced for-each Loop for(int num : numbers){ System.out.println(num); } ✅ Cleaner and simpler syntax ✅ No need to deal with indexes ⚠️ Limitation: Only forward iteration No direct access to index ------------------------------------------------------------------------------ 🔹 3. Java 8 forEach() (Functional Approach) Arrays.stream(numbers) .forEach(num -> System.out.println(num)); 👉 Even more concise: Arrays.stream(numbers) .forEach(System.out::println); ✅ Encourages functional programming ✅ Works seamlessly with Streams API ✅ More expressive and readable ✅ Can be used with parallel streams for better performance ------------------------------------------------------------------------------ 🔍 What happens internally? forEach() is a default method in the Iterable interface It takes a Consumer functional interface The lambda you provide is executed via: void accept(T t); ------------------------------------------------------------------------------ 🚀 Final Thought While traditional loops are still useful, forEach() brings a declarative and modern way of iterating data — especially when working with streams. #Java #Java8 #Programming #Developers #Coding #FunctionalProgramming
To view or add a comment, sign in
-
☕ OOPs Concepts with Real-Life Examples in Java 🔐 1. Encapsulation — "Bundle & Protect" ➤ Bundles data (fields) + methods into a single unit — the class ➤ Restricts direct access using private variables & exposes them via public getters/setters 🎒 Real-Life Example 1: A school bag — it holds books, pencil, eraser & tiffin inside. You don't reach into the mechanism; you just use the bag! 🏢 Real-Life Example 2: A large organization — HR, Sales, Production, and Accounts Dept. each work internally; outsiders interact with the company as one entity 💻 Java Example: BankAccount class — balance is private; accessed only via deposit(), withdraw(), getBalance() 🧬 2. Inheritance — "Parent Passes to Child" ➤ Child class inherits properties & behaviors from Parent class using the extends keyword ➤ Enables code reuse and hierarchical relationships 👩👧 Real-Life Example 1: Mom & Daughter — daughter inherits certain traits from mom naturally 🚗 Real-Life Example 2: Vehicle Hierarchy — Car, Bus, Bicycle all inherit from Vehicle (wheels, propulsion), but each adds its own unique traits 🐾 Real-Life Example 3: Animal Kingdom — Dog barks, Cat purrs, Horse neighs — all inherit from Animal 💻 Java Example: class Car extends Vehicle — Car calls super(), adds numberOfDoors, overrides start() 🔄 3. Polymorphism — "One Object, Many Forms" ➤ One method/object behaves differently based on context ➤ Two types: Method Overloading (compile-time) & Method Overriding (runtime) 💧 Real-Life Example 1: Water — same substance, takes form of Solid 🧊, Liquid 💧, or Gas 💨 🎭 Real-Life Example 2: A Person's Roles — 🏫 Student in school, 🛒 Customer in mall, 🚌 Passenger in bus, 🏠 Son at home 🐄 Real-Life Example 3: Sound of Animals — Cow moos, Sheep baas, Horse neighs, Bird tweets — all makeSound() but differently! 💻 Java Example: Shape class — calculateArea(radius) vs calculateArea(length, width) = Overloading; Circle & Rectangle each override calculateArea() = Overriding 🎭 4. Abstraction — "Show Only What's Needed" ➤ Hides complex internal workings, exposes only what the user needs ➤ Implemented via abstract classes & interfaces #OOPs #Java #JavaOOP #ObjectOrientedProgramming #Encapsulation #Inheritance #Polymorphism #Abstraction #JavaInterview #InterviewPrep #CrackJavaInterview #JavaDeveloper #MethodOverloading #MethodOverriding #Constructor #AbstractClass #Interface #RealLifeExamples #LearnJava #JavaBeginners #SoftwareEngineering #BackendDevelopment #ProgrammingConcepts #JavaProgramming #InterviewCafe #MicrosoftEngineer #TechBooks #PlacementPrep #ComputerScience #CodeWithJava
To view or add a comment, sign in
-
Not everything that looks equivalent on paper behaves the same in reality, especially at scale. Here’s a simple example to illustrate this: “Given a sorted array and a target value, return the index of the target if it exists, otherwise return -1.” This is the standard Binary Search problem. There are 2 clean ways to solve it in Java: 1. Iterative solution – Use a loop, keep narrowing the search space by updating left and right. 2. Recursive solution – At each step, call the function again on either the left half or the right half. Both are correct. Both run in O(log n). But which one actually performs better in Java? At first glance, they seem identical - they’re doing the same work and even take the same number of steps (~log n). But in practice, the iterative version usually wins. Why? 1️⃣ Every recursive call has a cost (CPU overhead) Each recursive step is a function call. That means the JVM has to: jump to a new method pass parameters (left, right) allocate a new stack frame return back after execution Even though each step is small, this overhead adds up across all calls. In the iterative version, all of this happens inside a single loop. ➡️ Same logic, but fewer method calls → less CPU work 2️⃣ Recursion uses extra memory (call stack) Every recursive call stores its state on the call stack: current bounds local variables like mid return information So memory usage grows with the depth of recursion (O(log n) here). Iteration reuses the same variables for every step. ➡️ Iteration uses constant memory (O(1)) 3️⃣ JVM + JIT optimizations favor loops Java uses a JIT (Just-In-Time) compiler that optimizes frequently executed (“hot”) code. Loops are predictable → easier to optimize (branching, bounds checks, etc.) Recursive calls still behave like method invocations → harder to fully optimize away The compiled code is stored in the JVM’s code cache, so hot loops become very efficient over time. ➡️ Iterative code aligns better with how the JVM optimizes execution 4️⃣ No tail-call optimization in Java In some languages, recursion can be internally converted into a loop (tail-call optimization). Java does not guarantee this, so every recursive step still: creates a new stack frame adds overhead ➡️ The cost of recursion remains 5️⃣ Simpler and safer execution model Iteration is easier to reason about at runtime: no deep call chains more predictable control flow ➡️ This matters as systems grow in complexity This isn’t just about binary search. Execution model matters. At scale, small differences become real issues: latency, memory, even stack overflows. I recently saw this in production where a recursive flow with large inputs hit a stack overflow. Same logic on paper. Very different behavior at runtime. #Java #JVM #PerformanceEngineering #Scalability #BackendEngineering
To view or add a comment, sign in
-
What’s ‘Static’ in Java? Why to use it? Static, as in fixed. Applying it to Object-Oriented tech - something that doesn’t change for every object, it’s fixed for all objects. Generally fields are created separately in memory for each instance of a class, i.e. Object variables. But, anything declared using static keyword belongs to the class instead of individual instances (objects). What does it mean? That every object of this class share this same copy of the variable, method, etc. We can apply static keyword with variables, methods, blocks and nested class. The benefit – memory management of course. public class Student{ private String Name; //Object variable private int Age; //Object variable private String StudentId; //Object variable public static int NumberOfStudents = 0; //Class variable public Student(String name, int age, String studentId) { this.Name = name; this.Age = age; this.StudentId = studentId; NumberOfStudents++; //Increase the no of students whenever an object is created. } } The most common example is << public static void main(String args[]) >> declared static because it must be called before any object exists. Making a method static in Java is an important decision. Does it make sense to call a method/variable, even if no object has been constructed yet? If so, it should be static. Static entity, • Will be initialized first, before any class objects are created. • Is accessed directly by the class name and doesn’t need any object. • Can access only static data. It cannot access non-static data (instance variables). • Can call only other static methods and cannot call a non-static method. Caution: Generally, it is bad practice to set the WebDriver instance as static. Instead create a base class that each test classes extend so that each test class has its own instance of WebDriver to be used (this is especially important with parallel execution), then just declare/define your WebDriver variable within the base class.
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
-
-
If you have a Java interview coming up, read this first. Not because I didn't know Java, but because I had never structured my thinking around the questions that actually get asked. Here's what I wish someone had handed me earlier. 👇 🔑 The OOP Pillars (know these cold) Java is built on 4 concepts. If you can't explain them clearly, the interview ends early. • Inheritance: a child class inherits properties from a parent. Think Dog extends to Animal. • Polymorphism: same method, different behaviour. A cat and a dog both have makeSound(), but they sound very different. • Encapsulation: hide your data behind private fields. Use getters and setters. Protect your class from the outside world. • Abstraction: expose only what is needed. Interfaces and abstract classes are your tools here. ⚡ The questions that always come up What's the difference between method overloading and overriding? → Overloading = same name, different parameters (compile-time) → Overriding = same name, same parameters, child redefines behaviour (runtime) What's JDK vs JRE vs JVM? → JVM runs the bytecode → JRE = JVM + libraries (for users) → JDK = JRE + dev tools like the compiler (for developers) Checked vs unchecked exceptions? → Checked = caught at compile time (FileNotFoundException) → Unchecked = caught at runtime (NullPointerException) "String vs StringBuilder vs StringBuffer?" → String is immutable → StringBuilder is mutable, not thread-safe (faster) → StringBuffer is mutable AND thread-safe (synchronized) 📦 Collections they love to ask about • ArrayList: resizable array, allows duplicates • HashMap: key-value pairs, one null key allowed • HashSet: no duplicates, unordered • LinkedList: dynamic sizing, great for frequent insertions/deletions • TreeSet: sorted, unique elements (red-black tree under the hood) 🔒 The keywords they test on • final: can't be changed/overridden/extended • static: belongs to the class, not the object • volatile: ensures visibility across threads • transient: skip this field during serialization • synchronized: one thread at a time, prevents race conditions 🧵 Threading basics they always sneak in Two ways to create a thread: extend Thread or implement Runnable. Know deadlock: it happens when two threads are each waiting for what the other holds. Know wait(), notify(), and notifyAll(): they coordinate thread communication. This is just the surface layer. But getting these right will take you through 80% of what you'll face in a Java interview. Hit a like and repost it to make it visible to a wider audience! Follow Tarun Tiwari for more! And if you're preparing right now, you've got this. 💪 #Java #JavaDeveloper #CodingInterview #SoftwareEngineering #ProgrammingTips #TechCareers #LearnJava #InterviewPrep #OOP #100DaysOfCode
To view or add a comment, sign in
-
𝑫𝒊𝒇𝒇𝒆𝒓𝒆𝒏𝒄𝒆 𝒃𝒆𝒕𝒘𝒆𝒆𝒏 "𝒕𝒉𝒓𝒐𝒘" 𝒂𝒏𝒅 "𝒕𝒉𝒓𝒐𝒘𝒔" 𝒊𝒏 𝑱𝒂𝒗𝒂 Before understanding "throw" and "throws", one important point ➡️ Throwable is the parent class of Exception ➡️ Exception is the parent class of all Exceptions in Java. 🔍what actually "𝐭𝐡𝐫𝐨𝐰𝐬" mean ➡️It is used in method declaration 📃 "throws" is used to delegate (pass) the exception from one method to the calling method (the one who calls it) and not actually handles the exception. 📃JVM also does not handle it at this stage. Calling method provides try catch blocks to handle this exception. 📃 If not handled Exception goes to JVM.JVM terminates the program ❌ 🔍 Definition of "throw" 📃 "throw" is used to explicitly throw an exception. It stops the normal execution flow. 📃It is used inside a method, The exception is then passed to caller method. 👨💻 Example 𝐢𝐦𝐩𝐨𝐫𝐭 𝐣𝐚𝐯𝐚.𝐢𝐨.*; 𝐜𝐥𝐚𝐬𝐬 𝐃𝐞𝐦𝐨 { 𝐬𝐭𝐚𝐭𝐢𝐜 𝐯𝐨𝐢𝐝 𝐫𝐞𝐚𝐝𝐅𝐢𝐥𝐞() 𝐭𝐡𝐫𝐨𝐰𝐬 𝐅𝐢𝐥𝐞𝐍𝐨𝐭𝐅𝐨𝐮𝐧𝐝𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧 { 𝐅𝐢𝐥𝐞 𝐟𝐢𝐥𝐞 = 𝐧𝐞𝐰 𝐅𝐢𝐥𝐞("𝐃://𝐟𝐢𝐥𝐞𝟏.𝐭𝐱𝐭"); 𝐭𝐡𝐫𝐨𝐰 𝐧𝐞𝐰 𝐅𝐢𝐥𝐞𝐍𝐨𝐭𝐅𝐨𝐮𝐧𝐝𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧("𝐅𝐢𝐥𝐞 𝐧𝐨𝐭 𝐟𝐨𝐮𝐧𝐝"); } 𝐩𝐮𝐛𝐥𝐢𝐜 𝐬𝐭𝐚𝐭𝐢𝐜 𝐯𝐨𝐢𝐝 𝐦𝐚𝐢𝐧(𝐒𝐭𝐫𝐢𝐧𝐠[] 𝐚𝐫𝐠𝐬) { 𝐭𝐫𝐲 { 𝐫𝐞𝐚𝐝𝐅𝐢𝐥𝐞(); } 𝐜𝐚𝐭𝐜𝐡 (𝐅𝐢𝐥𝐞𝐍𝐨𝐭𝐅𝐨𝐮𝐧𝐝𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧 𝐞) { 𝐒𝐲𝐬𝐭𝐞𝐦.𝐨𝐮𝐭.𝐩𝐫𝐢𝐧𝐭𝐥𝐧("𝐈𝐧𝐯𝐚𝐥𝐢𝐝 𝐅𝐢𝐥𝐞 𝐍𝐚𝐦𝐞"); } } } 📝𝐬𝐭𝐚𝐭𝐢𝐜 𝐯𝐨𝐢𝐝 𝐫𝐞𝐚𝐝𝐅𝐢𝐥𝐞() 𝐭𝐡𝐫𝐨𝐰𝐬 𝐅𝐢𝐥𝐞𝐍𝐨𝐭𝐅𝐨𝐮𝐧𝐝𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧 This method is declaring an exception using throws ⚖️“I will not handle this exception” ☎️“Whoever calls me should handle it” 📝 𝐭𝐡𝐫𝐨𝐰 𝐧𝐞𝐰 𝐅𝐢𝐥𝐞𝐍𝐨𝐭𝐅𝐨𝐮𝐧𝐝𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧("𝐅𝐢𝐥𝐞 𝐧𝐨𝐭 𝐟𝐨𝐮𝐧𝐝"); ▪️Here we are manually throwing exception using throw Important: Execution stops here immediately Control goes to calling method 📝𝐭𝐫𝐲 { 𝐫𝐞𝐚𝐝𝐅𝐢𝐥𝐞();} ▪️Calling the method which has throws Since it declared exception → ▪️We must handle it using try-catch 📝 𝐜𝐚𝐭𝐜𝐡 (𝐅𝐢𝐥𝐞𝐍𝐨𝐭𝐅𝐨𝐮𝐧𝐝𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧 𝐞) Catch block handles the exception ♣️ Key Difference "throws" → delegates exception (method level) ➡️ passing responsibility "throw" → actually throws exception (statement level) ➡️ creating the problem #Java #JavaDeveloper #JavaConcepts #ExceptionHandling #Programming #TechJourney #InterviewPrep
To view or add a comment, sign in
-
🔥 Java Deep Dive – Understanding How Java Really Works (Post #2) In my previous post, I explored Java Access Modifiers (public, private, protected, default) — how we control visibility 🔐 Today, I took the next step… 👉 Non-Access Modifiers in Java — controlling behavior ⚙️ I’m still learning and exploring, and sharing my understanding along the way to grow with the community 🙌 💡 My Understanding (with real-world + code) 🔹 static – Shared Across All Objects 🏢 ➡️ Like a company name — same for every employee class Company { static String companyName = "ABC Pvt Ltd"; } 👉 No need to create objects — shared everywhere 🔹 final – Cannot Be Changed 🔒 ➡️ Like your NIC / Date of Birth class Person { final String nic = "200012345678"; } 👉 Once assigned → ❌ cannot modify 🔹 abstract – Blueprint 🧩 ➡️ Like a Vehicle concept (rules, not implementation) abstract class Vehicle { abstract void start(); } class Car extends Vehicle { void start() { System.out.println("Start with key"); } } 👉 Defines what to do, not how 🔹 synchronized – One at a Time 🏧 ➡️ Like an ATM machine synchronized void withdraw() { // only one thread at a time } 🔹 transient – Do Not Store 🚫💾 ➡️ Like passwords / PINs transient String password; 🔹 volatile – Always Latest Value 📡 ➡️ Like a live cricket score volatile int score; 🔹 native – External Power ⚡ ➡️ Calls C/C++ code for system-level operations native void print(); 🧠 Big Picture ✔️ Access Modifiers → Who can access 🔐 ✔️ Non-Access Modifiers → How things behave ⚙️ 🚀 My Learning Approach I’m currently focusing on: ✔️ Understanding concepts with real-world thinking ✔️ Writing simple code examples ✔️ Building a strong Core Java foundation 📌 I’m still learning, and I know there’s a lot more to improve — So I’m sharing my journey to learn better and connect with others in the same path 🤝 🔜 What’s Next? 👉 Understanding how Access Modifiers and Non-Access Modifiers are stored in memory (Stack vs Heap) 💬 If you have suggestions, corrections, or tips — I’d truly appreciate it! #Java #SoftwareEngineering #BackendDevelopment #LearningJourney #100DaysOfCode
To view or add a comment, sign in
-
-
𝐉𝐚𝐯𝐚 𝟏𝟑: 𝐌𝐚𝐤𝐢𝐧𝐠 𝐭𝐡𝐞 𝐒𝐰𝐢𝐭𝐜𝐡 𝐒𝐭𝐚𝐭𝐞𝐦𝐞𝐧𝐭 𝐁𝐞𝐭𝐭𝐞𝐫! If you've ever spent hours debugging a logic error only to find you missed a single break; statement, you know the pain of the traditional Java switch. Java 12 and 13 introduced major upgrades to fix these "legacy" headaches. Here is a quick breakdown of how the Enhanced Switch makes your code cleaner and safer: 𝟏. 𝐍𝐨 𝐌𝐨𝐫𝐞 "𝐅𝐚𝐥𝐥-𝐓𝐡𝐫𝐨𝐮𝐠𝐡" 𝐓𝐫𝐚𝐩𝐬 Traditional switches require a break for every case. If you forget it, the code "falls through" to the next case. The Fix: Using the new arrow (->) syntax. It executes only the code on the right side. No break required! 𝟐. 𝐒𝐰𝐢𝐭𝐜𝐡 𝐚𝐬 𝐚𝐧 𝐄𝐱𝐩𝐫𝐞𝐬𝐬𝐢𝐨𝐧 You can now assign the result of a switch directly to a variable. This makes your code much more concise. Example: 𝐉𝐚𝐯𝐚 String device = switch (itemCode) { case 001 -> "Laptop"; case 002 -> "Desktop"; default -> "Unknown"; }; System.out.println("Output: " + device); 𝐎𝐮𝐭𝐩𝐮𝐭: Output: Laptop 𝟑. 𝐌𝐮𝐥𝐭𝐢𝐩𝐥𝐞 𝐕𝐚𝐥𝐮𝐞𝐬, 𝐎𝐧𝐞 𝐂𝐚𝐬𝐞 Gone are the days of stacking cases on top of each other. You can now comma-separate multiple values in a single line: case 001, 002, 003 -> System.out.println("Electronic Gadget"); 𝟒. 𝐓𝐡𝐞 𝐲𝐢𝐞𝐥𝐝 𝐊𝐞𝐲𝐰𝐨𝐫𝐝 In Java 13, if you are using the traditional colon syntax (:) but want to return a value from a switch expression, use yield. It returns the value and exits the switch immediately. 𝟓. 𝐄𝐱𝐡𝐚𝐮𝐬𝐭𝐢𝐯𝐞𝐧𝐞𝐬𝐬 (𝐒𝐚𝐟𝐞𝐭𝐲 𝐅𝐢𝐫𝐬𝐭!) When using switch as an expression, Java forces you to cover every possible case (or provide a default). This prevents those pesky "unhandled value" bugs from reaching production. 𝟔. 𝐌𝐨𝐝𝐞𝐫𝐧 𝐋𝐨𝐠𝐢𝐜 𝐰𝐢𝐭𝐡 𝐭𝐡𝐞 𝐰𝐡𝐞𝐧 𝐊𝐞𝐲𝐰𝐨𝐫𝐝 (𝐉𝐚𝐯𝐚 𝟐𝟏+) Introduced in Java 21, the when keyword acts as a Guard. It allows you to add extra boolean conditions directly to a case label. No more nesting if statements inside your cases! Example: 𝐉𝐚𝐯𝐚 switch (obj) { case String s when s.length() > 5 -> System.out.println("Long string: " + s); case String s -> System.out.println("Short string"); default -> System.out.println("Not a string"); } Deeply grateful to Syed Zabi Ulla Sir for his expert guidance. He has a gift for making even the trickiest Java updates feel intuitive. Thank you, sir, for helping us build such a strong technical base and for always being a guiding light in our learning journey! #Java #Programming #CodingTips #SoftwareDevelopment #Java21 #CleanCode #BackendDeveloper #Mentorship #PWIOI #LearningJourney
To view or add a comment, sign in
-
-
🚀 Stop Writing "How" and Start Telling Java "What" If you are still using nested for-loops and if-else blocks to process collections, you’re writing more code to do less work. The Java Stream API isn’t just a new way to iterate; it’s a shift from Imperative (how to do it) to Declarative (what to do) programming. Here is everything you need to know to master Streams in 2026: 🛠 The 3-Step Lifecycle Every Stream pipeline follows a strict structure: Source: Where the data comes from (List, Set, Array, I/O channel). Intermediate Operations: These transform the stream. They are lazy—they don’t execute until a terminal operation is called. Terminal Operation: This triggers the processing and produces a result (a value, a collection, or a side-effect). 💡 Core Operations You Must Know .filter(Predicate): The gatekeeper. Only let through what matches your criteria. .map(Function): The transformer. Change objects from one type to another (e.g., User → UserDTO). .flatMap(): The "flattener." Perfect for when you have a list of lists and want one single stream of elements. .reduce(): The aggregator. Great for summing values or combining elements into a single result. .collect(): The finisher. Converts the stream back into a List, Set, or Map. 🧠 Advanced Tip: The "Lazy" Advantage One of the most misunderstood parts of the Stream API is Lazy Evaluation. If you have a .filter() followed by a .findFirst(), Java doesn't filter the entire list first. It processes elements one by one until it finds a match and then stops immediately. This makes it incredibly efficient for large datasets. ⚡ Parallel Streams: Use with Caution list.parallelStream() can speed up CPU-intensive tasks on multi-core processors. However: ❌ Avoid if you have shared mutable state (thread-safety issues). ❌ Avoid for small datasets (the overhead of splitting the stream costs more than the gain). 📝 Example: Real-World Usage List<String> topPerformers = employees.stream() .filter(e -> e.getSalary() > 75000) // Filter by salary .sorted(Comparator.comparing(Employee::getRating).reversed()) // Sort by rating .map(Employee::getName) // Get names only .limit(5) // Top 5 .collect(Collectors.toList()); // Convert to list Clean. Readable. Maintainable. Are you a Stream enthusiast or do you still prefer the control of a traditional for-loop? Let's discuss in the comments! 👇 #Java #SoftwareEngineering #CleanCode #StreamAPI #BackendDevelopment #ProgrammingTips #Java21
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