Mostrando postagens com marcador switch. Mostrar todas as postagens
Mostrando postagens com marcador switch. Mostrar todas as postagens

Control Flow Statements (if, else, switch, loops)

Control flow statements are essential for controlling the flow of execution in a Java program. They allow you to make decisions, repeat blocks of code, and execute code based on conditions. Let's explore the main control flow statements in Java: `if`, `else`, `switch`, and loops.


1. if Statement

The `if` statement allows you to execute a block of code if a specified condition is true.

int num = 10;
if (num > 0) {
    System.out.println("The number is positive.");
}


2. if-else Statement

The `if-else` statement allows you to execute one block of code if a condition is true and another block of code if the condition is false.

int num = -5;
if (num > 0) {
    System.out.println("The number is positive.");
} else {
    System.out.println("The number is non-positive.");
}


3. Nested if-else Statement

You can nest `if-else` statements to handle multiple conditions.

int num = 0;
if (num > 0) {
    System.out.println("The number is positive.");
} else if (num < 0) {
    System.out.println("The number is negative.");
} else {
    System.out.println("The number is zero.");
}


4. switch Statement

The `switch` statement allows you to select one of many code blocks to be executed.

int day = 3;
String dayName;
switch (day) {
    case 1:
        dayName = "Monday";
        break;
    case 2:
        dayName = "Tuesday";
        break;
    case 3:
        dayName = "Wednesday";
        break;
    // Add cases for other days...
    default:
        dayName = "Unknown";
}
System.out.println("Today is " + dayName);


5. Loops

Loops are used to execute a block of code repeatedly as long as a specified condition is true.


a. while Loop

The `while` loop executes a block of code as long as the specified condition is true.

int i = 1;
while (i <= 5) {
    System.out.println("Count: " + i);
    i++;
}


b. do-while Loop

The `do-while` loop is similar to the `while` loop, but it guarantees that the block of code is executed at least once, even if the condition is false.

int i = 1;
do {
    System.out.println("Count: " + i);
    i++;
} while (i <= 5);


c. for Loop

The `for` loop is used to iterate over a range of values.

for (int i = 1; i <= 5; i++) {
    System.out.println("Count: " + i);
}


d. Enhanced for Loop (for-each Loop)

The enhanced `for` loop is used to iterate over elements in an array or a collection.

int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
    System.out.println("Number: " + num);
}


Conclusion

Control flow statements such as `if`, `else`, `switch`, and loops (`while`, `do-while`, `for`) are essential for writing flexible and efficient Java programs. They allow you to make decisions, handle different cases, and repeat code as needed. Understanding how to use these control flow statements effectively is crucial for becoming proficient in Java programming.

Switch in Java

In Java 17, the switch statement received several enhancements, including improvements to switch expressions. These enhancements aim to make switch statements more powerful, flexible, and concise. Here's an overview of how switch works:

1. Traditional switch Statement

Java's traditional switch statement has been in the language since its inception. It allows you to compare the value of a variable against multiple possible constant values, executing different blocks of code based on the match.

   int day = 3;
   String dayName;
   
   switch (day) {
       case 1:
           dayName = "Monday";
           break;
       case 2:
           dayName = "Tuesday";
           break;
       case 3:
           dayName = "Wednesday";
           break;
       // More cases...
       default:
           dayName = "Invalid day";
           break;
   }

2. Switch Expressions

Switch expressions were introduced as a preview feature in Java 12 and finalized in Java 14. In Java 17, switch expressions received further enhancements.

   int day = 3;
   String dayName = switch (day) {
       case 1 -> "Monday";
       case 2 -> "Tuesday";
       case 3 -> "Wednesday";
       // More cases...
       default -> "Invalid day";
   };

   - The arrow ("->") syntax is used to indicate the value to be returned for each case.

   - The "switch" expression evaluates to a value, which can be assigned directly to a variable.


3. Enhancements in Java 17

Java 17 introduced several enhancements to switch expressions:

- Multiple Labels Per Case
You can now have multiple labels in a single "case" label, separated by comma (",").

     int num = 2;
     String result = switch (num) {
         case 1, 2 -> "One or Two";
         case 3 -> "Three";
         default -> "Other";
     };

- Relaxed Scoping for Switch Variables
In Java 17, the scope of variables declared in the expression of a switch statement has been relaxed. This means that the variables declared in the expression can now be used in subsequent case blocks without requiring extra curly braces.

     int num = 2;
     String result = switch (num) {
         case 1 -> {
             int x = 10;
             yield "One";
         }
         case 2 -> {
             yield "Two";
         }
         default -> "Other";
     };

These enhancements make switch expressions more versatile and reduce boilerplate code, leading to more readable and concise code.

Java 14 vs. Java 17

Java 14 and Java 17 are two significant releases in the Java platform, each introducing various improvements, features, and changes. Here are some key differences between Java 14 and Java 17.


1. Records (Java 14)

   - Java 14 introduced records as a preview feature, providing a compact way to declare classes that are transparent holders for shallowly immutable data.

   - Java 17 finalized records, making them a standard feature, and providing a more concise syntax for defining immutable data classes.


2. Pattern Matching for instanceof (Java 14)

   - Java 14 introduced pattern matching for the instanceof operator as a preview feature, allowing simpler and more concise code when dealing with instanceof checks and type casting.

   - Java 17 finalized pattern matching for instanceof, enhancing its capabilities and making it a standard feature.


3. Foreign-Memory Access API (Java 14)

   - Java 14 introduced the Foreign-Memory Access API as an incubator feature, providing a way to access native memory outside of the Java heap.

   - Java 17 further improved and stabilized the Foreign-Memory Access API, making it a standard feature.


4. Switch Expressions Enhancements (Java 14)

   - Java 14 introduced enhancements to switch expressions, including allowing multiple constants in a single case label and introducing a new yield statement.

   - Java 17 continued to refine switch expressions, introducing enhancements like switch expressions with multiple labels, and relaxed scoping for switch variables.


5. Garbage Collectors (Java 17)

   - Java 14 included various garbage collectors, but Java 17 introduced further improvements and optimizations to existing garbage collectors, such as the Z Garbage Collector (ZGC).


6. Sealed Classes and Interfaces (Java 17)

   - Java 17 introduced sealed classes and interfaces as a preview feature, providing more control over class and interface hierarchies, allowing developers to define which classes can be subtypes.

   - Java 14 did not include sealed classes and interfaces.


7. Hidden Classes (Java 17)

   - Java 17 introduced hidden classes, allowing classes to be hidden from the class loader and providing better encapsulation and security.

   - Java 14 did not include hidden classes.


8. Long-Term Support (LTS) (Java 17)

   - Java 17 is a Long-Term Support (LTS) release, providing extended support and stability for users who require a stable and reliable platform for an extended period.

   - Java 14 was not an LTS release.


9. New APIs and Enhancements

   - Both Java 14 and Java 17 include various new APIs, enhancements, bug fixes, and performance optimizations to improve developer productivity, efficiency, and the overall Java platform.


These are some of the key differences between Java 14 and Java 17. Each release brings improvements and new features that contribute to the evolution and enhancement of the Java platform.

HashMap in Java

Let’s break down how   HashMap   works internally (Java 8+ implementation). What Is a HashMap? HashMap<K, V>  is a  hash table–based  ...