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.
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
-
🤔 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
-
-
🔹 Java Arrays: Reference vs Clone If you’ve ever seen your original array change unexpectedly… this is why 👇 🧠 1. Arrays are Reference Types int[] nums = {1, 2, 3}; 👉 nums stores a reference (address), not actual data nums ─────► [1, 2, 3] 🔴 2. Assignment copies reference (NOT array) int[] arr2 = nums; nums ─────► [1, 2, 3] arr2 ──────┘ 👉 Both point to SAME array arr2[0] = 99; System.out.println(nums[0]); // 99 ❗ 🔁 3. Method calls modify original array void change(int[] arr) { arr[0] = 50; } change(nums); 👉 Output: nums[0] = 50 Because 👉 same reference is passed 🟢 4. clone() creates a NEW array int[] copy = nums.clone(); nums ─────► [1, 2, 3] copy ─────► [1, 2, 3] 👉 Different objects in memory copy[0] = 99; System.out.println(nums[0]); // 1 ✅ System.out.println(copy[0]); // 99 ⚖️ 5. Same values ≠ Same reference int[] arr1 = {1, 2}; int[] arr2 = {1, 2}; System.out.println(arr1 == arr2); // false ❌ System.out.println(Arrays.equals(arr1, arr2)); // true ✅ arr1 ─────► [1, 2] arr2 ─────► [1, 2] 🔥 6. When are references SAME? int[] arr2 = arr1; System.out.println(arr1 == arr2); // true ✅ 🎯 7. Golden Rules ✔ Array variable = reference, not actual data ✔ = copies reference ✔ clone() creates new array ✔ == → compares reference ✔ Arrays.equals() → compares values 🚀 One-line takeaway 👉 Same values don’t mean same memory. Always clone if you want a safe copy. #Java #Programming #DSA #JavaBasics #CodingInterview #Developers #Learning #TechNotes
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
-
#60DaysOfJava 📚 Day 16 Constructor in Java 🔹 Constructor in Java 👉 Constructor is a special method 👉 Using the constructor we initialize objects at object creation time. 👉 Constructor is called at instance creation time 👉 While constructor is invoked, memory for the object will be allocated. 👉 Constructor doesn’t return anything and we don’t need to mention return type. 👉 abstract, static, final, and synchronized cannot be used with constructor 👉 We can use access modifiers (private, protected, public, default) to control object creation. 🔹 How to Create Constructor Syntax: AccessModifier ClassName() { } 👉 Example: public Employee(String name, double salary) { } 👉 Constructor will be called at object creation time 🔹 Types of Constructor 👉 No Parameterized Constructor 👉 Parameterized Constructor 👉 Copy Constructor 🔹 Example class Employee { String name; double salary; double bonous; 🔹Non parameterized constructor public Employee(){ System.out.println("Constructor called"); } 🔹Parameterized constructor public Employee(String empName,double empSalary){ name = empName; salary = empSalary; } 🔹 Parameterized constructor with different parameter size public Employee(String empName,double empSalary,double empBonous){ name = empName; salary = empSalary; bonous = empBonous; } 🔹 Copy constructor public Employee(Employee employee){ name = employee.name; salary = employee.salary; bonous = employee.bonous; } } 🔹 Notes 👉 Non-parameterized constructor is not mandatory compiler will add it by default 👉 Inside default constructor, values are not initialized explicitly 👉 JVM assigns default values based on data types 👉 Parameterized constructor ➡️ We can overload like normal methods (different type/size) 👉 Copy constructor ➡️ Used to copy values from one object to another ➡️ Not available by default in Java we need to define it 🤵 Follow Hariprasath V for daily more helpful resources. ♻ Repost Others also learn and grow together 👍 Hit if this was helpful. ✅ Save it future use. ================================================ #60DaysOfJavaWithHariprasathv6 #Java #JavaBasics #Programming #Coding #Developers #LearningJava #HighLevelDesign #SystemDesign #DSAChallenge #60DaysOfDSA #ProblemSolving #CodingJourney #Consistency #LearnByDoing #DataStructures #Algorithms #InterviewPrep #KeepCoding #Productivity #Focus #DreamBig #Java #SystemDesign #DataStructures #Algorithms #JavaDeveloper #DSA #CodingInterview #TechInterview #SystemDesignInterview #BackendDevelopment #SoftwareEngineering #JavaInterview #LeetCode #InterviewPrep #DataStructureAndAlgorithms #DesignPatterns #LowLevelDesign #Multithreading #SOLIDPrinciples #RESTAPI #BackendEngineer #CodeInterview #interviewtips #interviewexperience #Java #Programming #CoreJava #Learning #Developers #OOP
To view or add a comment, sign in
-
-
Day 11 ⛰️ Java Practice: Check if an Array is a Mountain Array While practicing Java, I came across an interesting array problem: A Mountain Array means: -> Elements first strictly increase -> Reach a peak -> Then strictly decrease -> And the array length must be greater than 2 Example: {5,7,10,14,12,4,2,1} ✅ Mountain Array To solve this, Instead of using extra variables or collections, I solved it using a single index and two while loops — one for climbing up and one for coming down. This approach keeps the logic simple and efficient. ================================================= // Online Java Compiler // Use this editor to write, compile and run your Java code online import java.util.*; class Main { public static void main(String[] args) { int a[]={5,7,10,14,12,4,2,1}; System.out.println(mountainArrayCheck(a)); } public static boolean mountainArrayCheck(int a []) { //1).Length of the Array must be greater than 2 if(a.length<3) { return false ; } int i=0; //2).Elements must be increasing order !!! while(i+1<a.length && a[i]<a[i+1]) { i++; } //2).When we reached at peack elements must be decreasing order !!! while(i+1<a.length && a[i]>a[i+1]) { i++; } if(a.length-1 ==i) { return true ; } else { return false ; } } } output : true #AutomationTestEngineer #Selenium #Java #InterviewPreparation #CodingPractice
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
-
-
🚀 100 Days Java + DSA Challenge | Day 3 Today I worked on Loops and Functions/Methods in Java. I know these are basic problems, but solving them gave me real hands-on experience with: ✔ How loops actually work step by step ✔ How to design and call methods ✔ Breaking problems into smaller reusable parts ✔ Writing cleaner and more structured code 💻 Problems I solved today: • Print numbers (1 to N, M to N) • Reverse printing • Sum & product of ranges • Factorial • Finding factors and counting factors 📌 Here’s the code I practiced 👇 import java.util.Scanner; public class Day3 { public static void printNumbers(int n) { for(int i = 1; i <= n; i++) { System.out.print(i + " "); } System.out.println(); } public static void printNumRange(int m, int n) { for(int i = m; i <= n; i++) { System.out.print(i + " "); } System.out.println(); } public static void printReverseFromNto1(int n) { for(int i = n; i > 0; i--) { System.out.print(i + " "); } System.out.println(); } public static void printReverseFromNtoM(int m, int n) { for(int i = n; i >= m; i--) { System.out.print(i + " "); } System.out.println(); } public static void sumOfNaturalNumbersFrom1toN(int n) { int sum = 0; for(int i = 1; i <= n; i++) { sum += i; } System.out.println(sum); } public static void factorialOfNumber(int n) { int fact = 1; for(int i = 1; i <= n; i++) { fact *= i; } System.out.println(fact); } public static void sumOfMtoN(int m, int n) { int sum = 0; for(int i = m; i <= n; i++) { sum += i; } System.out.println(sum); } public static void productOfMtoN(int m, int n) { int product = 1; for(int i = m; i <= n; i++) { product *= i; } System.out.println(product); } public static void printFactorsOfNumber(int n) { for(int i = 1; i <= n; i++) { if(n % i == 0) { System.out.print(i + " "); } } } public static void countOfFactors(int n) { int count = 0; for(int i = 1; i <= n; i++) { if(n % i == 0) { count++; } } System.out.println(count); } } These may look simple, but practicing them helped me think in terms of logic, loops, and functions, which is the foundation for solving bigger DSA problems. Day by day, I’m building my problem-solving muscle 💪 #100DaysOfCode #Java #DSA #CodingJourney #Programming #SoftwareDevelopment
To view or add a comment, sign in
-
💡 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
To view or add a comment, sign in
-
-
🚀 Backend Systems | Post - 3 | How to create Threads in JAVA In the last posts, we understood Multithreading, and the difference between Concurrency and Parallelism , now lets learns how do we actually create threads in Java. 1. Extending the Thread Class You can create a thread by having a subclass which extends the Thread class and overriding the run() method. class MyThread extends Thread { @Override public void run() { System.out.println("Hello World"); } } MyThread t1 = new MyThread(); t1.start(); 2. Implementing Runnable Interface (this is usually recommended) This is the most commonly used approach in real-world systems having a class implements the runnable interface and overriding the run method. what is Runnable interface ? It is functional interface which has only one abstract function run. class MyRunnable implements Runnable { @Override public void run() { System.out.println("Hello World"); } } Thread t1 = new Thread(new MyRunnable()); t1.start(); 💡 Why is this better? --> as in java multilevel inheritance isn't possible with classes but possible with interface , since runnable is a interface because of that it allows for multilevel inheritance , this approach is usually better in backend systems. 3. Using Lambda (Modern Java🔥) In modern java we use lambda as a shortcut way to implement a functional interface , since Runnable is also a functional interface , we use this way when this line of code will only be used only by this thread. Thread t1 = new Thread(() -> { System.out.println("Hello World"); }); t1.start(); ⚠️ Common Mistake (VERY IMPORTANT) Most beginners think this will create a thread: Calling run() directly -->This will NOT create a new thread --> It just runs like a normal function call. --> the correct way is to always use start() to create a new thread. 🚀 Key Takeaways --> Runnable is better than Thread for better design. --> Lambda is a clean way to implement Runnable. --> start() creates a thread, run() does not. #Multithreading #Java #OperatingSystem #BackenedSystems
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