Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikibooksThe Free Textbook Project
Search

Conditional blocks

100% developed
From Wikibooks, open books for an open world
<Java Programming
Thelatest reviewed version waschecked on6 January 2020. There aretemplate/file changes awaiting review.

StatementsJava Programming
Conditional blocks
Loop blocks
NavigateLanguage Fundamentals topic:()


Conditional blocks allow a program to take a different path depending on some condition(s). These allow a program to perform a test and then take action based on the result of that test. In the code sections, the actually executed code lines will be highlighted.

If

[edit |edit source]

Theif block executes only if the boolean expression associated with it is true. The structure of anif block is as follows:

if (boolean expression1) {
statement1
statement2
...
statementn

}

Here is a double example to illustrate what happens if the condition is true and if the condition is false:

ExampleCode section 3.22: Twoif blocks.
intage=6;System.out.println("Hello!");if(age<13){System.out.println("I'm a child.");}if(age>20){System.out.println("I'm an adult.");}System.out.println("Bye!");
Computer codeOutput for Code section 3.22
Hello!I'm a childBye!
NoteIf only one statement is to be executed after anif block, it does not have to be enclosed in curly braces. For example,if (i == 0) i = 1; is a perfectly valid portion of Java code. This works for most control structures, such aselse andwhile. However Oracle'sJava Code Conventions explicitly state that the braces should always be used.

If/else

[edit |edit source]

Theif block may optionally be followed by anelse block which will execute if that boolean expression is false. The structure of anif block is as follows:

if (boolean expression1) {
statement1
statement2
...
statementn

} else {

statement1bis
statement2bis
...
statementnbis

}


If/else-if/else

[edit |edit source]

Anelse-if block may be used when multiple conditions need to be checked.else-if statements come after theif block, but before theelse block. The structure of anif block is as follows:

if (boolean expression1) {
statement1.1
statement1.2
...
statementn

} else if (boolean expression2) {

statement2.1
statement2.2
...
statement2.n

} else {

statement3.1
statement3.2
...
statement3.n

}

Here is an example to illustrate:

Computer codeCode listing 3.3: MyConditionalProgram.java
publicclassMyConditionalProgram{publicstaticvoidmain(String[]args){inta=5;if(a>0){// a is greater than 0, so this statement will executeSystem.out.println("a is positive");}elseif(a>=0){// a case has already executed, so this statement will NOT executeSystem.out.println("a is positive or zero");}else{// a case has already executed, so this statement will NOT executeSystem.out.println("a is negative");}}}
Computer codeOutput for code listing 3.3
a is positive

Keep in mind thatonly a single block will execute, and it will be the first true condition.

All the conditions are evaluated whenif is reached, no matter what the result of the condition is, after the execution of theif block:

ExampleCode section 3.23: A new value for the variable a.
inta=5;if(a>0){// a is greater than 0, so this statement will executeSystem.out.println("a is positive");a=-5;}elseif(a<0){// a WAS greater than 0, so this statement will not executeSystem.out.println("a is negative");}else{// a does not equal 0, so this statement will not executeSystem.out.println("a is zero");}
Computer codeOutput for code section 3.23
a is positive

Conditional expressions

[edit |edit source]

Conditional expressions use the compound?: operator. Syntax:

boolean expression1 ?expression1 :expression2

This evaluatesboolean expression1, and if it istrue then the conditional expression has the value ofexpression1; otherwise the conditional expression has the value ofexpression2.

Example:

ExampleCode section 3.24: Conditional expressions.
Stringanswer=(p<0.05)?"reject":"keep";

This is equivalent to the following code fragment:

ExampleCode section 3.25: Equivalent code.
Stringanswer;if(p<0.05){answer="reject";}else{answer="keep";}

Switch

[edit |edit source]

Theswitch conditional statement is basically a shorthand version of writing manyif...else statements. Theswitch block evaluates achar,byte,short, orint (orenum, starting in J2SE 5.0; orString, starting in J2SE 7.0), and, based on the value provided, jumps to a specificcase within the switch block and executes code until thebreak command is encountered or the end of the block. If the switch value does not match any of the case values, execution will jump to the optionaldefault case.

The structure of aswitch statement is as follows:

switch (int1 or char1 or short1 or byte1 or enum1 or String value1) {
casecase value1:
statement1.1
...
statement1.n
break;
casecase value2:
statement2.1
...
statement2.n
break;
default:
statementn.1
...
statementn.n

}

Here is an example to illustrate:

ExampleCode section 3.26: A switch block.
inti=3;switch(i){case1:// i doesn't equal 1, so this code won't executeSystem.out.println("i equals 1");break;case2:// i doesn't equal 2, so this code won't executeSystem.out.println("i equals 2");break;default:// i has not been handled so far, so this code will executeSystem.out.println("i equals something other than 1 or 2");}
Computer codeOutput for code section 3.26
i equals something other than 1 or 2

If a case does not end with thebreak statement, then the next case will be checked, otherwise the execution will jump to the end of theswitch statement.

Look at this example to see how it's done:

ExampleCode section 3.27: A switch block containing a case without break.
inti=-1;switch(i){case-1:case1:// i is -1, so it will fall through to this case and execute this codeSystem.out.println("i is 1 or -1");break;case0:// The break command is used before this case, so if i is 1 or -1, this will not executeSystem.out.println("i is 0");}
Computer codeOutput for code section 3.27
i is 1 or -1

Starting in J2SE 5.0, theswitch statement can also be used with anenum value instead of an integer.

Thoughenums have not been covered yet, here is an example so you can see how it's done (note that the enum constants in the cases do not need to be qualified with the type:

ExampleCode section 3.28: A switch block with an enum type.
Dayday=Day.MONDAY;// Day is a fictional enum type containing the days of the weekswitch(day){caseMONDAY:// Since day == Day.MONDAY, this statement will executeSystem.out.println("Mondays are the worst!");break;caseTUESDAY:caseWEDNESDAY:caseTHURSDAY:System.out.println("Weekdays are so-so.");break;caseFRIDAY:caseSATURDAY:caseSUNDAY:System.out.println("Weekends are the best!");break;}
Computer codeOutput for code section 3.28
Mondays are the worst!

Starting in J2SE 7.0, theswitch statement can also be used with anString value instead of an integer.

ExampleCode section 3.29: A switch block with a String type.
Stringday="Monday";switch(day){case"Monday":// Since day == "Monday", this statement will executeSystem.out.println("Mondays are the worst!");break;case"Tuesday":case"Wednesday":case"Thursday":System.out.println("Weekdays are so-so.");break;case"Friday":case"Saturday":case"Sunday":System.out.println("Weekends are the best!");break;default:thrownewIllegalArgumentException("Invalid day of the week: "+day);}
Computer codeOutput for code section 3.29
Mondays are the worst!


StatementsJava Programming
Conditional blocks
Loop blocks
Retrieved from "https://en.wikibooks.org/w/index.php?title=Java_Programming/Conditional_blocks&oldid=3650382"
Category:

[8]ページ先頭

©2009-2025 Movatter.jp