🚀 Day 4/100 — If-Else & Switch in Java 🚦 Conditions are the brain of a program. They help your program make decisions based on different situations. In Java, the most common decision-making statements are if, else if, else, and switch. 🔹 If-Else Statement Used when a program needs to execute code based on a condition. Example: int age = 20; if(age >= 18){ System.out.println("Eligible to vote"); }else{ System.out.println("Not eligible to vote"); } ✔ If the condition is true, the first block runs. ✔ If it's false, the else block runs. 🔹 Else If Ladder Used when there are multiple conditions. ⚠️ Important: Java checks conditions top to bottom, and once one condition becomes true, the rest are skipped. Example: int marks = 85; if(marks >= 90){ System.out.println("Grade A"); } else if(marks >= 75){ System.out.println("Grade B"); } else if(marks >= 60){ System.out.println("Grade C"); } else{ System.out.println("Grade D"); } 🔹 Switch Statement Used when comparing one variable with multiple values. Example: int day = 3; switch(day){ case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; default: System.out.println("Invalid day"); } ⚠️ Important: If you forget break, Java will execute all cases after that one (called fall-through). Example without break: int num = 1; switch(num){ case 1: System.out.println("One"); case 2: System.out.println("Two"); case 3: System.out.println("Three"); } Output: One Two Three 🔴 Mini Example — Pass or Fail int marks = 40; if(marks >= 35){ System.out.println("Pass"); }else{ System.out.println("Fail"); } 🎯 Challenge: Build a Grade Calculator using if-else. Example logic: 90+ → Grade A 75–89 → Grade B 60–74 → Grade C Below 60 → Grade D Drop your solution in the comments 👇 #Java #CoreJava #100DaysOfCode #JavaLearning #ProgrammingJourney
Allaka Yamuna lakshmi’s Post
More Relevant Posts
-
🚀 Today I dived deep into Exception Handling in Java! Have you ever seen a "software not responding" popup or had an app suddenly crash?,. That is often because of an unhandled exception. What is an Exception? In Java, an exception is an unusual event that occurs during the runtime (execution) of a program,,. It is usually triggered by faulty user input—like trying to divide a number by zero or providing a string when a number is expected,,. If these aren't handled, they lead to abrupt termination, which ruins the user experience and can cause significant losses for a company,. How it works behind the scenes: When a problem occurs, the JVM automatically creates an Exception Object,. This object contains the "What" (type of error), "Where" (line number), and "Why" (the reason),. If we don't catch it, the Default Exception Handler prints the error and stops the program immediately,. The Solution: Try-Catch Blocks To ensure normal termination, we follow three simple steps: 1.Identify risky lines of code where a problem might occur,. 2.Place that code inside a try block,. 3.Write a catch block to intercept the exception object and handle it gracefully,. Pro Tip: The Order of Catch Blocks Matters! ⚠️ You can have multiple catch blocks for different errors (like ArithmeticException or ArrayIndexOutOfBoundsException),. However, you must always put specific exceptions first and the general Exception class last,. If you put the general one first, the specific ones become unreachable code because the general class has the capability to catch everything. Code Example: import java.util.Scanner; public class ExceptionDemo { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Connection established."); try { // Step 1 & 2: Identify and wrap risky code, System.out.print("Enter numerator: "); int a = scan.nextInt(); System.out.print("Enter denominator: "); int b = scan.nextInt(); int result = a / b; // Risky line: ArithmeticException if b=0 System.out.println("Result: " + result); } catch (ArithmeticException e) { // Step 3: Handle specific exception, System.out.println("Error: Please enter a non-zero denominator."); } catch (Exception e) { // General catch-all for other unexpected issues System.out.println("Some technical problem occurred."); } System.out.println("Connection terminated.");, } } Looking forward to exploring rethrowing and ducking exceptions tomorrow!. #Java #Coding #BackendDevelopment #ExceptionHandling #LearningJourney #SoftwareEngineering #TapAcademy
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
-
🚀 Day 6/100 — Methods in Java 🔧 As programs grow bigger, repeating the same code again and again becomes messy. This is where methods help. A method is a reusable block of code that performs a specific task. Instead of rewriting logic multiple times, you write it once and call it whenever needed. This follows the DRY principle — Don't Repeat Yourself. 🔹 Basic Method Syntax returnType methodName(parameters){ // method body } Example: public static void greet(){ System.out.println("Hello Java!"); } Calling the method: greet(); Output: Hello Java! 🔹 Method with Parameters Parameters allow methods to work with different inputs. Example: public static void add(int a, int b){ int sum = a + b; System.out.println(sum); } add(5, 3); Output: 8 🔹 Method with Return Value Sometimes a method needs to return a result. Example: public static int square(int num){ return num * num; } int result = square(4); System.out.println(result); Output: 16 🔹 Method Overloading Java allows multiple methods with the same name but different parameters. This is called method overloading. Java automatically chooses the correct method based on the arguments. Example: public static int add(int a, int b){ return a + b; } public static int add(int a, int b, int c){ return a + b + c; } Usage: System.out.println(add(5,3)); // calls first method System.out.println(add(5,3,2)); // calls second method 🔴 Live Example — Max of 3 Numbers public static int max(int a, int b, int c){ if(a >= b && a >= c){ return a; } else if(b >= a && b >= c){ return b; } else{ return c; } } public static void main(String[] args){ int result = max(10, 25, 15); System.out.println("Maximum number is: " + result); } Output: Maximum number is: 25 🎯 Challenge: Write a method to find the maximum of 3 numbers and test it with different inputs. Drop your solution in the comments 👇 #Java #CoreJava #100DaysOfCode #JavaMethods #ProgrammingJourney
To view or add a comment, sign in
-
-
Java 26 just dropped! But most developers have not even adopted Java 21 features yet. Here are 5 modern Java features you should be using every single day. —— 1. Switch Expressions: clean and exhaustive (Java 14+) // Before: verbose, fall-through prone String label; switch (status) { case ACTIVE: label = "Active"; break; case PENDING: label = "Pending"; break; default: label = "Unknown"; } // After: String label = switch (status) { case ACTIVE -> "Active"; case PENDING -> "Pending"; default -> "Unknown"; }; No fall-through bugs. Compiler ensures all cases are handled. —— 2. Text Blocks: readable multiline strings (Java 15+) // Before: String json = "{\n \"name\": \"Alice\",\n \"role\": \"admin\"\n}"; // After: String json = """ { "name": "Alice", "role": "admin" } """; Clean SQL, JSON, HTML — no escape characters. Just readable strings. —— 3. Optional: use it properly (Java 8+, daily practice) // Bad: Optional user = userRepo.findById(id); if (user.isPresent()) { return user.get(); } return null; // Good: return userRepo.findById(id) .orElseThrow(() -> new UserNotFoundException("User not found: " + id)); Optional exists to eliminate null checks — not to wrap them. Never use .get() alone. Always orElseThrow() or orElse(). —— 4. Pattern Matching for Switch: Java 21 flagship (Java 21) // Before: fragile instanceof chain if (obj instanceof Integer i) return "int: " + i; if (obj instanceof String s) return "str: " + s; // After: clean, compiler-verified return switch (obj) { case Integer i -> "int: " + i; case String s -> "str: " + s; default -> "unknown"; }; // Even better with guards: return switch (order) { case Order o when o.isPaid() -> "Paid"; case Order o when o.isPending() -> "Pending"; default -> "Unknown"; }; Replaces entire if-instanceof chains. Safe, readable, exhaustive. —— 5. New String methods: small but mighty (Java 11–17) input.strip(); // Unicode-aware trim() input.isBlank(); // true if empty or whitespace input.repeat(3); // repeats string N times "line1\nline2".lines(); // Stream by line "hello %s".formatted("world"); // cleaner than String.format() No libraries needed. Used constantly. Zero excuses not to. ---------------------------------------------------------------- Java is not the verbose language it used to be. Pick one feature. Use it in your next PR. Then the next one. Java 26 post coming next. Stay tuned! Which one are you already using daily? Drop a number below.. #Java #Java17 #Java21 #BackendDevelopment #SpringBoot #SoftwareEngineering #CleanCode
To view or add a comment, sign in
-
🚀 Java Wrapper Classes: Hidden Behaviors That Trip Up Even Senior Developers Most developers know wrapper classes. Very few understand what happens under the hood — and that’s exactly where top companies separate candidates. Here’s a deep dive into the concepts that actually matter 1. Integer Caching Integer a = 4010; Integer b = 4010; System.out.println(a == b); // false Integer c = 127; Integer d = 127; System.out.println(c == d); // true Q.Why? Java caches Integer values in the range -128 to 127. Inside range → same object (cached) Outside range → new object (heap) 💡 Pro Insight: You can even extend this range using: -XX:AutoBoxCacheMax=<size> 2. == vs .equals() — Silent Bug Generator System.out.println(a == b); // false → reference comparison System.out.println(a.equals(b)); // true → value comparison Using == with wrapper objects is one of the most common production bugs. Rule: == → checks memory reference .equals() → checks actual value 3. hashCode() vs identityHashCode() System.out.println(a.hashCode()); System.out.println(System.identityHashCode(a)); Two objects can have: Same value → same hashCode() Different memory → different identityHashCode() 4. Silent Overflow in Primitive Conversion Integer a = 4010; byte k = a.byteValue(); // -86 What actually happens: byte range = -128 to 127 4010 % 256 = 170 170 interpreted as signed → -86 No error. No warning. This is how real-world bugs sneak into systems. 5. Powerful Utility Methods (Underrated) Integer.toBinaryString(4010); Integer.toHexString(4010); Integer.bitCount(4010); Integer.numberOfLeadingZeros(4010); Useful in: Bit manipulation Competitive programming Low-level optimization 6. Character & Boolean — Also Cached Boolean b1 = true; Boolean b2 = true; System.out.println(b1 == b2); // true Boolean → fully cached Character → cached in ASCII range 7. Character Utilities = Clean Code Character.isLetter('a'); Character.isDigit('3'); Character.isWhitespace('\t'); Character.toUpperCase('a'); The Big Picture Wrapper classes are NOT just primitives with methods. They reveal how Java handles: Memory optimization Object identity Autoboxing behavior Performance trade-offs A big thanks to my mentors Syed Zabi Ulla, peers, and the amazing developer community Oracle for continuously pushing me to go beyond basics and truly understand concepts at a deeper level. #Java #JVM #CoreJava #CodingInterview #FAANG #SoftwareEngineering #BackendDevelopment #ProgrammingTips
To view or add a comment, sign in
-
-
Optional Misuse Patterns in Java: The Problem: A user lookup crashes in production with NoSuchElementException. The developer is confused — they used Optional, so it should be safe. But they called .get() directly without checking if the value is present. The Optional wrapper added zero safety. Root Cause: Optional was introduced in Java 8 to make absent values explicit and force callers to handle the empty case. But calling .get() on an empty Optional throws NoSuchElementException — just as calling a method on null throws NullPointe java User u = userRepo.findById(id).get(); That one line is no safer than a null dereference. Optional.get() on an empty Optional throws NoSuchElementException. Calling a method on null throws NullPointerException. Different exception, identical outcome. The Optional wrapper added zero protection. Optional was introduced to make absence explicit and force the caller to handle it. But calling .get() skips the entire contract. You have paid the ceremony tax with zero safety benefit. The other anti-pattern is isPresent() + get() — it works, but it is just a verbose null check. The same bug is still possible if someone removes the isPresent() guard later. Three correct patterns: java // 1 — fail with a meaningful exception (service layer default) .orElseThrow(() -> new UserNotFoundException(id)) // 2 — provide a safe default .orElse(User.anonymous()) // 3 — return Optional to caller, let them decide return userRepo.findById(id); Prevention Checklist: ->Never call Optional.get() without an explicit guard ->Prefer orElseThrow() at service layer — fail fast with meaningful exception ->Use orElseGet() instead of orElse() when the default is expensive to create ->Return Optional<T> from repo/service when absence is expected and valid ->Never use Optional as a method parameter or entity field — only as return type ->Enable IntelliJ inspection: "Optional.get() without isPresent()" Lesson: Optional.get() without a guard is just a different way to write a NPE. Optional forces you to think about the empty case — use its API to handle it. orElseThrow() for service layers. orElse() for defaults. Return Optional when absence is valid. Never call .get() directly. It is not a safe operation. #Java #DataStructures #DSA #SystemDesign #SpringBoot #BackendDevelopment #SoftwareEngineering #JavaDeveloper #Programming
To view or add a comment, sign in
-
-
🚨 This Java code looks 100% illegal. But it compiles. It runs. And it does something MAGICAL. outer: for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (i == 1 && j == 1) { break outer; // ← THIS LOOKS WRONG! } System.out.println(i + "," + j); } } Output: 0,0 0,1 0,2 1,0 Then it STOPS. Completely. Both loops. Gone. 💨 First time I saw this I thought: ❌ Is "outer" a variable? ❌ Is this some framework keyword? ❌ Did someone hack Java?! Nope. This is 100% pure Java. And it's called ➡️ Labeled break ━━━━━━━━━━━━━━━━━━ 🔍 What is happening here? ━━━━━━━━━━━━━━━━━━ Normally break only exits the INNER loop. But what if you want to break out of the OUTER loop from deep inside nested loops? Java gives you a secret weapon: You can NAME a loop with a label! outer: ← this names the outer loop Then break outer instantly kills BOTH loops no matter how deep you are! 🎯 Same trick works with continue: outer: for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (j == 1) { continue outer; // skips to next i! } System.out.println(i + "," + j); } } Output: 0,0 1,0 2,0 continue outer skips the rest of the INNER loop and jumps straight to the next iteration of OUTER! 🤯 ━━━━━━━━━━━━━━━━━━ 💡 When to use this? ━━━━━━━━━━━━━━━━━━ ✅ Searching in a 2D matrix — stop when found ✅ Parsing nested data — skip entire blocks ✅ Game loops — exit multiple layers cleanly ✅ Any time nested breaks make your code messy I am a Java beginner and this blew my mind today. Imagine dropping this in a Java interview! 🏆 Most senior developers I showed this to said: "Wait... Java can do THAT?!" Comment "LABEL" if you already knew this! Comment "MIND BLOWN" if you didn't! 👇 Follow me — I find Java secrets that nobody talks about. 🚀 #Java #JavaDeveloper #JavaTips #HiddenJava #JavaMagic #CodingSecrets #JavaInterview #LearnJava #Programming #SoftwareDevelopment
To view or add a comment, sign in
-
*⚡ Control Flow in Java (if-else & switch)* *✅ 1️⃣ What is Control Flow?* 👉 Control Flow determines which code runs and when. Example: If condition is true → do this Else → do something else *✅ 2️⃣ if Statement* Used when you want to execute code only if a condition is true. if (condition) { // code } Example: int age = 20; if (age >= 18) { System.out.println("You can vote"); } *✅ 3️⃣ if-else Statement* Used when you want two outcomes. if (condition) { // true block } else { // false block } Example: int age = 16; if (age >= 18) { System.out.println("Adult"); } else { System.out.println("Minor"); } *✅ 4️⃣ if-else if Ladder* Used when you have multiple conditions. int marks = 85; if (marks >= 90) { System.out.println("A Grade"); } else if (marks >= 75) { System.out.println("B Grade"); } else if (marks >= 50) { System.out.println("C Grade"); } else { System.out.println("Fail"); } *🔥 Important Rule ⭐* 👉 Conditions are checked top to bottom 👉 First true condition executes → rest are skipped *✅ 5️⃣ Nested if* 👉 if inside another if int age = 20; boolean hasID = true; if (age >= 18) { if (hasID) { System.out.println("Allowed"); } } *✅ 6️⃣ switch Statement* Used when you have multiple fixed values. 👉 Cleaner than multiple if-else switch (variable) { case value1: // code break; case value2: // code break; default: // code } Example: int day = 2; switch (day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; default: System.out.println("Invalid"); } *🔥 Important Concepts (switch ⭐)* 1️⃣ break keyword 👉 Stops execution after a case Without break: case 1: System.out.println("Monday"); case 2: System.out.println("Tuesday"); 👉 Output: Monday Tuesday 2️⃣ default case 👉 Runs when no case matches *✅ 7️⃣ When to Use What?* - Simple condition: Use if - Two outcomes: Use if-else - Multiple conditions: Use if-else if - Fixed values: Use switch *🔥 Example Program* 👉 This program performs two tasks: 1️⃣ Checks whether a number is positive or negative 2️⃣ Prints the day based on a number using switch class ControlFlowDemo { public static void main(String[] args) { int number = 10; if (number > 0) { System.out.println("Positive"); } else { System.out.println("Negative"); } int day = 1; switch (day) { case 1: System.out.println("Monday"); break; default: System.out.println("Other day"); } } } ✔ Checks number → Positive/Negative ✔ Uses switch → prints day ✔ Uses break → stops execution ✔ Uses default → fallback *⭐ Common Interview Questions* - Difference between if-else and switch - When to use switch over if - What happens if break is missing? - Can we use String in switch? (👉 Yes, Java 7+)
To view or add a comment, sign in
-
*⚡ Control Flow in Java (if-else & switch)* *✅ 1️⃣ What is Control Flow?* 👉 Control Flow determines which code runs and when. Example: If condition is true → do this Else → do something else *✅ 2️⃣ if Statement* Used when you want to execute code only if a condition is true. if (condition) { // code } Example: int age = 20; if (age >= 18) { System.out.println("You can vote"); } *✅ 3️⃣ if-else Statement* Used when you want two outcomes. if (condition) { // true block } else { // false block } Example: int age = 16; if (age >= 18) { System.out.println("Adult"); } else { System.out.println("Minor"); } *✅ 4️⃣ if-else if Ladder* Used when you have multiple conditions. int marks = 85; if (marks >= 90) { System.out.println("A Grade"); } else if (marks >= 75) { System.out.println("B Grade"); } else if (marks >= 50) { System.out.println("C Grade"); } else { System.out.println("Fail"); } *🔥 Important Rule ⭐* 👉 Conditions are checked top to bottom 👉 First true condition executes → rest are skipped *✅ 5️⃣ Nested if* 👉 if inside another if int age = 20; boolean hasID = true; if (age >= 18) { if (hasID) { System.out.println("Allowed"); } } *✅ 6️⃣ switch Statement* Used when you have multiple fixed values. 👉 Cleaner than multiple if-else switch (variable) { case value1: // code break; case value2: // code break; default: // code } Example: int day = 2; switch (day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; default: System.out.println("Invalid"); } *🔥 Important Concepts (switch ⭐)* 1️⃣ break keyword 👉 Stops execution after a case Without break: case 1: System.out.println("Monday"); case 2: System.out.println("Tuesday"); 👉 Output: Monday Tuesday 2️⃣ default case 👉 Runs when no case matches *✅ 7️⃣ When to Use What?* - Simple condition: Use if - Two outcomes: Use if-else - Multiple conditions: Use if-else if - Fixed values: Use switch *🔥 Example Program* 👉 This program performs two tasks: 1️⃣ Checks whether a number is positive or negative 2️⃣ Prints the day based on a number using switch class ControlFlowDemo { public static void main(String[] args) { int number = 10; if (number > 0) { System.out.println("Positive"); } else { System.out.println("Negative"); } int day = 1; switch (day) { case 1: System.out.println("Monday"); break; default: System.out.println("Other day"); } } } ✔ Checks number → Positive/Negative ✔ Uses switch → prints day ✔ Uses break → stops execution ✔ Uses default → fallback *⭐ Common Interview Questions* - Difference between if-else and switch - When to use switch over if - What happens if break is missing? - Can we use String in switch? (👉 Yes, Java 7+) *🔥 Quick Revision* if → single condition if-else → two outcomes if-else if → multiple conditions
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