[Java] Branch and repeat

if statement

: sunny: Can branch Enter the branch condition in () after: sunny: if : sunny: Consists of conditional expressions and blocks

For example, you can branch ...

Do you have bread at home? → Yes Let's make it toast and eat it! → No Let's go to the bakery to buy!

It is to be able to change the programming process depending on the conditions like.

Example.java


public class Main {
	public static void main(String[] args) {
	    boolean bread = true;
	    if (bread == true) {
	        System.out.println("Let's make it toast and eat it!");
	    } else {
	        System.out.println("Let's go to the bakery to buy!");
	    }
	}
}

Enter true (even false is OK) in the boolean type variable bread that represents the boolean value on the third line.

(Bread == true) after if on the 4th line describes the condition for branching. In this case, if true is assigned to the variable bread ...

If the 5th line is true, please do this kind of processing.

If else on the 6th line is something else (other than true in this case) Please do this kind of processing on the 7th line.

console.


Let's make it toast and eat it!

This time, since true is assigned in the 3rd line, it becomes the above: smile: If you change the third line from true to false ...

console.


Let's go to the bakery to buy!

Is displayed: smile:

if only syntax

: sunny: If the condition is met, the specified process is performed, and if it is not met, nothing is done.

Example.java


public class Main {
	public static void main(String[] args) {
		int number = 5;
		if (number == 5) {
		    System.out.println("Gorilla!");
		}
    }
}

In this case, if the variable number is assigned 5

Gorilla!

Is displayed, and if any other number is assigned, nothing is done.

if-else if-else syntax

: sunny: One if statement can branch to more than two routes.

Example.java


public class Main {
	public static void main(String[] args) {
		int number = 1;
		if (number == 1) {
		    System.out.println("Strawberry!");
		} else if (number == 2) {
		    System.out.println("Carrots!");
		} else if (number == 3) {
		    System.out.println("Sandals!");
		} else {
		    System.out.println("do not know");
		}
    }
}

If 1 is assigned to the variable number, strawberry! Is output, and if it is 2, carrots! If it is 3, sandals! Other numbers are displayed as "I don't know". I was able to branch to more than two routes using else if: smile:

switch statement

: sunny: An expression that compares whether the left and right sides of all conditional expressions match, such as variable == value, variable == variable. Enter the variable name instead of the expression in () after: sunny: switch : sunny: case value::: is a colon, so be careful not to confuse it with a semicolon. Enter break at the very end of the processing after: sunny: case : sunny: default has the same meaning as else in the if statement, and what to do when the condition is not met. It can be omitted if processing is not required together with else. break can also be omitted.

You can rewrite the programming used in the if-else if-else syntax earlier into a switch statement: smile:

Example.java


public class Main {
	public static void main(String[] args) {
		int number = 1;
		switch(number) {
		    case 1:
    		    System.out.println("Strawberry!");
    		    break;
		    case 2:
    		    System.out.println("Carrots!");
    		    break;
		    case 3:
    		    System.out.println("Sandals!");
    		    break;
    		default:
    		    System.out.println("do not know");
		}
    }
}

Compared to the if statement, there are fewer {} and () after the else if, so it's very easy to see: smile:

There is always a break at the end of each case, but what if I forget to fill it out? : thinking:

Example.java


public class Main {
	public static void main(String[] args) {
		int number = 1;
		switch(number) {
		    case 1:
    		    System.out.println("Strawberry!");
		    case 2:
    		    System.out.println("Carrots!");
    		    break;
		    case 3:
    		    System.out.println("Sandals!");
    		    break;
    		default:
    		    System.out.println("do not know");
		}
    }
}

I dared to delete the break in case 1 on the 7th line. What will happen?

console.


Strawberry!
Carrots!

Not only case 1 is displayed, but case 2 is also displayed. ..

A switch statement is an instruction that jumps processing to the case label that matches the variable in (). Therefore, no compilation error will occur. If you do not fill in a break and stop the process, the program in the next case will be executed.

Don't dare write break

You can also take advantage of the property that processing does not stop unless you fill in this break.

Example.java


public class Main {
	public static void main(String[] args) {
		int rank = 1;
		switch(rank) {
		    case 1:
    		    System.out.println("excellence!");
    		    break;
		    case 2:
		    case 3:
    		case 4:
    		    System.out.println("Usually");
    		    break;
    		case 5:
    		    System.out.println("Work hard!");
    		    break;
		}
    }
}

When rank is 1, it is displayed as excellent! If ranks 2 to 4 are all the same, the characters "normal" are output. I dared to delete breaks and statements in case 2 and case 3, so that the process jumps to case 4.

Doing so made the code more readable and easier to read: smile:

while statement

: sunny: Can perform iterative (loop) processing : sunny: Enter the condition to continue repeating in () behind while : sunny: Consists of conditional expressions and blocks

Example.java


public class Main {
	public static void main(String[] args) {
		int day = 1;
        while (day <= 7) {
            System.out.println(day + "Day");
            day++;
        }
        System.out.println("One week has passed");
    }
}

Substitute 1 for the variable day on the third line.

The (day <= 7) behind the while on the 4th line describes the conditions for continuing the repetition. In this case, repeat the processing on the 5th to 6th lines until the value of the variable day becomes 7. Currently 1 is assigned.

The fifth line is displayed as the first day because 1 is assigned to the variable day. On the 6th line, day ++ ;, add 1 to the variable day to make it 2. Go back to while on the 4th line.

Since we added 1 to the variable day earlier, 2 is assigned to the variable day. (day <= 7) That is, 2 <= 7 and the conditional expression is satisfied, so the processing of the 5th to 6th lines is repeated.

Since 2 is assigned to the variable day on the 5th line, it is displayed as the 2nd day. In day ++; on the 6th line, add 1 to the variable day to make it 3. It returns to while on the 4th line, and so on until the variable day becomes 7.

What happens when the variable day becomes 7, iterates as before, and finally day ++; assigns 8 to the variable day. Then go back to the 4th line while.

Currently, 8 is assigned to the variable day. (day <= 7) That is, 8 <= 7, but the conditional expression is not met. This is the end of the iterative process. When the iterative processing is completed, the processing of the 5th to 6th lines is not performed and the processing of the 8th line is skipped.

Then, the processing of the 8th line is performed and the program ends.

console.


First day
the 2nd day
Third day
Day 4
Day 5
Day 6
Day 7
One week has passed

do-while statement

The: sunny: While statement continues processing until the condition changes. In the case of do-while, processing is performed once and then processing is continued until the conditions change.

Example.java


public class Main {
    public static void main(String[] args) {
        int day = 1;
        do {
            System.out.println(day + "Day");
            day++;
        } while (day <= 7) ;
        System.out.println("One week has passed");
    }
}

Assign 1 to the variable day on the third line.

In the while statement, while came next, so I was checking the conditions. However, in this do-while statement, the processing is done earlier.

The 5th line displays the characters of the 1st day. On the 6th line, 1 is added to the variable day, so 1 + 1 substitutes 2.

On the 7th line, while (day <= 7) determines whether the condition is met. Since 2 is assigned to the variable day, the condition is satisfied with 2 <= 7. The return process is repeated until do on the 4th line.

If 8 is entered in the variable day with while (day <= 7), the condition is not satisfied and the iterative process ends.

The program ends with a message saying that one week has passed on the 8th line: smile:

for statement

: sunny: Repeat by specifying the number of times

Example.java


public class Main {
    public static void main(String[] args) {
        for (int cake = 0; cake < 5; cake++) {
            System.out.println("I want to eat pancakes!");
        }
    }
}

The third line is the for statement. I thought it would be very complicated ... Once you knew what each one meant, it wasn't too difficult: smile: I'll explain: smile:

in the for statement

int cake = 0;

What does this put in the initial value? That is. In the above statement, we assign 0 to the variable cake. That is.

And next

cake < 5;

How many times does this repeat the process? That is. By the way, do you know how many times to repeat? ?? : thinking: In fact, the process is repeated 5 times.

Earlier, I set the initial value as int cake = 0 ;. In other words ...

0  1  2  3  4

It has been iterated a total of 5 times, including 0 and 0.

Finally

cake++

This acts as a count to repeat the process. It counts as one after each process.

The order is ...

0 is assigned to the variable cake with int cake = 0 ;.

Because cake <5; that is, 0 <5; so the conditions match I want to eat pancakes! Is output.

Since it is cake ++, 1 is assigned to the variable cake by 0 + 1.

cake <5; that is, 1 <5; so the conditions match I want to eat pancakes! Is output.

Since it is cake ++, 2 is assigned to the variable cake by 1 + 1.

Because cake <5; that is, 2 <5; so the conditions match I want to eat pancakes! Is output.

Since it is cake ++, 3 is assigned to the variable cake by 2 + 1.

cake <5; In other words, 3 <5; so the conditions match I want to eat pancakes! Is output.

Since it is cake ++, 4 is assigned to the variable cake by 3 + 1.

Because cake <5; that is, 4 <5; so the conditions match I want to eat pancakes! Is output.

Since it is cake ++, 5 is assigned to the variable cake by 4 + 1.

Since cake <5; that is, 5 <5 ;, the conditions do not match. The process ends here.

I'm sure some of you may have noticed this. The int cake = 0; part has been processed only once. This part is the first one-time process.

If this is also a repetitive process

I added 1 with cake ++, but 0 was assigned again with int cake = 0 ;. Add 1 with cake ++, and 0 is assigned again with int cake = 0; You'll end up with an infinite loop that never ends: scream:

console.


I want to eat pancakes!
I want to eat pancakes!
I want to eat pancakes!
I want to eat pancakes!
I want to eat pancakes!

By the way, the initial value does not necessarily have to start with 0.

Example.java


for (int cake = 1; cake < 6; cake++) 

If you want to repeat 5 times, either make the number part cake <6; or cake <= 5 ;. The reverse pattern is also possible: smile:

Example.java


for (int cake = 5; cake > 0; cake--)

In this case, 5 is assigned to the initial value, and since it is cake--, the value of the variable cake is decremented by 1. cake> 0; In other words, it means to continue processing until 1> 0.

continue statement

: sunny: Skips processing for the specified lap and moves on to the next lap.

Example.java


public class Main {
    public static void main(String[] args) {
        for (int cake = 0; cake < 5; cake++) {
            if (cake == 3) {
                continue;
            }
            System.out.println("I want to eat pancakes!");
        }
    }
}

What does that mean

if (cake == 3) { continue; }

If 3 is assigned to the variable cake, do not process (I want to eat pancakes!) Move on to the next process. That means: smile:

So when you run

console.


I want to eat pancakes!
I want to eat pancakes!
I want to eat pancakes!
I want to eat pancakes!

Has only been run 4 times: smile: I think I stopped the process with break at the time of the switch statement.

break → The process is interrupted. continue → Skips the processing for the specified lap and moves to the next lap.

The two look similar but different. By the way, if you change the above continue part to break Since the process is interrupted after 3 times I want to eat pancakes! Is processed only 3 times.

Blocks and conditional expressions

block

: sunny: A collection of statements that are executed by branching or repeating

Example.java


public class Main {
	public static void main(String[] args) {
	    boolean bread = true;
	    if (bread == true) {
	        System.out.println("Let's make it toast and eat it!");
	    } else {
	        System.out.println("Let's go to the bakery to buy!");
	    }
	}
}

Let's take the code explained in the if statement earlier as an example: smile: What part will the block be? That is the 5th and 7th lines. To be more specific

Example.java


{
System.out.println("Let's make it toast and eat it!");
}

From {from {after if (bread == true) on the 4th line The block is up to} before else on the 6th line.

Example.java


{
System.out.println("Let's go to the bakery to buy!");
}

From {from {after else on the 6th line The block is up to the 8th line}.

Example.java


public class Main {
	public static void main(String[] args) {
		int day = 1;
        while (day <= 7) {
            System.out.println(day + "Day");
            day++;
        }
        System.out.println("One week has passed");
    }
}

I'll explain it in the while statement earlier: smile:

Example.java


{
System.out.println(day + "Day");
day++;
}

From {from {after while (day <= 7) on the 4th line Up to the 7th line}.

Conditional expression

The expression written in () after: sunny: if or while : sunny: The content of () is the condition to branch the process if it is an if statement, and the condition to continue repeating if it is a while statement.

Example.java


if (bread == true)

(Bread == true)

Example.java


while (day <= 7)

(Day <= 7).

Recommended Posts

[Java] Branch and repeat
Java conditional branch
java conditional branch
Java and JavaScript
XXE and Java
[Java] Conditional branch
Java true and false
[Java] String comparison and && and ||
Java --Serialization and Deserialization
timedatectl and Java TimeZone
[Java] Variables and types
java (classes and instances)
[Java] Overload and override
Study Java # 2 (\ mark and operator)
Java version 8 and later features
[Java] Difference between == and equals
[Java] Generics classes and generics methods
Java programming (variables and data)
Java and Iterator Part 1 External Iterator
Java if and switch statements
Java class definition and instantiation
Apache Hadoop and Java 9 (Part 1)
[Java] About String and StringBuilder
Java study # 7 (branch syntax type)
☾ Java / Iterative statement and iterative control statement
Java methods and method overloads
java Generics T and? Difference
Advantages and disadvantages of Java
java (conditional branching and repetition)
About Java Packages and imports
[Java] Upload images and base64
C # and Java Overrides Story
Java abstract methods and classes
Java while and for statements
Java encapsulation and getters and setters
I compared PHP and Java constructors
Differences between "beginner" Java and Kotlin
Use java with MSYS and Cygwin
Distributed tracing with OpenCensus and Java
[Java] Difference between Hashmap and HashTable
Java variable declaration, initialization, and types
Java Excel Insertion and Image Extraction
Install Java and Tomcat with Ansible
AWS SDK for Java 1.11.x and 2.x
[Java] Basic types and instruction notes
Java release date and EOL summary
Java and first-class functions-beyond functional interfaces-
[Java] Branch enum with switch statement
About fastqc of Biocontainers and Java
Java for beginners, expressions and operators 1
Java Primer Series (Variables and Types)
Encoding and Decoding example in Java
[Java beginner] About abstraction and interface
Basic data types and reference types (Java)
[Java] Loop processing and multiplication table
Java 15 implementation and VS Code preferences
Java arguments, return values and overloads
OpenJDK 8 java and javac command help
Java reference mechanism (stack and heap)
Java for beginners, expressions and operators 2
Java PowerPoint password setting and cancellation