Table of Contents

J1-2 if-else

Welcome to if-else. IF and ELSE is the fundamental branching control of Java.

Today's code is easy to understand. Please enter the following code:

The Code

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        // Code starts here:

        System.out.print("What is your name? ");
        String name = input();

        if (name.equals("fish")) {
            System.out.println("You are a fish!");
        } else {
            System.out.println("Hello Mr. " + name + "!");
        }
        
    }

    // input()
    // RETURNS: a string
    // This function reads the next line of text from STDIN
    // and returns it as a String.
    //
    public static String input() {
        Scanner scanner = new Scanner(System.in);
        String r = scanner.nextLine();
        scanner.close();

        return r;
    }

}

The Big "IF"

    if (name.equals("fish")) {
        System.out.println("You are a fish!");
    } else {
        System.out.println("Hello Mr. " + name + "!");
    }

A lot goes on here. If the conditional statement inside the (brackets) is TRUE, the first block of code will execute. If the statement is false, the code in the second block will execute. After that, code execution resumes as normal.

Intro to Functions

We also see the introduction of a function here, that retutns a String. Using functions like this to keep your code clean is a good idea.

How do you know when you should make a function? Each “function” in your code should not be longer than one screen in length! This is a general guideline, not a rule.