🚀 Java Learning Series — Day 5 Topic: Introduction to Threads in Java ☕️ A Thread is a sort of mini-worker within your program that performs tasks independently. Instead of doing everything one-by-one, threads let Java do multiple things at the same time. ------------------------------------- Quick Notes: • Thread → a lightweight process running independently • Multithreading: Running multiple threads together • Main thread → the one that starts automatically when program runs ------------------------------------- Simple Code: class MyWork extends Thread { public void run() { System.out.println("Thread is working: " + Thread.currentThread().getName()); } public static void main(String[] args) { MyWork t1 = new MyWork(); MyWork t2 = new MyWork(); t1.start(); t2.start(); System.out.println("Main thread continues…"); } } ------------------------------------- ⚙️ Real-World Places You See Threads: 1. You scroll Instagram while videos load in the background 2. WhatsApp: Sending message + loading DP + encryption — all parallel 3. Music App: audio playing + lyrics sync + animation ✨ 4. Browser: multiple tabs loading at once 5. PUBG/BGMI: render graphics + network updates + input controls ------------------------------------- Interview-Quick Questions: 1️⃣ What is a Thread in Java? 2️⃣ What is the difference between Process and Thread? 3️⃣ What is main thread? 4️⃣ Why do we use start() instead of calling run() directly? 5️⃣ What is Multithreading and its benefits? ------------------------- #Java #Threads #LearnWithRahulVarma #100DaysOfJava #CodingJourney #MultiThreading #SoftwareEngineer #LearningNeverStops #JavaDeveloper
"Java Learning Series: Introduction to Threads"
More Relevant Posts
-
🚀 Java Learning Journey – Day 22 🔥 Understanding Switch Case with Expressions (Java) Today I explored how switch-case works when we use expressions inside the case labels. ~ In Java, expressions like (0+1) or (1+2) get evaluated first, and then matched with the switch variable. The interesting part is fall-through, which happens when we don’t use a break statement. This helps in understanding how multiple cases can run together. ✅ Here’s the code I practiced today: -------------------------------------code start------------------------------------ public class SwitchDemo2 { public static void main(String[] args) { int x = 0; //x=0 (E) | x=1 (A,B) | x=2 (B) | x=3 (C,D,E) | x=4 (D,E) | x=5 (E) switch (x) { case (0+1): System.out.println("A"); case (1+1): System.out.println("B"); break; case (1+2): System.out.println("C"); case (2+2): System.out.println("D"); default: System.out.println("E"); } } } ----------------------------------code output------------------------------------ E -------------------------------------code end------------------------------------ 🧠 Key Takeaways case expressions are evaluated before matching. Without break, execution continues to the next case (fall-through). Helps in understanding how switch-case flows internally. 🌱 Personal Note: I’m continuously learning Java and exploring DevOps tools and practices to build a strong foundation for full-stack and automation development. If you like my daily progress posts, please support with a like, comment, or share ~ it truly motivates me to keep learning and sharing. 🙌 I’m also looking for internship opportunities in Java development or DevOps to apply my skills in real-world projects, learn from professionals, and grow further. If you know of any such opportunities or can guide me, I’d really appreciate your help 🙏 #JavaLearningJourney #day22 #Java #Programming #LearningInPublic #SwitchCase #JavaBeginners #CodeNewbie #FallThrough #DeveloperJourney #DevOps #TechJourney #LearningEveryday
To view or add a comment, sign in
-
-
😍 Day 17 of My Java Learning Journey – Finding Odd or Even Numbers 🔢 . Hey everyone 👋 . Today, I explored a simple but important concept 💯 ~ how to check whether numbers are odd or even in Java using conditional statements (if-else). . Here’s the code I practiced today: 👇 --------------------------------------code start-------------------------------------- public class FindOddOrEvenNumberDemo { public static void main(String[] args) { int c = 32; int d = 21; if (c % 2 == 0 && d % 2 == 0) { System.out.println("c & d both are even number"); } else if (c % 2 != 0 && d % 2 != 0) { System.out.println("c & d both are odd number"); } else if (c % 2 == 0) { System.out.println("c is even number and d is odd number"); } else { System.out.println("c is odd number and d is even number"); } } } ------------------------------------code output------------------------------------ c is even number and d is odd number ------------------------------------code end--------------------------------------- 💡 Explanation: The expression number % 2 gives the remainder when dividing the number by 2. If the remainder is 0, the number is even. If the remainder is not 0, the number is odd. . I used multiple if-else conditions to check all possibilities: Both numbers are even. Both numbers are odd. One is even and the other is odd. . 👉 In this example, c = 32 (even) and d = 21 (odd), so the output will be: ~ c is even number and d is odd number. . Building these logic-based programs helps strengthen my understanding of control flow and conditions in Java, which are essential for solving real-world coding problems. . #Java #Coding #LearnJava #100DaysOfCode #DevOps #JavaLearningJourney #Day16 #Programming #CodeWithYuvi #LogicBuilding .
To view or add a comment, sign in
-
-
The tables have turned! With the help of Artur Jakubiec we were able to optimize Rust implementation quite a bit. Let's dive into the mechanics to see why similar tricks aren't as helpful in Java. My algorithm parses Molecular Formulas (MFs). For this I create 2 arrays to keep some intermediate results. But creating arrays is expensive, and if we have to parse 1 million MFs, we'll be creating 2 million of temporary arrays. But what's the problems with the arrays? Why are they expensive? Well, each time an array is created Rust must: 1. Reach out to OS to allocate memory 2. After we used the arrays, ask OS to deallocate (free) memory Each call to the OS (aka syscall) is an expensive operation. So instead of creating arrays, the new implementation reuses them between calls. We just need to clear them. This alone adds ~45% to the performance! --- Can't we use the same optimization in Java? With some ugly hacks it's possible to improve the performance slightly - 5-10% tops. But if we simply Arrays.fill(0) - this actually degrades the performance! Why? JVM doesn't call OS every time we create arrays or Objects. Instead, it 𝑝𝑟𝑒-𝑎𝑙𝑙𝑜𝑐𝑎𝑡𝑒𝑠 a lot of memory (JVM Heap) during the startup, and it can extend it further during the runtime. So basically JVM creates a huge array of bytes (let's make it ~1 billion values aka 1GB) and writes the fields of our objects in that memory. Pre-allocating memory instead of going each time to OS isn't a rare technique in C/C++/Rust. Of course this means that we have to write our own allocator that keeps track of free/taken space in the "big array", but performance improvements could be substantial depending on the use case. All in all, (de)allocating memory in JVM is a lot cheaper than using standard allocation in Rust. That's why caching the short-living arrays doesn't have much effect in Java. --- Okay, what about the Garbage Collection (GC) you may (and should) ask? Since JVM creates many temporary arrays we should pay the cost when GC is invoked, right? Well, GC'ing short-living objects is insanely fast. In fact, my benchmark already runs ~150 GC's so the GC time is already accounted for. I create ~180 million short-living arrays (~6GB) throughout the run of the benchmark. On my M2 the usual GC takes 0.5 millisec, and together they sum up to 300ms. So given Java (de)allocations are so fast, why is it slower than Rust? I don't know yet 🙂 Stay tuned! Latest implementations: * #Rust: https://lnkd.in/dQby_YUj * #Java: https://lnkd.in/dETVVMm5 The original algorithm chart: https://lnkd.in/dZB8p8yA
To view or add a comment, sign in
-
-
🎯 Day 15 of My Java Learning Journey 🎯 . Hey everyone! 👋 .. Today I explored Selection Statements again — but this time, I focused on finding the smallest number among four values using if-else if ladder in Java. Here’s the code I wrote 👇 --------------------------------------code start--------------------------------------- public class FindSmallerNumberDemo2 { public static void main(String[] args) { int l = 1; int m = 2; int n = 3; int o = 4; if (l < m && l < n && l < o) { System.out.println("l is smaller"); } else if (m < o && m < n && m < l) { System.out.println("m is smaller"); } else if (o < n && o < m && o < l) { System.out.println("o is smaller"); } else { System.out.println("n is smaller"); } } } --------------------------------------code output---------------------------------- l is smaller number -------------------------------------code end--------------------------------------- . 💡 Explanation: I’ve declared four integer variables — l, m, n, and o. The if statement checks multiple conditions using logical AND (&&) to make sure one number is smaller than all others. . If the first condition fails, the program moves to the next else if condition. Finally, if none of the earlier conditions are true, the else block executes — meaning the last variable n is the smallest. . 🧠 This program is a simple way to understand how comparison and logical operators work together in decision-making statements. In the next few posts, I’ll share more concepts related to selection and looping statements in Java 🚀 . #Day15 #JavaLearningJourney #100DaysOfCode #LearnJava #Programming #DevOps #Coding #JavaBeginners #SelectionStatement #IfElseInJava .
To view or add a comment, sign in
-
-
💡 Ever wondered how Java sorts Strings so efficiently? Meet Timsort — the hybrid brain behind it. Java sorts Strings internally using a Hybrid Timsort Algorithm! While exploring sorting, I stumbled upon an interesting detail about Timsort — the algorithm behind Arrays.sort(), Collections.sort(), and List.sort() for Objects in Java. 👉 Timsort isn’t a simple bubble or quicksort. It’s a hybrid algorithm that: 🧩 Builds runs (already sorted chunks in the array) ⚙️ Uses merge sort + binary search to place elements efficiently 🧠 Example Input ["laptop", "mobile", "and", "desktop", "are", "not", "exempt"] 🔍 First few comparator calls: "mobile".compareTo("laptop") → "laptop" before "mobile" "and".compareTo("mobile") → "and" before "mobile" "and".compareTo("laptop") → "and" before "laptop" After 3 comparisons, the partial order becomes: ["and", "laptop", "mobile", ...] When "are" is processed, I expected it to be compared with "desktop" (the last element). But Timsort skipped "desktop" and only compared "are" with "mobile", "laptop", and "and". 🤔 Why did Timsort skip "desktop"? Because Timsort doesn’t linearly scan the entire list — it uses binary search inside runs. It picks the middle element (like binary search). If "are" < middle element, everything after that middle is automatically larger — no need for redundant comparisons. 💡 In this case: "are" compared with "laptop" (mid) → since "are" < "laptop", Timsort already knows "are" < "desktop" 🔑 Takeaway: Timsort = Merge Sort + Insertion Sort + Binary Search optimizations Efficient ✅ Stable ✅ Clever ✅ That’s why Java adopted Timsort for Object sorting. 🧠 Object sorting (String, Student, CustomObject) → Timsort ⚡ Primitive sorting (int[], long[], double[]) → Dual-Pivot Quicksort #Java #Programming #Algorithms #Timsort #Coding #JavaDeveloper #ComputerScience #TechInsights #SoftwareEngineering #ArraysSort #DeveloperCommunity
To view or add a comment, sign in
-
🌟 Day 14 of My Java Learning Journey 🔥 💯 Hey everyone! 👋 ~ Today’s topic was all about decision-making in Java — how a program chooses which path to follow based on given conditions. 💡 . I explored how to find the greatest number among multiple values using nested if-else statements, one of the core parts of selection statements in Java. 💻 Here’s the code I worked on today: 👇 -------------------------------------code start-------------------------------------- public class FindGreaterNumberDemo2 { public static void main(String[] args) { int p = 11; int q = 22; int r = 33; int s = 44; if (p > r && p > s && p > q) { System.out.println("p is greater number "); } else if (q > s && q > p && q > r) { System.out.println("q is greater number"); } else if (r > p && r > s && r > q) { System.out.println("r is greater number"); } else { System.out.println("s is greater number"); } } } -------------------------------------code output------------------------------------ s is greater number ---------------------------------------code end-------------------------------------- . 🔍 Explanation: We have four integer variables: p, q, r, and s. Using an if-else-if ladder, we compare each number with the others using the logical AND (&&) operator. The first condition that turns out true will print which number is the greatest. If none of them match, the else block executes, showing that s is the greatest. . 💡 Key Takeaway: Selection statements like if, else if, and else help control the program’s logic — deciding what happens next depending on the condition. . 🚀 What’s next? In the upcoming posts, I’ll share many more real-world examples related to selection statements, so we can deeply understand how decision-making works in Java programs. Stay tuned — it’s gonna get crazy cool and more practical! 💻🔥 . #Java #100DaysOfCode #Day14 #JavaLearningJourney #FlowControl #IfElse #SelectionStatements #DevOps #Programming #CodingJourney #LearnJava #TechLearner #CodeNewbie .
To view or add a comment, sign in
-
-
📅 DSA in Java | Weekly Update (25/10/2025 – 06/11/2025) 🚀 💯 #100DaysChallenge – Week 4 Progress This week in my DSA in Java journey, guided by Kunal Kushwaha’s tutorials and consistent practice, I explored some core problem-solving concepts that are essential for writing efficient and optimized code. 🔹 Topics Covered Recursion: Strengthened understanding of breaking problems into smaller subproblems. Worked on examples like Factorial, Tower of Hanoi, and started applying recursion in Merge Sort. Sorting Algorithms: Implemented and analyzed sorting algorithms — Merge Sort, Quick Sort, Heap Sort — and studied their time & space complexity. Dynamic Programming (Advanced): Solved problems like 0/1 Knapsack, Longest Common Subsequence, and Matrix Chain Multiplication, focusing on recurrence relation + memoization patterns. Binary Trees & BST: Learned tree traversal techniques — Pre-order, In-order, Post-order — and started exploring Binary Search Trees and their efficient lookups. Linked List: Implemented Singly, Doubly, and Circular Linked Lists along with common operations like insertion, deletion, and searching. Stack & Queue: Understood their role in function calls, expression evaluation, BFS/DFS, and solved problems using both array-based and linked-list-based implementations. Two Pointer & Sliding Window Techniques: Improved efficiency in problems related to arrays and strings through pointer optimization. Greedy Algorithms: Explored problems where locally optimal choices lead to global optimum, helping improve decision-making strategies in coding problems. 💻 Key Learnings Recursion builds strong problem breakdown ability — base cases matter! Sorting focuses on efficiency & logical structuring of comparisons. DP helps convert exponential brute-force solutions to polynomial time. Trees are foundational for real-world structures like indexing & file hierarchies. Optimization techniques like Two Pointers and Greedy improve runtime performance drastically. ✨ Takeaway Every day brings a new challenge — and that’s what makes this journey exciting. I’m building consistency, logic, discipline, and clarity in approach, one step at a time. > “It’s not about being the best — it’s about getting better every single day.” 🎯 Next Week’s Focus Graph Algorithms Binary Search (Deep Dive) Advanced Recursion Patterns #DSA #Java #100DaysChallenge #ProblemSolving #KunalKushwaha #LearningJourney #Coding #Recursion #SortingAlgorithms #DynamicProgramming #BinaryTree #LinkedList #Stack #Queue #Greedy #TwoPointers #Consistency #Motivation #Progress
To view or add a comment, sign in
-
Python vs Java – What Really Happens When You Run Them 👇 Ever run a Python script or a Java program and wondered what’s happening behind the scenes? Let’s break it down simply 👇 𝗣𝘆𝘁𝗵𝗼𝗻 (𝗖𝗣𝘆𝘁𝗵𝗼𝗻 𝗥𝘂𝗻𝘁𝗶𝗺𝗲) ◾ Your `.py` file is first compiled into bytecode automatically in memory. ◾ Python sometimes saves this as a `.pyc` file, so the next run is faster. ◾ The Import System loads all required modules and dependencies. ◾ Finally, the Python Virtual Machine (PVM) interprets the bytecode line by line — flexible and beginner-friendly, but a bit slower. 𝗝𝗮𝘃𝗮 (𝗝𝗩𝗠 𝗥𝘂𝗻𝘁𝗶𝗺𝗲) ◾ Your `.java` file is compiled into `.class` bytecode using `javac`. ◾ The Class Loader loads the bytecode into the Java Virtual Machine (JVM). ◾ The JVM verifies, interprets, and optimizes the code for execution. ◾ The Just-In-Time (JIT) Compiler converts frequently used code (hot paths) into native machine code, making Java faster over time. 𝗥𝗲𝘀𝘂𝗹𝘁 ◾ Python prioritizes simplicity and flexibility. ◾ Java focuses on speed and runtime optimization. __________ ♻️ Reshare if you found this helpful. ✅Follow Jafar Muzeyin for daily tips 📺 Watch more on my YouTube channel: [https://lnkd.in/eBmq2kuY] Reference -> ByteByteGo
To view or add a comment, sign in
-
-
💡 How Generics Make Object Comparison in Java Safer & Cleaner One of the most underrated benefits of Java Generics is how they simplify and secure the way we use Comparable and Comparator while comparing objects. Before Generics (pre-JDK 1.5), comparison logic often involved: ✔️ Storing objects as Object ✔️ Downcasting them manually ✔️ Hoping the cast doesn’t fail at runtime 😅 But with Generics, Java gives us compile-time type safety and eliminates unnecessary upcasting/downcasting. --- 🔍 What Problem Did Generics Solve? Without generics: class Student implements Comparable { int marks; public int compareTo(Object o) { Student s = (Student) o; // ❌ Risky downcast return this.marks - s.marks; } } Problems: You must cast from Object to Student. ⚠️ No compile-time checking — mistakes explode at runtime. Code becomes cluttered and unsafe. --- ✅ With Generics – Cleaner, Type-Safe, and Zero Casting class Student implements Comparable<Student> { int marks; public int compareTo(Student s) { // ✔️ No casting needed return this.marks - s.marks; } } And with Comparator: Comparator<Student> sortByName = (s1, s2) -> s1.name.compareTo(s2.name); Benefits: No upcasting to Object No downcasting back to original types Comparator & Comparable work with the specific type you intend Compiler ensures type correctness → safer & cleaner code --- 🎯 Why This Matters in Real Projects When working with large domain models (Employee, Product, Order, etc.), using generics avoids subtle runtime bugs. Collections like TreeSet, TreeMap, or Collections.sort() work perfectly with type-safe comparators. Your IDE offers better autocomplete because it knows the type you’re working with. --- 🚀 In short: Generics transformed the way we compare objects in Java—by replacing unsafe casting with clean, type-checked logic. Less boilerplate, more safety. #CleanCode #CodeQuality #SoftwareDevelopment #ProgrammingTips #LearnCoding
To view or add a comment, sign in
-
-
📌Understanding Java Arrays — The Foundation of Data Handling Today, I revised the fundamentals of Java Arrays, one of the most essential concepts in Java programming and interviews. 🔹 What is an Array in Java? A Java array is a fixed-size, indexed data structure used to store multiple values of the same data type. Arrays are stored in continuous memory locations and allow fast (O(1)) element access. ➜ Example: int[] marks = new int[10]; char[] letters = new char[15]; String[] names = new String[20]; 🔹 Array Structure Arrays use zero-based indexing Each element is stored at a specific index Accessing elements is extremely fast ➜Example: int[] arr = {21, 15, 37, 53, 17}; Memory view: Index: 0 1 2 3 4 Values: 21 15 37 53 17 🔹 Array Declaration (Two Ways) int[] arr; int arr[]; 🔹 Types of Arrays in Java ✔ 1. One-Dimensional Arrays Ideal for simple linear data: int[] scores = {10, 20, 30}; ✔ 2. Multidimensional Arrays Arrays inside arrays → used for matrices, tables, grids. 2D Array: int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; 3D Array: Used in simulations, 3D structures, games: int[][][] cube = new int[3][3][3]; ✔ 3. Jagged Arrays (Irregular Arrays) Rows can have different lengths. int[][] jagged = { {1, 2}, {3, 4, 5}, {6, 7, 8, 9} }; 🔹 Why Arrays Matter? Foundation for Data Structures (Lists, Maps, Matrices) Faster access compared to collections Used in interviews for logic & memory questions Understanding arrays is the first step toward mastering Java data structures. #Java #Programming #Arrays #DSA #BackendDevelopment #LearningInPublic #CodingJourney
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
Information and also Answer bro