Understanding Multithreading in Java 🔹 In this example, I explored two approaches for creating threads: • Extending the Thread class • Implementing the Runnable interface package multithreading; /* 1️⃣ Extending Thread Class When a class extends the Thread class, it becomes a thread class. Objects of this class can run in a separate thread. However, the actual task that the thread executes must be written inside the run() method. When start() is called, the JVM creates a new thread and internally invokes the run() method. */ class CommonResource extends Thread { public void commonResource(String t){ System.out.println("common resources " + t); } @Override synchronized public void run() { String currT = Thread.currentThread().getName(); if(currT.equals("bheem")){ System.out.println("bheem thread"); } else if(currT.equals("kalia")){ System.out.println("kalia thread"); } else{ System.out.println("raju thread"); } try{ Thread.sleep(5000); } catch(Exception e){ e.printStackTrace(); } commonResource(currT); } } /* 2️⃣ Creating a Common Resource using the Runnable interface. Instead of extending Thread, it is generally recommended to implement the Runnable interface. Advantages: • The task is separated from the thread. • The class can still extend another class (Java doesn't support multiple inheritance). • This approach is widely used in industry (especially with thread pools). */ class CommonResource1 implements Runnable { public void commonResource(String t){ System.out.println("common resources " + t); } /* Multiple threads will share the same object of this class. Because the run() method is synchronized, only one thread can execute it at a time for this shared object. */ @Override synchronized public void run() { String currT = Thread.currentThread().getName(); if(currT.equals("bheem")){ System.out.println("bheem thread"); } else if(currT.equals("kalia")){ System.out.println("kalia thread"); } else{ System.out.println("raju thread"); } try{ Thread.sleep(5000); } catch(Exception e){ e.printStackTrace(); } commonResource(currT); } } public class ThreadsUsesCommonResource { public static void main(String[] args){ // Creating a shared resource object CommonResource1 commonResource1 = new CommonResource1(); // Creating multiple threads that use the same resource Thread t1 = new Thread(commonResource1); t1.setName("kalia"); Thread t2 = new Thread(commonResource1); t2.setName("bheem"); Thread t3 = new Thread(commonResource1); t3.setName("raju"); // start() → JVM creates a new thread → run() method executes t1.start(); t2.start(); t3.start(); } } #Java #Multithreading #Synchronized #BackendDevelopment #LearningInPublic
Java Multithreading Approaches: Extending Thread Class vs Implementing Runnable Interface
More Relevant Posts
-
📌 Java 8 Functional Interfaces — Explained with Use Cases Java provides built-in functional interfaces to support lambda expressions and functional programming. Here are the most important ones every Java developer should know: --- 1️⃣ Runnable @FunctionalInterface public interface Runnable { void run(); } ✔ Takes: No input ✔ Returns: Nothing Use Case: • Multithreading tasks Example: Runnable r = () -> System.out.println("Task running"); --- 2️⃣ Callable @FunctionalInterface public interface Callable<V> { V call() throws Exception; } ✔ Takes: No input ✔ Returns: Result Use Case: • Tasks that return values (ExecutorService) Example: Callable<Integer> c = () -> 10; --- 3️⃣ Comparator @FunctionalInterface public interface Comparator<T> { int compare(T o1, T o2); } ✔ Takes: Two inputs ✔ Returns: int Use Case: • Sorting collections Example: list.sort((a, b) -> a - b); --- 4️⃣ Function<T, R> ✔ Takes: One input ✔ Returns: One output Use Case: • Transforming data Example: Function<String, Integer> f = s -> s.length(); --- 5️⃣ Predicate<T> ✔ Takes: One input ✔ Returns: boolean Use Case: • Filtering conditions Example: Predicate<Integer> p = x -> x > 10; --- 6️⃣ Consumer<T> ✔ Takes: One input ✔ Returns: Nothing Use Case: • Performing actions (printing, logging) Example: Consumer<String> c = s -> System.out.println(s); --- 7️⃣ Supplier<T> ✔ Takes: No input ✔ Returns: Value Use Case: • Lazy value generation Example: Supplier<Double> s = () -> Math.random(); --- 🧠 Quick Summary Runnable → No input, no output Callable → No input, returns output Function → Input → Output Predicate → Input → boolean Consumer → Input → action Supplier → No input → output --- 💡 Key Takeaway These interfaces form the backbone of Java 8 features like Streams and Lambdas. Mastering them helps write clean, functional, and expressive code. #Java #Java8 #FunctionalInterfaces #Lambda #BackendDevelopment
To view or add a comment, sign in
-
🚀 Mastering Java Stream API – Write Cleaner, Smarter Code If you're still writing verbose loops in Java, it's time to rethink your approach. The Stream API (introduced in Java 8) is not just a feature—it’s a paradigm shift toward functional-style programming in Java. It allows you to process collections of data in a declarative, concise, and efficient way. 🔍 What is Stream API? A Stream is a sequence of elements that supports various operations to perform computations. Unlike collections, streams: Don’t store data Are immutable (operations don’t modify the source) Support lazy evaluation Enable parallel processing effortlessly ⚙️ Core Concepts 1. Stream Creation List<String> names = Arrays.asList("John", "Jane", "Jack"); Stream<String> stream = names.stream(); 2. Intermediate Operations (Lazy) filter() map() sorted() These return another stream and are not executed until a terminal operation is invoked. names.stream() .filter(name -> name.startsWith("J")) .map(String::toUpperCase); 3. Terminal Operations (Trigger Execution) forEach() collect() count() List<String> result = names.stream() .filter(name -> name.length() > 3) .collect(Collectors.toList()); 💡 Why Use Stream API? ✅ Readable & Declarative Code Focus on what to do, not how to do it ✅ Less Boilerplate Goodbye nested loops ✅ Parallel Processing names.parallelStream().forEach(System.out::println); ✅ Functional Programming Power Lambdas + Streams = Clean pipelines 🔥 Real-World Example Traditional Approach List<String> filtered = new ArrayList<>(); for (String name : names) { if (name.length() > 3) { filtered.add(name.toUpperCase()); } } Stream API Approach List<String> filtered = names.stream() .filter(name -> name.length() > 3) .map(String::toUpperCase) .collect(Collectors.toList()); 👉 Less code. More clarity. Better maintainability. ⚠️ Common Pitfalls Overusing streams can hurt readability Avoid complex nested streams Be cautious with parallel streams (thread-safety matters) 🧠 Pro Tip Think of streams as a data pipeline: Source → Intermediate Operations → Terminal Operation 📌 Final Thoughts The Stream API is a must-have skill for modern Java developers. It helps you write clean, scalable, and expressive code, especially in microservices and data-heavy applications. If you're building backend systems with Java, mastering streams is not optional—it's essential. 💬 How often do you use Stream API in your projects? Any advanced patterns you rely on? #Java #StreamAPI #BackendDevelopment #Java8 #CleanCode #FunctionalProgramming #SoftwareEngineering
To view or add a comment, sign in
-
Day 15 Java Practice: Find Product with Maximum Total Quantity While practicing Java, I worked on a small problem involving strings, arrays, and maps. 👉 Given product data with quantity like: {"xyz 19","abc 30","xyz 21","abc 23"} The goal was to: Sum the quantities for the same product Find which product has the maximum total quantity 🧠 Approach: Split each string to get product name and quantity Store and add quantities using a HashMap Traverse the map to find the maximum value ============================================= // 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) { String a []={"xyz 19","abc 30","xyz 21","abc 23"}; Map<String,Integer>hmap=new HashMap<String,Integer>(); for(String s : a) { String data []=s.split(" "); String name=data[0]; int value=Integer.parseInt(data[1]); hmap.put(name,hmap.getOrDefault(name,0)+value); } int max=0; String result=""; for(Map.Entry<String,Integer>entry:hmap.entrySet()) { if(entry.getValue()>max) { max=entry.getValue(); result=entry.getKey(); } } System.out.println(result+" "+max); } } Output: abc 53 #JavaDeveloper #AutomationEngineer #CodingPractice #Collections #ProblemSolving #Learning
To view or add a comment, sign in
-
-
Standard Signature of main() Method in Java In every programming language there must be an entry point of execution from where program execution begins. In C/C++, the entry point is the main() function, which is invoked by the Operating System. OS expects 0 as exit status indicating successful program execution so the return type of main is commonly int. In Java, the entry point is also the main() method, but it is invoked by the Java Virtual Machine (JVM) instead of the OS. Since the JVM handles execution internally, there is no need to return a status code, therefore the return type of the main method is always void. In Java, every method belongs to a class, so the main method must be defined inside a class. Example: class Main { void main() { // code } } However, this method cannot be executed by the JVM because it is not accessible outside the class. To allow the JVM to access it, the method must be declared public. class Main { public void main() { // code } } In Java, methods normally belong to objects and are invoked using an object reference. If the main method were not static, the JVM would have to create an object of the class before calling it. Since main is the entry point of every program, this would add unnecessary overhead. To allow the JVM to invoke the method without creating an object, the main method is declared static. class Main { public static void main() { // code } } But this method still cannot receive data from the command line arguments. To accept input from the command line during program execution, the main method takes a parameter which is an array of strings. Each element of this array represents one argument passed from the command line. Final standard signature of the main method: class Main { public static void main(String[] args) { // code } } Here: public → allows the JVM to access the method static → allows the JVM to call the method without creating an object void → no return value required String[] args → receives command line arguments However, for a beginner writing "public static void main(String[] args)" is overwhelming. So Java developer decided to introduce simplified syntax for new comer to maintain language acceptance and popularity among all. In newer Java versions, we can write a simpler program like: void main() { System.out.println("Hello"); } Introduced in JDK 21 and finally accepted in JDK 25 (2025). The compiler automatically wraps this into a class behind the scenes. However, this feature is mainly designed for learning and small scripts, while the traditional main method remains the standard approach used in real applications. Grateful to my mentor Syed Zabi Ulla for explaining these concepts so clearly and helping me build a strong foundation in programming. #OOP #Java #Programming #ComputerScience #LearningJourney #SoftwareDevelopment
To view or add a comment, sign in
-
Java 26 just dropped! But most developers have not even adopted Java 21 features yet. Here are 5 modern Java features you should be using every single day. —— 1. Switch Expressions: clean and exhaustive (Java 14+) // Before: verbose, fall-through prone String label; switch (status) { case ACTIVE: label = "Active"; break; case PENDING: label = "Pending"; break; default: label = "Unknown"; } // After: String label = switch (status) { case ACTIVE -> "Active"; case PENDING -> "Pending"; default -> "Unknown"; }; No fall-through bugs. Compiler ensures all cases are handled. —— 2. Text Blocks: readable multiline strings (Java 15+) // Before: String json = "{\n \"name\": \"Alice\",\n \"role\": \"admin\"\n}"; // After: String json = """ { "name": "Alice", "role": "admin" } """; Clean SQL, JSON, HTML — no escape characters. Just readable strings. —— 3. Optional: use it properly (Java 8+, daily practice) // Bad: Optional user = userRepo.findById(id); if (user.isPresent()) { return user.get(); } return null; // Good: return userRepo.findById(id) .orElseThrow(() -> new UserNotFoundException("User not found: " + id)); Optional exists to eliminate null checks — not to wrap them. Never use .get() alone. Always orElseThrow() or orElse(). —— 4. Pattern Matching for Switch: Java 21 flagship (Java 21) // Before: fragile instanceof chain if (obj instanceof Integer i) return "int: " + i; if (obj instanceof String s) return "str: " + s; // After: clean, compiler-verified return switch (obj) { case Integer i -> "int: " + i; case String s -> "str: " + s; default -> "unknown"; }; // Even better with guards: return switch (order) { case Order o when o.isPaid() -> "Paid"; case Order o when o.isPending() -> "Pending"; default -> "Unknown"; }; Replaces entire if-instanceof chains. Safe, readable, exhaustive. —— 5. New String methods: small but mighty (Java 11–17) input.strip(); // Unicode-aware trim() input.isBlank(); // true if empty or whitespace input.repeat(3); // repeats string N times "line1\nline2".lines(); // Stream by line "hello %s".formatted("world"); // cleaner than String.format() No libraries needed. Used constantly. Zero excuses not to. ---------------------------------------------------------------- Java is not the verbose language it used to be. Pick one feature. Use it in your next PR. Then the next one. Java 26 post coming next. Stay tuned! Which one are you already using daily? Drop a number below.. #Java #Java17 #Java21 #BackendDevelopment #SpringBoot #SoftwareEngineering #CleanCode
To view or add a comment, sign in
-
Day 4/30 — Java Journey 🚀 Variables in Java = GAME CHANGER If you don’t understand variables… You don’t understand programming. Period. Most beginners treat variables like “just storage.” That’s the biggest mistake. ❌ Variables are NOT just containers — They are the foundation of how your program *thinks, behaves, and evolves.* Let’s break it down properly 👇 🧠 What is a Variable? A variable is a **named memory location** that stores data which can be used, modified, and manipulated during execution. 👉 In simple terms: It’s how your program *remembers things.* --- 🔥 Why Variables Change Everything 1. Control Data Flow Without variables → no dynamic behavior With variables → your app becomes interactive 2. Enable Logic Conditions, loops, decisions… all depend on variables 3. Power Real Applications User input, calculations, APIs, databases — everything uses variables --- ⚙️ Types of Variables in Java 👉 Based on Data Type: * int → stores integers (e.g., 10) * double → decimal values (e.g., 10.5) * char → single character ('A') * boolean → true/false * String → text ("Hello") 👉 Based on Scope: * Local → inside methods (temporary use) * Instance → tied to objects * Static → shared across all objects --- 💡 Example (Simple but Powerful) int age = 20; Here: * “int” = data type * “age” = variable name * “20” = value stored Now imagine this: 👉 Change age → program output changes 👉 That’s the power of variables --- ⚠️ Beginner Mistakes (Avoid This) ❌ Using wrong data types ❌ Not initializing variables ❌ Confusing scope (local vs global) ❌ Overwriting values unintentionally --- 🧩 Pro Insight (This is where most people fail) Variables are not about syntax… They are about **state management**. If you master variables → You understand how data flows → You understand how systems work. --- 🔥 Final Truth: No variables = No logic No logic = No programming Master this once… Everything else in Java becomes 10x easier. --- 👉 Follow now — every day I break down concepts that actually make you job-ready. #Java #Programming #Coding #Developers #LearnJava #TechSkills #SoftwareEngineering
To view or add a comment, sign in
-
-
Day 49 – Java 2026: Smart, Stable & Still the Future Difference Between Static and Non-Static Initializers in Java In Java, initializer blocks are used to initialize variables during the class loading or object creation phase. There are two types: Static Initializer Non-Static (Instance) Initializer Understanding their difference helps in learning how JVM memory management and class loading work. 1. Static Initializer A static initializer block is used to initialize static variables of a class. It executes only once when the class is loaded into memory by the ClassLoader. class Example { static int a; static { a = 10; System.out.println("Static initializer executed"); } public static void main(String[] args) { System.out.println(a); } } Key idea: It runs once during class loading. 2. Non-Static Initializer A non-static initializer block is used to initialize instance variables. It executes every time an object is created. class Example { int b; { b = 20; System.out.println("Non-static initializer executed"); } Example() { System.out.println("Constructor executed"); } public static void main(String[] args) { new Example(); new Example(); } } Key idea: It runs every time an object is created. 3. Key Differences FeatureStatic InitializerNon-Static InitializerKeywordUses staticNo keywordExecution timeWhen class loadsWhen object is createdRuns how many timesOnce per classEvery object creationVariables initializedStatic variablesInstance variablesMemory areaMethod AreaHeapExecution orderBefore main()Before constructor4. Execution Flow in JVM When a Java program runs: ClassLoader loads the class Static initializer executes main() method starts Object is created Non-static initializer executes Constructor executes Flow: Program Start ↓ Class Loaded ↓ Static Initializer ↓ Main Method ↓ Object Creation ↓ Non-Static Initializer ↓ Constructor Key Insight Static initializer → class-level initialization (runs once) Non-static initializer → object-level initialization (runs every object creation) Understanding these concepts helps developers clearly see how JVM manages class loading, memory, and object initialization. #Java #JavaDeveloper #JVM #OOP #Programming #BackendDevelopment
To view or add a comment, sign in
-
🔹 What is an Immutable Class in Java? In Java, an Immutable Class is a class whose objects cannot be modified once they are created. Once the object state is set during construction, it remains constant for its entire lifetime. A classic example is Java's String class. 📌 Why are Immutable Objects Important? Immutable objects bring several advantages in real-world systems: ✔ Thread Safety – Multiple threads can safely use the same object without synchronization. ✔ Predictability – No accidental state changes. ✔ Performance – JVM can cache and reuse immutable objects (like String Pool). ✔ Security – Sensitive data cannot be modified after creation. This is one of the reasons why many Java core classes are immutable. 📌 How to Create an Immutable Class To make a class immutable: 1️⃣ Declare the class final 2️⃣ Make fields private and final 3️⃣ Initialize fields via constructor 4️⃣ Do not provide setters 5️⃣ If fields contain mutable objects, return defensive copies 💻 Example final class Person { private final String name; private final int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } } Once created: Person p = new Person("John", 30); The object's state can never change. ⚙ What Happens Internally? When you modify an immutable object, Java does not change the original object. Instead, it creates a new object. Example: String s = "Hello"; s.concat(" World"); The original "Hello" remains unchanged. 🚀 Where We Use Immutability in Real Systems Immutable objects are extremely common in backend development: String, Integer, UUID Configuration objects DTOs in microservices Cache objects Multi-threaded applications They help build safe and predictable systems at scale. ⚠ Common Mistake If your class contains a mutable object (like List), always return a defensive copy. return new ArrayList<>(skills); Otherwise external code can modify your internal state. 💡 Key Takeaway Immutability is one of the most powerful design principles in Java. It improves: • Thread safety • System reliability • Performance optimization This is why many high-scale backend systems prefer immutable objects whenever possible. 💬 Interview Question: Why is String immutable in Java, and how does it help with security and the String Pool? Let’s discuss in the comments.
To view or add a comment, sign in
-
Hii everyone, Sharing some commonly asked Java interview questions for practice: 1. Why is Java a platform independent language? 2.Why is Java not a pure object oriented language? 3.Tell us something about JIT compiler. 4. Can you tell the difference between equals() method and equality operator (==) in Java? 5.Briefly explain the concept of constructor overloading 5.Define Copy constructor in java. 6.Can the main method be Overloaded.how? 7.Explain the use of final keyword in variable, method and class 8.Do final, finally and finalize keywords have the same function? 9. When can you use super keyword and this keyword? 10. Why is the main method static in Java? 11.. Can the static methods be overridden? 13.Difference between static methods, static variables, and static classes in java. 14.What is a ClassLoader Explain its types? 15.How would you differentiate between a String, StringBuffer, and a StringBuilder? 16.Why string is immutable? 17.What do you understand by class and object? Also, give example. 18.What are the characteristics of an abstract class? 19.What is composition? 20.What is Coupling in OOP and why it is helpful? 21.Explain overloading and overriding with example? 22.Give a real-world example of polymorphism? 23.What is inheritance explain its type? 24.EXplain Encapsulation? 25.What are the differences between error and exception? 26. Using relevant properties highlight the differences between interfaces and abstract classes. 27.type of exception explain it? 28.Different bw throw and throws? 29.What are the differences between HashMap and HashTable in Java? 30.What makes a HashSet different from a TreeSet? 31.Java works as “pass by value” or “pass by reference” phenomenon? 32.Different bw ISA relationship HAS a Relationship? 33. Will the finally block get executed when the return statement is written at the end of try block and catch block as shown below? 34. Explain various interfaces used in Collection framework? 35.What is the difference between ArrayList and LinkedList? 36.What is the difference between List and Set? 37.What is the difference between Comparable and Comparator? 38. How to remove duplicates from ArrayList? 39.HashMap internal works? 40.Can you explain the Java thread lifecycle? 41. What do you understand by marker interfaces in Java? 42.types of memory in java? 43.Why is multiple inheritance not supported in java? 44.Can we override the private methods? 45.What is the difference between compile-time polymorphism and runtime polymorphism? 46.What is exception propagation? 47.volatile keyword? 48.dead lock? 49.Synchronization in java? 50.what is HashMap and weak HashMap? 51.diff b/w jdk jre jvm? 52.what is sterilization and deserialization? 53.diff HashMap and hash table? 54.wrapper class in java?
To view or add a comment, sign in
-
Basic Java Interview Q&A ✅ 1. What is Java? Java is a high-level, object-oriented, platform-independent programming language. Its “Write Once, Run Anywhere” principle is powered by the Java Virtual Machine (JVM). ✅ 2. Key Features of Java Simple & Secure Object-Oriented Platform Independent (via JVM) Robust & Multithreaded High Performance (with JIT Compiler) ✅ 3. Difference Between JDK, JRE, and JVM JDK (Java Development Kit) → Includes compiler, tools, and JRE. JRE (Java Runtime Environment) → Contains JVM + core libraries. JVM (Java Virtual Machine) → Executes bytecode, platform-dependent. ✅ 4. Four OOP Principles in Java Encapsulation → Data hiding through classes. Inheritance → Reuse properties and methods. Polymorphism → One interface, multiple implementations. Abstraction → Hide implementation details, expose essential features. ✅ 5. Difference Between == and .equals() == → Compares memory references. .equals() → Compares actual values or content. ✅ 6. What is String Immutability? Strings in Java are immutable, meaning once created, they cannot be changed. Any modification results in a new String object in the memory pool. ✅ 7. What is the difference between Array and ArrayList? Array → Fixed size, can store primitives & objects ArrayList → Dynamic size, only stores objects, part of Collections framework ✅ 8. Types of Access Modifiers public → Accessible from anywhere. protected → Accessible within the same package and subclasses. default → Accessible only within the package. private → Accessible only within the same class. ✅ 9. What is Exception Handling? A mechanism to handle runtime errors using keywords: try, catch, finally, throw, and throws. ✅ 10. Checked vs. Unchecked Exceptions Checked → Compile-time (e.g., IOException, SQLException). Unchecked → Runtime (e.g., NullPointerException, ArithmeticException). ✅ 11. What is Garbage Collection? Automatic memory management that removes unused objects from the heap to free memory space. ✅ 12. What is the difference between Overloading and Overriding? Overloading → Same method name, different parameters (Compile-time polymorphism) Overriding → Subclass redefines parent class method (Runtime polymorphism) Follow Programming [Assignment-Project-Coursework-Exam-Report] Helper For Students | Agencies | Companies for more #Java #JavaInterview #CoreJava #OOP #BackendDevelopment #JavaProgramming #CodingInterview #100DaysOfCode
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