#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
Java Thread Creation Using Runnable and Extending Thread Class
More Relevant Posts
-
🤔 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
-
-
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
-
𝑫𝒊𝒇𝒇𝒆𝒓𝒆𝒏𝒄𝒆 𝒃𝒆𝒕𝒘𝒆𝒆𝒏 "𝒕𝒉𝒓𝒐𝒘" 𝒂𝒏𝒅 "𝒕𝒉𝒓𝒐𝒘𝒔" 𝒊𝒏 𝑱𝒂𝒗𝒂 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
-
Day 65 of Sharing What I’ve Learned 🚀 Creating Threads in Java — Turning Concepts into Execution After building a clear understanding of programs, processes, and threads, the next step was to move from theory to practice — how threads are actually created and used in Java. Understanding what a thread is is important. But knowing how to create and control it is where things start getting real. 🔹 Two Ways to Create Threads in Java Java provides two primary ways to create threads: 1️⃣ Extending the Thread class Here, we create a class that extends Thread and override the run() method. class MyThread extends Thread { public void run() { System.out.println("Thread is running..."); } } public class Main { public static void main(String[] args) { MyThread t1 = new MyThread(); t1.start(); // starts a new thread } } 👉 start() is important — it creates a new thread and calls run() internally. 2️⃣ Implementing the Runnable interface This is the more flexible and commonly used approach. class MyRunnable implements Runnable { public void run() { System.out.println("Thread using Runnable..."); } } public class Main { public static void main(String[] args) { Thread t1 = new Thread(new MyRunnable()); t1.start(); } } 👉 This approach is preferred because Java doesn’t support multiple inheritance, but it allows implementing multiple interfaces. 🔹 Key Difference Thread → Direct but less flexible Runnable → More scalable and widely used in real-world applications 🔹 Important Observation Creating a thread is not just about writing run() 👉 It’s about understanding how execution flow changes run() → normal method call (no new thread) start() → creates a new thread (parallel execution) 🔹 Simple Perspective Thread creation = defining a task start() = actually running it concurrently 🔹 Why This Matters This is where applications start becoming powerful: 👉 Multiple tasks can run independently 👉 Better performance and responsiveness 👉 Foundation for advanced concepts like thread synchronization and concurrency 🔹 My Realization Earlier, execution felt linear — one step after another. Now it’s clear that: 👉 Execution doesn’t have to wait 👉 Tasks can run side by side 👉 Efficiency comes from how we structure execution This is just the next layer — Up next: controlling threads and managing their lifecycle. #Java #Multithreading #Programming #JavaDeveloper #100DaysOfCode #DeveloperJourney #Day65 Grateful for guidance from TAP Academy Sharath R kshitij kenganavar
To view or add a comment, sign in
-
-
...........🅾🅾🅿🆂 !!! 𝑷𝒍𝒂𝒕𝒇𝒐𝒓𝒎 卩卂尺 𝑺𝒊𝒎𝒓𝒂𝒏 𝙎𝙚 𝕄𝕦𝕝𝕒𝕜𝕒𝕥 🅷🆄🅸, but 🆁🅾🅱🆄🆂🆃 𝔸𝕣𝕦𝕟 nikla D͓̽i͓̽l͓̽ ka 🅳🆈🅽🅰🅼🅸🅲......!!!.............. Guys you must be wondering, what nonsense things am I writing...."kuch shaayar likhna hai toa kaahi aur likh, linkedin pe kiyu"??? But guess what.....the above phrase represents features of java: 🅾🅾🅿🆂:- 𝗢𝗯𝗷𝗲𝗰𝘁 𝗢𝗿𝗶𝗲𝗻𝘁𝗲𝗱 𝗣𝗿𝗼𝗴𝗿𝗮𝗺𝗺𝗶𝗻𝗴 ....'S' is just a connect letter...don't consider it... 𝑷𝒍𝒂𝒕𝒇𝒐𝒓𝒎:- 𝗣𝗹𝗮𝘁𝗳𝗼𝗿𝗺 𝗶𝗻𝗱𝗲𝗽𝗲𝗻𝗱𝗲𝗻𝘁.....java apps doesn't need to be recoded if you change the operating system😇😇😇 卩卂尺:- the word "par" sounds similiar to "por" and you can then call it 𝗣𝗼𝗿𝘁𝗮𝗯𝗹𝗲...Definitely platform independence makes java portable 𝑺𝒊𝒎𝒓𝒂𝒏:- Either you can say Simran sounds similiar to simple, hence 𝗦𝗶𝗺𝗽𝗹𝗲 is another feature....or say Simran is a very 𝗦𝗶𝗺𝗽𝗹𝗲 girl... 𝕄𝕦𝕝𝕒𝕜𝕒𝕥:- To say Mulakat, you need to say "Mul"...and at the end you are also using a "t"......guess it guess it.....yes it is 𝑴𝒖𝒍𝒕𝒊 𝑻𝒉𝒓𝒆𝒂𝒅𝒊𝒏𝒈....you will love smaller tasks in your programs into individual threads and then executing them concurrently to save your time.... 🅷🆄🅸:- doesn't "Hui" sound almost similiar to "high" I know there is a lot difference but say you are requiring same energy....just you can say "Hui" se 𝙃𝙞𝙜𝙝 𝙋𝙚𝙧𝙛𝙤𝙧𝙢𝙖𝙣𝙘𝙚.....ofcourse java gives a High level of performance as it is 𝑱𝒖𝒔𝒕 𝒊𝒏 𝒕𝒊𝒎𝒆 𝒄𝒐𝒎𝒑𝒊𝒍𝒆𝒅.... 🆁🅾🅱🆄🆂🆃:- Yes ofcourse java is 𝗥𝗼𝗯𝘂𝘀𝘁 because of its strong memory management..... 𝔸𝕣𝕦𝕟:- Arun contains "A" and "N".....Arun se 𝘼𝙧𝙘𝙝𝙞𝙩𝙚𝙘𝙩𝙪𝙧𝙖𝙡 𝙉𝙚𝙪𝙩𝙧𝙖𝙡....right??? Size of all data types in java is same for both 32 bit compiler as well as 64 bit compiler D͓̽i͓̽l͓̽ :- "Dil" had "DI" and "DI" se 𝗗𝗶𝘀𝘁𝗿𝗶𝗯𝘂𝘁𝗲𝗱...java Applications can be distributed and run at the same time on diff computers in same network 🅳🆈🅽🅰🅼🅸🅲:- Yes Java is also 𝗗𝘆𝗻𝗮𝗺𝗶𝗰 due to it's Dynamic class loading feature.... Just repeat the above phrase 2 to 3 times and you will be ablte to retain all the features of java untill you take your last breath.......100% guarantee....
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
-
📦 Complete Guide to Java Collections Framework (JCF) – From Basics to Advanced I used to think Collections in Java meant just this: 👉 List, Set, Map… and some methods like add(), remove(). But that illusion didn’t last long. The moment I started solving real problems, I got stuck on questions like: - Why is HashMap so fast? - When should I use ArrayList vs LinkedList? - Why does Set not allow duplicates internally? - What actually happens when I store objects in a collection? I realized I wasn’t lacking practice — 👉 I was lacking understanding of how things work internally. --- 📌 What I changed in my learning Instead of jumping between topics, I slowed down and followed a structured approach: ✔️ Step 1: Understand the hierarchy - Collection vs Collections - Interfaces: List, Set, Map - How everything is connected ✔️ Step 2: Focus on one structure at a time I didn’t try to learn everything together: - List → ArrayList vs LinkedList - Set → HashSet vs TreeSet - Map → HashMap vs TreeMap ✔️ Step 3: Learn internals (game changer) This is where clarity came: - How HashMap works (hashing, buckets, collisions) - Why ArrayList is fast for reads but slow for inserts - How Tree structures maintain order ✔️ Step 4: Apply through problems - Removed duplicates using Set - Stored key-value mappings using Map - Optimized data retrieval using the right structure ✔️ Step 5: Connect to real-world usage - Backend systems rely heavily on collections - APIs, caching, data handling — everything uses them - Choosing the wrong structure = performance issues --- 💡 Key Realization Collections are not just “data structures in Java” 👉 They are decision-making tools for writing efficient code --- ✍️ I turned this learning into a structured blog: 👉 Complete Guide to Java Collections Framework (JCF) https://lnkd.in/gYxQwtSh --- 🎯 Why I’m sharing this I’m trying to build a habit of: - learning concepts deeply - understanding internals - and documenting everything publicly If you're preparing for backend roles or learning Java, this might help you move from using collections → to understanding them. --- 💬 Which collection confused you the most when you started? #Java #CoreJava #Collections #DataStructures #BackendDevelopment #SpringBoot #LearningInPublic #SoftwareDevelopment #CodingJourney
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
-
-
🚀 Java’s Game-Changing Update: Virtual Threads in Java 21 Virtual threads have changed the threading game forever. In traditional Java, when you create a platform thread, it blocks stack memory — often up to 1 MB per thread. Whether the thread uses that memory or not, it’s reserved upfront. That’s why platform threads are heavyweight and costly to create. You simply can’t create thousands of them without hitting memory limits. Here’s a quick demonstration: // Platform Threads (Traditional) - This will likely fail with OutOfMemoryError public class PlatformThreadsDemo { public static void main(String[] args) { for (int i = 0; i < 10_000; i++) { Thread.ofPlatform().start(() -> { System.out.println("Hello from platform thread: " + Thread.currentThread()); try { Thread.sleep(10_000); // Blocking operation for 10 seconds } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }); } } } Result? OutOfMemoryError: unable to create native thread (or similar resource limit error) — because each platform thread reserves significant native stack memory upfront. Now, the magic happens with just one small change: // Virtual Threads (Java 21+) - Runs smoothly even with 10,000+ threads public class VirtualThreadsDemo { public static void main(String[] args) { for (int i = 0; i < 10_000; i++) { Thread.ofVirtual().start(() -> { System.out.println("Hello from virtual thread: " + Thread.currentThread()); try { Thread.sleep(10_000); // Blocking operation } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }); } // Optional: Keep main thread alive to see output try { Thread.sleep(11_000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } Result? No error. It runs smoothly. You can easily scale this to 1 million virtual threads on a normal machine. Why it works: Virtual threads are lightweight — they live as regular objects in the Java heap and don’t reserve stack memory upfront. The JVM efficiently mounts/unmounts them on carrier (platform) threads during blocking operations. This makes massive concurrency possible with simple, readable, blocking-style code — perfect for I/O-heavy applications like web servers, microservices, or database calls. Java just leveled up concurrency big time. #Java21 #VirtualThreads #Java #Concurrency #ProjectLoom #SoftwareEngineering #BackendDevelopment #Programming #FullStack #AI #ML
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
-
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