1/6
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced |
---|
No study sessions yet.
The statements in a Java main method normally run or execute one at a time in the order they are found from top to bottom. If statements (also called conditionals or selection) change the flow of control through the program so that some code is only run when something is true. In an if statement, if the condition is true then the next statement or a block of statements will execute. If the condition is false then the next statement or block of statements is skipped.
// A single if statementif (boolean expression) Do statement; // Or a single if with {}if (boolean expression) { Do statement; } // A block if statement: { } requiredif (boolean expression) { Do Statement1; Do Statement2; ... Do StatementN; }
Note that there is no semicolon (;) at the end of the boolean expression in an if statement even if it is the end of that line. The semicolon goes at the end of the whole if statement, often on the next line. Or { } are used to mark the beginning and end of the block of code under the if condition.
Here are some rules to follow with if statements to avoid some common errors:
Always use curly braces ({ and }) to enclose the block of statements under the if condition. Java doesn’t care if you indent the code—it goes by the { }.
Don’t put in a semicolon ; after the first line of the if statement, if (test);. The if statement is a multiline block of code that starts with the if condition and then { the body of the if statement }.
Always use ==, not =, in the condition of an if statement to test a variable. One = assigns, two == tests!
if statements test a boolean expression and if it is true, go on to execute the following statement or block of statements surrounded by curly braces ({}
) like below.
*// A single if statement***if** (boolean expression) Do statement; *// A block if statement***if** (boolean expression) { Do Statement1; Do Statement2; ... Do StatementN; }
Relational operators (==, !=, <, >, <=, >=) are used in boolean expressions to compare values and arithmetic expressions.
Conditional (if) statements affect the flow of control by executing different statements based on the value of a Boolean expression.