English subtitles

← Boolean - Intro to Java Programming

Get Embed Code
6 Languages

Showing Revision 5 created 05/25/2016 by Udacity Robot.

  1. You've been working a lot with and and or now, and the expressions got kind of
  2. complicated. In fact, so complicated that they've attracted the interest of
  3. mathematicians, such as this stern looking fellow. His name is George Boole.
  4. And he figured out the rules for working with conditions that could be true or
  5. false. And ever since, that's been called Boolean logic. Now, why do we care?
  6. We want our programs to be simpler to read. And so, when we have a long and
  7. complex condition, such as this one, we might want to put it in a separate
  8. method. Let's think about what this test here was. This was the test for the s
  9. flag, where you had a blue square in the middle. And this test you checked, is
  10. our pixel, in the middle. Alright, so if we had a method that could test that,
  11. we could say, if x and y is in the middle, then we want blue, otherwise white.
  12. Much easier to read. Lets go and write this method. Here it is, isInMiddle,
  13. takes and x and a y, coordinate. And here, you have the exact same condition
  14. that we've had before. And we simply compute, and return that. There's just one
  15. catch. We have to specify a return type for this method. And what is this thing
  16. that's being returned? Well it's either true or false. In Java, the type, that
  17. has two values, true and false, is called, Boolean, in honor, of our friend
  18. George. Here it is. So when you have a method, that can return a condition,
  19. that's true or false, you declare it as a Boolean method. Then you can use that
  20. method inside an if statement just as much as you can use the relational
  21. operator. You would want to do that whenever a condition has become so
  22. complicated, that you want to put it inside its own method. You can also
  23. declare variables of Boolean type. Let me give you a quick example. [SOUND].
  24. I've reimplemented the isInMiddle method to use two Boolean variables. Let's
  25. check it out. The first variable, x in middle, checks where the x is between 1
  26. 3rd and 2 3rds of the weight. It's said to true if this condition is fulfilled.
  27. Or to false if it's not. And similarly. This variable over here, yInMiddle, is
  28. set to true when this condition is fulfilled, and to false if it's not. Why
  29. might I want to do this? Because each of those conditions is complicated enough
  30. that by saving it in a variable, it makes the code easier to read. Now over
  31. here, I say if both of these conditions are fulfilled then the point is in the
  32. middle, so I return the and of these two. Generally, you use a Boolean variable
  33. if you want to remember a value that's true of false, so that you can use it
  34. later. Sarah has an example of that for you, in a different context.