# Table Boolean Logic

In this section, we'll extend our code with "boolean logic" .. using and or to combine multiple true/false tests.

## Boolean Logic: && || !

• Want to be able to combine tests, in English like this
-- Name starts with "A" and ends with "y"
• In code "boolean logic"
• and `&&` (two ampersands)
• or `||` (two vertical bars)
• not `!` (exclamation mark, we're not doing this one)
• Sorry syntax is a bit cryptic -- historical syntax accident

## Boolean Logic Example 1

 table = new SimpleTable("baby-2010.csv"); for (row: table) { if (row.getField("name").startsWith("A") && row.getField("name").endsWith("y")) { print(row); } }

• The && joins a startsWith test and a endsWith test
• The whole test is written across two lines because it is kind of long (optional)
• Standalone rule
--Note that the tests joined by && || are syntactically complete tests on their own, then joined with && or ||
• Looks reasonable but is incorrect: `row.getField("name).startsWith("A") && endsWith("y")`
• Common error: too few right parenthesis around the test
• Run tries to detect certain common errors, like omitting the {, or typing & instead of &&, giving an error message

## Boolean Logic Example 2

Change the code below so it prints rows where the following is true:
Name starts with "A" and rank is <= 50

 table = new SimpleTable("baby-2010.csv"); for (row: table) { if (row.getField("name").startsWith("A")) { print(row); } }

## Boolean Logic Example 3

Now do an example with or || -- change the code below to print rows where the following is true:
Name starts with "X" or name starts with "Y" or name starts with "Z"

 table = new SimpleTable("baby-2010.csv"); for (row: table) { // your code here if (row.getField("name").startsWith("X")) { print(row); } }

## Many Boolean Examples

Here is the working code for the Popular A names test mentioned above.

 table = new SimpleTable("baby-2010.csv"); for (row: table) { if (row.getField("name").startsWith("A") && row.getField("rank") <= 50) { print(row); } }

Experiments to try:

• For these examples, we'll use one of && || but not both.
• 1. name starts with "Ab" or name starts with "Ac"
• 2. name starts with "Ab" or name starts with "Ac" or name starts with "Al"
• 3. name starts with "O" and name ends with "a"
• 4. name starts with "O" and gender is "girl"
• 5. name ends with "a" and gender is "boy"
• 6. rank is <= 10 and gender is "girl" (translation: "top 10 girl names")
• 7. rank is <= 10 or gender is "girl" (this one doesn't make a ton of sense, but what does this print?)
• 8. name ends with "ia" and gender is "boy" (hah, then try with gender is "girl")
• 9. name ends with "io" and gender is "girl" (then try "boy")
• 10. name ends with "o" and gender is boy and rank is >= 900

Experiment solution code: