Understanding Loops in Java: For, While, and Do-While While learning Java Programming Fundamentals, understanding loops is essential because they help us execute a block of code repeatedly until a condition is met. 🔹 For Loop vs While Loop For Loop: Used when the number of iterations is known. Initialization, condition, and update are written in a single line. Commonly used for counting or iterating through arrays. Example: for(int i = 1; i <= 5; i++){ System.out.println(i); } While Loop: Used when the number of iterations is not known in advance. The loop runs as long as the condition is true. Example: int i = 1; while(i <= 5){ System.out.println(i); i++; } 🔹 While Loop vs Do-While Loop While Loop: Condition is checked before executing the loop. If the condition is false, the loop may not execute even once. Do-While Loop: Condition is checked after executing the loop. The loop will execute at least once, even if the condition is false. Example: int i = 1; do{ System.out.println(i); i++; }while(i <= 5); Key Takeaway: Use for loop when iterations are known. Use while loop when iterations depend on a condition. Use do-while loop when the loop must run at least once. Learning these concepts strengthens the foundation for writing efficient and structured Java programs. #Java #Programming #JavaBasics #Coding #SoftwareDevelopment #LearningJourney #AnandKumarBuddarapu
Java Loops: For, While, and Do-While Explained
More Relevant Posts
-
💻 Today, I learned about Constructors in Java, and it was a very important topic in understanding how objects are created in Object-Oriented Programming. A constructor is a special method in Java that is automatically called when an object is created. Its main purpose is to initialize the object with values. One important point is that the constructor name must be the same as the class name, and it does not have any return type, not even void. In Java, constructors help make the code more organized and allow us to set default or custom values while creating objects. 🔸There are mainly two types of constructors: 1. Default Constructor A default constructor does not take any parameters. It is used to assign default values to the object. 2. Parameterized Constructor A parameterized constructor takes arguments, so we can initialize the object with different values at the time of creation. 🔸Here is a simple example: class Student { String name; int age; Student() { name = "Rakesh"; age = 20; } Student(String n, int a) { name = n; age = a; } void display() { System.out.println("Name: " + name + ", Age: " + age); } public static void main(String[] args) { Student s1 = new Student(); Student s2 = new Student("Kiran", 22); s1.display(); s2.display(); } } Through this topic, I understood that constructors are very useful because they make object creation easier and help initialize data properly from the beginning. Learning Java step by step is helping me build a strong foundation in programming, and today’s topic gave me more clarity about how classes and objects work in real-time. #Java #Programming #LearningJava #OOP #Constructors #JavaDeveloper #CodingJourney #Students #SoftwareDevelopment Meghana M 10000 Coders
To view or add a comment, sign in
-
Day 42 of My Java Learning Journey – Rules of Interface Today I explored the Rules of Interfaces in Java, which play a crucial role in achieving abstraction, polymorphism, and loose coupling in object-oriented programming. An Interface acts like a contract that defines what a class must implement. 🔹 Key Rules of Interfaces in Java: 1️⃣ Interface acts as a contract When a class implements an interface, it must provide implementation for its methods. 2️⃣ Interfaces promote polymorphism An interface reference can point to objects of implementing classes, helping achieve flexibility and loose coupling. 3️⃣ Methods in an interface are automatically public and abstract Example: void fun(); → public abstract void fun(); 4️⃣ Specialized methods cannot be accessed directly using an interface reference They can be accessed by downcasting the interface reference. 5️⃣ If a class partially implements an interface, it must be declared abstract. 6️⃣ A class can implement multiple interfaces This avoids the diamond problem, since interfaces do not have constructors. 7️⃣ An interface cannot implement another interface Because interfaces only declare methods, not implementations. 8️⃣ An interface can extend another interface It can also extend multiple interfaces, enabling multiple inheritance in Java. 9️⃣ A class can extend a class and implement an interface simultaneously Order must be: extends → implements 🔟 Variables inside interfaces are automatically: public static final (constants) 1️⃣1️⃣ Marker Interface An empty interface used to mark a class (e.g., Serializable). 1️⃣2️⃣ Objects of interfaces cannot be created But interface references can point to implementing class objects, enabling polymorphism. #Java #JavaLearning #Interfaces #ObjectOrientedProgramming #ProgrammingJourney #DeveloperLearning
To view or add a comment, sign in
-
-
💡 Java Concept: Exception Handling in Method Overriding 🚀 While learning Java, I discovered an important rule that many beginners miss 👇 👉 How exceptions behave when a child class overrides a parent method 🔹 Simple Definition When a subclass overrides a method, it cannot throw broader or new checked exceptions than the superclass. 🧠 Golden Rule 👉 Child class can: ✔ Throw same exception ✔ Throw smaller (child) exception ✔ Throw unchecked exception ✔ Throw no exception 👉 Child class cannot: ❌ Throw new checked exception (not in parent) 🔴 Example (Wrong ❌) class Parent { void show() { } } class Child extends Parent { void show() throws IOException { // ❌ Compile Error System.out.println("Child"); } } 👉 Reason: Parent didn’t declare any exception 🟢 Example (Correct ✅) class Parent { void show() throws Exception { System.out.println("Parent"); } } class Child extends Parent { void show() throws ArithmeticException { System.out.println("Child"); } } 👉 Allowed because: ✔ ArithmeticException is unchecked ✔ OR smaller than parent exception 💡 Why this rule exists? To maintain runtime safety and avoid unexpected errors Parent p = new Child(); p.show(); 👉 Compiler only knows Parent → so child cannot introduce new checked exceptions 🔥 Easy Trick to Remember 👉 "Child can reduce risk, but not increase it" 📌 Small concept, but very important for interviews & real-world coding! #Java #OOP #ExceptionHandling #Programming #Developers #Coding #SoftwareEngineering #LearningJourney
To view or add a comment, sign in
-
-
🚀 Day – Java Learning Update ⏳ 🎯 Understanding Switch Case in Java Today, I learned about the Switch Case statement in Java, which is used to execute different blocks of code based on the value of a variable or expression. It is mainly used when we have multiple conditions to check for a single variable, making the code more readable compared to many if-else statements. 🔹 What is Switch Case? The switch statement allows a variable to be tested against multiple possible values called cases. ✔ Each case represents a possible value ✔ break stops execution after a case runs ✔ default runs if no case matches 🔹 Syntax of Switch Case switch(expression) { case value1: // code block break; case value2: // code block break; case value3: // code block break; default: // default code block } 🧑💻 Task Practiced: Traffic Signal Program I implemented a simple program using switch case to represent a traffic signal. #Java #CoreJava #JavaFullStack #SwitchCase #Programming #SoftwareDeveloper #LearningJourney 10000 Coders Meghana M
To view or add a comment, sign in
-
-
🚀 Starting My Java Learning Journey – Day 6 🔹 Topic: Loops in Java Loops in Java are used to execute a block of code repeatedly until a certain condition is met. Java mainly provides three types of loops: 1️⃣ for Loop Used when the number of iterations is known. Example: public class Main { public static void main(String[] args) { for(int i = 1; i <= 5; i++) { System.out.println(i); } } } 2️⃣ while Loop Used when the number of iterations is not known beforehand. Example: public class Main { public static void main(String[] args) { int i = 1; while(i <= 5) { System.out.println(i); i++; } } } 3️⃣ do-while Loop The do-while loop executes the code at least once even if the condition is false. Example: public class Main { public static void main(String[] args) { int i = 1; do { System.out.println(i); i++; } while(i <= 5); } } 💡 Key Point: Loops help automate repetitive tasks and make programs more efficient. #Java #JavaLearning #Programming #BackendDevelopment #CodingJourney #JavaLoops
To view or add a comment, sign in
-
Day 4 – Understanding Garbage Collection in Java ⏳ 1 Minute Java Clarity – How Java manages memory automatically When I first heard about Garbage Collection, I thought it was just a fancy Java term. But it’s actually one of the reasons Java programs manage memory efficiently. Here’s the simple idea 👇 🧹 What is Garbage Collection? Garbage Collection is the process where the JVM automatically removes unused objects from memory. This helps free up space in Heap memory. 📦 How objects become eligible for Garbage Collection An object becomes eligible when no reference is pointing to it anymore. Example: Student s = new Student(); s = null; 👉 The Student object no longer has any reference 👉 JVM marks it as eligible for Garbage Collection 🧐 Why is Garbage Collection useful? ✔ Prevents memory leaks ✔ Automatically manages memory ✔ Reduces manual memory handling (unlike some other languages) 💡 Important thing to remember Even though Java has Garbage Collection, developers still need to write efficient and clean code to avoid unnecessary memory usage. 📌 I’ve also added a simple visual summary in the image for quick understanding. Sometimes the power of a language is not just in writing code, but in how it manages things behind the scenes. 🔹 Next in my #1MinuteJavaClarity series → JDK vs JRE vs JVM ❓ When did Garbage Collection finally make sense to you? #Java #BackendDeveloper #JavaFullStack #LearningInPublic #OpenToWork #SoftwareEngineering #Programming #JavaProgramming #TechCommunity
To view or add a comment, sign in
-
-
Day 21 of Learning Java Continuing my Java journey! On Day 21, I learned about: ✅ Immutable Classes ✅ How Immutable Objects Work ✅ Defensive Copying ✅ Why String is Immutable ✅ Common Interview Questions on Immutability 🔹 What is an Immutable Class? An immutable class is a class whose object state cannot be changed after it is created. Once the object is initialized, its data remains constant throughout its lifetime. A common example in Java is the String class. 🔹 Key Rules to Create an Immutable Class To make a class immutable: • Declare the class as final • Make all variables private and final • Initialize variables through the constructor • Do not provide setter methods • If the class contains mutable objects, use defensive copying 🔹 What is Defensive Copying? Defensive copying means returning a copy of an object instead of the original reference so that the internal state of the object cannot be modified externally. 🔹 Why is String Immutable? (Very Common Interview Question) String is immutable mainly because of: • Security (used in networking, file paths, class loading) • Thread safety • String Pool optimization • Hashcode caching for performance 1️⃣ What is an immutable object? An object whose state cannot change after creation. 2️⃣ Why are immutable objects thread-safe? Because their state cannot be modified after creation. 3️⃣ Can immutable classes contain mutable objects? Yes, but they must use defensive copying. 4️⃣ Give examples of immutable classes in Java. String, Integer, Boolean, LocalDate. 5️⃣ What is the advantage of immutability? Better security, thread safety, and predictability. special thanks to Aditya Tandon Rohit Negi sir
To view or add a comment, sign in
-
-
🚀 Starting My Java Learning Journey – Day 5 🔹 Topic: Control Statements in Java Control statements are used to control the flow of execution of a program based on certain conditions. In Java, the main control statements are: 1️⃣ if Statement The if statement executes a block of code only if the condition is true. Example: public class Main { public static void main(String[] args) { int num = 10; if (num > 0) { System.out.println("Number is positive"); } } } 2️⃣ if-else Statement The if-else statement executes one block of code if the condition is true and another block if it is false. Example: public class Main { public static void main(String[] args) { int num = -5; if (num > 0) { System.out.println("Positive number"); } else { System.out.println("Negative number"); } } } 3️⃣ switch Statement The switch statement is used when we want to compare one value with multiple possible cases. Example: public class Main { public static void main(String[] args) { int day = 2; switch(day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; default: System.out.println("Other day"); } } } 💡 Key Point: Control statements help make programs dynamic and decision-based. #Java #JavaLearning #Programming #BackendDevelopment #CodingJourney #ControlStatements
To view or add a comment, sign in
-
☕ Java Handwritten Notes 📘 I’m sharing Java Handwritten Notes that cover all the essential programming concepts in a simple, structured, and easy-to-revise format. These notes include: • Introduction to Java • Variables & Data Types • Operators • Conditional Statements (if–else, switch) • Loops (for, while, do-while) • Functions / Methods • Arrays & Strings • Object-Oriented Programming (OOP) • Classes & Objects • Inheritance & Polymorphism • Exception Handling • Basic Java Concepts 💡 Perfect for students, beginners, and quick revision before interviews 📌 All credits go to the original creator of this material. If you want the PDF, just comment “Java Notes” below 👇 — I’ll share it with you! Let’s keep learning and growing . #Java #Programming #Coding #JavaDeveloper #Developers #ComputerScience #Learning
To view or add a comment, sign in
-
🚀 Understanding Strings in Java – A Fundamental Concept for Every Developer While learning Java, one of the most important topics to understand is Strings and how Java manages them in memory. 🔹 A String is a sequence of characters enclosed in double quotes, like "JAVA". 🔹 In Java, Strings are treated as objects and stored in the heap memory. 📌 Key Concepts I Learned: ✅ Immutable vs Mutable Strings Immutable: Cannot be changed after creation (e.g., names, date of birth). Mutable: Values that may change, like passwords or email IDs. ✅ String Pool & Memory Allocation Constant Pool → Created without new keyword (String s = "JAVA";) Non-Constant Pool → Created using new keyword (new String("JAVA")) Duplicate literals share the same memory reference in the pool. ✅ String Comparison Methods in Java == → Compares memory reference equals() → Compares actual string value compareTo() → Compares character by character equalsIgnoreCase() → Compares values ignoring case 💡 Example Insight: Two "JAVA" literals may refer to the same memory location, but new String("JAVA") always creates a new object. Understanding these fundamentals helps write efficient and optimized Java programs. 📚 Currently exploring more core Java concepts and strengthening my programming foundation in TAP Academy . #Java #Programming #JavaDeveloper #Coding #SoftwareDevelopment #LearningJava #CoreJava #Developers
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