🚀 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
Java DSA Challenge Day 3 Loops and Functions
More Relevant Posts
-
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
-
-
⏳Day 32 – 1 Minute Java Clarity – Comparable vs Comparator** Both sort. But who controls the sorting logic? ⚡ 📌 Core Difference: Comparable = object sorts itself (natural order). Comparator = external class defines custom sort logic. 📌 Code Comparison: import java.util.*; // Comparable – natural order (by age) class Student implements Comparable<Student> { String name; int age; Student(String name, int age) { this.name = name; this.age = age; } public int compareTo(Student other) { return this.age - other.age; // sort by age ascending } public String toString() { return name + "(" + age + ")"; } } // Comparator – custom order (by name) class NameComparator implements Comparator<Student> { public int compare(Student a, Student b) { return a.name.compareTo(b.name); // sort by name } } public class SortingDemo { public static void main(String[] args) { List<Student> students = Arrays.asList( new Student("Charlie", 22), new Student("Alice", 20), new Student("Bob", 21) ); Collections.sort(students); // Comparable → by age System.out.println(students); // [Alice(20), Bob(21), Charlie(22)] students.sort(new NameComparator()); // Comparator → by name System.out.println(students); // [Alice(20), Bob(21), Charlie(22)] // Java 8 Lambda Comparator students.sort((a, b) -> b.age - a.age); // sort by age descending System.out.println(students); } } 📌 Head-to-Head Comparison: | Feature | Comparable | Comparator | |---|---|---| | Package | java.lang | java.util | | Method | compareTo() | compare() | | Sort logic location | Inside the class | Outside the class | | Multiple sort orders | ❌ One only | ✅ Multiple | | Modifies class | ✅ Yes | ❌ No | 💡 Real-time Example: 👨🎓 Student Leaderboard : Comparable → Default sort by marks (fixed rule) Comparator → Sort by name, age, or rank depending on view ⚠️ Interview Trap: Can you use both Comparable and Comparator together? 👉 Yes! Comparable sets the default order. 👉 Comparator overrides it when passed explicitly. 📌 Pro Tip: // Java 8 Comparator chaining: students.sort( Comparator.comparing((Student s) -> s.age) .thenComparing(s -> s.name) ); // sort by age, then by name ✅ 💡 Quick Summary: ✔ Comparable → natural sort, modifies the class ✔ Comparator → custom sort, external, flexible ✔ Comparable uses compareTo(), Comparator uses compare() ✔ Use Comparator when you can't modify the class ✔ Java 8+ → prefer lambda Comparators ✅ 🔹 Next Topic → Java 8 Streams Introduction Did you know you can chain multiple Comparators in Java 8 with thenComparing()? Drop 🔥 if this was new to you! #Java #Comparable #Comparator #Sorting #JavaCollections #CoreJava #1MinuteJavaClarity #JavaDeveloper #100DaysOfCode
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
-
-
Java Method Overloading I was revising notes on method overloading, and it reminded me how easy it is to memorize definitions… but miss the real mechanics behind it. Let’s break it down in a way that actually sticks What the Compiler Actually Uses When Java resolves an overloaded method, it ONLY looks at: ✔️ Method name ✔️ Number of parameters ✔️ Data types of parameters ✔️ Order (sequence) of parameters This combination is called the method signature ❌ Return type is completely ignored What is “Overload Resolution”? It’s the process where the compiler decides which method to call from multiple overloaded methods. Important: This decision happens at compile time, not runtime That’s why method overloading is also called: Compile-time polymorphism Static polymorphism Early binding Static binding Real Understanding (From Notes → Reality) “Compiler binds method call with method body during compilation” Let’s make that practical: void add(int x, int y) { } void add(int x, float y) { } void add(float x, float y) { } add(10.5f, 20.5f); 👉 Compiler instantly picks: add(float, float) ✔️ Decision made at compile time ✔️ Execution happens later at runtime ⚡ Where Most People Go Wrong Many think: “Return type helps differentiate methods” ❌ Wrong. int add(int a, int b) { return 0; } double add(int a, int b) { return 0; } // ❌ Error 👉 Same signature → Compilation Error The Hidden Rule When multiple methods match, Java follows priority: 1️⃣ Exact match 2️⃣ Widening 3️⃣ Autoboxing 4️⃣ Varargs If two methods fall at same level → ❌ Compilation Error The Illusion “It creates an illusion that one method performs multiple activities” In reality: Methods are different Only the name is same Each method handles a specific case Overloading improves readability, not magic Reference For deeper understanding of invalid cases: 🔗 https://lnkd.in/gD3W_efG Thanks to PW Institute of Innovation and my mentor Syed Zabi Ulla sir for helping me truly understand how Java thinks under the hood. Your guidance made these concepts much clearer and interview-ready. 🚨 One-Line Truth Method overloading is not about flexibility at runtime — it’s about clarity and compile-time precision #Java #Programming #SoftwareEngineering #CodingInterview #FAANG #JavaDeveloper #TechLearning
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
-
-
Hello Connections, Post 17 — Java Fundamentals A-Z ☕ Java Streams have completely transformed coding approach. 🚀 However, many developers still have misconceptions about what a Stream truly is. Let's clear the air! 💡 🚫 What a Stream is NOT: ❌ A data structure ❌ A place to store data ❌ Anything like an ArrayList ✅ What a Stream actually IS: 🌊 A pipeline that processes data 📖 Reads from a source ⚙️ Transforms it step by step 🏁 Produces a result Example in Action: 💻 List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David"); long count = names.stream() // 1. SOURCE 📥 .filter(n -> n.length() > 3) // 2. INTERMEDIATE ⚙️ .count(); // 3. TERMINAL 🏁 System.out.println(count); // Output: 3 ⚠️ The Golden Rule: Streams are LAZY! 😴 Stream<String> stream = names.stream() .filter(n -> { System.out.println("Checking: " + n); return n.length() > 3; }); // 🤫 Nothing happens yet! stream.count(); // 🔥 NOW it runs! This laziness is a superpower—it avoids unnecessary processing, even in pipelines with millions of records! ⚡ 🧠 Quick Quiz — Test Your Knowledge! Problem 1 — What is the output? 🔢 List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5); long result = nums.stream().filter(n -> n > 2).count(); System.out.println(result); 👉 Answer: 3 (Numbers 3, 4, and 5 pass the filter!) Problem 2 — How many times does filter run? ⏱️ List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); Optional<String> result = names.stream() .filter(n -> n.startsWith("C")) .findFirst(); 👉 Answer: 3 times (Alice ❌, Bob ❌, Charlie ✅... then it stops!) Problem 3 — Will this print anything? 🙊 List<Integer> nums = Arrays.asList(1, 2, 3); Stream<Integer> stream = nums.stream() .filter(n -> n > 1) .map(n -> n * 2); 👉 Answer: Nothing! Remember: No terminal operation = No execution! 🚫 Post 17 Summary: 📝 🔴 Unlearned → "Stream is just another collection." 🟢 Relearned → "Stream is a lazy processing pipeline." 🤯 Biggest surprise → filter() does NOTHING without a terminal operation! Follow along for more👇 #Java #JavaFundamentals #BackendDevelopment #LearningInPublic #SDE2 #CodingTips #SoftwareEngineering
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
-
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
-
-
✨ Most Useful Keywords In Java✨ ➡️final : The final keyword can be applied to classes, variables, methods, and blocks. Once assigned, it cannot be changed. A final class cannot be extended, a final variable cannot be reassigned, and a final method cannot be overridden. ➡️static : The static keyword can be applied to variables, methods, and blocks. Static members can be accessed using the class name without creating an object. Static methods cannot be overridden. ➡️abstract : Used to create a class or method that is incomplete and must be implemented by sub-classes ➡️assert : Used for debugging to test assumptions during runtime ➡️boolean : Represents a logical data type with values true or false ➡️break : Terminates a loop or switch statement immediately ➡️byte : Data type to store 8-bit integer values ➡️case : Defines a branch in a switch statement ➡️catch : Handles exceptions raised in a try block ➡️char : Stores a single character ➡️class : Used to declare a class ➡️continue : Skips the current loop iteration and continues with the next one ➡️default : Executes when no case matches in switch Defines default methods in interfaces ➡️do : Used in a do-while loop (executes at least once) ➡️double : Stores 64-bit decimal numbers ➡️else : Executes when an if condition is false ➡️enum :Defines a fixed set of constants ➡️extends : Used by a subclass to inherit another class ➡️finally : Block that always executes, used for cleanup ➡️float : Stores 32-bit decimal values ➡️for : Used for loop execution with initialization, condition, and increment ➡️if : Executes code when a condition is true ➡️implements : Used by a class to implement an interface ➡️import : Allows access to classes defined in other packages ➡️instanceof : Checks whether an object belongs to a specific class ➡️int : Stores 32-bit integer values ➡️interface : Used to declare a contract that classes must follow ➡️long : Stores 64-bit integer values ➡️new : Creates an object or instance ➡️package : Groups related classes and interfaces ➡️return : Sends a value back from a method and exits it ➡️short : Stores 16-bit integer values ➡️static : Belongs to the class, not object ➡️super : Refers to parent class object or constructor ➡️switch : Selects execution paths based on an expression ➡️synchronized : Controls thread access to prevent data inconsistency ➡️this : Refers to the current object ➡️throw : Explicitly throws an exception ➡️throws : Declares exceptions that a method may pass upward ➡️transient : Prevents variable from being serialized ➡️try : Wraps code that may generate exceptions ➡️void : Indicates a method returns no value ➡️volatile : Ensures variable value is read from main memory, not cache ➡️while: Executes a loop while condition remains true ➡️var: var enables local variable type inference ➡️record: record is a special immutable class used to store data only #javafeatures #oops #opentowork #fresher #softwareengineer #hiring #javadeveloper
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