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
Creating Threads in Java: Extending Thread or Implementing Runnable
More Relevant Posts
-
Day 16 — #100DaysJava today I learned Stream API in Java. And honestly, this one changed how I write code. ☕ Before streams, I used to write for loops for everything. Filter this, transform that, add them up. Five lines of code for something simple. Streams do the same thing in one line. Clean, readable, powerful. Here is what clicked for me today — saving this for anyone learning Java --- What is a Stream? A Stream is a pipeline. You take data, pass it through a series of operations, and get a result at the end. You are not changing the original data. You are just processing it. Think of it like a factory assembly line. Raw material goes in. Each station does one job. Final product comes out. --- The three operations I practiced today: filter() — keep only the elements that match a condition. I used it to get only even numbers from an array. Arrays.stream(arr).filter(n -> n % 2 == 0) map() — transform every element. I used it to double every number in the array. Arrays.stream(arr).map(n -> n * 2) reduce() — combine everything into one result. I used it to calculate the sum of all numbers. Arrays.stream(arr).reduce(0, (a, b) -> a + b) --- One thing that confused me first — boxed(). When you have an int array, Java creates an IntStream not a Stream of Integer objects. boxed() converts it from primitive int to Integer object so you can collect it into a List. IntStream → boxed() → Stream of Integer → collect to List Once I understood that, everything made sense. --- collect(Collectors.toList()) is how you end the stream and get your result back as a List. The stream itself does not store data — it just processes it. collect() is what actually creates the final collection. --- The real power of Streams — you can chain all of this together. Filter the evens, double them, collect into a list. One line. No loop. No temporary variables. This is exactly how modern Java code looks in real companies. --- 16 days in. Every day something new clicks. 💪 Day 1 ...................................... Day 16 Are you using Streams in your daily Java work? What is the most useful stream operation you use? Drop it below! 🙏 #Java #StreamAPI #FunctionalProgramming #100DaysOfJava #JavaDeveloper #LearningInPublic #BackendDevelopment #100DaysOfCode #CleanCode #ModernJava
To view or add a comment, sign in
-
🚀 Mastering Java Exception Handling & Propagation! 🚀 Today was an intensive deep dive into how Java manages those "unusual events" that occur during runtime—Exceptions. Here’s a breakdown of what I learned about keeping programs running smoothly instead of letting them crash abruptly! 💡 What is an Exception? An Exception is an unusual event that occurs during a program's runtime, often due to faulty user input, which leads to abrupt termination. Our goal as developers is to handle these gracefully to ensure normal termination. 🔍 3 Ways to Get Exception Information: When an exception object is generated, we have three main ways to see what went wrong: 1) Printing the Reference (e): Provides the Type of exception and the Reason (Description). This works because the toString method is overridden in the Exception class. 2) e.getMessage(): Provides only the Reason/Description why the exception occurred. 3) e.printStackTrace(): The "complete description." It shows the Type, the Reason, and the exact Location (method and line number) where it occurred. 🌊 Exception Propagation If an exception isn't handled where it occurs, it propagates (travels) up the call stack to the caller method. If no one handles it, the Default Exception Handler takes over, printing the error and abruptly terminating the program. 🛠️ The 3 Strategies for Handling: The sources identify three primary ways to manage these situations: ✅ Try-Catch: Handling it directly at the source. This is considered the best practice. 🔄 Rethrowing: Catching the exception, performing some action, and then using the throw keyword to pass it back to the caller. 🦆 Ducking: "Escaping" or dodging the exception. You don't use a try-catch block; instead, you use the throws keyword in the method signature to warn the caller they must handle it. 💻 Coding Example: The Power of finally One of the most important keywords is finally. This block compulsory executes whether an exception is thrown or not—perfect for closing connections!. public class ExceptionDemo { // Ducking the exception using 'throws' public void calculate() throws ArithmeticException { try { int a = 100, b = 0; int c = a / b; // Risky code! System.out.println("Result: " + c); } catch (ArithmeticException e) { System.out.println("Reason: " + e.getMessage()); throw e; // Rethrowing the exception object reference } finally { // This ALWAYS runs, ensuring normal cleanup System.out.println("Connection Terminated Safely."); } } } 🗝️ Key Takeaway Polymorphism is at the heart of this! Since Exception is the parent class of all exceptions, a parent reference can catch any child exception object (loose coupling). #Java #Coding #BackendDevelopment #ExceptionHandling #ProgrammingTips #LearningJourney #TapAcademy #HarshitT
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
-
🚀 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
-
🚀 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
-
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
-
-
#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
-
☕ Core JAVA Notes — Complete Study Guide 📖 About the Document A thorough, beginner-to-intermediate Core Java study guide spanning 130 pages, packed with clear explanations, syntax breakdowns, real code examples, and comparison tables. Scanned and formatted for students and aspiring Java developers. 🚀 🏗️ What's Inside? 🔷 Chapter 1 — Java Introduction ➤ What is Java? — A high-level, object-oriented, platform-independent language by Sun Microsystems (now Oracle), born in 1995 ➤ The legendary "Write Once, Run Anywhere" (WORA) principle powered by the JVM ➤ Key features: Platform Independence, OOP, Robustness, Multithreading, Rich Standard Library ➤ Where Java is used: Web Development, Mobile Apps (Android), Enterprise Systems ➤ First program: Hello, World! 👋 🔶 Chapter 2 — OOP Concepts (Object-Oriented Programming) ➤ Classes & Objects — Blueprints and instances of real-world entities ➤ POJO (Plain Old Java Object) — private fields, constructors, getters/setters, toString/hashCode ➤ Constructors — Default, Parameterized, this() and super() keywords ➤ Inheritance — extends keyword, parent-child relationships, super calls ➤ Polymorphism — Method Overloading & Overriding ➤ Abstraction — Abstract classes & Interfaces ➤ Encapsulation — Access modifiers: public, private, protected 🟡 Chapter 3 — Core Language Features ➤ Data Types, Variables, Operators, Control Statements (if, switch, loops) ➤ Arrays — single/multi-dimensional, iteration patterns ➤ Exception Handling — try, catch, finally, throws, custom exceptions 🟢 Chapter 4 — String Handling ➤ String class — immutable, pool concept ➤ Key methods: length(), charAt(), substring(), equals(), compareTo(), replace() ➤ StringBuilder — mutable, faster, single-threaded environments ➤ StringBuffer — mutable, thread-safe for concurrent modifications 🔵 Chapter 5 — Collections Framework ➤ ArrayList vs Array — dynamic sizing, java.util.ArrayList ➤ List, Set, Map interfaces — HashMap, HashSet, LinkedList ➤ Iterating with for, for-each, and Iterator ➤ Java Collections = store & manipulate groups of objects efficiently 📦 #CoreJava #Java #JavaProgramming #OOPConcepts #LearnJava #JavaForBeginners #ObjectOrientedProgramming #JVM #WORA #JavaCollections #StringHandling #StringBuilder #Inheritance #Polymorphism #Encapsulation #Abstraction #LambdaExpressions #AnonymousClass #Multithreading #JavaInterviewPrep #PlacementPreparation #ComputerScience #CodingNotes #ProgrammingLanguage #SoftwareDevelopment #JavaDeveloper #BackendDevelopment #TechNotes #StudyMaterial #CodeWithJava
To view or add a comment, sign in
-
🚀 Day 38 – Deep Dive into Java Multithreading Today I learned about Class Lock and Object Lock in Java synchronization 🔐 🔹 Object Lock (Instance Level Lock) I understood that object lock is applied to instance methods. Each object has its own lock, so multiple threads can access different objects simultaneously without waiting. This improves concurrency when working with multiple instances. 🔹 Class Lock (Class Level Lock) Class lock is applied to static methods. Here, the lock is on the class itself, meaning only one thread can execute the synchronized static method, regardless of how many objects are created. This ensures strict control over shared static data. 💡 Key Difference: Object Lock → Works on individual objects (more parallelism) Class Lock → Works on the entire class (more control & safety) 📌 Key Takeaway: Understanding when to use class-level vs object-level locking helps in designing efficient and thread-safe applications. #Java #Multithreading #Synchronization #LearningJ🚀 Day 38 – Deep Dive into Java Multithreading Today I learned about Class Lock and Object Lock in Java synchronization 🔐 🔹 Object Lock (Instance Level Lock) I understood that object lock is applied to instance methods. Each object has its own lock, so multiple threads can access different objects simultaneously without waiting. This improves concurrency when working with multiple instances. 🔹 Class Lock (Class Level Lock) Class lock is applied to static methods. Here, the lock is on the class itself, meaning only one thread can execute the synchronized static method, regardless of how many objects are created. This ensures strict control over shared static data. 💡 Key Difference: Object Lock → Works on individual objects (more parallelism) Class Lock → Works on the entire class (more control & safety) 📌 Key Takeaway: Understanding when to use class-level vs object-level locking helps in designing efficient and thread-safe applications. #Java #Multithreading #Synchronization #LearningJo🚀 Day 38 – Deep Dive into Java Multithreading Today I learned about Class Lock and Object Lock in Java synchronization 🔐 🔹 Object Lock (Instance Level Lock) I understood that object lock is applied to instance methods. Each object has its own lock, so multiple threads can access different objects simultaneously without waiting. This improves concurrency when working with multiple instances. 🔹 Class Lock (Class Level Lock) Class lock is applied to static methods. Here, the lock is on the class itself, meaning only one thread can execute the synchronized static method, regardless of how many objects are created. This ensures strict control over shared static data. #Java #Multithreading #Synchronization #LearningJourney #Programming #Day38
To view or add a comment, sign in
-
-
🚀 Exploring Emojis in Java 21 – Complete Guide with Examples! 😄🔥 Did you know that emojis in Java are handled using Unicode code points? Even in Java 21, there is no direct API like isEmoji(), but we can still work with emojis effectively using built-in features. Here’s a complete set of practical programs you can use 👇 💡 1. Print Emoji from Unicode Code Point public class EmojiFromCode { public static void main(String[] args) { int codePoint = 0x1F604; // 😄 String emoji = new String(Character.toChars(codePoint)); System.out.println("Emoji: " + emoji); } } 💡 2. Print Multiple Emojis public class MultipleEmoji { public static void main(String[] args) { int[] codePoints = {0x1F525, 0x1F680, 0x1F44D}; for (int cp : codePoints) { System.out.print(new String(Character.toChars(cp)) + " "); } } } 💡 3. Get Unicode from Emoji (Reverse) public class EmojiToCode { public static void main(String[] args) { String emoji = "😄"; int codePoint = emoji.codePointAt(0); System.out.println("Unicode: U+" + Integer.toHexString(codePoint).toUpperCase()); } } 💡 4. Print All Code Points in a String public class EmojiString { public static void main(String[] args) { String text = "Hello 🔥😄"; text.codePoints().forEach(cp -> System.out.println("U+" + Integer.toHexString(cp).toUpperCase()) ); } } 💡 5. Detect Emoji in a String (Custom Logic) public class EmojiDetector { public static boolean containsEmoji(String text) { return text.codePoints() .anyMatch(cp -> cp >= 0x1F600 && cp <= 0x1F64F); } public static void main(String[] args) { String messageWithEmoji = "Hello Java 21! 😄"; String messageWithoutEmoji = "Hello Java!"; System.out.println(containsEmoji(messageWithEmoji)); // true System.out.println(containsEmoji(messageWithoutEmoji)); // false } } 💡 6. JUnit Test for Emoji Detection import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; public class EmojiTest { boolean containsEmoji(String text) { return text.codePoints() .anyMatch(cp -> cp >= 0x1F600 && cp <= 0x1F64F); } @Test void testEmoji() { String messageWithEmoji = "Hello Java 21! 😄"; String messageWithoutEmoji = "Hello Java!"; assertTrue(containsEmoji(messageWithEmoji)); assertFalse(containsEmoji(messageWithoutEmoji)); } } 🔍 Key Takeaways: ✔ Emojis are Unicode characters (code points) ✔ Use codePoints() instead of charAt() ✔ Convert Unicode → Emoji using Character.toChars() ✔ Java doesn’t provide direct emoji detection (custom logic needed) ✔ Great concept for interviews & teaching Core Java #Java21 #CoreJava #Unicode #Programming #Developers #JavaLearning #CodingTips #JUnit
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