Chapter 5
1 / 34

Chapter 5 - PowerPoint PPT Presentation

  • Uploaded on

Chapter 5. In Which We Finally Learn Conditional Statements. The If Statement. We don’t always want to run every single line of code. For example: If a bank account is empty, we don’t want to allow someone to withdraw money.

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
Download Presentation

PowerPoint Slideshow about ' Chapter 5' - duard

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
Chapter 5

Chapter 5

In Which We Finally Learn Conditional Statements

The if statement
The If Statement

  • We don’t always want to run every single line of code.

    • For example: If a bank account is empty, we don’t want to allow someone to withdraw money.

    • That means we don’t want the line of code that actually takes money out to run.

  • IF the account has enough money, allow the withdrawal – or ELSE tell them they have insufficient funds (and charge them a fee, because that makes sense).

How to make an if statement
How to make an IF statement

  • Take the phrase: “IF the account has enough money, allow the withdrawal – or ELSE tell them they have insufficient funds”

  • In Java, it would look like:

  • if (withdrawal <= balance)


    balance -= amount;




    balance -= OVERDRAFT_FEE;

    System.out.println(“Insufficient Funds.”);


A closer look
A closer look

  • In general, a basic if statement is:

    if (condition)


    //code to be run if condition is true




    //code to be run if condition is false


What goes in the condition part
What goes in the Condition part?

  • Whatever goes into the condition must evaluate to a boolean.

  • Java provides several comparison operators that help:

  • > Greater than

  • < Less than

  • >= Greater than or equal to

  • <= Less than or equal to

  • == Is equal to

  • != Is not equal to

Why the extra curly braces
Why the extra curly braces?

  • In Java, the { and } define what are called “block statements.” They group together many lines of code.

  • With a conditional statement in which you only want a single line of code to execute, they aren’t strictly necessary, but I still recommend them.

    • Easier to add code later.

    • Easier to pick out conditional statements (readability).

Selection operator
Selection Operator

  • This operator is not strictly necessary, but in case you run into it:

  • There is a shorthand for small if/else statements.

  • condition ? value1 : value2;

  • For example:

    • y = x >= 0 ? x : -x;

  • Which translates to:

    • if (x>=0)

      y = x;


      y = -x;

  • I find it confusing and unnecessary, but just in case…

Issues with comparing things
Issues with comparing things

  • Integers are pretty straightforward to compare.

  • Floats can be tricky if you are looking to compare numbers exactly using “==“

    • Remember rounding error?

  • The book has a good example involving Math.pow(Math.sqrt(2), 2) – 2;

    • Mathematically, this should = 0, but with rounding error, it ends up being merely very close to 0.

  • To combat this, if you ever suspect that you may run into fiddly floats/doubles with rounding error, use the method found on page 189.

    • Add minor error tolerance into == statements.

Comparing strings
Comparing Strings

  • What is held in a String variable (or indeed, in any object variable)?

  • Can you see how this would make comparisons tricky?

  • In the case of this code, what is actually being compared?

    String msg1 = “Hi!”;

    String msg2 = “Hi!”;

    if (msg1 == msg2)

Object variables hold object references
Object Variables hold object references

  • What would we generally like the == to do in this case?

  • Have to use specialized methods to accomplish this.

  • Another great reason to use pre-made classes: the .equals() method!

  • In the previous example, rather than “==“ use:

    if (msg1.equals(msg2))

Yay premade classes
Yay, premade classes!

  • Even better, the String class has other ways to compare the Strings:

    • .equalsIgnoreCase(String)

    • .compareTo(String)

    • Etc.

  • Many premade classes have specialized .equals() methods to help you compare objects, just be aware that if you make your own objects you want to compare, you’ll need to make your own as well.

Comparing other objects
Comparing other objects

  • Just like Strings, objects have to compared in a way specific to that particular object.

  • Look at page 191:

    • Rectangle objects can only be compared using “==“ to test if the reference is the same between the two.

    • Otherwise, each value inside the objects have to be compared to check that the two referenced objects are equivalent if not exactly the same object.

    • Since the Rectangle class has a defined .equals(Rectangle) method, we can use that. Otherwise, we’d have to do it the long way.

  • The take-home lesson: the .equals() method is great, but the people who programmed the object must have written one specific to the class, otherwise we’re out of luck.

One side note about comparing objects
One side note about comparing Objects

  • There is one other way that two object variables can be equal, other than pointing to the same object.

  • Empty object variables point to “null.”

  • If you want to see if (for example) an object has been initialized, you can use the “==“ operator to check in this way:

    if (myObject == null)



Checking for different cases
Checking for different cases

  • What if we have more than one possible condition we want to check a variable for?

  • For example:

    • If an account has more than enough money, withdraw it.

    • If the account just enough funds, tell them that they now have no money in the account.

    • If the account does not have enough, tell the customer than they don’t have the dough and charge them an overdraft fee.

More specific case checking
More specific case checking

  • Here is an example of the aforementioned statement:

    if (balance > withdrawal)


    balance -= withdrawal;


    else if ( balance == withdrawal)


    balance -= withdrawal;

    System.out.println(“Now you broke, Holmes.”);




    System.out.println(“Not enough cash… Stranger.”);


Switch statements
Switch statements

  • If you have a long series of if-else if- else if – etc, then it can be helpful to use a particular shorthand. Unlike selection, I have found considerable use from this format.

  • Shortcomings: Can only use ints or chars (or enums, more on that later) for comparisons, and each test case has to be a constant.

  • Advantages: a very simple and straightforward way to group together large numbers of else ifs.

Other ways to use if statements
Other ways to use if statements

  • You can have an if statement inside of another if statement.

  • Check page 199.

  • There are two choices, if you are married or single and then what your household income bracket is.

  • Each choice is made independently and should be checked seperately.

Boolean operators
Boolean Operators

  • The value in an if statement’s parentheses must evaluate to a boolean value.

  • (x > 1000) will evaluate to either true or false.

  • A method with a boolean return type is called a predicate method.

  • Many useful methods of this type are available in various classes, for example:

    • .isDigit(index) of the string class

    • .isEmpty() in several classes

    • .hasNext() of the Scanner class

    • etc.

Combining boolean checks
Combining boolean checks

  • Logic has several words that can be used to combine comparisons.

  • AND means that the whole statement is only true if case1 AND case2 are true. Use the && operator.

  • OR means that the whole statement is true if case1 OR case2 are true (at least one, technically an “inclusive OR”). Use the || operator.

  • NOT flips the boolean to the other value. It is shown with a ! so:(!true) => false

You can t do that
You can’t do that

  • Compound inequalities cannot be written as they are in mathematics.

  • (0 < val < 100) is not a valid way of checking to see if val is between 0 and 100.

  • You must use (val > 0) && (val < 100)

Convert these to java
Convert these to Java

  • myVal is less than 5 but more than -3

  • yourVal is greater than or equal to 16 or its less than 4

  • Either (x is equal to 7 AND y is less than 4), OR y is greater than or equal to 5.

True or false
True or False

  • !(4 <5)

  • !false

  • (2 > 2) || (( 4 == 4) && ( 1 < 0))

  • (2 > 2) || ( 4 == 4) && ( 1 < 0)

  • (34 != 33) && !false

Lazy evaluation
Lazy evaluation

  • For an &&, if the first condition is false, the second condition won’t be checked, because the outcome has already been determined.

  • For an || if the first condition is true, then the second condition won’t be checked for the same reason.

  • Because of this, it is unwise to try to use conditional statements to actually accomplish things.

Using boolean vars
Using booleanvars

  • Rather than testing a boolean like this:

    • if (married == true)

  • Since a test will evaluate to true or false anyways, just use this:

    • if (married)

  • It works out to the same, and then the book won’t consider you “gauche.”

Testing comments
Testing comments

  • Black box testing:

    • Testing without any sense of the internal structure of a program.

  • White box testing:

    • Look inside the program and target your testing where you think it might fail.

  • You are the programmer, so what do you think is more efficient and powerful?

Choosing test cases
Choosing test cases

  • Don’t just pick randomly.

  • Think about what numbers might cause bad behavior.

  • These tend to be on the boundaries:

    • 0

    • null references

    • Unexpected negative numbers

    • Numbers that might cause rounding errors

  • If you try as hard as you can to break your programs before users get their hands on it, it will be less likely to fail in the real world.

Code niceties
Code niceties

  • It helps a lot to have your program spit out a lot of words when you’re testing to make sure it works right.

  • Once you’re done testing, it can be annoying to erase/comment each line so that the output doesn’t have all the extra information.

  • You can fix this by using the Logger class. The book has more info on how to use it on p.214.

  • In one line, you can disable or enable any message you output using the command:

    •“my message.”);

  • Not necessary, but handy.

A word on the ap test
A Word on the AP test

  • The upcoming test will have sample AP test questions on it.

  • Like other standardized tests, the questions are written carefully so that they challenge your abilities.

    • The level of nuance is much higher than in the normal questions you are being asked.

  • Your skill level is now high enough in Java essentials that I can begin to give you genuine AP questions, so be prepared.

  • Don’t immediately answer… Think first! They can be tricky questions!

Filling in a gap
Filling in a gap

  • While examining the AP questions, there was a topic that I had skipped that showed up at least once in every test.

  • Since our goal is to do well on the AP test, I want you to know this property.

  • I will continue to add in these extra specifics as time goes by.

Demorgan s law
DeMorgan’s Law

  • If you want to negate an && or an ||, there is a simple formula:

  • Move the negation (!) inwards and swap the &&/||. What does that mean?

  • These two are logically equivalent:

    • !(A && B)

    • !A || !B

  • So are these two:

    • !(A || B)

    • !A && !B

More demorgan s law
More DeMorgan’s Law

  • Keep in mind that the negation of certain things can also be rewritten without a !

  • What is the negation of x > 5?

  • Using DeMorgan’s Law, negate the following expression:

    • if (0 < amount && amount < 1000)

  • DeMorgan himself was Augustus DeMorgan, a British Mathematician who lived in the 19thcentury.

Things i would study if i were taking the test
Things I would study if I were taking the test

  • Conditional Statements

    • Nested statements

    • Else and else if

  • Comparisons

    • Basic symbols: ==, >=, <, !, etc.

    • Comparison methods like .equals();

    • Know when to use one, and when to use the other

  • Compound statements

    • &&, ||

    • DeMorgan’s Law

Things i would study if i were taking the test part deux
Things I would study if I were taking the test, part deux

  • Finer points of boolean logic

    • Lazy Evaluation

    • What is a predicate method?

    • Not being gauche by using a boolean itself, and not (myBool == true)

      • -- Just kidding –

  • Black box vs. White Box testing:

    • Black Box is more like the real world

    • White Box is more efficiently targeted at potential weak spots in the code.

Old topics you should keep in mind
Old topics you should keep in mind

  • String methods

    • A String can be played with character by character.

    • If you have a bunch of things connected by a ‘+’ and even one of them is a String, the result will be a String.

      • E.g. 5 + 12 + “6” will result in “176”

      • This is a quick and dirty way to turn primitives into Strings.

  • Shorthand

    • +=, *=, ++, etc.