💡 SOLID Principles with Real Java Examples 🚀 Understanding SOLID is one thing… Applying it in real code is what makes you a better developer 👇 ___________________________________________________________________ 🔹 S — Single Responsibility Principle (SRP) 👉 A class should have only ONE responsibility ❌ Bad: class UserService { void saveUser() { } void sendEmail() { } // ❌ extra responsibility } ✅ Good: class UserService { void saveUser() { } } class EmailService { void sendEmail() { } } ___________________________________________________________________ 🔹 O — Open/Closed Principle (OCP) 👉 Open for extension, closed for modification ❌ Bad: class Discount { double getDiscount(String type) { if(type.equals("NEW")) return 10; else if(type.equals("OLD")) return 5; return 0; } } ✅ Good: interface Discount { double getDiscount(); } class NewCustomer implements Discount { public double getDiscount() { return 10; } } class OldCustomer implements Discount { public double getDiscount() { return 5; } } ___________________________________________________________________ 🔹 L — Liskov Substitution Principle (LSP) 👉 Child class should behave like parent ❌ Bad: class Bird { void fly() { } } class Penguin extends Bird { void fly() { throw new RuntimeException("Can't fly"); // ❌ violation } } ✅ Good: class Bird { } class FlyingBird extends Bird { void fly() { } } class Penguin extends Bird { } // no forced fly() ___________________________________________________________________ 🔹 I — Interface Segregation Principle (ISP) 👉 Don’t force unnecessary methods ❌ Bad: interface Worker { void work(); void eat(); } class Robot implements Worker { public void work() { } public void eat() { } // ❌ not needed } ✅ Good: interface Workable { void work(); } interface Eatable { void eat(); } class Robot implements Workable { public void work() { } } ___________________________________________________________________ 🔹 D — Dependency Inversion Principle (DIP) 👉 Depend on abstraction, not implementation ❌ Bad: class MySQLDatabase { } class UserService { MySQLDatabase db = new MySQLDatabase(); // tight coupling } ✅ Good: interface Database { } class MySQLDatabase implements Database { } class UserService { Database db; UserService(Database db) { this.db = db; } } ___________________________________________________________________ 🚀 Why SOLID Matters? ✔️ Cleaner code ✔️ Easier to maintain ✔️ Better scalability ✔️ Loose coupling #Java #SOLID #CleanCode #SystemDesign #Backend #Developers
SOLID Principles with Java Examples
More Relevant Posts
-
#Post10 In the previous post(https://lnkd.in/gAHA3K52), we understood the lifecycle of a thread. Now let’s see How Threads Are Created in Java. There are two ways to create a thread in Java: 1. Using Runnable class (most commonly used) 2. Extending Thread class Before we go into implementation, one important detail: The Thread class itself already implements Runnable. So basically, Runnable is an interface and Thread class implements it. Let’s start with the first approach. 1. Using Runnable We define the task separately from the thread. Step 1: Create a class that implements Runnable public class MultithreadingLearning implements Runnable { @Override public void run() { System.out.println("Code executed by thread: " + Thread.currentThread().getName()); } } Step 2: Pass it to a Thread and start it public class Main { public static void main(String[] args) { System.out.println("Going inside main method: " + Thread.currentThread().getName()); MultithreadingLearning runnableObj = new MultithreadingLearning(); Thread thread = new Thread(runnableObj); thread.start(); System.out.println("Finish main method: " + Thread.currentThread().getName()); } } Output: Going inside main method: main Finish main method: main Code executed by thread: Thread-0 Notice how the main thread finishes first, and the new thread runs independently. Now let’s look at the second approach. 2. Extending Thread Step 1: Create a class that extends Thread public class MultithreadingLearning extends Thread { @Override public void run() { System.out.println("Code executed by thread: " + Thread.currentThread().getName()); } } Step 2: Start the thread public class Main { public static void main(String[] args) { System.out.println("Going inside main method: " + Thread.currentThread().getName()); MultithreadingLearning myThread = new MultithreadingLearning(); myThread.start(); System.out.println("Finish main method: " + Thread.currentThread().getName()); } } Now the important question: Why do we have two ways? Because Java allows: • Extending only one class • Implementing multiple interfaces If you extend Thread, you lose the ability to extend any other class. That’s why Runnable is preferred. Key takeaway Both approaches can be used to create threads. However: • Runnable is more flexible and commonly used • Extending Thread is simpler but has limitations Next: Why creating threads manually is not scalable and how Executor Framework solves this. #Java #Multithreading #Concurrency #BackendDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
🛡️ Shipped a major upgrade to AI-MR-Reviewer — a GitHub App that reviews your Java pull requests the moment you open them. Inline comments on the diff. Three severity levels. Zero configuration. Built for teams who want fast feedback without setting up SonarQube. What lands in this release: 19 hand-tuned Java rules. 🔴 HIGH RISK — 9 rules - Empty catch blocks (silent exception swallowing) - printStackTrace() in production code - Broad catches — Exception / Throwable / RuntimeException - SQL injection in createQuery / prepareStatement (concat + String.format) - Hardcoded credentials (password / apiKey / authToken) - Thread.sleep() in non-test code - Resource leaks — FileReader / Socket without try-with-resources - String compared with == instead of .equals() - Raw generics — new ArrayList() without the diamond operator 🟡 MID RISK — 5 rules - System.out / System.err in production - Magic strings in local assignments - PascalCase class / interface / enum naming - Methods with more than 5 parameters (god-method signal) - new Date() — prefer java.time (Instant, LocalDateTime) 🔵 LOW RISK — 5 rules - Numbered method names (toResponse2, handler3) - Wildcard imports (import java.util.*) - Missing Javadoc on public API surfaces (Service / Controller / Facade) - Unresolved TODO / FIXME / HACK comments - Files left behind as "ClassName copy.java" Every rule is tuned for a low false-positive rate. JPA/Spring annotation attributes are whitelisted, so @Table(name = "user") will never show up as a "magic string". Common numeric suffixes — sha256, base64, int32, ipv4 — are excluded from the numbered-method rule. Under the hood: TypeScript · Node.js · Octokit · Express · Docker. Deployed on Hostinger. Reviews land within seconds of opening the PR. Next up: the same treatment for Python and PHP, plus a semantic layer on top of the regex foundation — equals()/hashCode() pairing, Optional misuse detection, and blocking calls inside reactive chains. If your team reviews Java PRs every day, this saves an hour per dev per week. DMs open. #Java #SpringBoot #CodeReview #DeveloperTools #StaticAnalysis #OpenSource #DevEx
To view or add a comment, sign in
-
-
Created 1 million objects. App crashed with OutOfMemoryError. Nobody understood why. 😱 Java Fundamentals A-Z | Post 25 Can you spot the bug? 👇 public void processTransactions() { for (int i = 0; i < 1000000; i++) { Transaction t = new Transaction(); // 💀 Heap! t.setId(i); t.process(); // t goes out of scope // But GC hasn't cleaned yet! 💀 } } // Result → OutOfMemoryError! 💀 // Heap filled faster than GC could clean! Every new Transaction() goes to Heap. GC couldn’t keep up. Understanding Stack vs Heap prevents this! 💪 Here’s how Java memory actually works 👇 public void calculate() { // ✅ Stack — primitive, fast, auto-cleaned! int x = 10; // Stack double rate = 0.05; // Stack boolean isValid = true; // Stack // ⚠️ Heap — objects, slower, needs GC! String name = new String("DBS"); // Heap List<Integer> nums = new ArrayList<>(); // Heap // ✅ Fix — reuse objects where possible! StringBuilder sb = new StringBuilder(); for (int i = 0; i < 1000000; i++) { sb.setLength(0); // ✅ Reuse — no new Heap allocation! sb.append("Transaction: ").append(i); } } Fixed batch job OutOfMemoryError by reusing objects instead of creating new ones in loop. Memory usage dropped 60%. 🔥 Stack vs Heap cheat sheet 👇 — Stack → primitives, method calls, references — fast, auto-cleaned — Heap → all objects — slower, needs Garbage Collector — Stack overflow → too many method calls (infinite recursion!) — OutOfMemoryError → too many objects in Heap — Solution → reuse objects, avoid new inside loops! Summary: 🔴 Creating new objects inside million-iteration loops 🟢 Reuse objects — Stack for primitives, Heap wisely for objects! 🤯 60% memory reduction by just reusing StringBuilder in batch job! Have you faced OutOfMemoryError in production? Drop a 🧠 below! #Java #JavaFundamentals #BackendDevelopment #LearningInPublic #SDE2
To view or add a comment, sign in
-
-
🤔 Ever wondered how Java handles multiple threads safely? Let’s break it down in a simple way 👇 🚀 **Synchronized vs Atomic Classes in Java — Explained Simply Multithreading is powerful, but handling shared data safely is critical. Let’s break it down 👇 🔒 What is `synchronized`? A keyword in Java used to control access to shared resources. ✔ Ensures only one thread executes at a time (Mutual Exclusion) ✔ Prevents race conditions Example: public synchronized void increment() { count++; } 🔑 How it works? * Every object has an **Intrinsic Lock (Monitor)** * Thread acquires lock → executes → releases lock * Other threads must wait Automatic: When you use the synchronized keyword, Java handles the locking and unlocking for you behind the scenes. 💡 Think: One door, one key — whoever holds the key gets access --- ### 🧠 Guarantees ✔ Mutual Exclusion(Only one thread can access a shared resource at a time) ✔ Visibility (changes visible to other threads) ✔ Ordering (Happens-Before) ⚙️ Memory Visibility (Internals) Based on Java Memory Model 1️⃣ Write → Store Barrier → Writing updated values from a thread’s local CPU cache to the shared main memory (RAM) 2️⃣ Read → Load Barrier → Ensure fresh values are read from main memory 💡 Ensures threads don’t read stale data from CPU cache ⚡ What is `AtomicInteger`? A class from: java.util.concurrent.atomic ✔ Thread-safe without locks ✔ Uses **CAS (Compare-And-Swap)** + memory barriers Example: AtomicInteger count = new AtomicInteger(0); count.incrementAndGet(); 🔄 CAS Logic If current value == expected → update Else → retry Key Methods get() // read value set() // update value incrementAndGet() // ++count getAndIncrement() // count++ compareAndSet(a, b) // CAS operation Example Thread-1: expected = 0 → update to 1 ✅ Thread-2: expected = 0 → fails ❌ (value already changed) retries → succeeds later 📦 Atomic Package Categories * **Primitive** → AtomicInteger, AtomicLong * **Reference** → AtomicReference, Stamped, Markable * **Array** → AtomicIntegerArray * **Field Updaters** → Fine-grained updates * **High Concurrency** → LongAdder, DoubleAdder 🚀 Why `LongAdder`? (Java 8) Problem with Atomic: ❌ High contention ❌ Too many CAS retries Solution: ✔ Split into multiple counters AtomicInteger → [ 0 ] ❌ ← all threads update here ❌ (bottleneck) LongAdder → [1][2][3][4] ← threads distributed ✅ ✔ Better performance under heavy load ✅ When to Use **Use synchronized** ✔ Complex operations ✔ Multiple variables **Use Atomic** ✔ Counters ✔ Simple updates **Use LongAdder** ✔ High concurrency systems (metrics, counters) 🎯 Final Takeaway 👉 Use synchronized for safety. 👉 Atomic for performance 👉LongAdder for scalability #Java #Multithreading #Concurrency #CoreJava #InterviewPrep
To view or add a comment, sign in
-
-
I spent my first 2 years writing Java the hard way. Verbose. Fragile. Full of boilerplate I didn't need. Then I discovered these 5 features — and I've never looked back. If you're a Java developer, save this post. 🔖 --- 1. Optional — stop pretending null doesn't exist How many NullPointerExceptions have you chased at midnight? I lost count. Then I started using Optional properly. Before: String city = user.getAddress().getCity(); // NPE waiting to happen After: Optional.ofNullable(user) .map(User::getAddress) .map(Address::getCity) .orElse("Unknown"); Clean. Safe. Readable. No more defensive if-null pyramids. --- 2. Stream API — ditch the for-loops I used to write 15-line loops to filter and transform lists. Streams cut that to 2 lines — and made the intent crystal clear. Before: List<String> result = new ArrayList<>(); for (User u : users) { if (u.isActive()) result.add(u.getName()); } After: List<String> result = users.stream() .filter(User::isActive) .map(User::getName) .collect(toList()); Once you think in streams, you can't go back. --- 3. Records — goodbye boilerplate data classes How many times have you written a POJO with getters, setters, equals, hashCode, and toString? Java Records (Java 16+) killed all of that in one line. Before (~50 lines): public class User { private String name; private String email; // getters, setters, equals, hashCode, toString... 😩 } After (1 line): public record User(String name, String email) {} Your DTOs and value objects will thank you. --- 4. var — let the compiler do the obvious work I was skeptical at first. Felt "un-Java-like." But for local variables, var makes code dramatically less noisy. Before: HashMap<String, List<Order>> map = new HashMap<String, List<Order>>(); After: var map = new HashMap<String, List<Order>>(); Still strongly typed. Just less noise. Use it for local scope — not method signatures. --- 5. CompletableFuture — async without the headache Threading used to terrify me. CompletableFuture changed that. Chain async tasks, handle errors, combine results — all without callback hell. CompletableFuture.supplyAsync(() -> fetchUser(id)) .thenApply(user -> enrichWithOrders(user)) .thenAccept(result -> sendResponse(result)) .exceptionally(ex -> handleError(ex)); Readable async Java. Yes, it's possible. --- I wasted months writing verbose, fragile code because nobody told me these existed. Now you have no excuse. 😄 Which of these changed your code the most? Drop a number (1–5) in the comments 👇 — I read every one. #Java #SoftwareEngineering #FullStackDeveloper #CleanCode #SpringBoot #CodingTips
To view or add a comment, sign in
-
Here are some tricky Java fundamental questions 🔹 Primitive Data Types & Variables Why is Java called a statically typed language? How is it different from a strongly typed language? Why can variable names start only with $, _, or letters? Why not digits or symbols like @? 🔹 Type Promotion & Casting What is type promotion in Java? Why does this fail? byte a = 10; byte b = 20; byte c = a + b; 👉 Why is byte + byte automatically converted to int? Why does this work? int x = 10; long y = x; But this doesn’t: long x = 10; int y = x; What are the limitations of downcasting? When does data loss happen? 🔹 Static Concepts When are static variables initialized in Java? When does a static block execute? Can it run multiple times? 🔹 Floating Point (Most misunderstood topic) How are float and double stored in memory? Why don’t we use float much in real-world applications? Why does this happen? float a = 0.1f; float b = 0.2f; System.out.println(a + b); Why does 0.7f print as 0.699999... internally? What does System.out.printf("%.2f", 0.7f); actually do? Does double completely fix floating-point precision issues? 🔹 BigDecimal & Precision How does BigDecimal handle precision differently from float/double? Why is this bad? new BigDecimal(0.1) and why is this correct? new BigDecimal("0.1") If BigDecimal is perfect, why don’t we use it everywhere? 🔹 BigInteger & Overflow When do we use BigInteger instead of long? What happens when a number exceeds long range? 🔹 Bonus Core Concepts What happens when primitives overflow? Where are primitives stored: stack or heap? What is the default value of primitive variables vs local variables? Is Java truly pass-by-value even for primitives? 🔥 Critical Understanding Question 👉 Why does Java convert byte + byte into int automatically? Because in Java, any arithmetic on byte/short/char is internally promoted to int for performance and safety, so operations are done at a CPU-efficient level and then must be explicitly narrowed back if needed. #Java #JavaBasics #Programming #CodingInterview #SoftwareEngineering #Developers #ComputerScience #FloatingPoint #BigDecimal #CoreJava
To view or add a comment, sign in
-
🛑 #Stop blindly using ArrayList<T>() and understand why ConcurrentModificationException is your friend. As Java developers, we use the Collection Framework daily. But we rarely stop to consider how it actually works under the hood—and that affects performance. Choosing the right structure—like ArrayList versus LinkedList—impacts your application’s speed and memory usage. This diagram visualizes how Java manages that data internally. Let’s break it down using real code: 1. ArrayList and the Cost of Dynamic Resizing ArrayList is excellent for random access, but it has to manage an underlying array. When it reaches capacity, Java must create a new, larger array and copy all the data over—an O(n) operation. The diagram shows: ArrayList -> Check Capacity -> Dynamic Resize -> MEMORY (Heap) How it looks in Java: import java.util.ArrayList; import java.lang.reflect.Field; public class ArrayListResizingDemo { public static void main(String[] args) throws Exception { // We initialize with a specific size. ArrayList<String> list = new ArrayList<>(5); System.out.println("1. New ArrayList created with capacity 5."); checkInternalCapacity(list); // Fill it up. The internal array size (5) matches the element count (5). System.out.println("\n2. Filling up capacity..."); for (int i = 0; i < 5; i++) { list.add("Element " + (i + 1)); } checkInternalCapacity(list); // The next addition triggers "Dynamic Resize." System.out.println("\n3. Adding the 6th element (triggers dynamic resize)..."); list.add("Element 6"); // The underlying array has now grown (~50%). checkInternalCapacity(list); } /** Helper function (uses Reflection, not for production!). */ private static void checkInternalCapacity(ArrayList<?> list) throws Exception { Field dataField = ArrayList.class.getDeclaredField("elementData"); dataField.setAccessible(true); Object[] internalArray = (Object[]) dataField.get(list); System.out.println(" --> Current internal array size: " + internalArray.length); System.out.println(" --> Number of actual elements stored: " + list.size()); } } #java #springboot
To view or add a comment, sign in
-
-
When was the last time you paused before typing CompletableFuture in a Spring controller and asked yourself: why exactly is this needed here? I’m not talking about legacy projects where this pattern emerged back in the Java 8 era and persists through sheer inertia—that's understandable; history is history. I’m talking about the new code we’re writing in 2026, knowing what we know about virtual threads, already running Spring Boot 3.2+ with spring.threads.virtual.enabled=true, and realizing that the world has shifted. If we’re being honest, CompletableFuture in a controller wasn't born out of a desire for elegance—it was an engineering compromise made when OS threads were expensive, the Tomcat thread pool was a limited resource, and the only way to avoid blocking it during I/O was to retreat into callback-driven asynchrony. We did this even at the cost of unreadable thenApply → thenCompose → exceptionally chains and the manual plumbing of MDC and SecurityContext between threads. But what happens to that compromise when its original premise is no longer true? Ron Pressler, tech lead of Project Loom at Oracle, answered this directly: with virtual threads, calling .get() on a Future becomes a practically free operation because the virtual thread simply parks without holding onto an OS thread. Consequently, the motivation to write complex asynchronous chains instead of simple sequential code disappears. The Spring team went even further in their blog, asking an uncomfortable question: if the entire request-handling process now lives on a virtual thread, why do we even need the asynchronous Servlet API, which was designed specifically to free up server threads? That said, I’m not sure the answer is black and white—and that’s what interests me. There is still a scenario where CompletableFuture in a controller feels justified: the parallel aggregation of several independent calls. Using allOf(fetchUser(), fetchOrders(), fetchRecommendations()) gives you a declarative composition that is hard to express as cleanly in synchronous code even with virtual threads—especially while StructuredTaskScope remains in preview. On the flip side, if your project is already on Java 21+ with virtual threads enabled, wrapping a standard I/O call in CompletableFuture.supplyAsync() is ceremony for ceremony's sake. It adds complexity to stack traces and forces manual context management where things used to just work. So, where is the line between a conscious tool and a pattern we reproduce out of habit because "that's how it's done"? Tell me—in your production environment, is CompletableFuture in controllers an active choice or a historical given? And if it's a choice, what is the objective?
To view or add a comment, sign in
-
𝗜'𝘃𝗲 𝗯𝗲𝗲𝗻 𝘄𝗿𝗶𝘁𝗶𝗻𝗴 𝗝𝗮𝘃𝗮 𝗳𝗼𝗿 𝗮 𝘄𝗵𝗶𝗹𝗲 𝗻𝗼𝘄 — 𝗮𝗻𝗱 𝗜 𝘀𝘁𝗶𝗹𝗹 𝗰𝗼𝗺𝗲 𝗮𝗰𝗿𝗼𝘀𝘀 𝗸𝗲𝘆𝘄𝗼𝗿𝗱𝘀 𝗜 𝗻𝗲𝘃𝗲𝗿 𝗳𝘂𝗹𝗹𝘆 𝘂𝗻𝗱𝗲𝗿𝘀𝘁𝗼𝗼𝗱. Turns out Java has 67 reserved keywords. Most of us use ~20 in our daily code. Here's what the rest actually do. 𝗖𝗮𝘁𝗲𝗴𝗼𝗿𝘆 𝟭 — Data Types (11) byte · short · int · long · float · double · char · boolean · void · var · enum var (Java 10) enables local type inference. enum values are full objects under the hood — not just constants. 𝗖𝗮𝘁𝗲𝗴𝗼𝗿𝘆 𝟮 — Control Flow (13) if · else · switch · case · default · yield · for · while · do · break · continue · return · when yield (Java 13) returns a value from a switch expression. when (Java 21) is a pattern matching guard — case Integer i when i > 0. 𝗖𝗮𝘁𝗲𝗴𝗼𝗿𝘆 𝟯 — Modifiers (10) public · protected · private · static · final · abstract · synchronized · transient · volatile · native volatile forces reads from main memory, not thread cache. transient skips fields during serialization. native calls JNI-based C/C++ code. 𝗖𝗮𝘁𝗲𝗴𝗼𝗿𝘆 𝟰 — Exception Handling (6) try · catch · finally · throw · throws · assert assert validates assumptions in dev. Enable with -ea JVM flag. Never use it for production logic. 𝗖𝗮𝘁𝗲𝗴𝗼𝗿𝘆 𝟱 — Class & Module (18) class · interface · extends · implements · package · import · sealed · non-sealed · permits · record · module · exports · requires · opens · uses · provides · with · to sealed (Java 17) restricts subclassing. record (Java 16) eliminates boilerplate — auto-generates constructors, getters, equals(), hashCode(). Module keywords power JPMS (Java 9). 𝗖𝗮𝘁𝗲𝗴𝗼𝗿𝘆 𝟲 — Object Reference (4) new · instanceof · super · this instanceof now supports pattern matching (Java 16) — no explicit cast needed. 𝗖𝗮𝘁𝗲𝗴𝗼𝗿𝘆 𝟳 — Literals (3) true · false · null null is not an object — it's the absence of a reference. Still a top cause of NullPointerException in production. 𝗖𝗮𝘁𝗲𝗴𝗼𝗿𝘆 𝟴 — Unused & Obsolete (4) goto · const · strictfp · _ Reserved but non-functional. strictfp is a no-op since Java 17. _ is illegal as an identifier from Java 21+. Java's keyword list grows every LTS release. yield, record, sealed, when — all added in the last few years. Not tracking Java releases = working with an incomplete language. A special thanks to Syed Zabi Ulla sir at PW Institute of Innovation for their clear explanations and continuous guidance throughout this topic. Which category is most underused in your day-to-day Java code? #Java #JavaDeveloper #CoreJava #Programming #SoftwareDevelopment #BackendDevelopment #LearnJava
To view or add a comment, sign in
-
Day 5: #Java #Coding #Array 👉 yesterday I posted the question. today I will post the answer 👉 This line imports the Scanner class. Scanner is used to take input from the user 👉 Declares your class name. Java program always runs inside a class. 👉 This isthe starting point of execution. JVM starts running your program from here. 👉Creates a Scanner object. System.in → means input comes from keyboard. 👉 Prints message to user. Takes input (size of array). Example: if user enters 5, array size = 5. 👉 Creates an integer array a. Size is decided by user. 👉 Loop runs from 0 to size-1. Stores user input into array. 👉 step 1: Count Unique Elements int count=0; 🔸 Outer loop → picks each element. for(int i = 0; i < a.length; i++) 🔸 Assume element is not duplicate. boolean ispresent = false; 🔸 Inner loop → checks previous elements only. for(int k = 0; k < i; k++) 🔸 If current element already appeared before → duplicate. Set ispresent = true and stop checking. if(a[i] == a[k]) ispresent = true; break; 🔸 If element is not duplicate, increase count. if(!ispresent) count++; 🔸. New array b stores only unique values. index tracks position in array b. int[] b = new int[count]; int index = 0; 🔸Outer Loop This loop runs from 0 to last index of array a. i represents the current element index. for(int i = 0; i < a.length; i++) 🔸Initialize Flag Assume current element is not duplicate. This variable checks: 👉 “Is this element already seen before boolean ispresent = false; 🔸Inner Loop for(int k = 0; k < i; k++) This loop checks only previous elements. k runs from 0 to i-1. 🔸 Compare Elements if(a[i] == a[k]) Compare current element a[i] with previous element a[k]. 🔸 Duplicate Found ispresent = true; break; If match found: Mark ispresent = true (duplicate exists) break → stop checking further (no need) 🔸 Check if Unique if(!ispresent) ! means NOT So this means: 👉 “If element is NOT present before (unique)” 🔸 Store Unique Element b[index] = a[i]; Store the unique element into new array b. 🔸 Move Index index++; Move to next position in array b.
To view or add a comment, sign in
Explore related topics
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
Nice examples, SOLID really becomes clear when you see how it improves real code structure and scalability