☕ Java for-each Loop – Enhanced Loop Simplified The for-each loop (also called the enhanced for loop) in Java is a powerful repetition control structure that makes iterating over arrays and collections simple and readable. It is especially useful when: ✔ You need to execute a loop a specific number of times ✔ You want to iterate without using an index ✔ You don’t know the exact number of iterations 🔹 Syntax of for-each Loop for (declaration : expression) { // Statements } Execution Process: Declaration → A variable compatible with the array element type Expression → The array or collection being iterated The declared variable holds the current element during each iteration. 🔹 Example 1: Iterating Over a List of Integers List<Integer> numbers = Arrays.asList(10, 20, 30, 40, 50); for (Integer x : numbers) { System.out.print(x); System.out.print(","); } 📌 Output: 10, 20, 30, 40, 50, 🔹 Example 2: Iterating Over a List of Strings List<String> names = Arrays.asList("James", "Larry", "Tom", "Lacy"); for (String name : names) { System.out.print(name); System.out.print(","); } 📌 Output: James, Larry, Tom, Lacy, 🔹 Example 3: Iterating Over an Array of Objects Student[] students = { new Student(1, "Julie"), new Student(3, "Adam"), new Student(2, "Robert") }; for (Student student : students) { System.out.print(student); System.out.print(","); } This demonstrates how the enhanced for loop works seamlessly with custom objects as well. 💡 The for-each loop improves readability, reduces boilerplate code, and minimizes errors related to index handling. Mastering looping concepts is essential for writing clean and efficient Java programs. #Java #ForEachLoop #EnhancedForLoop #JavaProgramming #Collections #Arrays #Coding #FullStackJava #Developers #AshokIT
Java For-Each Loop Simplified with Examples
More Relevant Posts
-
💡 Java Tip: Using getOrDefault() in Maps When working with Maps in Java, we often need to handle cases where a key might not exist. Instead of writing extra conditions, Java provides a simple and clean method: getOrDefault(). 📌 What does it do? getOrDefault(key, defaultValue) returns the value for the given key if it exists. Otherwise, it returns the default value you provide. ✅ Example: Map<String, Integer> map = new HashMap<>(); map.put("apple", 10); map.put("banana", 20); System.out.println(map.getOrDefault("apple", 0)); // Output: 10 System.out.println(map.getOrDefault("grapes", 0)); // Output: 0 🔎 Why use it? • Avoids null checks • Makes code shorter and cleaner • Very useful for frequency counting problems 📊 Common Use Case – Counting frequency map.put(num, map.getOrDefault(num, 0) + 1); This small method can make your code more readable and efficient. Thankful to my mentor, Anand Kumar Buddarapu, and the practice sessions that continue to strengthen my core Java knowledge. Continuous learning is the key to growth! #Java #Programming #JavaDeveloper #CodingTips #SoftwareDevelopment
To view or add a comment, sign in
-
-
🚀 Learning Core Java – Immutable Strings & String Comparison Today, I learned more about Immutable Strings in Java and the different ways to compare them. In Java, the String class is immutable, which means once a string object is created, its value cannot be changed. Any modification results in a new object being created in memory. Because strings are objects, Java provides multiple built-in methods to compare them in different ways. ⸻ 🔹 1️⃣ == (Reference Comparison) The == operator compares references (memory addresses), not actual content. If two string variables point to the same object, it returns true. Otherwise, false — even if the content is the same. ⸻ 🔹 2️⃣ equals() (Value Comparison) The equals() method compares actual string values (content). It checks whether the characters inside both strings are the same. ⸻ 🔹 3️⃣ compareTo() (Character-by-Character Comparison) The compareTo() method compares strings lexicographically (character by character). • Returns 0 → if both strings are equal • Returns positive value → if first string is greater • Returns negative value → if first string is smaller ⸻ 🔹 4️⃣ equalsIgnoreCase() This method compares string values while ignoring uppercase and lowercase differences. ⸻ 🔹 5️⃣ compareToIgnoreCase() This compares strings character by character, ignoring case differences. ⸻ 🔎 Key Takeaway: • Use == for reference comparison • Use equals() for content comparison • Use compareTo() for sorting or lexicographical comparison • Use ignore-case methods when case sensitivity doesn’t matter Understanding these differences helps avoid common bugs and write more predictable Java programs. Excited to keep strengthening my Java fundamentals! 🚀 #CoreJava #JavaProgramming #ImmutableString #JavaDeveloper #StringComparison #ProgrammingFundamentals #LearningJourney #StudentDeveloper
To view or add a comment, sign in
-
-
🚀 Day 25 – Core Java | Method Overloading & Compile-Time Polymorphism Today’s session was not just about syntax. It was about understanding how Java actually thinks. We deeply explored one of the most important OOP concepts: 🔹 Method Overloading ✔ Multiple methods ✔ Same method name ✔ Within the same class ✔ Different parameter list But we didn’t stop at the definition. 🔎 What Really Happens Internally? We understood the 3 Rules Java Compiler Follows: 1️⃣ Method Name 2️⃣ Number of Parameters 3️⃣ Type of Parameters And this happens during Compilation Phase, not execution. That’s why method overloading is called: Compile-Time Polymorphism Static Binding Early Binding False Polymorphism 🔹 Type Promotion If an exact match is not found, Java performs implicit type casting (type promotion) and selects the closest possible method. Example: int can promote to long or float. Understanding this prevents major confusion in interviews. 🔹 Ambiguity If two methods are equally eligible after type promotion → Java throws: “Method is ambiguous” That means even the compiler gets confused. This is where most candidates fail in interviews. 🔹 Real Example of Method Overloading in Java We discovered something powerful: System.out.println() itself is overloaded. It accepts: int float double char String Object We were using overloading from Day 1 — but never realized it. That realization changes perspective. 💡 Biggest Takeaway Anyone can say: “Method overloading means multiple methods with same name.” But very few can explain: Compiler rules Type promotion Ambiguity Real-world example Internal behavior That difference is what creates interview impact. Day 25 strengthened OOP fundamentals before moving deeper into Object-Oriented Programming pillars. Consistency + Clarity + Practice = Confidence 🚀 #Day25 #CoreJava #MethodOverloading #Polymorphism #JavaInterview #OOPS #DeveloperJourney
To view or add a comment, sign in
-
🚀 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
To view or add a comment, sign in
-
-
Day 40 – Java 2026: Smart, Stable & Still the Future Topic: Object in Java (Core of OOP) What is an Object? An object is a runtime instance of a class that represents a real-world entity. It contains: • State (variables) • Behavior (methods) • Identity (unique memory location) Steps to Create an Object Declare a reference variable Create an object using the new keyword Assign object to reference Student s1 = new Student(); Reference Variable A reference variable stores the memory address of an object, not the actual object. It is used to access the object. Example: s1 → reference variable new Student() → object Declaration and Initialization Declaration only Student s1; Initialization only s1 = new Student(); Declaration + Initialization Student s1 = new Student(); Object vs Reference Variable FeatureObjectReference VariableMemory LocationHeapStackStoresActual dataAddress of objectCreated Usingnew keywordClass typeExamplenew Student()s1Key Points • One class can create multiple objects • Each object has separate memory • Reference variable points to object • Objects are created at runtime • Java programs work using objects Simple Example class Student { String name; } public class Main { public static void main(String[] args) { Student s1 = new Student(); s1.name = "Sneha"; System.out.println(s1.name); } } Key Takeaway: Object = Real entity Reference = Way to access that entity #Java #40 #OOP #LearnJava #JavaDeveloper #Programming #100DaysOfCode #CareerGrowth
To view or add a comment, sign in
-
-
DAY 26: CORE JAVA 🚀 Understanding the Use Cases of Static Variables and Static Methods in Java In Java, the "static" keyword plays a powerful role in managing shared data and class-level behavior. It allows variables and methods to belong to the class itself rather than to individual objects. Let’s explore why and when we use them. 👇 🔹 Static Variables (Class Variables) Static variables are shared among all objects of a class. Only one copy exists in memory, making them highly efficient. ✅ Use Cases • Storing common data shared by all objects (e.g., interest rate, company name, configuration values) • Reducing memory usage since the variable is created only once • Accessing class-level constants and configuration settings Example: class Businessman { static float rate = 15.2f; // shared interest rate } Here, every object of "Businessman" will use the same interest rate value. 🔹 Static Methods Static methods belong to the class, not the object. They can be called without creating an instance of the class. ✅ Use Cases • Utility or helper methods (e.g., Math calculations) • When method logic does not depend on instance variables • Entry point of Java programs ("main()" method) Example: class Test { static void display() { System.out.println("Inside static method"); } } Called as: Test.display(); 🔹 Key Advantages ✔ Efficient memory utilization ✔ Easy access without object creation ✔ Useful for shared data and utility functions ✔ Improves program organization and readability 📌 Real-world example: In a simple interest calculator, the interest rate can be static because it remains the same for all customers. 💡 Takeaway: Use static variables for shared data and static methods for operations that do not depend on object state. TAP Academy #Java #Programming #JavaDevelopment #Coding #SoftwareEngineering #LearnToCode
To view or add a comment, sign in
-
-
🚀 Mastering Core Java | Day 10 📘 Topic: Exception Handling Today’s session focused on Exception Handling, a critical concept in Java that helps manage runtime errors gracefully and ensures smooth program execution. 🔑 What is an Exception? An unexpected event that disrupts normal program flow Occurs during execution (e.g., invalid input, missing files, divide by zero) If not handled, it can cause program termination 🧠 Why Exception Handling is Important? Prevents application crashes Improves program reliability and stability Separates error-handling logic from core business logic Makes debugging and maintenance easier 🧩 Key Keywords in Exception Handling: try – Contains risky code catch – Handles the exception finally – Executes whether an exception occurs or not throw / throws – Used to explicitly pass exceptions Simple Syntax & Example: try { int result = 10 / 0; } catch (ArithmeticException e) { System.out.println("Cannot divide by zero"); } finally { System.out.println("Execution completed"); } 📌 Types of Exceptions: Compile‑Time (Checked) – Detected at compile time Examples: IOException, SQLException Run‑Time (Unchecked) – Occur during execution Examples: NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException 💡 Key Takeaway: Exception Handling allows applications to handle errors gracefully, improving user experience and making systems more robust. Grateful to my mentor Vaibhav Barde sir for the clear explanations and real‑world examples, which made this concept easy to understand and apply. 📈 Continuing to strengthen my Core Java and OOP fundamentals step by step. #ExceptionHandling #CoreJava #JavaLearning #Day10 #OOPConcepts #SoftwareDevelopment #LearningJourney #ProfessionalGrowth
To view or add a comment, sign in
-
-
Day 42 – Java 2026: Smart, Stable & Still the Future Topic: Constructor in Java What is a Constructor? A constructor is a special method in Java that is automatically executed when an object is created. It is mainly used to initialize object data. Simple definition: A constructor initializes the state of an object at the time of object creation. Rules for Creating a Constructor • Constructor name must be the same as the class name • Constructor does not have a return type (not even void) • Constructor is automatically called when the object is created • Can be overloaded • Cannot be static, final, or abstract • If no constructor is written, Java provides a default constructor Types of Constructors in Java Default Constructor No-Argument Constructor Parameterized Constructor Copy Constructor (User-defined) One-Line Explanation of Each Constructor 1. Default Constructor Automatically provided by JVM when no constructor is defined in the class. 2. No-Argument Constructor A constructor explicitly created by programmer that takes no parameters. 3. Parameterized Constructor A constructor that accepts parameters to initialize object values. 4. Copy Constructor A constructor that copies values from one object to another object. Small Example (All Types) class Student { String name; int age; // No-Argument Constructor Student() { name = "Unknown"; age = 0; } // Parameterized Constructor Student(String n, int a) { name = n; age = a; } // Copy Constructor Student(Student s) { name = s.name; age = s.age; } } public class Main { public static void main(String[] args) { Student s1 = new Student(); // No-arg Student s2 = new Student("Sneha", 22); // Parameterized Student s3 = new Student(s2); // Copy System.out.println(s1.name + " " + s1.age); System.out.println(s2.name + " " + s2.age); System.out.println(s3.name + " " + s3.age); } } Key Points • Constructor runs only once per object • Used for initialization • Supports overloading • Improves object creation control Key Takeaway: Constructor ensures every object starts with a valid and predictable state. #Java #Constructor #OOP #LearnJava #JavaDeveloper #Programming #100DaysOfCode
To view or add a comment, sign in
-
More from this author
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