Computer Science

Java If Statements

Java if statements are used to make decisions in a program based on a condition. They allow the program to execute certain code if the condition is true, and optionally execute different code if the condition is false. If statements are fundamental to controlling the flow of a Java program and are essential for creating logic and decision-making processes.

Written by Perlego with AI-assistance

9 Key excerpts on "Java If Statements"

  • Book cover image for: Developing Java Software
    • Russel Winder, Graham Roberts(Authors)
    • 2014(Publication Date)
    • Wiley
      (Publisher)
    20 20 Flow Control 20 Objectives This chapter presents flow control statements. These statements allow the programmer to control the order in which statements are executed. Each statement is presented by first giving a summary of its features and purpose, and then providing examples of it in use. Keywords break for selection continue if switch do iteration while flow control return 666 Chapter 20: Flow Control Java provides a selection of flow control statements to control the order in which statements are executed. There are three categories of flow control statement: • Selection statements: if and switch. • Iteration (loop) statements: while, do and for . • Transfer statements: break, continue and return. Most algorithms depend, at some point, on the ability to choose between different actions depending on some set of conditions (see Figure 20.1). Selection statements provide the mechanisms for making choices and come in two forms: binary selection and multi-way selection. Binary selection allows a choice between two possible statement sequences, while multi-way selection allows a choice out of many statement sequences. 20.2.1 The If Statement Purpose The if statement provides binary selection, allowing conditional execution of a statement depending on the value of a Boolean expression. Intention It is frequently the case that a statement should be executed only if some condition is met, for example ‘if the value of x is less than 10 then add 1 to x’. If the condition is not met then the statement should be bypassed and not executed. The condition is in the form of a Boolean expression which evaluates to true or false, with a value of true resulting in the statement being executed. Syntax if ( booleanExpression ) statement or if ( booleanExpression ) statement else statement Description An if statement allows a choice over which statement to execute next, based on a Boolean condition. The statement has two variants, referred to as if-then and if-then-else.
  • Book cover image for: Introduction to Programming
    No longer available |Learn more

    Introduction to Programming

    Learn to program in Java with data structures, algorithms, and logic

    Control Flow Statements

    This chapter describes one particular kind of Java statement
    , called control statements, which allow the building of a program flow according to the logic of the implemented algorithm, which includes selection statements, iteration statements, branching statements, and exception handling statements.
    In this chapter, we will cover the following topics:
    • What is a control flow?
    • Selection statements: if, if....else, switch...case
    • Iteration statements: for, while, do...while
    • Branching statements: break, continue, return
    • Exception handling statements: try...catch...finally, throw, assert
    • Exercise – Infinite loop
    Passage contains an image

    What is a control flow?

    A Java program is a sequence of statements that can be executed and produce some data or/and initiate some actions. To make the program more generic, some statements are executed conditionally, based on the result of an expression
    evaluation. Such statements are called control flow statements because, in computer science, control flow (or flow of control) is the order in which individual statements are executed or evaluated.
    By convention, they are divided into four groups: selection statements, iteration statements, branching statements, and exception handling statements. In the following sections, we will use the term block, which means a sequence of statements enclosed in braces. Here is an example: { x = 42; y = method(7, x); System.out.println("Example"); } A block can also include control statements – a doll inside a doll, inside a doll, and so on.
    Passage contains an image

    Selection statements

    The control flow statements of the selection statements group are based on an expression evaluation. For example, here is one possible format: if(expression) do something. Or, another possible format: if(expression) {do something} else {do something else}.
    The expression may return a boolean value (as in the previous examples) or a specific value that can be compared with a constant. In the latter case, the selection statement has the format of a switch statement, which executes the statement or block that is associated with a particular constant value.
  • Book cover image for: OCP Oracle Certified Professional Java SE 17 Developer Study Guide
    • Scott Selikoff, Jeanne Boyarsky(Authors)
    • 2022(Publication Date)
    • Sybex
      (Publisher)
    In this section, we discuss decision-making state-ments including if and else , along with the new pattern matching feature. Statements and Blocks As you may recall from Chapter 1, “Building Blocks,” a Java statement is a complete unit of execution in Java, terminated with a semicolon ( ; ). In this chapter, we introduce you to var-ious Java control flow statements. Control flow statements break up the flow of execution by using decision-making, looping, and branching, allowing the application to selectively exe-cute particular segments of code. These statements can be applied to single expressions as well as a block of Java code. As described in Chapter 1, a block of code in Java is a group of zero or more statements between balanced braces ( {} ) and can be used anywhere a single statement is allowed. For example, the following two snippets are equivalent, with the first being a single expression and the second being a block containing the same statement: // Single statement patrons++; Creating Decision-Making Statements 103 // Statement inside a block { patrons++; } A statement or block often serves as the target of a decision-making statement. For example, we can prepend the decision-making if statement to these two examples: // Single statement if(ticketsTaken > 1) patrons++; // Statement inside a block if(ticketsTaken > 1) { patrons++; } Again, both of these code snippets are equivalent. Just remember that the target of a decision-making statement can be a single statement or block of statements. For the rest of the chapter, we use both forms to better prepare you for what you will see on the exam. While both of the previous examples are equivalent, stylistically using blocks is often preferred, even if the block has only one statement. The second form has the advantage that you can quickly insert new lines of code into the block, without modifying the surrounding structure. The if Statement Often, we want to execute a block only under certain circumstances.
  • Book cover image for: Java Concepts
    eBook - PDF
    • Cay S. Horstmann(Author)
    • 2014(Publication Date)
    • Wiley
      (Publisher)
    156 One of the essential features of computer programs is their ability to make decisions. Like a train that changes tracks depending on how the switches are set, a program can take different actions depending on inputs and other circumstances. In this chapter, you will learn how to program simple and complex decisions. You will apply what you learn to the task of checking user input. 4.1 The if Statement The if statement is used to implement a decision (see Syntax 4.1). When a condition is fulfilled, one set of statements is executed. Otherwise, another set of statements is executed. Here is an example using the if statement: In many countries, the number 13 is considered unlucky. Rather than offending superstitious ten- ants, building owners sometimes skip the thir- teenth floor; floor 12 is immediately followed by floor 14. Of course, floor 13 is not usually left empty or, as some conspiracy theorists believe, filled with secret offices and research labs. It is simply called floor 14. The computer that controls the building elevators needs to compensate for this foible and adjust all floor numbers above 13. Let’s simulate this process in Java. We will ask the user to type in the desired floor number and then compute the actual floor. When the input is above 13, then we need to decrement the input to obtain the actual floor. For example, if the user provides an input of 20, the program determines the actual floor to be 19. Otherwise, it simply uses the supplied floor number. int actualFloor; if (floor > 13) { actualFloor = floor - 1; } else { actualFloor = floor; } The flowchart in Figure 1 shows the branching behavior. In our example, each branch of the if statement contains a single statement. You can include as many statements in each branch as you like. Sometimes, it happens that The if statement allows a program to carry out different actions depending on the nature of the data to be processed.
  • Book cover image for: Java All-in-One For Dummies
    • Doug Lowe(Author)
    • 2023(Publication Date)
    • For Dummies
      (Publisher)
    The if statement lets you execute a statement or a block of statements only if some conditional test turns out to be true. And the switch statement lets you execute one of several blocks of statements depending on the value of an integer variable. The if statement relies heavily on the use of Boolean expressions, which are, in general, expressions that yield a simple true or false result. Because you can’t do even the simplest if statement without a Boolean expression, this chapter begins by showing you how to code simple Java Boolean expressions that test the value of a variable. Later, after looking at the details of how the if statement works, I revisit Boolean expressions to show how to combine them to make complicated logical decisions. Then I get to the switch statement. Chapter 4 IN THIS CHAPTER » Boring into Boolean expressions for fun and profit » Focusing on your basic, run-of-the- mill if statement » Looking at else clauses and else-if statements » Understanding nested if statements » Considering logical operators » Looking at the weird ?: operator » Knowing the proper way to do string comparisons 128 BOOK 2 Programming Basics You’re going to have to put your thinking cap on for much of this chapter, as most of it plays with logic puzzles. Find yourself a comfortable chair in a quiet part of the house, turn off the TV, and pour yourself a cup of coffee. Using Simple Boolean Expressions All if statements, as well as several of the other control statements that I describe in Book 2, Chapter 5 (while, do, and for), use Boolean expressions to determine whether to execute or skip a statement (or a block of statements). A Boolean expression is a Java expression that, when evaluated, returns a Boolean value: true or false. As you discover later in this chapter, Boolean expressions can be very complicated.
  • Book cover image for: Big Java
    eBook - PDF

    Big Java

    Early Objects

    • Cay S. Horstmann(Author)
    • 2019(Publication Date)
    • Wiley
      (Publisher)
    131 C H A P T E R 5 C H A P T E R G O A L S To implement decisions using if statements To compare integers, floating-point numbers, and strings To write statements using the Boolean data type To develop strategies for testing your programs To validate user input C H A P T E R C O N T E N T S © zennie/iStockphoto. 5.1 THE IF STATEMENT 132 SYN if Statement 134 CE 1 A Semicolon After the if Condition 134 PT 1 Brace Layout 135 PT 2 Always Use Braces 135 PT 3 Tabs 136 PT 4 Avoid Duplication in Branches 136 ST 1 The Conditional Operator 137 5.2 COMPARING VALUES 137 SYN Comparisons 138 CE 2 Using == to Compare Strings 143 HT 1 Implementing an if Statement 143 C&S Dysfunctional Computerized Systems 145 WE1 Extracting the Middle 146 5.3 MULTIPLE ALTERNATIVES 146 ST 2 The switch Statement 148 5.4 NESTED BRANCHES 149 CE 3 The Dangling else Problem 152 PT 5 Hand-Tracing 153 ST 3 Block Scope 154 ST 4 Enumeration Types 155 5.5 PROBLEM SOLVING: FLOWCHARTS 156 5.6 PROBLEM SOLVING: SELECTING TEST CASES 159 PT 6 Make a Schedule and Make Time for Unexpected Problems 160 ST 5 Logging 161 5.7 BOOLEAN VARIABLES AND OPERATORS 161 CE 4 Combining Multiple Relational Operators 164 CE 5 Confusing && and || Conditions 164 ST 6 Short-Circuit Evaluation of Boolean Operators 165 ST 7 De Morgan’s Law 165 5.8 APPLICATION: INPUT VALIDATION 166 C&S Artificial Intelligence 168 DECISIONS 132 One of the essential features of computer programs is their ability to make decisions. Like a train that changes tracks depending on how the switches are set, a program can take different actions depending on inputs and other circumstances. In this chapter, you will learn how to program simple and complex decisions. You will apply what you learn to the task of checking user input. 5.1 The if Statement The if statement is used to implement a decision (see Syntax 5.1). When a condition is fulfilled, one set of statements is executed.
  • Book cover image for: Big C++
    eBook - PDF

    Big C++

    Late Objects

    • Cay S. Horstmann(Author)
    • 2017(Publication Date)
    • Wiley
      (Publisher)
    59 C H A P T E R 3 DECISIONS C H A P T E R G O A L S To be able to implement decisions using if statements To learn how to compare integers, floating-point numbers, and strings To understand the Boolean data type To develop strategies for validating user input C H A P T E R C O N T E N T S © zennie/iStockphoto. 3.1 THE IF STATEMENT 60 SYN if Statement 61 CE 1 A Semicolon After the if Condition 63 PT 1 Brace Layout 63 PT 2 Always Use Braces 64 PT 3 Tabs 64 PT 4 Avoid Duplication in Branches 65 ST 1 The Conditional Operator 65 3.2 COMPARING NUMBERS AND STRINGS 66 SYN Comparisons 67 CE 2 Confusing = and == 68 CE 3 Exact Comparison of Floating-Point Numbers 68 PT 5 Compile with Zero Warnings 69 ST 2 Lexicographic Ordering of Strings 69 HT 1 Implementing an if Statement 70 WE1 Extracting the Middle 72 C&S Dysfunctional Computerized Systems 72 3.3 MULTIPLE ALTERNATIVES 73 ST 3 The switch Statement 75 3.4 NESTED BRANCHES 76 CE 4 The Dangling else Problem 79 PT 6 Hand-Tracing 79 3.5 PROBLEM SOLVING: FLOWCHARTS 81 3.6 PROBLEM SOLVING: TEST CASES 83 PT 7 Make a Schedule and Make Time for Unexpected Problems 84 3.7 BOOLEAN VARIABLES AND OPERATORS 85 CE 5 Combining Multiple Relational Operators 88 CE 6 Confusing && and || Conditions 88 ST 4 Short-Circuit Evaluation of Boolean Operators 89 ST 5 De Morgan’s Law 89 3.8 APPLICATION: INPUT VALIDATION 90 C&S Artificial Intelligence 92 60 One of the essential features of computer programs is their ability to make decisions. Like a train that changes tracks depending on how the switches are set, a program can take different actions, depending on inputs and other circumstances. In this chapter, you will learn how to program simple and complex decisions. You will apply what you learn to the task of checking user input. 3.1 The if Statement The if statement is used to implement a decision. When a condition is fulfilled, one set of statements is executed. Otherwise, another set of statements is executed (see Syntax 3.1).
  • Book cover image for: Programming with C++
    • Kyla McMullen, Elizabeth Matthews, June Jamrich Parsons, , Kyla McMullen, Kyla McMullen, Elizabeth Matthews, June Jamrich Parsons(Authors)
    • 2021(Publication Date)
    Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it. PROGRAMMING WITH C++ 102 Boolean expressions conditional logical operator conditional statement control structure decision control structure else-if structure equal operator fall through if-then structure if-then-else structure nested-if structures relational operator switch-case structure truth table Key Terms SUMMARY • A control structure alters the sequential execution of statements in a computer program. A decision control structure alters the sequential flow by branching to specific statements based on a condition or decision. Decision control structures help programs seem intelligent because they can make responses that correspond to user input. • Decision control structures can be classified as if-then, if-then-else, nested-if, else-if, and switch-case. • Decision control structures begin with a conditional statement such as if choice == 1. • Conditional statements include relational operators, such as == != > < >= and <=. • The == equal operator, not the = assignment operator, is used in conditional statements. • Relational operators and operands form Boolean expressions, such as choice == 1, that evaluate to True or False. • Boolean expressions have similarities to Boolean data types. Both carry a value of True or False. In practice, however, you use a Boolean expression as part of a conditional statement, whereas you use a Boolean data type when making declaration or assignment statements. • Fall through refers to program execution that continues to the next conditional statement within a struc- ture. Switch-case structures typically have fall through unless break keywords are added.
  • Book cover image for: Programming Fundamentals Using JAVA
    No longer available |Learn more

    Programming Fundamentals Using JAVA

    A Game Application Approach

    if statement that determines if it is raining.
    if (raining == true )
    {
    System.out.println( " Take your umbrella, " );
    if (temperature < 50) // begins a nested if statement
    {
       System.out.println( " and carry your raincoat too " );
    } // end of the inner if statement
    else {
       System.out.println( " but not your raincoat " );
    }
    { // end of the outer if statement
    The following code segment is another example of the use of a nested if statement. It is an alternate way of determining when snowmen s1 and s2 have collided and s1 is visible.
    if ( !(s2.getX( ) > s1.getX() + w || s2.getX() + w < s1.getX()||
    s2.getY( ) > s1.getY() + h || s2.getY() + h < s1.getY())) //collision
    {
       if (s1.getVisible == true ) // and s1 is visible
      {     score = score + 1;
        s1.setVisible( false );
      } }
    4.6 THE SWITCH STATEMENT
    The switch statement is another control-of-flow statement available in Java. It is not as versatile as the if and if-else statements in that the decisions these statements make cannot be based on an explicitly written simple or compound Boolean expression. The syntax of the switch statement limits the operator used in its decision making to equality. In addition, the equality must be between:
    two String objects
    two byte , short , char , or int primitive-data types (or classes that "wrap" these data types), or
    two instances of a previously defined enumerated type (which will be discussed in Chapter 7 )
    All uses of the switch statement can be coded using an if-else statement, but not vice versa. That being said, there are times when the use of the switch statement makes our programs more readable and therefore easier to understand, modify, and maintain. It can only be used when the decision as to which statements to execute and which statements to skip is based on a choice selected from a group, or menu, of finite choices. When this is the case, the use of the switch
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.