Exploring Java : My Learning Adventure Part - 5

Exploring Java : My Learning Adventure Part - 5

Conditional Statements

Relational and Logical Operations

Relational Operators : <, <=, >, =>, ==, != they are used for comparing data types. They always return Boolean result.

Logical Operation:

  1. AND (&&): Returns true if both operands are true.

     boolean result = (5 > 3) && (8 > 6); // true
    
  2. OR (||): Returns true if at least one of the operands is true.

     boolean result = (5 > 3) || (8 < 6); // true
    
  3. NOT (!): Inverts the value of the operand.

     boolean result = !(5 > 3); // false
    

These operators are typically used in control flow statements like if, while, and for loops to combine multiple conditions.

Conditional Statements

if condition, else condition. If this -> do this, else -> do that.

class Test
{
    public static void main(String[] args) 
    {
        int x = 5;
        if  (x>=0) 
        {
            System.out.println("Positive");
        }
        else
        {
            System.out.println("Negative");
        }
    }
}

Nested condition/ Branching : Condition under condition.

class Test
{
    public static void main(String[] args);
    {
        int a = 3,b = 4, c =10;
        if (a>b && a>c)
        {
            System.out.println(a)
        }
        else
        {
            if (b>c)
            {
                System.put.println(b);
            }
            else
            {
                Ststem.out.println(c);
            }
        }
    }
}
if (condition)
{
    =
}
else if (condition)
{
    =
}
else
{
    =    
}

Practicing Conditional Statement

Just looking at them should be enough to understand.

Homework #1

Question 1: Find a is odd or even. Find a person is young or not. Find grades for given marks

Question 2: Find if a person is young or not. If the age is greater than 18 and less than 55, then the person is young.

Question3: Find grades for given marks. Above 90 -> A, Above 50 -> C, Below 50 ->F

Homework #2

  1. Find radix (the base of a number system) of a number given in a string. (out of syllabus, will cover later. Topic to learn : Regular expression, String Category)

  2. Find if a given year is a leap year or not. Input will be a year.

Homework #3

  1. Display name of a day based on number (Day 1 means Monday)

  2. Find type of website and the protocol used.

    ( String url = "google.com". you have to find what is there before the colon, take out the substring. If it's http, say "hyper text transfer protocol", if it's ftp then say "file transfer protocol". Next thing you need to do is, you have to take out com. So search for the dot, then take out the leftover and if that's com print commercial website, if it's org print organization, if it's net print network. )

Switch Case

A switch statement in Java is a control flow statement that allows you to execute one block of code out of many, based on the value of an expression. It's similar to using multiple if-else statements but can be more readable and efficient when dealing with many possible values for a single variable.

Here's a simple way to understand the switch statement:

  1. The switch keyword: It starts with the switch keyword followed by an expression (usually a variable).

  2. Cases: Inside the switch block, you define case labels. Each case label represents a possible value for the expression.

  3. The break statement: After each case block, you usually include a break statement to exit the switch statement. If you omit the break, execution will "fall through" to the next case.

  4. The default case: Optionally, you can include a default case that executes if none of the other cases match the expression value.

Well, Let's see a program that uses a switch statement to print the name of the day based on a given number (1 for Sunday, 2 for Monday, etc.):

public class DayOfWeek 
{
    public static void main(String[] args) 
    {
        int day = 3; // You can change this value to test different cases

        switch (day) 
        {
            case 1:
                System.out.println("Sunday");
                break;
            case 2:
                System.out.println("Monday");
                break;
            case 3:
                System.out.println("Tuesday");
                break;
            case 4:
                System.out.println("Wednesday");
                break;
            case 5:
                System.out.println("Thursday");
                break;
            case 6:
                System.out.println("Friday");
                break;
            case 7:
                System.out.println("Saturday");
                break;
            default:
                System.out.println("Invalid day number");
                break;
        }
    }
}

What happens if we don't add break at the end of a case? Well, the following cases will be executed and printed, and that's exactly we are trying to avoid by using Switch Case. We don't want anymore executions after getting our desirable output.

Important Points

  • Break Statement: Each case ends with a break statement to prevent "fall-through". Without break, the code will continue executing the next case's statements.

  • Default Case: The default case is optional but useful for handling unexpected values

  • Case data types: Here, in the cases we can't write float values. We can write byte, short, int, char, strings also. But not float.

Switch Case VS if-else condition

Both switch and if-else statements are used for making decisions in Java, but they have different use cases and structures.

Switch Case

switch (expression) 
{
    case value1:
        // code to be executed if expression == value1
        break;
    case value2:
        // code to be executed if expression == value2
        break;
    // more cases
    default:
        // code to be executed if expression doesn't match any case
}
  • Best for: When you have a single variable or expression that can have many possible discrete values.

  • Data Types: Works with int, char, byte, short, String, and enums (from Java 7 onwards).

  • Readability: More readable and organized for multiple discrete values.

  • Performance: Can be faster than if-else in some cases, especially when there are many branches, due to the underlying jump table mechanism.

Summery - Organized, fast, will jump directly on the code block rather than checking each and every condition.

if-else condition

if (condition1) 
{
    // code to be executed if condition1 is true
} 
else if (condition2) 
{
    // code to be executed if condition2 is true
} 
else 
{
    // code to be executed if none of the conditions are true
}
  • Best for: When you have complex conditions that may involve ranges, multiple variables, or more complex logical expressions.

  • Data Types: Works with any boolean expression.

  • Readability: Can become less readable with many conditions, especially if the conditions are complex.

  • Performance: Generally slower than switch for many branches due to multiple conditional checks, but this difference is often negligible in most applications.

Summery - Efficient for multiple variables, complex programs.

Homework #4

Question 1. Display name of a day based on number

Question 2. Display name of a month based on number

Question 3. Display type of website

Homework #5

Question 1. Make a Menu Driven Program for Arithmetic Operations.

String Homework Answers

  1. Find if the email id is on Gmail. Find username and domain from email.

    String str = "programmer@gmail.com"

That's it for today and be sure to try them out.

In the next blog, i will talk about Loops. In the meantime, don't forget to stay hydrated! Happy learning!

Reminder : Don't forget about your homework. Don't worry, I will attach the answer in the next blog.