Kotlinlearncs.online LogoJava

    ← Prev

    Index

    Next →

    Kotlin
    Java
    • Compound Conditionals : 4

    • Conditional Expressions and Statements : 3

    • Operations on Variables : 2

    • Variables and Types : 1

    • Hello, world! : 0

    Conditional Expressions and Statements

    double temperature = 89.9;
    boolean isHot = temperature > 80;
    if (isHot) {
    System.out.println("It's hot!");
    }

    This lesson introduces how computers make decisions. We’ll start simple, and get a bit more complicated tomorrow. But simple computer decision making is what gives birth to all of the more complex computer behaviors.

    An important reminder: you are not alone. Our calendar is packed with opportunities to get help and meet the course staff and fellow students.

    Warm Up Debugging Challenge
    Warm Up Debugging Challenge

    Let’s warm up with your first debugging challenge!

    Conditional Expressions
    Conditional Expressions

    Computers can make decisions based on data. They do this by evaluating whether a given expression is true or false. We can do this with only literal values:

    boolean goodGrade = 95 > 90; // 95 > 90 is the conditional expression
    System.out.println(goodGrade);

    Try changing the literal values in the example above and see what happens. You should be able to get goodGrade to be either true or false, depending on the literal values that you choose.

    But the example above is a bit silly. We don’t need a computer to tell us whether 95 is greater than 90! So usually our conditional expressions involve at least one variable:

    int grade = 95;
    boolean goodGrade = grade > 90;
    System.out.println(goodGrade);

    In the examples above we’re using a conditional expression to set the value of a boolean variable. What makes the expresion a conditional expression is the use of the > operator. For example:

    // The right side of this assignment evaluates to an int because the operator is +
    int grade = 10 + 80;
    // The right side of this assignment evaluates to a boolean because the operator is >
    boolean goodGrade = grade > 90;

    Java includes a variety of useful conditional operators that you can use on numeric variables and literals: <, >, <=, >=, ==, and !=.

    // Let's have fun with Java conditional operators!
    int i = 10;
    int j = 20;

    Tomorrow we’ll look at how we can chain multiple conditional expressions together to make more complicated decisions. For now, we’ll keep things simple.

    Assignment v. Equality Testing
    Assignment v. Equality Testing

    Last time we emphasized how = is an assignment operator in Java and does not test equality. The way that we do test for equality is using a slightly-different but similar-looking operator: ==.

    When you are getting started it can be very hard to see the difference between = and ==. (You’ll get way, way better at this.)

    But it’s worth emphasizing the difference now and starting to be on the lookout for it.

    int i = 10;
    i == 20;

    Conditional Statements
    Conditional Statements

    Conditional expressions form the basis for computer decision making because they are the basis for conditional statements. A conditional statement allows you to tell the computer that it should do one thing or another thing depending on the result of a conditional expression. Put more simply, they allow our programs to make decisions based on data.

    Let’s dive right in and look at our first example. There are multiple new ideas emerging here all at once—so don’t worry, we’ll go over it slowly and carefully below.

    double temperature = 88.8;
    if (temperature > 80) {
    System.out.println("It's hot");
    }

    Parts of this snippet should be familiar to us. The first line is a standard variable declaration and initialization (double temperature = 88.8). The middle of the second line is a conditional expression (temperature > 80). It evaluates to true if the value in the variable temperature is greater than 80 and false otherwise.

    But the rest is new—and represents our first conditional statement. Run the example above and see what happens. Now, change the value of temperature or the threshold (80) and see what happens. See if you get the program to not display any output.

    Now let’s go through it carefully together:

    double temperature = 88.8;
    if (temperature > 80) {
    System.out.println("It's hot");
    }

    Blocks
    Blocks

    if statements introduce us to our first block of code. Blocks begin with a { and end with a }. In the case of an if statement, the block contains the code that should be executed if the condition is true:

    int i = 10;
    if (i != 8) { // Block starts here
    // What to do if i is not equal to 8
    } // Block ends here
    System.out.println("The rest of the program...");

    Blocks of code can contain all of the basic building blocks that we’ve already seen. We can declare variables inside blocks, manipulate them, and even include other conditional statements:

    double distanceinKilometers = 9.8;
    if (distance > 14.8) {
    double distanceInMeters = 1000 * distanceInKilometers;
    if (distanceInMeters > 500) {
    System.out.println("That's more than half a kilometer!");
    }
    }

    We use blocks to help organize our programs. In the case above, blocks identify the code that should be executed if the condition is true. Over the next few lessons we’ll see how blocks can be used to identify code that should be repeated, and name parts of the code that we want to reuse.

    if-else Statements
    if-else Statements

    To conclude, let’s look at one useful addition to the if statement that we introduced above. We’ve seen how it can be used to decide what to do:

    double temperature = 88.8;
    if (temperature > 80) {
    System.out.println("It's hot");
    }

    In the example above, either the block is executed or it is not. But we can also extend this idea to make more complicated decisions. Here’s an example:

    double temperature = 88.8;
    if (temperature > 80) {
    System.out.println("It's hot");
    } else {
    System.out.println("Today is a nice day");
    }

    Practice: Simple Conditional

    Created By: Geoffrey Challen
    / Version: 2020.8.0

    Computers can make decisions based on data. In Java we do this using conditional statements. While they may seem simple, conditional statements are the building block of every more complex computer behavior.

    Let's get some practice with real world decision making using conditional statements. The University of Illinois is using regular frequent testing to monitor the coronavirus on campus. Maybe the most important piece of data produced by coronavirus testing is the positivity rate: the percent of tests that come back positive. A high positivity rate indicates community spread, and may mean that it is time to shut down the campus again.

    Your friend is fairly unconcerned about the coronavirus. They wrote the following snippet of code that uses a 10% positivity rate to decide whether to continue an in-person semester. You think that is too high. (10% is fairly high.) Modify the code below to use 5% as the positivity rate threshold. When you are correct, your code should print "Time to go home" if the value of the variable positivity is greater than 5%. Do not modify the value of positivity.

    Big Little Decisions
    Big Little Decisions

    While the decision-making capabilities that we’ve introduced may seem simple, they are the basis for all more complex computer decision making. When you combine lots of tiny decisions, the end result can be astonishing…

    Homework: Advertising Conditional

    Created By: Harsh Deep
    / Version: 2021.8.0

    By combining data from a marketing platform with the results from personality tests that users have completed, we know that people with more than 500 friends are likely to be extroverts, otherwise they're more likely to be introverts. Based on analysis of user-uploaded photos using computer-vision algorithms, we also know that people who are extroverts are more likely to have many photos of dogs, and introverts are more likely to have many photos of cats. Market research has shown that dog people are highly likely to be positively influenced by advertisements for any product that includes dogs, and similar for cat people and cats.

    For an already initialized int variable friendsCount, if a user has more than 500 friends, print the message "Adopt a Dog Today!" and otherwise print "Buy Cat Food At 20% Off".

    If you'd like to find out more about targeted advertising, you may find these articles interesting:

    More Practice

    Need more practice? Head over to the practice page.