🚀 Day 5/100 — Loops in Java 🔁 Loops allow a program to repeat a block of code multiple times without writing the same code again and again. They are one of the most important concepts in programming. Java mainly provides three types of loops: 🔹 1. for Loop Used when the number of iterations is known. Syntax: for(initialization; condition; update){ // code to run } Example: for(int i = 1; i <= 5; i++){ System.out.println(i); } Output: 1 2 3 4 5 Here: i = 1 → start value i <= 5 → condition check i++ → increment after each iteration 🔹 2. while Loop Used when the number of iterations is unknown and depends on a condition. Example: int i = 1; while(i <= 5){ System.out.println(i); i++; } The loop runs as long as the condition is true. 🔹 3. do-while Loop Runs the block at least once, even if the condition is false. Example: int i = 1; do{ System.out.println(i); i++; }while(i <= 5); Difference: while → condition checked before execution do-while → condition checked after execution 🔹 Nested Loops A loop inside another loop is called a nested loop. Commonly used for pattern printing problems. Example: Triangle pattern for(int i = 1; i <= 5; i++){ for(int j = 1; j <= i; j++){ System.out.print("* "); } System.out.println(); } Output: * * * * * * * * * * * * * * * 🔴 Live Example — Inverted Triangle Pattern int rows = 5; for(int i = rows; i >= 1; i--){ for(int j = 1; j <= i; j++){ System.out.print("* "); } System.out.println(); } Output: * * * * * * * * * * * * * * * 🎯 Challenge: Write a program to print an inverted triangle pattern using nested loops. Drop your code in the comments 👇 #Java #CoreJava #100DaysOfCode #JavaLoops #ProgrammingJourney
Allaka Yamuna lakshmi’s Post
More Relevant Posts
-
Generic Classes in Java – Clean Explanation with Examples 🚀 Generics in Java are a compile-time type-safety mechanism that allows you to write parameterized classes, methods, and interfaces. Instead of hardcoding a type, you define a type placeholder (like T) that gets replaced with an actual type during usage. 🔹Before Generics (Problem): class Box { Object value; } Box box = new Box(); box.value = "Hello"; Integer x = (Integer) box.value; // Runtime error ❌ Issues: • No type safety • Manual casting required • Errors occur at runtime 🔹With Generics (Solution): class Box<T> { private T value; public void set(T value) { this.value = value; } public T get() { return value; } } 🔹Usage: public class Main { public static void main(String[] args) { Box<Integer> intBox = new Box<>(); intBox.set(10); int num = intBox.get(); // ✅ No casting Box<String> strBox = new Box<>(); strBox.set("Hello"); String text = strBox.get(); } } 🔹Bounded Generics: 1.Upper Bound (extends) → Read Only: Restricts type to a subclass List<? extends Number> list; ✔ Allowed: Integer, Double ❌ Not Allowed: String 👉 Why Read Only? You can safely read values as Number, but you cannot add specific types because the exact subtype is unknown at compile time. 2.Lower Bound (super) → Write Only: Restricts type to a superclass List<? super Integer> list; ✔ Allowed: Integer, Number, Object ❌ Not Allowed: Double, String 👉 Why Write Only? You can safely add Integer (or its subclasses), but when reading, you only get Object since the exact type is unknown. 🔹Key Takeaway: Generics = Type Safety + No Casting + Compile-Time Errors Clean code, fewer bugs, and better maintainability - that’s the power of Generics 💡 #Java #Generics #Programming #SoftwareEngineering #Coding
To view or add a comment, sign in
-
🔍 Understanding Arrays in Java (Memory & Indexing) Today I learned an important concept about arrays in Java: Given an array: int[] arr = {10, 20, 30, 40, 50}; We often think about how elements are stored in memory. In Java: ✔ Arrays are stored in memory (heap) ✔ Each element is accessed using an index ✔ JVM handles all memory internally So when we write: arr[0] → 10 arr[1] → 20 arr[2] → 30 arr[3] → 40 arr[4] → 50 👉 We are NOT accessing memory directly 👉 We are using index-based access Very-Important Point: 👉 Concept (Behind the scenes) we access elements using something like base + (bytes × index) in Java 💡 Let’s take an example: int[] arr = {10, 20, 30, 40, 50}; When we write: arr[2] 👉 We directly get 30 But what actually happens internally? 🤔 Behind the scenes (Conceptual): Address of arr[i] = base + (i × size) let's suppose base is 100 and we know about int takes 4 bytes in memory for every element :100,104,108,112,116 So internally: arr[2] → base + (2 × 4) Now base is : 100+8=108 now in 108 we get the our value : 30 Remember guys this is all happening behind the scenes 👉 You DON’T calculate it 👉 JVM DOES it for you 👉 But You Still need to know ✔ Instead, it provides safety and abstraction 🔥 Key Takeaway: “In Java, arrays are accessed using indexes, and memory management is handled by the JVM.” This concept is very useful for: ✅ Beginners in Java ✅ Understanding how arrays work internally ✅ Building strong programming fundamentals #Java #Programming #DSA #Coding #Learning #BackendDevelopment
To view or add a comment, sign in
-
Day 9 of Java Series ☕💻 Today’s topic is BufferedReader — a powerful way to take fast input in Java 🚀 🧠 What is BufferedReader? BufferedReader is a class in Java used to read text efficiently from input streams (like keyboard or file). It reads data in chunks (buffer) instead of character-by-character → faster performance ⚡ ⚙️ Why Use BufferedReader? ✔ Faster than Scanner ✔ Efficient for large input ✔ Reduces I/O operations ✔ Used in competitive programming 🔗 How it Works? 👉 Works with InputStreamReader to convert bytes into characters System.in → InputStreamReader → BufferedReader 💻 Example Code: import java.io.*; public class Main { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter your name: "); String name = br.readLine(); System.out.println("Hello " + name); } } ⚡ Important Methods: readLine() → Reads full line read() → Reads single character close() → Closes stream ⚠️ Important Notes: Does NOT parse input automatically Must handle exceptions (IOException) Needs conversion for numbers 👉 Example: Java id="br2" Copy code int num = Integer.parseInt(br.readLine()); 🎯 Why Important? ✔ Used in interviews & CP ✔ Improves performance ✔ Important for backend & file handling 🚀 Pro Tip: Use BufferedReader + StringTokenizer for ultra-fast input in competitive programming 🔥 📢 Hashtags: #Java #BufferedReader #JavaSeries #Coding #Programming #Developers #LearnJava #Tech
To view or add a comment, sign in
-
-
🚀 Mastering ArrayDeque in Java — A Powerful Alternative to Stack & Queue If you're working with Java collections, one underrated yet powerful class you should know is ArrayDeque. It’s fast, flexible, and widely used in real-world applications. Here’s a crisp breakdown 👇 🔹 What is ArrayDeque? ArrayDeque is a resizable-array implementation of the Deque interface, which allows insertion and deletion from both ends. 💡 Key Features of ArrayDeque ✔️ Default initial capacity is 16 ✔️ Uses a Resizable Array as its internal data structure ✔️ Capacity grows using: CurrentCapacity × 2 ✔️ Maintains insertion order ✔️ Allows duplicate elements ✔️ Supports heterogeneous data ❌ Does NOT allow null values 🛠️ Constructors in ArrayDeque There are 3 types of constructors: 1️⃣ ArrayDeque() → Default capacity (16) 2️⃣ ArrayDeque(int numElements) → Custom initial capacity 3️⃣ ArrayDeque(Collection<? extends E> c) → Initialize with another collection 🔍 Accessing Elements Unlike Lists, ArrayDeque has some restrictions: ❌ Cannot use: Traditional for loop (index-based) ListIterator ✅ You can use: for-each loop Iterator Descending Iterator (for reverse traversal) 🧬 Hierarchy of ArrayDeque Iterable ↓ Collection ↓ Queue ↓ Deque ↓ ArrayDeque 👉 In simple terms: ArrayDeque implements Deque Deque extends Queue Queue extends Collection Collection extends Iterable 🔥 Why use ArrayDeque? ✔️ Faster than Stack (no synchronization overhead) ✔️ Efficient double-ended operations ✔️ Ideal for sliding window, palindrome checks, and BFS/DFS algorithms 💬 Final Thought If you're still using Stack, it might be time to switch to ArrayDeque for better performance and flexibility! #Java #DataStructures #ArrayDeque #Programming #JavaCollections #CodingInterview #SoftwareDevelopment TAP Academy
To view or add a comment, sign in
-
-
Java Puzzle for Today What will be the output of this program? String a = "Java"; String b = "Java"; String c = new String("Java"); System.out.println(a == b); System.out.println(a == c); System.out.println(a.equals(c)); Take a moment and guess before scrolling. Most beginners think the output will be: true true true But the actual output is: true false true Why does this happen? Because Java stores string literals in a special memory area called the String Pool. So when we write: String a = "Java"; String b = "Java"; Both variables point to the same object in the String Pool. But when we write: String c = new String("Java"); Java creates a new object in heap memory, even if the value is the same. That’s why: - "a == b" → true (same object) - "a == c" → false (different objects) - "a.equals(c)" → true (same value) Lesson: Use "equals()" to compare values, not "==". Small Java details like this can save you from real bugs in production. #Java #Programming #JavaPuzzle #Coding #SoftwareDevelopment
To view or add a comment, sign in
-
Primitives vs. Objects in Java Why does some Java code turn purple in your IDE while other code stays black? It's not random—it's telling you something important. Primitive types like int, char, long, and double turn purple because they're baked directly into Java. They're the building blocks, the simplest forms of data the language recognizes. Objects like String don't get that color treatment because they're more complex structures. Here's the practical difference that matters: Objects give you access to the dot (.) operator—a key that unlocks built-in methods. With a String, you can call .toUpperCase(), .toLowerCase(), .length(), and dozens of other methods that manipulate your data. Primitives? They just hold a value. No dot, no methods, no extras. Once you understand this distinction, you'll start reading your IDE's color coding like a second language. Did you know this difference when you started? Drop a 🟣 if this clicked something for you. #java
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
-
-
The Diamond Problem in Java occurs in languages that allow multiple inheritance, where a class inherits from two classes that share a common superclass. This situation leads to ambiguity when both parent classes define the same method, raising the question of which method should be used. Java circumvents this issue by not supporting multiple inheritance with classes. However, a similar problem can arise with interfaces and default methods. Consider the following 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(); // This results in a compilation error } } In this case, since both interfaces provide the same method, Java requires the class to override it explicitly. Here’s how to resolve it with specific interface calls: class Test implements A, B { public void show() { A.super.show(); // Calls method from interface A B.super.show(); // Calls method from interface B } } This approach allows for explicit selection or combination of behavior from both interfaces. #Java #OOP #InterviewQuestions #BackendDevelopment #Programming
To view or add a comment, sign in
-
-
💻 Understanding Buffer Problem & Wrapper Classes in Java While working with Java input using scanner, many beginners face a tricky issue called the Buffer Problem when using Scanner. What happens? --->>When you use nextInt() or nextFloat(), it reads only the number and leaves the newline (\n) in the buffer. --->>So the next nextLine() gets skipped unexpectedly! ~Quick Fix: Always clear the buffer: int n = scan.nextInt(); scan.nextLine(); // clear buffer String name = scan.nextLine(); 🔄 Wrapper Classes in Java Java provides Wrapper Classes to convert primitive data types into objects. @Examples: int → Integer float → Float char → Character #These are super useful when: ✔ Converting String → primitive ✔ Working with collections (like ArrayList) ✔ Using built-in utility methods 🌍 Real-Time Example Imagine a job application system: User input: 101,John,50000 **To process this** 👇 String[] data = input.split(","); int id = Integer.parseInt(data[0]); String name = data[1]; int salary = Integer.parseInt(data[2]); Here, Wrapper Classes help convert text into usable data types. #Key Takeaways ✔ Always clear buffer when mixing nextInt() & nextLine() ✔ Wrapper classes make data conversion easy ✔ Essential for real-world input handling & backend systems #Mastering these small concepts builds a strong foundation in Java! TAP Academy #Java #Programming #OOP #JavaDeveloper #Coding #SoftwareDevelopment #LearnJava
To view or add a comment, sign in
-
-
🚀 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
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