Thread Life Cycle in Java 1. NEW (Thread Created) 👉 Meaning: Thread object is created, but not started yet. Example: Thread t = new Thread(() -> { System.out.println("Running"); }); 📌 State: t.getState(); // NEW 2. RUNNABLE (Ready + Running) 👉 Meaning: Thread is ready to run and may be executing. ⚠️ In Java: RUNNING is part of RUNNABLE OS decides when it runs Example: t.start(); // Goes to RUNNABLE 📌 State: RUNNABLE 3. BLOCKED (Waiting for Lock) 👉 Meaning: Thread is waiting to acquire monitor lock. Example: synchronized(obj) { // other thread holds lock } If lock busy → BLOCKED. 4. WAITING (Waiting Indefinitely) 👉 Meaning: Thread waits until another thread wakes it. Caused by: wait() join() park() Example: obj.wait(); // WAITING 5. TIMED_WAITING (Waiting for Time) 👉 Meaning: Thread waits for a fixed time. Caused by: sleep(1000) wait(1000) join(1000) Example: Thread.sleep(1000); // TIMED_WAITING 6. TERMINATED (Dead) 👉 Meaning: Thread finished execution. Example: run() ends → TERMINATED #Java #Multithreading #interview #sde #interviewpreparation #ThreadLifecycle
Java Thread Lifecycle States Explained
More Relevant Posts
-
🚀 Java Trap: Why "finally" Doesn’t Change the Returned Value 👇 👉 Primitive vs Object Behavior in "finally" 🤔 Looks tricky… but very important to understand. --- 👉 Example 1 (Primitive): public static int test() { int x = 10; try { return x; } finally { x = 20; } } 👉 Output: 10 😲 Why not 20? 💡 Java stores return value before executing "finally" - "x = 10" stored - "finally" runs → changes "x" to 20 - But already stored value (10) is returned --- 👉 Example 2 (Object): public static StringBuilder test() { StringBuilder sb = new StringBuilder("Hello"); try { return sb; } finally { sb.append(" World"); } } 👉 Output: Hello World 😲 Why changed here? 💡 Object reference is returned - Same object is modified in "finally" - So changes are visible --- 🔥 Rule to remember: - Primitive → value copied → no change - Object → reference returned → changes visible --- 💭 Subtle concept… very common interview question. #Java #Programming #Coding #Developers #JavaTips #InterviewPrep 🚀
To view or add a comment, sign in
-
🔥 Day 14: Immutable Class (How String is Immutable in Java) One of the most important concepts in Java — especially for interviews 👇 🔹 What is an Immutable Class? 👉 Definition: An immutable class is a class whose objects cannot be changed once created. 🔹 Example: String String s = "Hello"; s.concat(" World"); System.out.println(s); // Hello (not changed) 👉 Why Because String is immutable 🔹 How String Becomes Immutable? ✔ String class is final (cannot be extended) ✔ Internal data is private & final ✔ No methods modify the original object ✔ Any change creates a new object 🔹 Behind the Scenes String s1 = "Hello"; String s2 = s1.concat(" World"); System.out.println(s1); // Hello System.out.println(s2); // Hello World 👉 s1 remains unchanged 👉 s2 is a new object 🔹 Why Immutability is Important? ✔ Thread-safe (no synchronization needed) ✔ Security (safe for sharing data) ✔ Caching (String Pool optimization) ✔ Reliable & predictable behavior 🔹 How to Create Your Own Immutable Class? ✔ Make class final ✔ Make fields private final ✔ No setters ✔ Initialize via constructor only ✔ Return copies of mutable objects 🔹 Real-Life Analogy 📦 Like a sealed box — once created, you cannot change what’s inside. 💡 Pro Tip: Use immutable objects for better performance and safety in multi-threaded applications. 📌 Final Thought: "Immutability = Safety + Simplicity + Performance" #Java #Immutable #String #Programming #JavaDeveloper #Coding #InterviewPrep #Day14
To view or add a comment, sign in
-
-
Interview Question: What is the Diamond Problem in Java? The Diamond Problem arises in languages that support multiple inheritance, where a class inherits from two classes that both derive from a common superclass. This creates ambiguity when both parent classes define the same method. The question becomes: which method should be used? Java avoids this issue by not supporting multiple inheritance with classes. However, with interfaces and default methods, a similar situation can occur. Example: interface A { default void show() { System.out.println("A"); } } interface B { default void show() { System.out.println("B"); } } class Test implements A, B { public static void main(String[] args){ Test t = new Test(); t.show(); // Compilation error! } } Since both interfaces provide the same method, Java forces the class to override it explicitly. Solution with Specific Interface Call: class Test implements A, B { public void show() { A.super.show(); // calling method from interface A B.super.show(); // calling method from interface B } } 👉 This way, we can explicitly choose or combine behavior from both interfaces. #Java #OOP #InterviewQuestions #BackendDevelopment #Programming
To view or add a comment, sign in
-
-
☕ Java Core Concepts – Interview Question 📌 How is String creation using new() different from a literal? In Java, Strings can be created in two ways, and they behave differently in memory: 🔹 String Literal ("abc") • Stored in the String Pool (inside Heap) • JVM checks if the value already exists • If yes → returns reference of existing object • If no → creates a new object in the pool ✅ Memory efficient (reuses objects) 🔹 Using new Keyword (new String("abc")) • Always creates a new object in Heap memory • Does NOT reuse objects from String Pool ❌ Less memory efficient (creates duplicate objects) 🔹 Example: String s1 = "hello"; String s2 = "hello"; // reuses same object String s3 = new String("hello"); // new object in heap 🔹 Key Difference: ✔ Literal → Reuses existing objects (String Pool) ✔ new → Always creates a new object 💡 In Short: String literals save memory using the String Pool, while new always creates a fresh object, even if the value already exists. 👉For Java Course Details Visit : https://lnkd.in/gwBnvJPR . #Java #CoreJava #String #JavaInterview #Programming #Coding #TechSkills#Ashokit
To view or add a comment, sign in
-
-
⏳ Day 13 – 1 Minute Java Clarity – String Immutability in Java Strings look simple… but there’s something powerful happening behind the scenes 📌 What is String Immutability? In Java, once a String object is created, it cannot be changed. 👉 Instead of modifying the existing string, Java creates a new object. 📌 Example: String str = "Hello"; str.concat(" World"); System.out.println(str); 👉 Output: Hello ❌ (not "Hello World") 💡 Why? Because concat() creates a new object, but we didn’t store it. ✔ Correct way: str = str.concat(" World"); System.out.println(str); // Hello World ✅ 💡 Real-time Example: Think of a username in a system: String username = "user123"; username.toUpperCase(); Even after calling toUpperCase(), the original value stays "user123" unless reassigned. 📌 Why Strings are Immutable? ✔ Security (used in passwords, URLs) ✔ Thread-safe (no synchronization issues) ✔ Performance optimization using String Pool ⚠️ Important: Too many string modifications? Use StringBuilder instead. 💡 Quick Summary ✔ Strings cannot be modified after creation ✔ Operations create new objects ✔ Always reassign if you want changes 🔹 Next Topic → Type casting in Java Have you ever faced issues because of String immutability? 👇 #Java #JavaProgramming #Strings #CoreJava #JavaDeveloper #BackendDeveloper #Coding #Programming #SoftwareEngineering #LearningInPublic #100DaysOfCode #ProgrammingTips #1MinuteJavaClarity
To view or add a comment, sign in
-
-
☕ Java Interview Question 📌 When is ArrayStoreException thrown? ArrayStoreException occurs when you try to store an incompatible data type in an array. 🔹 Why it happens: ✔ Arrays in Java are type-safe at runtime ✔ Storing a different object type than the array’s actual type triggers this exception 🔹 Example Scenario: ✔ Assigning an Integer into an array declared as Double[] ✔ The compiler may allow it (due to polymorphism), but it fails at runtime 🔹 Key Insight: ✔ Happens during runtime, not compile time ✔ Common in cases involving inheritance and object arrays 💡 In Short: ArrayStoreException ensures type safety by preventing invalid object assignments in arrays 🚀 👉For Java Course Details Visit : https://lnkd.in/gwBnvJPR . #Java #CoreJava #ExceptionHandling #Programming #InterviewPreparation #TechLearning #AshokIT
To view or add a comment, sign in
-
-
🚀 Java Basic That Many Ignore: What is String[] args in main()? 🤔 We write this every day: public static void main(String[] args) { System.out.println("Hello"); } 👉 But what exactly is args? 💡 args = Command Line Arguments It is an array of Strings passed when running your program 👉 Example: public class Test { public static void main(String[] args) { System.out.println(args[0]); } } Run this: java Test Hello 👉 Output: Hello 🤯 Important Points: args is just a variable name (you can change it) It is always an array of String It can be empty (no arguments passed) 🔥 Fun Fact: public static void main(String[] xyz) 👉 This also works! 😄 ⚠️ Be careful: System.out.println(args[0]); ❌ If no argument → ArrayIndexOutOfBoundsException 💡 Safe way: if (args.length > 0) { System.out.println(args[0]); } Small concept… but important for interviews & real-world usage 💪 #Java #Programming #Coding #JavaDeveloper #InterviewPrep #Developers
To view or add a comment, sign in
-
💻 String vs StringBuffer vs StringBuilder in Java – Know the Difference! In Java, handling text data is very common. Let’s understand the three important classes: 🔹 1. String ✔ Immutable (cannot be changed once created) ✔ Any modification creates a new object ✔ Safe and widely used Example: "String s = "Hello";" "s = s + " World"; // creates new object" --- 🔹 2. StringBuffer ✔ Mutable (can be changed) ✔ Thread-safe (synchronized) ✔ Slightly slower due to synchronization Example: "StringBuffer sb = new StringBuffer("Hello");" "sb.append(" World");" --- 🔹 3. StringBuilder ✔ Mutable (can be changed) ✔ Not thread-safe ✔ Faster than StringBuffer Example: "StringBuilder sb = new StringBuilder("Hello");" "sb.append(" World");" --- 💡 Key Difference: String = Immutable StringBuffer = Mutable + Thread-safe StringBuilder = Mutable + Faster 🚀 Use String for simple tasks, StringBuffer for multi-threading, and StringBuilder for better performance in single-threaded applications. #FortuneCloudTechnology #Java #Programming #String #JavaBasics #Coding #Developers #Learning
To view or add a comment, sign in
-
Day14 Java Practice: Maximum Product of Three Elements in an Array While practicing Java, I solved an interesting array problem: 👉 Find the maximum product that can be formed using any three elements from the array. Example: Input: {10, 3, 5, 6, -20} At first, it looks like we just need the three largest numbers. But the twist is: negative numbers can change the result! 🧠 Key Idea: The product of two negative numbers becomes positive So we must compare: Product of the three largest numbers Product of two smallest (most negative) numbers and the largest number ================================================= // 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 [] ={10,3,5,6,-20}; Arrays.sort(a); int n=a.length; System.out.println(Arrays.toString(a)); int result1=a[n-1]*a[n-2]*a[n-3]; int result2=a[0]*a[1]*a[n-1]; int result =Math.max(result1,result2); System.out.println(result); } } Output:[-20, 3, 5, 6, 10] 300 #JavaDeveloper #Arrays #CodingPractice #QualityEngineering #TechLearning
To view or add a comment, sign in
-
-
🚀 Java Deep Dive: "try-with-resources" Closing Order (Real Example) 🔥 Most developers know it auto-closes resources… But the ORDER? That’s where interviews get tricky 😏 👉 Real-world example: import java.io.*; public class Main { public static void main(String[] args) throws Exception { try (FileInputStream fis = new FileInputStream("test.txt"); InputStreamReader isr = new InputStreamReader(fis); BufferedReader br = new BufferedReader(isr)) { System.out.println("Reading file..."); } } } 💡 Output: Reading file... (then resources close automatically) 👉 Actual closing order: BufferedReader InputStreamReader FileInputStream Why reverse order? Because Java follows LIFO (Last In, First Out) 👉 Last opened → First closed 🔥 Understand the chain: Open order: FileInputStream → InputStreamReader → BufferedReader Close order: BufferedReader → InputStreamReader → FileInputStream ⚠️ Interview Tip: Always remember dependency: - Outer resource depends on inner ones - So it must close FIRST 💬 One-liner to remember: “Resources open in sequence… but close in reverse.” #Java #JavaInterview #Coding #ExceptionHandling #IO #Programming #Developers #TechTips
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