Computer Science

Java If Else Statements

Java If Else Statements are conditional statements used to make decisions in a program. They allow the program to execute different blocks of code based on whether a specified condition is true or false. If the condition is true, the code within the "if" block is executed; otherwise, the code within the "else" block is executed.

Written by Perlego with AI-assistance

8 Key excerpts on "Java If Else Statements"

  • Book cover image for: Java Programming Fundamentals
    eBook - PDF

    Java Programming Fundamentals

    Problem Solving Through Object Oriented Analysis and Design

    • Premchand S. Nair(Author)
    • 2008(Publication Date)
    • CRC Press
      (Publisher)
    Consider the syntax of if and if … else structure you have already learned. For the sake of convenience, those structures are reproduced here. if (logicalExpression) ActionStatement if (logicalExpression) ActionStatement else ActionStatement In the above structures, ActionStatement stands for any executable Java statement, including a block statement. In particular, ActionStatement can be another if or if … else statement. Example 4.19 In this example, we graphically illustrate some of the possible nested structures using if and if … else . The structure shown in Figure 4.4 is an if … else structure nested inside an if structure. The two structures shown in Figure 4.5 are obtained by nesting one if structure inside an if … else . The structure shown in Figure 4.6 is created by nesting two if structures inside an if … else structure. 158 ■ Java Programming Fundamentals FIGURE 4.6 Nesting control structure 3 . logicalExp3 true false logicalExpOne logicalExpTwo true false true false FIGURE 4.4 Nesting control structure 1. logicalExpOne true false logicalExpTwo true false FIGURE 4.5 Nesting control structure 2. logicalExpOne logicalExpTwo true false true false true false logicalExpOne logicalExpTwo true false Decision Making ■ 159 The structure shown in Figure 4.7 shows the nesting of two if … else struc-tures inside an if … else structure. Observe that it can make a four-way decision. The four different selections are logicalExpOne is false and logicalExpTwo is false logicalExpOne is false and logicalExpTwo is true logicalExpOne is true and logicalExp3 is false logicalExpOne is true and logicalExp3 is true Example 4.19 shows that a wide variety of structures can be created through nesting of if and if … else structures. Example 4.20 Consider the income tax rules of a certain country. There is no income tax for the first $25,000.00. The next $75,000.00 is taxed at the rate of 15% and the amount above 100,000.00 is taxed at the rate of 25%.
  • 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 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: 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: Programming with C++
    • Kyla McMullen, Elizabeth Matthews, June Jamrich Parsons, , Kyla McMullen, Kyla McMullen, Elizabeth Matthews, June Jamrich Parsons(Authors)
    • 2021(Publication Date)
    All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. 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++ 96 To handle algorithms that require multiple conditions, you can use an else-if structure. Figure 6-14 provides the syntax, rules, and best practices. Syntax: if (condition) statement; else if (condition) statement; else if (condition) { statement; statement; } else statement; Rules and best practices: • Begin with an if statement. • Use the keyword else if for subsequent conditional statements. • When else-if blocks contain more than one statement, use curly braces. • Use the keyword else for the final condition. • No semicolon is necessary after the parentheses or else keyword. Figure 6-14 Syntax for an else-if structure Figure 6-15 contains code for a program that uses an else-if structure to handle menu selections. Else If Structures (6.3.5) Programming languages provide syntax for structures that involve multiple conditions. Suppose you want to offer customers a menu of the following options: Press or say 1 to connect to an account agent. Press or say 2 to troubleshoot your cable service. Press or say 3 to troubleshoot your Internet connection. Press or say 0 to quit. Copyright 2022 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. 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.
  • 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
  • Book cover image for: Processing
    eBook - ePub

    Processing

    An Introduction to Programming

    else statement:
    if (integer == 1)
    {  println("Computer picks: Rock!"); }
    else if (integer == 2)
    {  println("Computer picks: Paper!"); } else {  println("Computer picks: Scissors!"); }
    Now, whenever we run this program and the randomly chosen integer is 1, Processing tests the condition in the if clause and determines it to be true, so the statement associated with the if clause is performed: computer picks “rock.” However, any else if or else clauses following the if clause will not be performed.
    On the other hand, whenever the randomly chosen integer is 2, the condition in the if clause is tested first and determined to be false, so the statement it contains is not performed. Processing then goes on to test the condition in the else if clause and determines it to be true, so the statement it contains is performed, and the computer chooses “paper.” However, any remaining else if or else clauses are skipped over. In this particular case, it is the else clause that is not performed.
    Such skipping over unnecessary conditions is sometimes known as short-circuit evaluation.
    As in an if-else statement, the else clause of an if-else -if- else statement defines the default action(s). These are statements that are performed only when all the preceding conditions of the if clause and any else if clauses have already been determined to be false. In our program, if the randomly chosen integer has already been determined to be neither 1 nor 2, then the only remaining possibility is for the integer to be 3 , and in this case, the computer should pick “scissors .” This is why the else
  • Book cover image for: Brief Java
    eBook - PDF

    Brief Java

    Early Objects

    • Cay S. Horstmann(Author)
    • 2019(Publication Date)
    • Wiley
      (Publisher)
    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. 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 tenants, building owners sometimes skip the thirteenth floor; floor 12 is immediately followed by floor 14. Of course, floor 13 is not usually left empty. 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; } © DrGrounds/iStockphoto. This elevator panel “skips” the thirteenth floor. The floor is not actually missing—the computer that controls the elevator adjusts the floor numbers above 13. The if statement allows a program to carry out different actions depending on the nature of the data to be processed. An if statement is like a fork in the road. Depending upon a decision, different parts of the program are executed. © Media Bakery. 5.1 The if Statement 133 floor > 13? True False actualFloor = floor - 1 actualFloor = floor Condition floor > 13? True False actualFloor-- No else branch Figure 1 Flowchart for if Statement Figure 2 Flowchart for if Statement with No else Branch The flowchart in Figure 1 shows the branching behavior.
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.