From 4c8ea02867155a4f57fb32014d6608308eb03e90 Mon Sep 17 00:00:00 2001 From: Ethan McCue Date: Sun, 7 May 2023 00:03:26 -0400 Subject: [PATCH 1/9] Methods + Classes (#23) * Add start of if/else! ... Co-Authored-By: Mitch Masia <7084914+masiamj@users.noreply.github.com> * loops * ... * Update SUMMARY.md * loop challenges * Update challenges.md * .. * Move iteration into loops * More arrays * Update access_individual_elements.md * ... * Close out arrays I sans challenges * Rename features.py to features.java to placate folks Update book.toml Update book.toml * Format * Fix typo * .. * ... * ... * ... * classes * ... * Update labeled_continue.md * Update book.toml * ... --------- Co-authored-by: Mitch Masia <7084914+masiamj@users.noreply.github.com> --- book.toml | 7 +- src/SUMMARY.md | 109 +++++++++++++++----- src/arguments.md | 21 ++++ src/arguments/declaration.md | 13 +++ src/arrays/challenges.md | 1 + src/classes.md | 43 ++++++++ src/classes/aliasing.md | 1 + src/classes/declaration.md | 6 ++ src/classes/field_declaration.md | 1 + src/classes/naming_classes.md | 1 + src/classes/naming_fields.md | 14 +++ src/classes/new.md | 1 + src/classes/zero_values.md | 1 + src/constructors/final_fields.md | 1 + src/constructors/multiple_constructors.md | 1 + src/constructors/the_default_constructor.md | 1 + src/constructors/this.md | 1 + src/drawing_shapes/right_triangles.md | 1 + src/instance | 1 + src/instance_methods.md | 1 + src/instance_methods/aliasing.md | 1 + src/instance_methods/declaration.md | 1 + src/instance_methods/derived_values.md | 1 + src/instance_methods/invocation.md | 1 + src/instance_methods/this.md | 1 + src/integers/division.md | 2 +- src/loops/do_while.md | 4 +- src/loops_ii.md | 9 ++ src/loops_ii/break.md | 21 ++++ src/loops_ii/challenges.md | 100 ++++++++++++++++++ src/loops_ii/comparison_to_while.md | 78 ++++++++++++++ src/loops_ii/continue.md | 59 +++++++++++ src/loops_ii/delayed_assignment.md | 35 +++++++ src/loops_ii/drawing_isosceles_triangles.md | 47 +++++++++ src/loops_ii/drawing_right_triangles.md | 55 ++++++++++ src/loops_ii/empty_expressions.md | 31 ++++++ src/loops_ii/empty_initializers.md | 25 +++++ src/loops_ii/empty_statements.md | 51 +++++++++ src/loops_ii/final_variables.md | 35 +++++++ src/loops_ii/for.md | 28 +++++ src/loops_ii/for_counting_up_and_down.md | 23 +++++ src/loops_ii/for_syntax.md | 39 +++++++ src/loops_ii/i.md | 48 +++++++++ src/loops_ii/inferred_types.md | 26 +++++ src/loops_ii/iterate_over_a_string.md | 13 +++ src/loops_ii/iterate_over_an_array.md | 14 +++ src/loops_ii/labeled_break.md | 30 ++++++ src/loops_ii/labeled_continue.md | 27 +++++ src/methods.md | 21 ++++ src/methods/arguments.md | 20 ++++ src/methods/declaration.md | 9 ++ src/methods/invocation.md | 32 ++++++ src/methods/main.md | 17 +++ src/methods/pure_functions.md | 25 +++++ src/methods/return.md | 42 ++++++++ src/methods/return_values.md | 36 +++++++ src/methods/scope.md | 39 +++++++ src/methods/unreachable_statements.md | 35 +++++++ src/methods/void.md | 23 +++++ src/null/checking_for_null.md | 1 + src/null/field_access.md | 1 + src/null/instance_methods.md | 1 + src/return | 1 + src/return_values.md | 37 +++++++ src/return_values/conversion.md | 27 +++++ src/return_values/pure_functions.md | 34 ++++++ src/return_values/void.md | 25 +++++ src/strings/access_individual_characters.md | 8 +- 68 files changed, 1428 insertions(+), 37 deletions(-) create mode 100644 src/arguments.md create mode 100644 src/arguments/declaration.md create mode 100644 src/arrays/challenges.md create mode 100644 src/classes/aliasing.md create mode 100644 src/classes/declaration.md create mode 100644 src/classes/field_declaration.md create mode 100644 src/classes/naming_classes.md create mode 100644 src/classes/naming_fields.md create mode 100644 src/classes/new.md create mode 100644 src/classes/zero_values.md create mode 100644 src/constructors/final_fields.md create mode 100644 src/constructors/multiple_constructors.md create mode 100644 src/constructors/the_default_constructor.md create mode 100644 src/constructors/this.md create mode 100644 src/drawing_shapes/right_triangles.md create mode 100644 src/instance create mode 100644 src/instance_methods.md create mode 100644 src/instance_methods/aliasing.md create mode 100644 src/instance_methods/declaration.md create mode 100644 src/instance_methods/derived_values.md create mode 100644 src/instance_methods/invocation.md create mode 100644 src/instance_methods/this.md create mode 100644 src/loops_ii.md create mode 100644 src/loops_ii/break.md create mode 100644 src/loops_ii/challenges.md create mode 100644 src/loops_ii/comparison_to_while.md create mode 100644 src/loops_ii/continue.md create mode 100644 src/loops_ii/delayed_assignment.md create mode 100644 src/loops_ii/drawing_isosceles_triangles.md create mode 100644 src/loops_ii/drawing_right_triangles.md create mode 100644 src/loops_ii/empty_expressions.md create mode 100644 src/loops_ii/empty_initializers.md create mode 100644 src/loops_ii/empty_statements.md create mode 100644 src/loops_ii/final_variables.md create mode 100644 src/loops_ii/for.md create mode 100644 src/loops_ii/for_counting_up_and_down.md create mode 100644 src/loops_ii/for_syntax.md create mode 100644 src/loops_ii/i.md create mode 100644 src/loops_ii/inferred_types.md create mode 100644 src/loops_ii/iterate_over_a_string.md create mode 100644 src/loops_ii/iterate_over_an_array.md create mode 100644 src/loops_ii/labeled_break.md create mode 100644 src/loops_ii/labeled_continue.md create mode 100644 src/methods/declaration.md create mode 100644 src/methods/invocation.md create mode 100644 src/methods/main.md create mode 100644 src/methods/pure_functions.md create mode 100644 src/methods/return.md create mode 100644 src/methods/scope.md create mode 100644 src/methods/unreachable_statements.md create mode 100644 src/null/checking_for_null.md create mode 100644 src/null/field_access.md create mode 100644 src/null/instance_methods.md create mode 100644 src/return create mode 100644 src/return_values.md create mode 100644 src/return_values/conversion.md create mode 100644 src/return_values/pure_functions.md create mode 100644 src/return_values/void.md diff --git a/book.toml b/book.toml index 5a16912..13693d4 100644 --- a/book.toml +++ b/book.toml @@ -16,9 +16,10 @@ level = 0 # the depth to start folding [preprocessor.features] command = "python3 features.java" +# Going to start writing the rest of the book +# Assuming this is true +toplevel_anonymous_class = true # Not ready -toplevel_anonymous_class = false -# Not ready -simple_io = false +simple_io = true # Turn on when Java 21 released java_21 = false \ No newline at end of file diff --git a/src/SUMMARY.md b/src/SUMMARY.md index fa5ac49..3fec735 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -132,44 +132,97 @@ - [Printing the Contents of an Array](./arrays/printing_the_contents_of_an_array.md) - [Empty Array](./arrays/empty_array.md) - [Difference between Initializer and Literal](./arrays/difference_between_initializer_and_literal.md) - - [Challenges](./arrays/challenges) + - [Challenges](./arrays/challenges.md) # Control Flow II - +- [Arrays II]() + - [Default Values]() + - [Populate Array]() +- [Boxed Primitives]() + - [Boolean]() + - [Character]() + - [Integer]() + - [Double]() + +- [Example: "Growable" Array]() + +# Code Structure II +- [Documentation]() + - [Documentation Comments]() +- [Testing]() # User Defined Types -- [Classes](./classes.md) - - [Primitive Classes](./classes/primitive_classes.md) - - [Reference Classes](./classes/reference_classes.md) - - [null](./classes/null.md) - - [Class Declaration](./classes/class_declaration.md) - - [Naming](./classes/naming.md) -- [Fields](./fields.md) - - [Default Values](./fields/default_values.md) -- [Methods](./methods.md) - - [Arguments](./methods/arguments.md) - - [Return Values](./methods/return_values.md) - - [void](./methods/void.md) -- [Constructors](./constructors.md) +- [Primitive Classes](./classes/primitive_classes.md) +- [Reference Classes](./classes/reference_classes.md) \n\n\nFor an explanation of the mechanics, I'll defer to this old Computerphile video.\n\n\n", "number": [7, 2], "sub_items": [], "path": "floating_point_numbers/accuracy.md", "source_path": "floating_point_numbers/accuracy.md", "parent_names": ["Floating Point Numbers"]}}, {"Chapter": {"name": "Addition", "content": "# Addition\n\nYou can add any two `double`s using the `+` operator.\n\n```java\ndouble x = 5.1;\n// y will be 14.2\ndouble y = x + 9.1;\n```\n\nBecause of the previously mentioned inaccuracy, the results of additions might not always be what you expect.\n\n```java\n// z will be 19.299999999999997\ndouble z = x + y;\n```\n\nYou can add any `int` to a `double` and the result of any such addition will also be a `double`.\n\n```java\nint x = 5;\ndouble y = 4.4;\n// z will be 9.4\ndouble z = x + y;\n\nSystem.out.println(x);\nSystem.out.println(y);\nSystem.out.println(z);\n```\n\nEven if the result of such an expression will not have any fractional parts, you cannot directly assign it to an int.\n\n```java\nint x = 5;\ndouble y = 4;\n// even though z would be 9, which can be stored in an int\n// this will not work. The result of the expression is a double.\nint z = x + y;\n\nSystem.out.println(x);\nSystem.out.println(y);\nSystem.out.println(z);\n```\n", "number": [7, 3], "sub_items": [], "path": "floating_point_numbers/addition.md", "source_path": "floating_point_numbers/addition.md", "parent_names": ["Floating Point Numbers"]}}, {"Chapter": {"name": "Subtraction", "content": "# Subtraction\n\nYou can subtract any two `double`s using the `-` operator.\n\n```java\ndouble x = 5.1;\n// y will be 4.1\ndouble y = x - 9.2;\n\nSystem.out.println(x);\nSystem.out.println(y);\n```\n\nBecause of the previously mentioned inaccuracy, the results of subtractions might not always be what you expect.\n\n```java\n// z will be -4.199999999999999\ndouble z = y - 0.1;\n\nSystem.out.println(z);\n```\n\nYou can subtract any `int` to or from a `double` and the result of any such subtraction will also be a `double`.\n\n```java\nint x = 5;\ndouble y = 4.5;\n// z will be 0.5\ndouble z = x - y;\n\nSystem.out.println(x);\nSystem.out.println(y);\nSystem.out.println(z);\n```\n\nEven if the result of such an expression will not have any fractional parts, you cannot directly assign it to an `int`.\n\n```java\nint x = 5;\ndouble y = 4;\n// even though z would be 1, which can be stored in an int\n// this will not work. The result of the expression is a double.\nint z = x - y;\n```\n", "number": [7, 4], "sub_items": [], "path": "floating_point_numbers/subtraction.md", "source_path": "floating_point_numbers/subtraction.md", "parent_names": ["Floating Point Numbers"]}}, {"Chapter": {"name": "Multiplication", "content": "# Multiplication\n\nYou can multiply any two `double`s using the `*` operator.\n\n```java\ndouble x = 3;\n// y will be 27\ndouble y = x * 9;\n// z will be 13.5\ndouble z = y * 0.5;\n\nSystem.out.println(x);\nSystem.out.println(y);\nSystem.out.println(z);\n```\n\nJust like with addition and subtraction, it is fine to use both integers and integer literals when doing\nmultiplication on doubles. So long as any number being used is a `double` the overall result will be a double.\n\n```java\n// a will be 3\ndouble a = 1.5 * 2;\n```\n", "number": [7, 5], "sub_items": [], "path": "floating_point_numbers/multiplication.md", "source_path": "floating_point_numbers/multiplication.md", "parent_names": ["Floating Point Numbers"]}}, {"Chapter": {"name": "Division", "content": "# Division\n\nYou can divide any two `double`s using the `/` operator.\n\n```java\ndouble x = 8;\n// y will be 4.0\ndouble y = x / 2;\n// z will be 1.3333333333333333\ndouble z = y / 3;\n\nSystem.out.println(x);\nSystem.out.println(y);\nSystem.out.println(z);\n```\n\nUnlike with integer division, floating point division will include the remainder in the result.[^caveat]\n\n[^caveat]: With the caveat that the result is now potentially inaccurate.\n", "number": [7, 6], "sub_items": [], "path": "floating_point_numbers/division.md", "source_path": "floating_point_numbers/division.md", "parent_names": ["Floating Point Numbers"]}}, {"Chapter": {"name": "Equality", "content": "# Equality\n\nJust like `int`s, `double`s can be inspected to see if they are equal to one another using `==`.\n\n```java\ndouble numberOfToes = 10.0;\ndouble numberOfFingers = 10.0;\n\nboolean humanGenerated = numberOfToes == numberOfFingers;\n```\n\nBecause of floating point inaccuracy, this might not always give you the result you expect though.\n\n```java\ndouble x = 0.1;\ndouble y = 0.2;\n// z will be 0.30000000000000004\ndouble z = x + y;\n\n// this will be false.\nboolean doesWhatYouExpect = z == 0.3;\n```\n\nA `double` can also be compared to an `int` and, if they represent the same value, they will be reported as equal.\n\n```java\nint x = 5;\ndouble y = 5.0;\n\n// will be true\nboolean fiveIsFive = x == y;\n```\n", "number": [7, 7], "sub_items": [], "path": "floating_point_numbers/equality.md", "source_path": "floating_point_numbers/equality.md", "parent_names": ["Floating Point Numbers"]}}, {"Chapter": {"name": "Comparison", "content": "# Comparison\n\nIn addition to comparing for equality with `==` and `!=`, `doubles`s can be compared to see if one is bigger than another using\n`>`, `<`, `>=`, and `<=`.\n\nThis works the same as it does with `int`s.\n\n```java\ndouble x = 1.5;\ndouble y = 0.2;\n\n// true\nSystem.out.println(x > y);\n// false\nSystem.out.println(x < y);\n```\n", "number": [7, 8], "sub_items": [], "path": "floating_point_numbers/comparison.md", "source_path": "floating_point_numbers/comparison.md", "parent_names": ["Floating Point Numbers"]}}, {"Chapter": {"name": "Shorthands for Reassignment", "content": "# Shorthands for Reassignment\n\nAll the same shorthands for reassignment work with `double`s the same as they do with `int`s.\n\n```java\ndouble x = 0.5;\n// 0.5\nSystem.out.println(x);\n\nx += 3;\n// 3.5\nSystem.out.println(x);\n\nx -= 1;\n// 2.5\nSystem.out.println(x);\n\nx++;\n// 3.5\nSystem.out.println(x);\n\nx--;\n// 2.5\nSystem.out.println(x);\n\nx *= 5;\n// 12.5\nSystem.out.println(x);\n\nx /= 2;\n// 6.25\nSystem.out.println(x);\n```\n", "number": [7, 9], "sub_items": [], "path": "floating_point_numbers/shorthands_for_reassignment.md", "source_path": "floating_point_numbers/shorthands_for_reassignment.md", "parent_names": ["Floating Point Numbers"]}}, {"Chapter": {"name": "NaN", "content": "# NaN\n\nThere is a special floating point number called `NaN`, which stands for \"Not a Number.\"\n\nYou generally only encounter `NaN` as the result of doing something silly like dividing zero by zero.\n\n```java\ndouble nan = 0.0 / 0.0;\n```\n\n`NaN` is not equal to itself.\n\n```java\n// will be false\nboolean equalToItself = nan == nan;\n\nSystem.out.println(equalToItself);\n```\n\n`NaN` is not greater than itself.\n\n```java\n// will be false\nboolean greaterThanItself = nan > nan;\n\nSystem.out.println(greaterThanItself);\n```\n\n`NaN` is not less than itself.\n\n```java\n// will be false\nboolean lessThanItself = nan < nan;\n\nSystem.out.println(lessThanItself);\n```\n\n`NaN` is not greater than, less than, or equal to any number.\n\n```java\n// will all be false\nSystem.out.println(nan < 5);\nSystem.out.println(nan > 5);\nSystem.out.println(nan == 5);\n```\n\nNone of this is usually useful, but it is fun to know about.\n", "number": [7, 10], "sub_items": [], "path": "floating_point_numbers/nan.md", "source_path": "floating_point_numbers/nan.md", "parent_names": ["Floating Point Numbers"]}}, {"Chapter": {"name": "Positive and Negative Infinity", "content": "# Positive and Negative Infinity\n\nIn addition to the wackyness of `NaN`, floating point numbers can also represent both positive\nand negative infinity.\n\nYou can get positive infinity by dividing any positive number by zero.\n\n```java\ndouble positiveInfinity = 1.0 / 0.0;\n```\n\nYou can get negative infinity by dividing any negative number by zero.\n\n```java\ndouble negativeInfinity = -1.0 / 0.0;\n```\n\nAs you might expect, positive infinity is greater than any number and negative infinity is less than any number.\n\n```java\n// true\nSystem.out.println(positiveInfinity > 99999999);\n\n// true\nSystem.out.println(negativeInfinity < -99999999);\n```\n\nExcept for `NaN`, of course.\n\n```java\ndouble nan = 0.0 / 0.0;\n\n// false\nSystem.out.println(positiveInfinity > nan);\n\n// false\nSystem.out.println(negativeInfinity < nan);\n```\n", "number": [7, 11], "sub_items": [], "path": "floating_point_numbers/positive_and_negative_infinity.md", "source_path": "floating_point_numbers/positive_and_negative_infinity.md", "parent_names": ["Floating Point Numbers"]}}, {"Chapter": {"name": "Square Root", "content": "# Square Root\n\nA relatively common operation to want to perform on floating point numbers\nis to find their square root.\n\nYou can do this with `Math.sqrt`.\n\n```java\ndouble x = 4;\ndouble y = Math.sqrt(x);\n\n// This will output 2\nSystem.out.println(y);\n```\n\nYou need to write `Math.sqrt` and then inside of parentheses the expression whose value you want to take the square root of..\n\n```java\ndouble x = 5;\ndouble y = 13;\ndouble z = Math.sqrt(9 * x + y);\n\n// This will output 7.615773105863909\nSystem.out.println(z);\n```\n\nIf you try to take the square root of a negative number, the result will be `NaN`.\n\n```java\n// will output NaN\nSystem.out.println(Math.sqrt(-5.2));\n```\n", "number": [7, 12], "sub_items": [], "path": "floating_point_numbers/square_root.md", "source_path": "floating_point_numbers/square_root.md", "parent_names": ["Floating Point Numbers"]}}, {"Chapter": {"name": "Conversion to Integers", "content": "# Conversion to Integers\n\nNormally, a `double` value cannot be assigned to an `int`.\n\n```java\ndouble x = 5.0;\n// will not work\nint y = x;\n```\n\nThe reason for this is that there are numbers like `2.5`, the infinities, and `NaN` which do not have an\nobvious way to be represented as an integer.\n\nThere are also numbers which a `double` can represent like `4207483647.0` and `-9999999999.0`\nwhich happen to be too big or too small to fit into the limits of an `int` even though they\ndo have an obvious \"integer representation.\"\n\nAs such, to make an `int` out of a `double` you need to accept that it is a \"narrowing conversion.\"\nThe number you put in won't neccesarily be the number you get out.\n\nTo perform such a narrowing conversion, you need to put `(int)` before a literal or expression that\nevaluates to a `double`.\n\n```java\ndouble x = 5.0;\n// will be 5\nint y = (int) x;\n\nSystem.out.println(y);\n```\n\nAny decimal part of the number will be dropped. So numbers like `2.1`, `2.5`, and `2.9` will all be converted into\nsimply `2`.\n\n```java\nint x = (int) 2.1;\nint y = (int) 2.5;\nint z = (int) 2.9;\n\nSystem.out.println(x);\nSystem.out.println(y);\nSystem.out.println(z);\n```\n\nAny number that is too big to store in an `int` will be converted to the biggest possible `int`, 231 - 1.\n\n```java\n// 2147483647\nSystem.out.println((int) 4207483647.0);\n\ndouble positiveInfinity = 5.0 / 0.0;\n// 2147483647\nSystem.out.println((int) positiveInfinity);\n```\n\nAny number that is too small to store in an `int` will be converted to the smallest possible `int`, -231.\n\n```java\n// -2147483648\nSystem.out.println((int) -9999999999.0);\n\ndouble negativeInfinity = -5.0 / 0.0;\n// -2147483648\nSystem.out.println((int) negativeInfinity);\n```\n\nAnd `NaN` will be converted to zero.\n\n```java\ndouble nan = 0.0 / 0.0;\nSystem.out.println((int) nan);\n```\n\nWhen you use `(int)` to convert, we call that a \"cast[^cast] expression\". The `(int)` is a \"cast operator.\" It even has\na place in the operator precedence order just like `+`, `-`, `==`, etc.\n\nThe main difference is that instead of appearing between two expressions like the `+` in `2 + 5`, it appears to the left of a single expression.\n\n[^cast]: https://english.stackexchange.com/questions/220001/etymology-of-type-cast\n", "number": [7, 13], "sub_items": [], "path": "floating_point_numbers/conversion_to_integers.md", "source_path": "floating_point_numbers/conversion_to_integers.md", "parent_names": ["Floating Point Numbers"]}}, {"Chapter": {"name": "Conversion from Integers", "content": "# Conversion from Integers\n\nTo convert from an `int` to a `double`, you don't need to do any special work. All `int`s are\nrepresentable as `double`s so it is a \"widening conversion\" and will be handled automatically\nby Java when performing an assignment.\n\n```java\nint x = 5;\ndouble y = x;\n\nSystem.out.println(x);\nSystem.out.println(y);\n```\n\nThis is not true in an expression. Even if the result of a computation between `int`s is being assigned to\na `double`, the computation will still be performed using the same rules `int`s usually follow.\n\n```java\nint x = 7;\nint y = 2;\n// integer division of 7 and 2 gives 3.\ndouble z = x / y;\n\nSystem.out.println(z);\n```\n\nTo perform math on an `int` and have that `int` behave as if it were a `double`, you need to convert said `int` into\na `double` using a cast expression and the `(double)` cast operator.\n\n```java\nint x = 7;\nint y = 2;\n// This converts x into a double before performing the division\n// so the result will be 3.5.\ndouble z = (double) x / y;\n\nSystem.out.println(z);\n```\n", "number": [7, 14], "sub_items": [], "path": "floating_point_numbers/conversion_from_integers.md", "source_path": "floating_point_numbers/conversion_from_integers.md", "parent_names": ["Floating Point Numbers"]}}, {"Chapter": {"name": "Challenges", "content": "# Challenges\n\nRemember the rules for this are\n\n- Try to use only the information given up to this point in this book.\n- Try not to give up until you've given it a solid attempt\n\n## Challenge 1\n\nWhat will this program output when run? Write down your guess and then try running it.\n\n~IF toplevel_anonymous_class\n\n```java\nvoid main() {\n double x = 5.1;\n double y = 2.4;\n System.out.println(x + y);\n}\n```\n\n~ELSE\n\n```java\npublic class Main {\n public static void main(String[] args) {\n double x = 5.1;\n double y = 2.4;\n System.out.println(x + y);\n }\n}\n```\n\n~ENDIF\n\n## Challenge 2\n\nWhat will this program output when run? Write down your guess and then try running it.\n\n~IF toplevel_anonymous_class\n\n```java\nvoid main() {\n double x = 5.1;\n double y = 2.1;\n System.out.println(x + y);\n}\n```\n\n~ELSE\n\n```java\npublic class Main {\n public static void main(String[] args) {\n double x = 5.1;\n double y = 2.1;\n System.out.println(x + y);\n }\n}\n```\n\n~ENDIF\n\n## Challenge 3\n\nWhat will this program output when run? Write down your guess and then try running it.\n\nHow can you make it give the \"right\" answer?\n\n~IF toplevel_anonymous_class\n\n```java\nvoid main() {\n double x = 5 / 2;\n System.out.println(x);\n}\n```\n\n~ELSE\n\n```java\npublic class Main {\n public static void main(String[] args) {\n double x = 5 / 2;\n System.out.println(x);\n }\n}\n```\n\n~ENDIF\n\n## Challenge 4\n\nThese two expressions give different results. Why is that, and what results do they give?\n\n```java\ndouble resultOne = (int) 5.0 / 2 + 5.0 / 2;\ndouble resultTwo = (int) (5.0 / 2 + 5.0 / 2);\n\nSystem.out.println(resultOne);\nSystem.out.println(resultTwo);\n```\n\n## Challenge 5\n\nThe following is a quadratic equation.\n\n\\\\[ 2x^2 + 8x + 3 = 0 \\\\]\n\nTo find the solutions of any quadratic equation you can use the following formula.\n\n\\\\[ x = \\frac{-b \\pm \\sqrt{b^2 - 4ac} }{2a} \\\\]\n\nWhere \\\\(a\\\\), \\\\(b\\\\), and \\\\(c\\\\) are the prefixes of each term in the following equation.\n\n\\\\[ ax^2 + bx + c = 0 \\\\]\n\nWrite some code that finds both solutions to any quadratic equation defined by some variables\n`a`, `b`, and `c`. If the equation has imaginary solutions, you are allowed to just output `NaN`.\n\n~IF toplevel_anonymous_class\n\n```java\nvoid main() {\n // For this one in particular, you should output\n // -3.5811388300842 and -0.41886116991581\n // but your code should work with these three numbers changed to\n // represent any given quadratic equation.\n double a = 2;\n double b = 8;\n double c = 3;\n\n double resultOne = ???;\n double resultTwo = ???;\n\n System.out.println(resultOne);\n System.out.println(resultTwo);\n}\n```\n\n~ELSE\n\n```java\npublic class Main {\n public static void main(String[] args) {\n // For this one in particular, you should output\n // -3.5811388300842 and -0.41886116991581\n // but your code should work with these three numbers changed to\n // represent any given quadratic equation.\n double a = 2;\n double b = 8;\n double c = 3;\n\n double resultOne = ???;\n double resultTwo = ???;\n\n System.out.println(resultOne);\n System.out.println(resultTwo);\n }\n}\n```\n\n~ENDIF\n", "number": [7, 15], "sub_items": [], "path": "floating_point_numbers/challenges.md", "source_path": "floating_point_numbers/challenges.md", "parent_names": ["Floating Point Numbers"]}}], "path": "floating_point_numbers.md", "source_path": "floating_point_numbers.md", "parent_names": []}}, {"Chapter": {"name": "Characters", "content": "# Characters\n\nA character, represented by the data type `char`, is a single\nletter or symbol.\n\n```java\nchar letter = 'a';\n```\n\nI choose to pronounce it like the \"char\" in \"Charmander.\"\n", "number": [8], "sub_items": [{"Chapter": {"name": "Character Literals", "content": "# Character Literals\n\nIn order to write a character in a program, you write that one character surrounded\nby single quotes.\n\n```java\n'a'\n```\n\nThis is called a \"character literal.\" It has the same relationship to `char` that an integer literal like 123 has to `int`.\n\n```java\n// Same as this \"integer literal\" is used to write a number\nint sesameStreet = 123;\n// A \"character literal\" is used to write text\nchar thisEpisodeIsBroughtToYouBy = 'c';\n```\n", "number": [8, 1], "sub_items": [], "path": "characters/character_literals.md", "source_path": "characters/character_literals.md", "parent_names": ["Characters"]}}, {"Chapter": {"name": "Common Escape Sequences", "content": "# Common Escape Sequences\n\nWhile most characters can be written directly into a program, as is the\ncase for `a`, `b`, or `t`, there are some which cannot.\n\nFor these, you need to use what is called an \"escape sequence.\"\n\nThe most common escape sequence you will use will be the one for a \"new line.\"\nWhich is a backslash followed by an `n`.\n\n```java\nchar newline = '\\n';\n```\n\nBecause a backslash is used for this special syntax, to put a backslash into a character literal\nyou need to escape it with a backslash of its own.\n\n```java\nchar backslash = '\\\\';\n```\n\nAnd because single quotes are used to mark the start and end of a character literal, they need to be escaped\nas well.\n\n```java\nchar singleQuote = '\\'';\n```\n", "number": [8, 2], "sub_items": [], "path": "characters/common_escape_sequences.md", "source_path": "characters/common_escape_sequences.md", "parent_names": ["Characters"]}}, {"Chapter": {"name": "Conversion to Integers", "content": "# Conversion to Integers\n\nAll `char`s have a matching numeric value. `'a'` is `97`, `'b'` is `98`,\n`'&'` is `38`, and so on.\n\nSame as assigning an `int` to a `double`, you can perform a widening conversion\nby attempting to assign a `char` to an `int`.\n\n```java\nint valueOfA = 'a';\n\nSystem.out.println(valueOfA);\n```\n\n`char`s will be automatically converted to `int`s when used with mathmatical operators like `+`, `-`, `>`, `<`, etc.\n\n```java\nchar gee = 'g';\n\n// all the letters from a to z have consecutive numeric values.\nboolean isLetter = gee >= 'a' && gee <= 'z';\n\nSystem.out.println(isLetter);\n```\n\nThis can be useful if you are stranded on Mars[^onmars] or\nif you want to see if a character is in some range.\n\n[^onmars]: https://www.youtube.com/watch?v=k-GH3mbvUro\n", "number": [8, 3], "sub_items": [], "path": "characters/conversion_to_integers.md", "source_path": "characters/conversion_to_integers.md", "parent_names": ["Characters"]}}, {"Chapter": {"name": "Conversion from Integers", "content": "# Conversion from Integers\n\nAn `int` can represent more values than a `char`, so conversion from `int` to\n`char` requires the use of the cast operator `(char)`.\n\n```java\nint x = 120;\n\nchar xAsChar = (char) x;\n\nSystem.out.println(xAsChar);\n```\n\nThis conversion is narrowing, so information might be lost if the `int` value is too big or too small to fit into a `char`.\n\nThe initial value of a `char` can also be given by an integer literal if the integer literal represents a small enough letter.\n\n```java\nchar z = 122;\n\nSystem.out.println(z);\n```\n", "number": [8, 4], "sub_items": [], "path": "characters/conversion_from_integers.md", "source_path": "characters/conversion_from_integers.md", "parent_names": ["Characters"]}}, {"Chapter": {"name": "Unicode", "content": "# Unicode\n\nMost letters and symbols that are common in the English speaking world fit into\na single `char`, so pretending that a `char` is always \"a single\nletter or symbol\" is generally a good enough mental model.\n\nWhere this falls apart is with things like emoji (\ud83d\udc68\u200d\ud83c\udf73) which are generally considered to be one symbol, but\ncannot be represented in a single `char`.\n\n```java\nchar chef = '\ud83d\udc68\u200d\ud83c\udf73';\n```\n\n`char`s are actually \"utf-16 code units\". Many symbols require multiple \"code units\" to represent.\n\nFor a full explanation, refer to this old Computerphile video.\n\nIt describes \"utf-8\", which is 8 bits per \"code unit.\" Java's `char`\nuses 16 bits, but that is the only difference.\n\n\n", "number": [8, 5], "sub_items": [], "path": "characters/unicode.md", "source_path": "characters/unicode.md", "parent_names": ["Characters"]}}, {"Chapter": {"name": "Challenges", "content": "# Challenges\n\nRemember the rules for this are\n\n- Try to use only the information given up to this point in this book.\n- Try not to give up until you've given it a solid attempt\n\n## Challenge 1\n\nA lot of math problems ask you to find \\\\( x^2 \\\\). What is the value of the character `x` squared?\n\nTry to work it out on paper before running the program below.\n\n~IF toplevel_anonymous_class\n\n```java\nvoid main() {\n char x = 'x';\n\n System.out.println(x * x);\n}\n```\n\n~ELSE\n\n```java\npublic class Main {\n public static void main(String[] args) {\n char x = 'x';\n\n System.out.println(x * x);\n }\n}\n```\n\n~ENDIF\n\n## Challenge 2\n\nAlter the program below so that it will output `true` if the character declared at the top is a letter.\n\nMake use of the fact that the numeric values for `a` - `z` and `A` - `Z` are contiguous.\n\n~IF toplevel_anonymous_class\n\n```java\nvoid main() {\n char c = 'a';\n\n boolean isLetter = ???;\n\n System.out.println(isLetter);\n}\n```\n\n~ELSE\n\n```java\npublic class Main {\n public static void main(String[] args) {\n char c = 'a';\n\n boolean isLetter = ???;\n\n System.out.println(isLetter);\n }\n}\n```\n\n~ENDIF\n\n## Challenge 3\n\nHow many UTF-16 code units does it take to represent this emoji? `\ud83d\udc68\u200d\ud83c\udf73`.\n", "number": [8, 6], "sub_items": [], "path": "characters/challenges.md", "source_path": "characters/challenges.md", "parent_names": ["Characters"]}}], "path": "characters.md", "source_path": "characters.md", "parent_names": []}}, {"Chapter": {"name": "Strings", "content": "# Strings\n\nThe `String` data type is used to represent text.\n\n```java\nString shortStory = \"Everyone lived happily ever after, the end.\"\n```\n\nThe word \"string\" comes from the fact that text is just individual characters \"strung together\".\n\nAs a concrete example `j`, `o`, and `e` can be \"strung together\" into the \"string\"\n`joe`.\n", "number": [9], "sub_items": [{"Chapter": {"name": "String Literals", "content": "# String Literals\n\nIn order to write text in a program, you surround it with\ndouble quotes.\n\n```java\n\"Hello, World\"\n```\n\nThis is called a \"string literal.\" It has the same relationship to `String`\nthat an integer literal like `123` has to `int`.\n\n```java\n// Same as this \"integer literal\" is used to write a number\nint abc = 123;\n// A \"string literal\" is used to write text\nString name = \"penelope\";\n```\n", "number": [9, 1], "sub_items": [], "path": "strings/string_literals.md", "source_path": "strings/string_literals.md", "parent_names": ["Strings"]}}, {"Chapter": {"name": "Common Escape Sequences", "content": "# Common Escape Sequences\n\nInside of a string literal, there are some characters that cannot be written normally.\n\nAn easy example is double quotes. You can't write double quotes in the middle of\na string literal because Java will think the extra quote is the end of the `String`.\n\n```java\nString title = \"The \"Honorable\" Judge Judy\";\n```\n\nIn order to make it work, the `\"`s need to be \"escaped\" with a backslash.\n\n```java\nString title = \"The \\\"Honorable\\\" Judge Judy\";\n```\n\nSince the backslash is used to escape characters, it too needs to escaped\nin order to have it be in a `String`. So to encode `\u00af\\_(\u30c4)_/\u00af` into a String\nyou need to escape the first backslash.\n\n```java\n// The first backslash needs to be escaped. \u00af\\_(\u30c4)_/\u00af\nString shruggie = \"\u00af\\\\_(\u30c4)_/\u00af\";\n```\n\nAnd much the same as with `char`, you need to use `\\n` to write in a newline.\n\n```java\nString letter = \"To Whom It May Concern,\\n\\nI am writing this letter to complain.\";\n```\n", "number": [9, 2], "sub_items": [], "path": "strings/common_escape_sequences.md", "source_path": "strings/common_escape_sequences.md", "parent_names": ["Strings"]}}, {"Chapter": {"name": "The Empty String", "content": "# The Empty String\n\nThere is a special `String` which contains no characters at all.\n\n```java\n// There is nothing to say.\nString conversationWithDog = \"\";\n```\n\nYou write it just like any other string, just with nothing between the double quotes.\n\n```java\n\"\"\n```\n\nIt is different from a `String` that just contains spaces because to Java those \"space characters\"\nare just as much real characters as `a`, `b`, or `c`.\n\n```java\n// There is noteworthy silence.\nString conversationWithInlaws = \" \";\n```\n\nThis is one of those things that feels totally useless, but comes in handy pretty often.\n\n- Say you are writing a message to send to your friend. The messenger\n app can represent the state of the input box before you type anything with\n an empty `String`.\n- If you want to digitally record responses to legal paperwork, you might choose\n to represent skipped fields as empty `String`s.\n- Video Games where characters have assigned names can assign an empty `String`\n as the name of otherwise \"unnamed\" characters.\n- etc.\n", "number": [9, 3], "sub_items": [], "path": "strings/empty_string.md", "source_path": "strings/empty_string.md", "parent_names": ["Strings"]}}, {"Chapter": {"name": "Multiline String Literals", "content": "# Multiline Strings\n\nIf the text you want to store in a `String` has multiple lines, you can use\nthree quotation marks to represent it in code.\n\n```java\nString poem = \"\"\"\n I met a traveller from an antique land,\n Who said\u2014\u201cTwo vast and trunkless legs of stone\n Stand in the desert. . . . Near them, on the sand,\n Half sunk a shattered visage lies, whose frown,\n And wrinkled lip, and sneer of cold command,\n Tell that its sculptor well those passions read\n Which yet survive, stamped on these lifeless things,\n The hand that mocked them, and the heart that fed;\n And on the pedestal, these words appear:\n My name is Ozymandias, King of Kings;\n Look on my Works, ye Mighty, and despair!\n Nothing beside remains. Round the decay\n Of that colossal Wreck, boundless and bare\n The lone and level sands stretch far away.\n \"\"\";\n```\n\nInside of the this \"Multiline String Literal\" you don't need to escape quotation marks `\"`\nand you gain the ability to write newlines without having to use `\\n`.\n", "number": [9, 4], "sub_items": [], "path": "strings/multiline.md", "source_path": "strings/multiline.md", "parent_names": ["Strings"]}}, {"Chapter": {"name": "Concatenation", "content": "# Concatenation\n\nAny two strings can be concatenated by using the `+` operator.\n\n```java\nString he = \"he\";\nString llo = \"llo\";\n\nString hello = he + llo;\n\nSystem.out.println(hello);\n```\n\nThis will make a new `String` where the characters from the first one all appear followed by the characters in the second one.\n\nIf you try to concatenate a `String` to something that is not a `String`, like an `int` or a `double`,\nthen the result will be a new `String` with the characters from the \"string representation\" of that\nother thing.\n\n```java\nint numberOfApples = 5;\ndouble dollahs = 1.52;\n\nString message = \"I have \" + numberOfApples +\n \" apples and $\" + dollahs + \" in my pocket.\";\n\nSystem.out.println(message);\n```\n", "number": [9, 5], "sub_items": [], "path": "strings/concatenation.md", "source_path": "strings/concatenation.md", "parent_names": ["Strings"]}}, {"Chapter": {"name": "Equality", "content": "# Equality\n\nYou can check if two `String`s have the same contents by using `.equals`.\n\n```java\nString lyricOne = \"Green, Green, Dress\";\nString lyricTwo = \"Green, Green, Dress\";\n\nboolean areSameLyric = lyricOne.equals(lyricTwo);\nboolean isMyName = lyricOne.equals(\"Bop Bop\");\n\nSystem.out.println(areSameLyric);\nSystem.out.println(isMyName);\n```\n\nYou write one `String` on the left, `.equals`, and then the `String` you want to check it\nagainst inside of parentheses.\n\nTo see if strings have different contents, you need to use the not operator (`!`) on\nthe result of `.equals`.\n\n```java\nString bow = \"bow\";\nString wow = \"WOW\";\n\nboolean areNotSame = !bow.equals(wow);\n\nSystem.out.println(areNotSame);\n```\n", "number": [9, 6], "sub_items": [], "path": "strings/equality.md", "source_path": "strings/equality.md", "parent_names": ["Strings"]}}, {"Chapter": {"name": "Length", "content": "# Length\n\nThe number of `char`s which comprise a `String` can be accessed by using `.length()`.[^codepoints]\n\n```java\nString fruit = \"strawberry\";\nint numberOfChars = fruit.length();\n\n// strawberry is 10 characters long\nSystem.out.println(\n fruit + \" is \" numberOfChars + \" characters long\"\n);\n```\n\n[^codepoints]: This is different from the number of unicode codepoints.\n", "number": [9, 7], "sub_items": [], "path": "strings/length.md", "source_path": "strings/length.md", "parent_names": ["Strings"]}}, {"Chapter": {"name": "Access Individual Characters", "content": "# Access Individual Characters\n\nGiven a `String`, you can access the individual characters which\ncomprise it by using `.charAt`.\n\nThe first character can be accessed by putting `0` in the parentheses.\nThe second by using `1`, and so on.\n\n```java\nString spy = \"loid\";\n\nchar l = spy.charAt(0);\nSystem.out.println(l);\n\nchar o = spy.charAt(1);\nSystem.out.println(o);\n\nchar i = spy.charAt(2);\nSystem.out.println(i);\n\nchar d = spy.charAt(3);\nSystem.out.println(d);\n```\n\nWe call this number the \"index\" of the character.[^otherds]\n\nThe index of the character to access can come from a variable.\n\n```java\nString assassin = \"yor\";\nint indexOfR = 2;\n\nchar r = assassin.charAt(indexOfR);\nSystem.out.println(r);\n```\n\nIf you give a number equal to or greater than the length of the `String` or a number less than zero,\nyou will get an error.\n\n```java\nString student = \"anya\";\n// Crash!\nstudent.charAt(999);\n```\n\n```java\nString dog = \"bond\";\n// Crash!\ndog.charAt(-1);\n```\n\n[^otherds]:\n There will be more things\n which have their individual elements accessible by indexes. They will all generally start from 0 for the first element\n but there are rare exceptions.\n", "number": [9, 8], "sub_items": [], "path": "strings/access_individual_characters.md", "source_path": "strings/access_individual_characters.md", "parent_names": ["Strings"]}}, {"Chapter": {"name": "Challenges", "content": "# Challenges\n\nRemember the rules for this are\n\n- Try to use only the information given up to this point in this book.\n- Try not to give up until you've given it a solid attempt\n\n## Challenge 1\n\nWhat will this program output when run? Write down your guess and then try running it.\n\n~IF toplevel_anonymous_class\n\n```Java\nvoid main() {\n String first = \"1\";\n String second = \"2\";\n String result = first + second;\n\n System.out.println(result);\n}\n```\n\n~ELSE\n\n```Java\npublic class Main {\n public static void main(String[] args) {\n String first = \"1\";\n String second = \"2\";\n String result = first + second;\n\n System.out.println(result);\n }\n}\n```\n\n~ENDIF\n\n## Challenge 2\n\nWhat will this program output when run? Write down your guess and then try running it.\n\n~IF toplevel_anonymous_class\n\n```Java\nvoid main() {\n String first = \"1\";\n int second = 2;\n\n System.out.println(first + second);\n}\n```\n\n~ELSE\n\n```Java\npublic class Main {\n public static void main(String[] args) {\n String first = \"1\";\n int second = 2;\n\n System.out.println(first + second);\n }\n}\n```\n\n~ENDIF\n\n## Challenge 3\n\nWhat will this program output when run? Write down your guess and then try running it.\n\n~IF toplevel_anonymous_class\n\n```Java\nvoid main() {\n char first = 'a';\n String second = \"b\";\n String third = \"ab\";\n\n System.out.println((first + second).equals(second));\n}\n```\n\n~ELSE\n\n```Java\npublic class Main {\n public static void main(String[] args) {\n char first = 'a';\n String second = \"b\";\n String third = \"ab\";\n\n System.out.println((first + second).equals(second));\n }\n}\n```\n\n~ENDIF\n\n## Challenge 4\n\nMake it so this program will output `abc` by only changing one line and\nnot altering the `println` statement.\n\nBefore your change, why does it output `294`?\n\n~IF toplevel_anonymous_class\n\n```java\nvoid main() {\n char a = 'a';\n char b = 'b';\n char c = 'c';\n System.out.println(a + b + c);\n}\n```\n\n~ELSE\n\n```Java\npublic class Main {\n public static void main(String[] args) {\n char a = 'a';\n char b = 'b';\n char c = 'c';\n // Change above this line\n System.out.println(a + b + c);\n }\n}\n```\n\n~ENDIF\n\n## Challenge 5\n\nWithout adding any new `println`s,\nchange one line in this program so that it outputs `racecar`.\n\nTry to find two ways to do that.\n\n~IF toplevel_anonymous_class\n\n```java\nvoid main() {\n String racecar = \"racecar\";\n\n int diff = 1;\n\n int index = 6;\n\n System.out.print(racecar.charAt(index));\n index += diff;\n System.out.print(racecar.charAt(index));\n index += diff;\n System.out.print(racecar.charAt(index));\n index += diff;\n System.out.print(racecar.charAt(index));\n index += diff;\n System.out.print(racecar.charAt(index));\n index += diff;\n System.out.print(racecar.charAt(index));\n index += diff;\n System.out.println(racecar.charAt(index));\n}\n```\n\n~ELSE\n\n```Java\npublic class Main {\n public static void main(String[] args) {\n String racecar = \"racecar\";\n\n int diff = 1;\n\n int index = 6;\n\n System.out.print(racecar.charAt(index));\n index += diff;\n System.out.print(racecar.charAt(index));\n index += diff;\n System.out.print(racecar.charAt(index));\n index += diff;\n System.out.print(racecar.charAt(index));\n index += diff;\n System.out.print(racecar.charAt(index));\n index += diff;\n System.out.print(racecar.charAt(index));\n index += diff;\n System.out.println(racecar.charAt(index));\n }\n}\n```\n\n~ENDIF\n", "number": [9, 9], "sub_items": [], "path": "strings/challenges.md", "source_path": "strings/challenges.md", "parent_names": ["Strings"]}}], "path": "strings.md", "source_path": "strings.md", "parent_names": []}}, {"PartTitle": "Control Flow I"}, {"Chapter": {"name": "Branching Paths", "content": "# Branching Paths\n\nAll the code I have shown you so far has run from top to bottom. That is, it has followed a single \"path.\"\n\nNot all programs can follow a single path though.\n\nImagine trying to rent a car online. The first thing you might be asked is your age.\nThis is because most car rental companies do not want to rent to people under the age of 25.[^insurance].\n\nIf you enter an age that is less than 25, the program should immediately tell you that you cannot\nrent a car. If you enter an age that is greater than or equal to 25, the program should continue to prompt you\nfor more information.\n\nThere are multiple \"branching paths\" that the program might take.\n\n[^insurance]: For insurance reasons.\n", "number": [10], "sub_items": [{"Chapter": {"name": "If", "content": "# If\n\nThe way to represent a branching path in Java is by using an `if` statement.\n\n```java\nint age = 5; // \ud83d\udc76\nif (age < 25) {\n System.out.println(\"You are too young to rent a car!\");\n}\n```\n\nYou write the word `if` followed by an expression which evaluates to a `boolean` inside of `(` and `)`.\nThis expression is the \"condition\". Then you write some code inside\nof `{` and `}`.\n\n```java\nif (CONDITION) {\n \n}\n```\n\nWhen the condition evaluates to `true`, the code inside of the `{` and `}` will run.\nIf it evaluates to `false` that code will not run.\n\nIn this example the condition is `age < 25`. When `age` is less than 25 it will evaluate to `true`\nand you will be told that you cannot rent a car.\n\n```java\nint age = 80; // \ud83d\udc75\nif (age < 25) {\n System.out.println(\"You are too young to rent a car!\");\n}\n```\n\nIf this condition evaluates to `false`, then the code inside of `{` and `}`\nwill not run.\n", "number": [10, 1], "sub_items": [], "path": "branching_logic/if.md", "source_path": "branching_logic/if.md", "parent_names": ["Branching Paths"]}}, {"Chapter": {"name": "Else", "content": "# Else\n\nWhen you want to do one thing when a condition evaluates to `true`\nand another when that same condition evaluates to `false` you can use `else`.\n\n```java\nint age = 30; // \ud83d\ude4e\u200d\u2640\ufe0f\nif (age < 25) {\n System.out.println(\"You cannot rent a car!\");\n}\nelse {\n System.out.println(\"You might be able to rent a car.\");\n}\n```\n\nYou write the word `else` immediately after the `}` at the end of an `if` statement, then\nsome code inside of a new `{` and `}`.\n\n```java\nif (CONDITION) {\n \n}\nelse {\n \n}\n```\n\nWhen the condition evaluates to `false`, the code inside of `else`'s `{` and `}` will run.\n\n`else` cannot exist without a matching `if`, so this code does not work.\n\n```java\nelse {\n System.out.println(\"No if.\");\n}\n```\n", "number": [10, 2], "sub_items": [], "path": "branching_logic/else.md", "source_path": "branching_logic/else.md", "parent_names": ["Branching Paths"]}}, {"Chapter": {"name": "Nested Ifs", "content": "# Nested Ifs\n\nThe code inside of the `{` and `}` can be anything, including more `if` statments.\n\n```java\nint age = 5; // \ud83d\udc76\nif (age < 25) {\n System.out.println(\"You are too young to rent a car!\");\n if (age == 24) {\n System.out.println(\"(but it was close)\");\n }\n}\n```\n\nWhen an `if` is inside another `if` we say that it is \"nested\".\n\nIf you find yourself nesting more than a few `if`s that might be a sign that\nyou should reach out for help.\n\n```java\nif (...) {\n if (...) {\n if (...) {\n if (...) {\n // Seek professional help\n }\n }\n }\n}\n```\n", "number": [10, 3], "sub_items": [], "path": "branching_logic/nested_ifs.md", "source_path": "branching_logic/nested_ifs.md", "parent_names": ["Branching Paths"]}}, {"Chapter": {"name": "Else If", "content": "# Else If\n\nIf you have an `if` nested in an `else` branch, you can simplify that by using\n`else if`.\n\n```java\nboolean cool = true; // \ud83d\udd76\ufe0f\nint age = 30; // \ud83d\ude4e\u200d\u2640\ufe0f\nif (age < 25) {\n System.out.println(\"You cannot rent a car!\");\n}\nelse {\n if (!cool) {\n System.out.println(\"You failed the vibe check.\");\n }\n else {\n System.out.println(\"You are rad enough to rent a car.\");\n }\n}\n```\n\nSo the following will work the same as the code above.\n\n```java\nboolean cool = true; // \ud83d\udd76\ufe0f\nint age = 30; // \ud83d\ude4e\u200d\u2640\ufe0f\n\nif (age < 25) {\n System.out.println(\"You cannot rent a car!\");\n}\nelse if (!cool) {\n System.out.println(\"You failed the vibe check.\");\n}\nelse {\n System.out.println(\"You are rad enough to rent a car.\");\n}\n```\n\nYou can have as many `else if`s as you need. Each one will only run if all the previous conditions\nevaluate to `false`.\n\n```java\nboolean cool = true; // \ud83d\udd76\ufe0f\nint age = 100; // \ud83d\udc74\n\nif (age < 25) {\n System.out.println(\"You cannot rent a car!\");\n}\nelse if (!cool) {\n System.out.println(\"You failed the vibe check.\");\n}\nelse if (age > 99) {\n System.out.println(\"You are too old to safely drive a car!\");\n}\nelse if (age > 450) {\n System.out.println(\"There can only be one! \u2694\ufe0f\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc73\udb40\udc63\udb40\udc74\udb40\udc7f\");\n}\nelse {\n System.out.println(\"You are rad enough to rent a car.\");\n}\n```\n", "number": [10, 4], "sub_items": [], "path": "branching_logic/else_if.md", "source_path": "branching_logic/else_if.md", "parent_names": ["Branching Paths"]}}, {"Chapter": {"name": "Relation to Delayed Assignment", "content": "# Relation to Delayed Assignment\n\nDelayed assignment of variables becomes useful with `if` and `else`.\n\nSo long as Java can figure out that a variable will always be given an initial value\ninside of an `if` and `else`, you will be allowed to use that variable.\n\n```java\nint age = 22;\n\nString message;\nif (age > 25) {\n message = \"You might be able to rent a car\";\n}\nelse {\n message = \"You cannot rent a car!\";\n}\n\nSystem.out.println(message);\n```\n\nIf it will not always be given an initial value, then you will not be allowed to\nuse that variable.\n\n```java\nint age = 22;\n\nString message;\nif (age > 25) {\n message = \"You might be able to rent a car\";\n}\n\n// message is not always given an initial value\n// so you cannot use it.\nSystem.out.println(message);\n```\n", "number": [10, 5], "sub_items": [], "path": "branching_logic/relation_to_delayed_assignment.md", "source_path": "branching_logic/relation_to_delayed_assignment.md", "parent_names": ["Branching Paths"]}}, {"Chapter": {"name": "Conditional Operator", "content": "# Conditional Operator\n\nWhen the only operation being performed inside of an `if` and `else` pair\nis setting the initial value of a variable, you can use the \"conditional operator\"[^ternary]\nto perform that assignment instead.\n\n```java\nint age = 22;\n\nString message = age < 25\n ? \"You cannot rent a car!\"\n : \"You might be able to rent a car\";\n```\n\nYou write a condition followed by a `?`, a value to use when that condition evaluates to `true`, a `:`,\nand then a value to use when that condition evaluates to `false`.\n\n```java\nCONDITION ? WHEN_TRUE : WHEN_FALSE\n```\n\n[^ternary]:\n Some people will call this a ternary expression. Ternary meaning \"three things.\"\n Same idea as tres leches.\n", "number": [10, 6], "sub_items": [], "path": "branching_logic/conditional_operator.md", "source_path": "branching_logic/conditional_operator.md", "parent_names": ["Branching Paths"]}}, {"Chapter": {"name": "Boolean Expressions", "content": "# Boolean Expressions\n\nA common thing I've seen students do is set the initial value of some\n`boolean` variable based on some condition.\n\n```java\nint age = 22;\n\nboolean canRent;\nif (age > 25) {\n canRent = true;\n}\nelse {\n canRent = false;\n}\n\n// or\n// boolean canRent = age > 25 ? true : false;\n\nSystem.out.println(canRent);\n```\n\nThis is valid code, but very often can be made simpler if you remember that the condition\nitself already evaluates to a `boolean`. You can directly assign the variable to that value.\n\n```java\nint age = 22;\nboolean canRent = age > 25;\n\nSystem.out.println(canRent);\n```\n", "number": [10, 7], "sub_items": [], "path": "branching_logic/boolean_expressions.md", "source_path": "branching_logic/boolean_expressions.md", "parent_names": ["Branching Paths"]}}, {"Chapter": {"name": "Challenges", "content": "# Challenges\n\nRemember the rules for this are\n\n- Try to use only the information given up to this point in this book.\n- Try not to give up until you've given it a solid attempt\n\n## Challenge 1\n\nWrite code that will outputs `The number is even` if `x` is an even number.\n\n~IF toplevel_anonymous_class\n\n```java\nvoid main() {\n // Change this variable to different numbers\n // to test your code\n int x = 5;\n\n // < YOUR CODE HERE >\n}\n```\n\n~ELSE\n\n```java\npublic class Main {\n public static void main(String[] args) {\n // Change this variable to different numbers\n // to test your code\n int x = 5;\n\n // < YOUR CODE HERE >\n }\n}\n```\n\n~ENDIF\n\n## Challenge 2\n\nMake it so that your code from the previous problem will also output `The number is odd`\nif the number is odd.\n\n## Challenge 3\n\nWrite code that will output `allowed` if the the `password` variable is equal to\n`\"abc123\"` and `not allowed` if it isn't.\n\n~IF toplevel_anonymous_class\n\n```java\nvoid main() {\n // Change this variable to different strings\n // to test your code\n String password = \"apple\";\n\n // < YOUR CODE HERE >\n}\n```\n\n~ELSE\n\n```java\npublic class Main {\n public static void main(String[] args) {\n // Change this variable to different strings\n // to test your code\n String password = \"apple\";\n\n // < YOUR CODE HERE >\n }\n}\n```\n\n~ENDIF\n\n## Challenge 4\n\nWrite code that will assign the string `The number is {x} even` to `message` if `x` is an even number\nand `The number is {x} odd` if `x` is an even number.\n\nSo if `x` is 12 the string you should assign `The number 12 is even` to `message`.\n\n~IF toplevel_anonymous_class\n\n```java\nvoid main() {\n String message;\n\n // Change this variable to different numbers\n // to test your code\n int x = 5;\n\n // < YOUR CODE HERE >\n\n System.out.println(message);\n}\n```\n\n~ELSE\n\n```java\npublic class Main {\n public static void main(String[] args) {\n String message;\n\n // Change this variable to different numbers\n // to test your code\n int x = 5;\n\n // < YOUR CODE HERE >\n\n System.out.println(message);\n }\n}\n```\n\n~ENDIF\n", "number": [10, 8], "sub_items": [], "path": "branching_logic/challenges.md", "source_path": "branching_logic/challenges.md", "parent_names": ["Branching Paths"]}}], "path": "branching_paths.md", "source_path": "branching_paths.md", "parent_names": []}}, {"Chapter": {"name": "Loops", "content": "# Loops\n\n`if` and `else` let you write programs which can take branching paths,\nbut they will still run from the beginning to the end.\n\nNot all programs can just _end_ though.\nVideo games should draw their world at one second and do it again the next.\nIf you enter the wrong password on your phone, it should ask you for your password again.\n\nThis is what \"loops\" are for. You run code starting from some point and then\nloop back to that same point and run that code again.\n", "number": [11], "sub_items": [{"Chapter": {"name": "While", "content": "# While\n\nOne way to make a loop in code is to use `while`.\n\n```java\nint x = 5;\nwhile (x != 0) {\n System.out.println(x);\n x--;\n}\n```\n\nYou write `while` followed by a condition inside of `(` and `)` and some code inside of `{` and `}`.\n\n```java\nwhile (CONDITION) {\n \n}\n```\n\nIf the condition evaluates to `true` then the code inside of `{` and `}` will run.\nAfter that code runs, the condition will be evaluated again. If it still evaluates to\n`true` then the code `{` and `}` will run again.\n\nThis will continue until the code in the condition evaluates to `false`.\n\n```java\nint glassesOfMilk = 99;\nwhile (glassesOfMilk > 0) {\n System.out.println(\n glassesOfMilk + \" glasses of milk left\"\n );\n\n glassesOfMilk--;\n}\n```\n\nIf a loop is made with `while` we call it a \"while loop.\"[^tortoise]\n\n[^tortoise]: \"We called him Tortoise because he taught us.\" - Lewis Carroll\n", "number": [11, 1], "sub_items": [], "path": "loops/while.md", "source_path": "loops/while.md", "parent_names": ["Loops"]}}, {"Chapter": {"name": "Endless Loops", "content": "# Endless Loops\n\nIf a while loop will never end, we call that an endless loop.\n\nThis can happen if the condition is a constant like `while (true)`\n\n```java\nwhile (true) {\n System.out.println(\"This is the song that never ends\");\n}\n```\n\nOr if the variables tested in the condition are not updated inside of the loop.\n\n```java\n// x is never changed\nint x = 0;\nwhile (x != 1) {\n System.out.println(\"It goes on and on my friends\");\n}\n```\n\nMany games should never really \"finish\" so at the very start of that sort of program it is not uncommon\nto see a `while (true)`.\n", "number": [11, 2], "sub_items": [], "path": "loops/endless_loops.md", "source_path": "loops/endless_loops.md", "parent_names": ["Loops"]}}, {"Chapter": {"name": "Break", "content": "# Break\n\nWhile loops will usually stop running when the condition at the top evaluates\nto `false`.\n\nThis can be bypassed by using the `break` statement.\n\n```java\nint x = 5;\nwhile (x > 0) {\n if (x == 2) {\n break;\n }\n x--;\n}\n\nSystem.out.println(\n \"Final value of x is \" + x\n);\n```\n\nIf a `break` is reached, the code in the loop stops running immediately.\nThe condition of the loop is not checked again.\n\nThis can be useful in a variety of situations, but notably it is the only way to exit\nfrom an otherwise endless loop.\n\n```java\nwhile (true) {\n System.out.println(\n \"The people started singing it not knowing what it was\"\n );\n\n // Will immediately leave the loop\n break;\n}\n```\n", "number": [11, 3], "sub_items": [], "path": "loops/break.md", "source_path": "loops/break.md", "parent_names": ["Loops"]}}, {"Chapter": {"name": "Continue", "content": "# Continue\n\nUnless there is a `break`, while loops will usually run all the code in their body from top to bottom.\n\nThe only other situation this will not happen is if a `continue` statement is reached.\n\n```java\n// Will output a message for every number except 4\nint x = 5;\nwhile (x > 0) {\n if (x == 4) {\n continue;\n }\n System.out.println(x + \" is a good number\");\n x--;\n}\n```\n\nIf a `continue` is reached the code in the loop stops running immediately but, unlike `break`,\nthe condition of the loop _is_ checked again. If it still evaluates to `true` then the code\nin the loop will run again.\n", "number": [11, 4], "sub_items": [], "path": "loops/continue.md", "source_path": "loops/continue.md", "parent_names": ["Loops"]}}, {"Chapter": {"name": "Unreachable Code", "content": "# Unreachable Code\n\nIf you write some code directly after a `break` or `continue`\nthat code will be \"unreachable.\"\n\nJava knows this and so won't let any code like that run.\n\n```java\n// This will not work\nwhile (true) {\n continue;\n\n System.out.println(\"this is unreachable\");\n}\n```\n", "number": [11, 5], "sub_items": [], "path": "loops/unreachable_code.md", "source_path": "loops/unreachable_code.md", "parent_names": ["Loops"]}}, {"Chapter": {"name": "Do While", "content": "# Do\n\nOne variation on a `while` loop is a \"do-while loop.\"\n\n```java\nint x = 0;\ndo {\n System.out.println(x);\n x++\n} while(x < 5);\n```\n\nYou write `do`, some code inside of `{` and `}`, and then `while`, a condition inside of\n`(` and `)`, and finally a semicolon.\n\n```java\ndo {\n \n} while (CONDITION);\n```\n\nIn most situations it works exactly the same as a regular while loop. The only difference\nis that the first time the loop is reached the condition for the loop is not checked.\n\n```java\nint x = 0;\ndo {\n System.out.println(\"this will run\");\n} while (x != 0)\n\nwhile (x != 0) {\n System.out.println(\"this will not run\");\n}\n```\n\nOne way to remember the difference is that in a \"do-while loop\" you always \"do the thing\"\nat least once.\n", "number": [11, 6], "sub_items": [], "path": "loops/do_while.md", "source_path": "loops/do_while.md", "parent_names": ["Loops"]}}, {"Chapter": {"name": "Nested Loops", "content": "# Nested Loops\n\nJust like with `if`, The code inside of the `{` and `}` can be anything, including more loops.\n\n```java\nint x = 5;\nint y = 3;\n\nwhile (x != 0) {\n while (y != 0) {\n System.out.println(\n \"x is \" + x\n );\n System.out.println(\n \"y is \" + y\n );\n\n x--;\n y--;\n }\n}\n```\n\nIf you are inside such a \"nested loop\", `continue` and `break` apply to the\n\"closest\" loop.\n\nThat is, if a `continue` or a `break` were to appear here\n\n```java\nwhile (x != 0) {\n while (y != 0) {\n if (y == 2) {\n break;\n }\n\n System.out.println(\n \"x is \" + x\n );\n System.out.println(\n \"y is \" + y\n );\n\n x--;\n y--;\n }\n}\n```\n\nThen the `y != 0` loop will be broken out of, not the `x != 0` one.\nAnd if a `continue` or a `break` were to appear here\n\n```java\nwhile (x != 0) {\n if (x == 2) {\n break;\n }\n while (y != 0) {\n\n\n System.out.println(\n \"x is \" + x\n );\n System.out.println(\n \"y is \" + y\n );\n\n x--;\n y--;\n }\n}\n```\n\nThen the `x != 0` loop would be the \"target.\"\n", "number": [11, 7], "sub_items": [], "path": "loops/nested_loops.md", "source_path": "loops/nested_loops.md", "parent_names": ["Loops"]}}, {"Chapter": {"name": "Labeled Break", "content": "# Labeled Break\n\nIf you want to break out of a nested loop from one of the inner loops, you can use a \"labeled break.\"\n\n```java\nouterLoop:\nwhile (true) {\n while (true) {\n break outerLoop;\n }\n}\n```\n\nTo do this, before your outer while or do-while loop you need to add a \"label\" followed by a `:`.\nA label is an arbitrary name just like a variable's name.\n\n```java\n