Day 18 : looping statement A statements are used to execute some set of instructions repeatedly is called a looping statement. we can iterate loop desired number of time based on requirement. In java 4 types of loops 1.for loop 2.while loop 3. do-while loop 4.for each loop or enhance for loop loops has 3 part ie. initialization, condition , updation. for each loop doesn't contain this parts. for loop: A statements are used to execute some set of instructions repeatedly. used when we know the number of iterations. In this loop first we initialize a variable then give a condition and the updation statement if we doens't specify the condition by default jvm adds true then loop goes infinite. Syntax. for(initialization; Condition; updation){ // Statement } ex. for(int i=1;i<=10;i++){ s.o.p(i); } while loop: used to execute some set of instructions repeatedly. We use while loop when we don’t know the number of iterations Initialization, condition and updation are not declared at the same line. It throws a compile time error if we are not specifying the condition. syntax: initialization; while(condition){ // statements; updation; } ex. int a =1; while(a<=10){ s.o.p("hello "+a); a++; } #corejava #java #loop #forloop #whileloop
Java Looping Statements: For, While, Do-While, and Enhanced For Loop
More Relevant Posts
-
🚀 Day 8 — Restarting My Java Journey with Consistency Today’s topic looked familiar: 🔹 while loop 🔹 do-while loop 🔹 for loop 🔹 break & continue Most of this was already known to me. But revision with depth always reveals something new. 🔁 Loops — More Than Just Repetition We often write: for(int i = 0; i < n; i++) { // code } But today I revisited some important insights: ✔ All three parts in a for loop are optional ✔ Multiple variables can be initialized using comma separation ✔ Conditional statements rely completely on logical operators ✔ do-while is very useful in menu-driven programs (runs at least once) 🤯 Interesting Question Why don’t we usually use short instead of int in loops? Because in Java, due to type promotion, short gets promoted to int during arithmetic operations. So practically, using short in loops doesn’t provide any benefit. That’s not syntax knowledge. That’s understanding how Java works internally. 🆕 The New Concept I Learned — Labels in Java This was something I had never used before. outer: for(int i = 1; i <= 10; i++) { inner: for(int j = 1; j <= i; j++) { break outer; // breaks the outer loop directly } } 🔹 Labels allow us to control outer loops from inside inner loops 🔹 Useful in nested loop scenarios 🔹 Makes flow control very powerful (if used wisely) Learning daily with Coder Army and Aditya Tandon Bhaiya and Rohit Negi Bhaiya #Day8 #Java #Consistency #BackendDevelopment #LearningJourney #SoftwareEngineering #CoderArmy
To view or add a comment, sign in
-
-
Started learning Strings and StringBuilder in Java today. At first it looked simple, but once I began writing code, I realized the real challenge was understanding how strings actually behave in memory and how comparisons really work. Things that became clear: - Using == checks memory reference, not the actual text inside a string - Using .equals() compares the real content, which is what we usually need - Creating strings with new changes how memory is allocated and affects comparison results A small example that made this obvious: String a = "abcxyz"; String b = "abcxyz"; System.out.println(a == b); // true (same reference in string pool) System.out.println(a.equals(b)); // true (same content) String c = new String(a); System.out.println(a == c); // false (different memory) System.out.println(a.equals(c)); // true (same content) Output clearly showed why .equals() is the correct way to compare strings in real programs. Still early in this section, but the confusion from the beginning is slowly reducing. Continuing with StringBuilder and performance differences next. #java #strings #stringbuilder #codingjourney #learninginpublic #softwaredevelopment
To view or add a comment, sign in
-
𝐓𝐡𝐢𝐬 𝐜𝐨𝐝𝐞 𝐬𝐧𝐢𝐩𝐩𝐞𝐭 𝐢𝐬 𝐞𝐧𝐨𝐮𝐠𝐡 𝐭𝐨 𝐜𝐨𝐧𝐟𝐮𝐬𝐞 𝐬𝐨𝐦𝐞𝐨𝐧𝐞 𝐰𝐢𝐭𝐡 𝐉𝐚𝐯𝐚. 😁 Let me introduce you to the concept of wrapper classes and autoboxing first. 𝐖𝐑𝐀𝐏𝐏𝐄𝐑 𝐂𝐋𝐀𝐒𝐒𝐄𝐒: These are classes used to wrap primitive values so we can treat them like objects. This is essential for the Collection framework (like ArrayList), which only works with objects. 𝐀𝐔𝐓𝐎𝐁𝐎𝐗𝐈𝐍𝐆: The process of converting primitive values to wrapper objects is implicit. We don't need the new keyword. Now let's discuss the code: 𝐂𝐎𝐃𝐄 1: 𝘪𝘯𝘵 𝘢 = 100; 𝘪𝘯𝘵 𝘣 = 100; These are primitive values. For primitives, the == operator compares the actual values. Since both are 100, the output is 𝐭𝐫𝐮𝐞. 𝐂𝐎𝐃𝐄 2: Integer wrapper classes have an Integer Cache. By default, Java caches all Integer objects in the range of -128 to 127. 𝘐𝘯𝘵𝘦𝘨𝘦𝘳 𝘱 = 100; 𝘐𝘯𝘵𝘦𝘨𝘦𝘳 𝘲 = 100; Since 100 is in the cache, Java points both variables to the same object memory location. The output is 𝐭𝐫𝐮𝐞. 𝐂𝐎𝐃𝐄 3: 𝘐𝘯𝘵𝘦𝘨𝘦𝘳 𝘺 = 128; 𝘐𝘯𝘵𝘦𝘨𝘦𝘳 𝘻 = 128; Because 128 is outside the cache range, Java creates two distinct objects in memory. Since == compares memory references for objects, the output is 𝐟𝐚𝐥𝐬𝐞. ~Anuprash Gautam 🍵 𝘒𝘦𝘦𝘱 𝘭𝘦𝘢𝘳𝘯𝘪𝘯𝘨 𝘢𝘯𝘥 𝘣𝘳𝘦𝘸𝘪𝘯𝘨 𝘤𝘰𝘧𝘧𝘦𝘦.😊 #Java #programming #autoboxing #oops
To view or add a comment, sign in
-
-
🚀 Java Deep Dive — Daemon Threads (Something many developers overlook) In Java, not all threads behave the same way. There are two types: • User Threads • Daemon Threads The JVM keeps running as long as at least one user thread is alive. But daemon threads work differently. They are background service threads used for supporting tasks like: • Garbage Collection • Monitoring • Background cleanup If all user threads finish, the JVM will terminate immediately, even if daemon threads are still running. Example: Java Example Thread thread = new Thread(() -> { while(true){ System.out.println("Running..."); } }); thread.setDaemon(true); thread.start(); If the main thread finishes, this daemon thread will not keep the JVM alive. Important rule: You must call "setDaemon(true)" before starting the thread, otherwise Java throws "IllegalThreadStateException". 💡 Key Insight Daemon threads are useful for background tasks that should not block application shutdown. #Java #Multithreading #BackendDevelopment #SoftwareEngineering #LearningInPublic
To view or add a comment, sign in
-
Ever wondered what happens behind the scenes when you hit "Run" in Java? 🤔 Let’s break down how the JVM actually executes your code: 1️⃣ Compile – Your .java source code is compiled into bytecode (.class files) by the Java compiler. 2️⃣ Class Load – The JVM loads these classes into memory using the ClassLoader subsystem. 3️⃣ Bytecode Verify – Bytecode is checked for security and correctness. 4️⃣ Interpreter + JIT – The interpreter runs the bytecode line by line. Frequently used code gets compiled into native machine code by the JIT (Just-In-Time) compiler for faster execution. 5️⃣ Execute – The native code runs on the underlying hardware. 🎯 Result? Platform independence + high performance. Q1: Why does Java need both an interpreter and a JIT compiler? A: The interpreter starts execution quickly without waiting for compilation. The JIT compiler optimizes hot paths at runtime, giving the best of both startup speed and long-term performance. Q2: Is bytecode really platform-independent? A: Yes! Bytecode runs on any device with a JVM, which acts as an abstraction layer. The JVM itself is platform-specific, but your code doesn't have to be. Q3: What happens if bytecode fails verification? A: The JVM throws a VerifyError and won't execute the code. This prevents malicious or corrupt code from harming the system. #Java #JVM #Programming #SoftwareEngineering #TechExplained
To view or add a comment, sign in
-
Threads state & Priority in java 🧵 After understanding what thread is and how to create one, the next question is: ➡️What state my thread is and how does the JVM schedule it? 🧠Threads States in Java A thread can be in one of these states during its lifecycle: 🔸NEW Thread is created but not yet started (start() method is not called) 🔸RUNNABLE Thread is ready to run or concurrently running 🔸BLOCKED Waiting to acquire a monitor lock (synchronized block) 🔸 WAITING Waiting indefinitely for another thread to act 🔸TIMED_WAITING Waiting for a specified time( sleep(), wait(timeout), join(timeout) ) 🔸TERMINATED Execution completed 👉A thread doesn't move linearly - it can jump between states multiple times. ---------------------------------------------------------------------- ⚡Thread Priority in Java Each thread has a priority that hints the scheduler: ✓MIN_PRIORITY — 1 ✓NORM_PRIORITY — 5(default) ✓MAX_PRIORITY — 10 ☘️Example: Thread t = new Thread(task); t.setPriority(Thread.MAX_PRIORITY); IMPORTANT ⚠️ 1.Priority is a hint, not a guarantee. 2.Behaviour is OS and JVM dependent. 3.High priority doesn't mean it will always run first. #Java #Threads #Concurrency #Multithreading #SoftwareEngineering #Backend #Programming
To view or add a comment, sign in
-
-
Ever wondered why Java’s main method only accepts String[] args? 🤔 We often see and write public static void main(String[] args) almost every day in codebases, but recently, I paused and asked myself: why is it designed this way? While running a program, I passed a numeric value through the command line. Java accepted it without any issue. That made me stop. If args is a String[], shouldn’t passing a number cause a mismatch? Looking closer, the reasoning became clear 👇 When a program starts, the operating system provides all command-line inputs as text. Even if we pass an int, float, or boolean (for example, 42), the JVM still receives it as "42" — a string. From there, the responsibility is intentionally left to the application to convert inputs to the required type. String[] args isn’t a limitation — it’s what makes Java programs portable across shells, scripts, and CI pipelines, while keeping the interaction between the environment and the application clean. It clearly defines where the JVM stops and application logic begins. 👉 Standardization isn’t just about syntax—it’s what makes programs portable, predictable, and automation-ready. For me, this small doubt turned into a bigger insight: design choices often hide powerful reasoning. 💡 What’s a design choice you’ve questioned that later revealed deeper logic? #Java #SoftwareEngineering #Programming #LearningInPublic #CareerGrowth
To view or add a comment, sign in
-
Journey Today I solved the Anagram String Problem in Java. An anagram means two strings contain the same characters with the same frequency, just arranged in a different order. Example: listen → silent ✅ triangle → integral ✅ 🔍 What I practiced today: String traversal Converting String to char[] using toCharArray() Using Arrays.sort() for comparison Understanding character frequency logic Improving problem-solving thinking 💡 One important learning: Small mistakes like case sensitivity (toCharArray() not tocharArray()) can break the entire program. Attention to detail matters! Consistency is teaching me more than talent ever could. Every day I understand Java a little deeper. 36 days completed. No breaks. Just progress. 💪 #Day36 #CodingJourney #Java #Anagram #ProblemSolving #100DaysOfCode #Consistency #Learning My code ===== //import java.util.Arrays; class Solution { public static boolean areAnagrams(String s1, String s2) { // code here char a[]=s1.toCharArray(); char b[]=s2.toCharArray(); Arrays.sort(a); Arrays.sort(b); if(a.length!=b.length) { return false; } for(int i=0;i<a.length;i++) { if(a[i]!=b[i]) { return false; } } return true; } }
To view or add a comment, sign in
-
-
A variable is a container used to store data that can change during the execution of a program. In Java, every variable must have a data type, which defines what kind of data it can store (like int, double, String, etc.). 🔸 Types of Variables in Java 1️⃣ Local Variable A local variable is declared inside a method, constructor, or block. ✔️ Scope: Accessible only within that method/block ✔️ Lifetime: Exists only while the method is executing ✔️ Must be initialized before use 2️⃣ Instance Variable An instance variable is declared inside a class but outside any method. ✔️ Scope: Accessible throughout the class ✔️ Lifetime: Exists as long as the object exists ✔️ Each object has its own copy 🔎 Quick Difference 🔹 Local Variable → Belongs to a method 🔹 Instance Variable → Belongs to an object #Java #Programming #SoftwareDevelopment #Coding #LearningJourney #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Stop Writing Boilerplate: Java Records in 17+ If you are still writing private final fields, constructors, getters, equals(), hashCode(), and toString() for simple data carriers, it's time to switch to Records. Introduced as a standard feature in Java 17, Records provide a compact syntax to model immutable data. Why use them? ✅ Conciseness: 1 line of code replaces 30+ lines of boilerplate. ✅ Immutability by default: Thread-safe and predictable. ✅ Intent: Explicitly declares that a class is a pure data carrier. // The old way (before Java 14/16) public class User { private final String name; private final int age; public User(String name, int age) { this.name = name; this.age = age; } // ... getters, equals, hashCode, toString ... } // The Java 17 way public record User(String name, int age) {} #java #java17 #programming #softwareengineering #backend
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