From 23932367fe87ccc2b1277225de242c0518408d85 Mon Sep 17 00:00:00 2001 From: Ethan McCue Date: Mon, 8 May 2023 11:08:47 -0400 Subject: [PATCH 01/69] more sections --- src/SUMMARY.md | 58 +++++++++++++------ src/arguments/aliasing.md | 1 + src/arguments/challenges.md | 1 + src/arguments/declaration.md | 17 +++++- src/arguments/final_arguments.md | 1 + src/arguments/inferred_types.md | 27 +++++++++ src/arguments/invocation_with_arguments.md | 1 + src/arguments/overloading.md | 1 + src/arguments/reassignment.md | 1 + src/arrays/challenges.md | 7 +++ src/arrays_ii.md | 1 + src/arrays_ii/default_values.md | 1 + src/boxed_primitives.md | 1 + .../arrays_of_boxed_primitives.md | 1 + src/boxed_primitives/boolean.md | 1 + src/boxed_primitives/boxing_conversion.md | 1 + src/boxed_primitives/character.md | 1 + src/boxed_primitives/double.md | 1 + src/boxed_primitives/integer.md | 1 + src/boxed_primitives/primitive_types.md | 7 +++ src/boxed_primitives/unboxing_conversion.md | 1 + src/classes.md | 16 +++++ src/classes/field_access | 1 + src/identity_types.md | 1 + .../comparison_with_equalsequals.md | 1 + src/methods/challenges.md | 8 +++ src/primitive_types.md | 1 + src/retu | 1 + src/return_values/impure_functions.md | 1 + 29 files changed, 142 insertions(+), 20 deletions(-) create mode 100644 src/arguments/aliasing.md create mode 100644 src/arguments/challenges.md create mode 100644 src/arguments/final_arguments.md create mode 100644 src/arguments/inferred_types.md create mode 100644 src/arguments/invocation_with_arguments.md create mode 100644 src/arguments/overloading.md create mode 100644 src/arguments/reassignment.md create mode 100644 src/arrays_ii.md create mode 100644 src/arrays_ii/default_values.md create mode 100644 src/boxed_primitives.md create mode 100644 src/boxed_primitives/arrays_of_boxed_primitives.md create mode 100644 src/boxed_primitives/boolean.md create mode 100644 src/boxed_primitives/boxing_conversion.md create mode 100644 src/boxed_primitives/character.md create mode 100644 src/boxed_primitives/double.md create mode 100644 src/boxed_primitives/integer.md create mode 100644 src/boxed_primitives/primitive_types.md create mode 100644 src/boxed_primitives/unboxing_conversion.md create mode 100644 src/classes/field_access create mode 100644 src/identity_types.md create mode 100644 src/identity_types/comparison_with_equalsequals.md create mode 100644 src/methods/challenges.md create mode 100644 src/primitive_types.md create mode 100644 src/retu create mode 100644 src/return_values/impure_functions.md diff --git a/src/SUMMARY.md b/src/SUMMARY.md index 3fec735..e363ebc 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -167,16 +167,53 @@ - [Return](./methods/return.md) - [Unreachable Statements](./methods/unreachable_statements.md) - [main](./methods/main.md) + - [Challenges](./methods/challenges.md) - [Arguments](./arguments.md) - [Declaration](./arguments/declaration.md) + - [Reassignment](./arguments/reassignment.md) + - [Aliasing](./arguments/aliasing.md) + - [Final Arguments](./arguments/final_arguments.md) + - [Invocation with Arguments](./arguments/invocation_with_arguments.md) + - [Overloading](./arguments/overloading.md) + - [Inferred Types](./arguments/inferred_types.md) + - [Challenges](./arguments/challenges.md) - [Return Values](./return_values.md) - [void](./return_values/void.md) - [Conversion](./return_values/conversion.md) - [Pure Functions](./return_values/pure_functions.md) + - [Impure Functions](./return_values/impure_functions.md) + + +# Data Types III +- [Identity Types](./identity_types.md) + - [Comparison with ==](./identity_types/comparison_with_equalsequals.md) +- [Primitive Types](./primitive_types.md) +- [null](./null.md) + - [Checking for null](./null/checking_for_null.md) + - [Field Access](./null/field_access.md) + - [Instance Methods](./null/instance_methods.md) +- [Boxed Primitives](./boxed_primitives.md) + - [Primitive Types](./boxed_primitives/primitive_types.md) + - [Integer](./boxed_primitives/integer.md) + - [Double](./boxed_primitives/double.md) + - [Character](./boxed_primitives/character.md) + - [Boolean](./boxed_primitives/boolean.md) + - [Unboxing Conversion](./boxed_primitives/unboxing_conversion.md) + - [Boxing Conversion](./boxed_primitives/boxing_conversion.md) + - [Arrays of Boxed Primitives](./boxed_primitives/arrays_of_boxed_primitives.md) + - [Challenges](./arguments/challenges.md) +- [Arrays II](./arrays_ii.md) + - [Default Values](./arrays_ii/default_values.md) + - [Populate Array]() + + + +# Code Structure II - [Classes](./classes.md) - [Class Declaration](./classes/class_declaration.md) - [Naming Classes](./classes/naming_classes.md) - [Field Declaration](./classes/field_declaration.md) + - [Field Access](./classes/field_access) - [Naming Fields](./classes/naming_fields.md) - [new](./classes/new.md) - [Zero Values](./classes/zero_values.md) @@ -196,29 +233,12 @@ - [Aliasing](./instance_methods/aliasing.md) - [Derived Values](./instance_methods/derived_values.md) -# Data Types III - -- [null](./null.md) - - [Checking for null](./null/checking_for_null.md) - - [Field Access](./null/field_access.md) - - [Instance Methods](./null/instance_methods.md) - -- [Arrays II]() - - [Default Values]() - - [Populate Array]() -- [Boxed Primitives]() - - [Boolean]() - - [Character]() - - [Integer]() - - [Double]() - -- [Example: "Growable" Array]() - -# Code Structure II - [Documentation]() - [Documentation Comments]() - [Testing]() + +- [Example: "Growable" Array]() # User Defined Types - [Primitive Classes](./classes/primitive_classes.md) diff --git a/src/arguments/aliasing.md b/src/arguments/aliasing.md new file mode 100644 index 0000000..81497a6 --- /dev/null +++ b/src/arguments/aliasing.md @@ -0,0 +1 @@ +# Aliasing diff --git a/src/arguments/challenges.md b/src/arguments/challenges.md new file mode 100644 index 0000000..9358534 --- /dev/null +++ b/src/arguments/challenges.md @@ -0,0 +1 @@ +# Challenges diff --git a/src/arguments/declaration.md b/src/arguments/declaration.md index 5ec05ee..5b0e723 100644 --- a/src/arguments/declaration.md +++ b/src/arguments/declaration.md @@ -10,4 +10,19 @@ Each argument declaration looks the same as a variable declaration and has both // has a type of "String". void eat(String food) { System.out.println("I ate " + food); -} \ No newline at end of file +} + +// This declares two arguments +// "to", which is a String and +// "age", which is an int. +void happyBirthday(String to, int age) { + System.out.println( + "Happy " + age + "th birthday " + to + "!" + ); +} + +void main() { + happyBirthday("Charlotte", 24); + eat("Cake"); +} +``` \ No newline at end of file diff --git a/src/arguments/final_arguments.md b/src/arguments/final_arguments.md new file mode 100644 index 0000000..9408f76 --- /dev/null +++ b/src/arguments/final_arguments.md @@ -0,0 +1 @@ +# Final Arguments diff --git a/src/arguments/inferred_types.md b/src/arguments/inferred_types.md new file mode 100644 index 0000000..ed003ac --- /dev/null +++ b/src/arguments/inferred_types.md @@ -0,0 +1,27 @@ +# Inferred Types + +With variable declarations, you can use `var` to let Java figure out the type +of the variable. + +```java +var name = "Jupiter"; +``` + +This is *not* allowed with argument declarations. + +```java +// You aren't allowed to use var for arguments! +void makeHorchata(var milkFatPercent) { + // ... +} +``` + +You must always explicitly write out the types of arguments. + +```java +void makeHorchata(double milkFatPercent) { + System.out.println( + "Making a horchata with " + milkFatPercent + "% milk." + ); +} +``` \ No newline at end of file diff --git a/src/arguments/invocation_with_arguments.md b/src/arguments/invocation_with_arguments.md new file mode 100644 index 0000000..c56a751 --- /dev/null +++ b/src/arguments/invocation_with_arguments.md @@ -0,0 +1 @@ +# Invocation with Arguments diff --git a/src/arguments/overloading.md b/src/arguments/overloading.md new file mode 100644 index 0000000..35bfafe --- /dev/null +++ b/src/arguments/overloading.md @@ -0,0 +1 @@ +# Overloading diff --git a/src/arguments/reassignment.md b/src/arguments/reassignment.md new file mode 100644 index 0000000..f5103a6 --- /dev/null +++ b/src/arguments/reassignment.md @@ -0,0 +1 @@ +# Reassignment diff --git a/src/arrays/challenges.md b/src/arrays/challenges.md index 9358534..b983d03 100644 --- a/src/arrays/challenges.md +++ b/src/arrays/challenges.md @@ -1 +1,8 @@ # Challenges + +Remember the rules for this are + +* Try to use only the information given up to this point in this book. +* Try not to give up until you've given it a solid attempt + +## Challenge 1 diff --git a/src/arrays_ii.md b/src/arrays_ii.md new file mode 100644 index 0000000..564d2de --- /dev/null +++ b/src/arrays_ii.md @@ -0,0 +1 @@ +# Arrays II diff --git a/src/arrays_ii/default_values.md b/src/arrays_ii/default_values.md new file mode 100644 index 0000000..0541532 --- /dev/null +++ b/src/arrays_ii/default_values.md @@ -0,0 +1 @@ +# Default Values diff --git a/src/boxed_primitives.md b/src/boxed_primitives.md new file mode 100644 index 0000000..b5588f5 --- /dev/null +++ b/src/boxed_primitives.md @@ -0,0 +1 @@ +# Boxed Primitives diff --git a/src/boxed_primitives/arrays_of_boxed_primitives.md b/src/boxed_primitives/arrays_of_boxed_primitives.md new file mode 100644 index 0000000..19f0099 --- /dev/null +++ b/src/boxed_primitives/arrays_of_boxed_primitives.md @@ -0,0 +1 @@ +# Arrays of Boxed Primitives diff --git a/src/boxed_primitives/boolean.md b/src/boxed_primitives/boolean.md new file mode 100644 index 0000000..d1a73fc --- /dev/null +++ b/src/boxed_primitives/boolean.md @@ -0,0 +1 @@ +# Boolean diff --git a/src/boxed_primitives/boxing_conversion.md b/src/boxed_primitives/boxing_conversion.md new file mode 100644 index 0000000..6c5fae9 --- /dev/null +++ b/src/boxed_primitives/boxing_conversion.md @@ -0,0 +1 @@ +# Boxing Conversion diff --git a/src/boxed_primitives/character.md b/src/boxed_primitives/character.md new file mode 100644 index 0000000..1a2a6bd --- /dev/null +++ b/src/boxed_primitives/character.md @@ -0,0 +1 @@ +# Character diff --git a/src/boxed_primitives/double.md b/src/boxed_primitives/double.md new file mode 100644 index 0000000..918bffd --- /dev/null +++ b/src/boxed_primitives/double.md @@ -0,0 +1 @@ +# Double diff --git a/src/boxed_primitives/integer.md b/src/boxed_primitives/integer.md new file mode 100644 index 0000000..52361c8 --- /dev/null +++ b/src/boxed_primitives/integer.md @@ -0,0 +1 @@ +# Integer diff --git a/src/boxed_primitives/primitive_types.md b/src/boxed_primitives/primitive_types.md new file mode 100644 index 0000000..905d194 --- /dev/null +++ b/src/boxed_primitives/primitive_types.md @@ -0,0 +1,7 @@ +# Primitives + +`int`, `double`, `char`, and `bool` are classified as "primitive types. + +1. Using `==`will tell you + + and types like `String` or `int[]` are diff --git a/src/boxed_primitives/unboxing_conversion.md b/src/boxed_primitives/unboxing_conversion.md new file mode 100644 index 0000000..851b558 --- /dev/null +++ b/src/boxed_primitives/unboxing_conversion.md @@ -0,0 +1 @@ +# Unboxing Conversion diff --git a/src/classes.md b/src/classes.md index 60ce908..89d4670 100644 --- a/src/classes.md +++ b/src/classes.md @@ -1,5 +1,21 @@ # Classes +Up until now all the data types you have used - `int`, `String`, etc. - +came with Java. This works for awhile, but eventually you will want or need to define your own types. + +The way to do this is with a "class." + +```java +class Person { + +} +``` + +Every +A class can be thought of as a "blueprint" for making an +to represent things in your programs. + + Methods can only have one return value. This means that if you wanted to make a method that returned two values, such as the location of buried treasure, you would have trouble. diff --git a/src/classes/field_access b/src/classes/field_access new file mode 100644 index 0000000..87c6259 --- /dev/null +++ b/src/classes/field_access @@ -0,0 +1 @@ +# Field Access diff --git a/src/identity_types.md b/src/identity_types.md new file mode 100644 index 0000000..39e2c2a --- /dev/null +++ b/src/identity_types.md @@ -0,0 +1 @@ +# Identity Types diff --git a/src/identity_types/comparison_with_equalsequals.md b/src/identity_types/comparison_with_equalsequals.md new file mode 100644 index 0000000..3ad9d98 --- /dev/null +++ b/src/identity_types/comparison_with_equalsequals.md @@ -0,0 +1 @@ +# Comparison with == diff --git a/src/methods/challenges.md b/src/methods/challenges.md new file mode 100644 index 0000000..b159a19 --- /dev/null +++ b/src/methods/challenges.md @@ -0,0 +1,8 @@ +# Challenges + +Remember the rules for this are + +* Try to use only the information given up to this point in this book. +* Try not to give up until you've given it a solid attempt + +## \ No newline at end of file diff --git a/src/primitive_types.md b/src/primitive_types.md new file mode 100644 index 0000000..ae84efe --- /dev/null +++ b/src/primitive_types.md @@ -0,0 +1 @@ +# Primitive Types diff --git a/src/retu b/src/retu new file mode 100644 index 0000000..8534eb2 --- /dev/null +++ b/src/retu @@ -0,0 +1 @@ +# Impure Functions diff --git a/src/return_values/impure_functions.md b/src/return_values/impure_functions.md new file mode 100644 index 0000000..8534eb2 --- /dev/null +++ b/src/return_values/impure_functions.md @@ -0,0 +1 @@ +# Impure Functions From 25924c104cccdd42cef022d71e6d2c6a10c1c7dc Mon Sep 17 00:00:00 2001 From: Ethan McCue Date: Mon, 8 May 2023 11:16:10 -0400 Subject: [PATCH 02/69] First feedback round --- src/first_steps/comments.md | 4 ++++ src/prelude/lies.md | 4 ++-- src/prelude/toy_problems.md | 3 +-- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/first_steps/comments.md b/src/first_steps/comments.md index c5b0731..63ff229 100644 --- a/src/first_steps/comments.md +++ b/src/first_steps/comments.md @@ -4,6 +4,8 @@ At various points, I am going to leave "comments" in the code. Comments are part are solely there for a human to be able to read as an explanation and can be written in regular words. +## In-line commenting + ~IF toplevel_anonymous_class ```java @@ -58,6 +60,8 @@ public class Main { You might want to do that at various points where you want to see what happens if you "turn off" parts of the code. +## Multi-line commenting + If you put `/*` in the code then everything up until the next `*/` will be treated as a comment. The distinction here is that this style of comment can span multiple lines. diff --git a/src/prelude/lies.md b/src/prelude/lies.md index afcf171..7641fae 100644 --- a/src/prelude/lies.md +++ b/src/prelude/lies.md @@ -7,11 +7,11 @@ If there are five ways to do something, I might pretend that there is only one way to do it until I give you enough context so that I can talk about the other four. -This can be particuarly annoying if you are in a course that is teaching things +This can be particularly annoying if you are in a course that is teaching things in a different order or if you feel rushed to just get some project done. I get that. I just ask that you trust me and go in the sequence I am laying out. I am honestly trying to make it so that you end with a stronger understanding than you would have otherwise. -If I fail, there is the question mark in the top right of every page. +There is the question mark in the top right of every page. diff --git a/src/prelude/toy_problems.md b/src/prelude/toy_problems.md index b3384d2..e19155b 100644 --- a/src/prelude/toy_problems.md +++ b/src/prelude/toy_problems.md @@ -5,5 +5,4 @@ As you go through this book there will be a lot of what can be considered "toy p That is, you will be shown or asked to write programs that have no obvious real world use. They will be similar in spirit to math problems like "if you have 8 apples and I take 3, how many apples do you have left?" -The intent is not for these to be annoying, although I am sure they will be. I just don't know any other way to help you -build an understanding of mechanics. +The intent is not for these to be annoying, although I am sure they will be. The intent is for these problems to help you build an understanding of mechanics and structure. From 850323346f49efb2342b952b479497020e51ed9a Mon Sep 17 00:00:00 2001 From: Ethan McCue Date: Mon, 8 May 2023 11:19:47 -0400 Subject: [PATCH 03/69] Update prelude.md --- src/prelude.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/prelude.md b/src/prelude.md index 43af524..3c8546d 100644 --- a/src/prelude.md +++ b/src/prelude.md @@ -15,6 +15,6 @@ there will also be challenges. I want you to at least attempt all of them before This book is written specifically for those folks that feel like giving up, like they are too stupid to get it, or like they didn't understand a damn thing their professor has said for the last three months. -I see you. You are not stupid. This is not your fault, it is theirs.[^probably] +I see you. You are not stupid. This is not your fault.[^probably] [^probably]: probably. From 914cd8266ec12439d5bdddfb035d3d26de2606fc Mon Sep 17 00:00:00 2001 From: Ethan McCue Date: Sat, 13 May 2023 14:08:14 -0400 Subject: [PATCH 04/69] ... --- features.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/features.java b/features.java index f3fb5e4..921c5d9 100755 --- a/features.java +++ b/features.java @@ -29,7 +29,7 @@ def preprocess_content(context, content): continue else: if options.get("simple_io", False) and options.get("toplevel_anonymous_class", False): - newContent.append(line.replace("System.out.println", "println").replace("System.out.print", "print")) + newContent.append(line.replace("System.out.println", "printLine").replace("System.out.print", "print")) else: newContent.append(line) From ff8df0dd0b7fc33ef04b575d211b7e2b6915d574 Mon Sep 17 00:00:00 2001 From: Ethan McCue Date: Fri, 9 Jun 2023 17:26:47 -0400 Subject: [PATCH 05/69] Spelling fix Co-Authored-By: Firas Regaieg <37019463+firasrg@users.noreply.github.com> --- src/getting_started.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/getting_started.md b/src/getting_started.md index c193ec0..8eb91d9 100644 --- a/src/getting_started.md +++ b/src/getting_started.md @@ -2,7 +2,7 @@ There are a lot of ways to "get set up" to run Java code. -For the purposes of this book, I am going to reccomend that you +For the purposes of this book, I am going to recommend that you start with [replit.com](https://replit.com). It requires an internet connection and you will have to make an account, but From 9c2678a6359f6b0808ddcd42e184601d6ae6d646 Mon Sep 17 00:00:00 2001 From: Ethan McCue Date: Sat, 17 Jun 2023 11:53:54 -0400 Subject: [PATCH 06/69] Arguments chapter --- book.toml | 9 ++++-- src/SUMMARY.md | 5 +-- src/arguments.md | 3 -- src/arguments/aliasing.md | 27 ++++++++++++++++ src/arguments/declaration.md | 7 +--- src/arguments/final_arguments.md | 36 +++++++++++++++++++++ src/arguments/invocation_with_arguments.md | 30 ++++++++++++++++++ src/arguments/overloading.md | 37 ++++++++++++++++++++++ src/arguments/reassignment.md | 34 ++++++++++++++++++++ src/classes/user_defined_types.md | 3 ++ src/return_values/conversion.md | 2 +- 11 files changed, 178 insertions(+), 15 deletions(-) create mode 100644 src/classes/user_defined_types.md diff --git a/book.toml b/book.toml index 13693d4..5903260 100644 --- a/book.toml +++ b/book.toml @@ -18,8 +18,11 @@ level = 0 # the depth to start folding command = "python3 features.java" # Going to start writing the rest of the book # Assuming this is true -toplevel_anonymous_class = true +toplevel_anonymous_class = false # Not ready -simple_io = true +simple_io = false # Turn on when Java 21 released -java_21 = false \ No newline at end of file +java_21 = false + +[output.html.playground] +editable = true \ No newline at end of file diff --git a/src/SUMMARY.md b/src/SUMMARY.md index e363ebc..8785e74 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -170,10 +170,10 @@ - [Challenges](./methods/challenges.md) - [Arguments](./arguments.md) - [Declaration](./arguments/declaration.md) + - [Invocation with Arguments](./arguments/invocation_with_arguments.md) - [Reassignment](./arguments/reassignment.md) - - [Aliasing](./arguments/aliasing.md) - [Final Arguments](./arguments/final_arguments.md) - - [Invocation with Arguments](./arguments/invocation_with_arguments.md) + - [Aliasing](./arguments/aliasing.md) - [Overloading](./arguments/overloading.md) - [Inferred Types](./arguments/inferred_types.md) - [Challenges](./arguments/challenges.md) @@ -211,6 +211,7 @@ # Code Structure II - [Classes](./classes.md) - [Class Declaration](./classes/class_declaration.md) + - [User Defined Types](./classes/user_defined_types.md) - [Naming Classes](./classes/naming_classes.md) - [Field Declaration](./classes/field_declaration.md) - [Field Access](./classes/field_access) diff --git a/src/arguments.md b/src/arguments.md index 64eaf15..026bd52 100644 --- a/src/arguments.md +++ b/src/arguments.md @@ -3,9 +3,6 @@ If methods always had to do the same thing each time they were run, they wouldn't be that useful. The way to customize what happens when a method is called is to have them take "arguments." -Arguments let the caller of the method change what happens when a method runs. -As part of a method declaration, you can include a comma separated list of "arguments" -to that method. These arguments let the caller of the method change what happens when a method runs. ```java void sayHello(String name) { diff --git a/src/arguments/aliasing.md b/src/arguments/aliasing.md index 81497a6..7ed4e6c 100644 --- a/src/arguments/aliasing.md +++ b/src/arguments/aliasing.md @@ -1 +1,28 @@ # Aliasing + +Because arguments work like variables, if you pass something +like an array as an argument the array referenced by the argument will be the exact same as the array referenced by the variable given to the method. + +```java +void incrementFirst(int[] numbers) { + numbers[0] = numbers[0] + 1; +} + +void main() { + int nums = new int[] { 8 }; + + // The first number is 8 + System.out.println( + "The first number is " + nums[0] + ); + + incrementFirst(nums); + + // Now it is 9 + System.out.println( + "Now it is " + nums[0] + ); +} +``` + +The argument aliases the value passed to the method. \ No newline at end of file diff --git a/src/arguments/declaration.md b/src/arguments/declaration.md index 5b0e723..3a4d7de 100644 --- a/src/arguments/declaration.md +++ b/src/arguments/declaration.md @@ -1,6 +1,6 @@ # Declaration -To declare a method take an argument, instead of putting `()` after the method name +To declare a method which takes arguments, instead of putting `()` after the method name you need to put a comma separated list of argument declarations. Each argument declaration looks the same as a variable declaration and has both a type and a name. @@ -20,9 +20,4 @@ void happyBirthday(String to, int age) { "Happy " + age + "th birthday " + to + "!" ); } - -void main() { - happyBirthday("Charlotte", 24); - eat("Cake"); -} ``` \ No newline at end of file diff --git a/src/arguments/final_arguments.md b/src/arguments/final_arguments.md index 9408f76..beb4060 100644 --- a/src/arguments/final_arguments.md +++ b/src/arguments/final_arguments.md @@ -1 +1,37 @@ # Final Arguments + +Just like normal variable declarations, arguments can be marked +`final`. This makes it so that they cannot be reassigned. + +```java +void eat(final String food) { + System.out.println("I ate " + food); +} + +void main() { + eat("Welsh Rarebit"); +} +``` + +If you try to reassign a final argument, Java will not accept your program. + + +```java +void eat(final String food) { + System.out.println("I ate " + food); + // Will not work + food = "toast"; + System.out.println(food); +} + +void main() { + eat("Welsh Rarebit"); +} +``` + +This has the same use as regular final variables. If there are lots of lines +of code where a variable might be reassigned, it can be useful to not have +to read all that code to know that it does happen. + +Generally though, adding final to arguments make it harder to read the code, simply +because of visual noise. \ No newline at end of file diff --git a/src/arguments/invocation_with_arguments.md b/src/arguments/invocation_with_arguments.md index c56a751..7374307 100644 --- a/src/arguments/invocation_with_arguments.md +++ b/src/arguments/invocation_with_arguments.md @@ -1 +1,31 @@ # Invocation with Arguments + +To invoke a method which takes arguments you need to, instead of writing +`()` after the method name, write `(` followed by a comma separated list +of literals or variable names ending with `)`. + +```java +void eat(String food) { + System.out.println("I ate " + food); +} + +void happyBirthday(String to, int age) { + System.out.println( + "Happy " + age + "th birthday " + to + "!" + ); +} + +void main() { + // This calls the 'eat' method with the String "cake" + // as an argument. + eat("Cake"); + + // You can also call methods using values stored in + // variables. + String veggie = "carrot"; + eat(veggie); + + // For more than one argument, you separate them with commas + happyBirthday("Charlotte", 24); +} +``` \ No newline at end of file diff --git a/src/arguments/overloading.md b/src/arguments/overloading.md index 35bfafe..1a2b835 100644 --- a/src/arguments/overloading.md +++ b/src/arguments/overloading.md @@ -1 +1,38 @@ # Overloading + +Multiple methods can be declared that have the same name. +This is allowed so long as each method takes different types +or different numbers of arguments. + +```java +void doThing(int x) { + System.out.println(x); +} + +void doThing(String name) { + System.out.println("Hello " + name); +} + +void doThing(int x, int y) { + System.out.println(x + y); +} +``` + +When you call the method, Java will know what code to run +because it knows the types of and number of arguments +you are passing. + +```java +void main() { + // Java can figure out what to do + doThing(1); + doThing("abc"); + doThing(1, 2); +} +``` + +When there are multiple methods that have the same name but take different arguments, +those methods are considered "overloads" of eachother[^overload] + +[^overload]: "Overloading" in this context means when one word has more than +one possible meaning depending on how it is used. Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo. \ No newline at end of file diff --git a/src/arguments/reassignment.md b/src/arguments/reassignment.md index f5103a6..06be8a2 100644 --- a/src/arguments/reassignment.md +++ b/src/arguments/reassignment.md @@ -1 +1,35 @@ # Reassignment + +Inside of a method, arguments work the same as normal variable declarations. +This means that their value can be reassigned +within the method body; + +```java +void eat(String food) { + System.out.println("I ate " + food); + food = "nothing"; + System.out.println("Now I have " + food) +} + +void main() { + eat("Cake"); +} +``` + +Reassigning an argument's value will not affect the value assigned to +any variables passed to the method by the caller. + +```java +void eat(String food) { + System.out.println("I ate " + food); + food = "nothing"; + System.out.println("Now I have " + food) +} + +void main() { + String fruit = "apple"; + eat(fruit); + System.out.println( + "But in the caller I still have an " + fruit + ); +} \ No newline at end of file diff --git a/src/classes/user_defined_types.md b/src/classes/user_defined_types.md new file mode 100644 index 0000000..51c095f --- /dev/null +++ b/src/classes/user_defined_types.md @@ -0,0 +1,3 @@ +# User Defined Types + +Declaring a class \ No newline at end of file diff --git a/src/return_values/conversion.md b/src/return_values/conversion.md index 3b5a591..1036c0a 100644 --- a/src/return_values/conversion.md +++ b/src/return_values/conversion.md @@ -15,7 +15,7 @@ double returnFive() { } ``` -But if that conversion might potentially be lossy, as with converting `double`s to `int`s, +But if that conversion might potentially be lossy or, as with converting `double`s to `int`s, you must do it yourself. ```java From f08cd2225c17fd7de828028058f0e5fc23ef39f5 Mon Sep 17 00:00:00 2001 From: Ethan McCue Date: Sun, 25 Jun 2023 08:50:03 -0400 Subject: [PATCH 07/69] More Challenges --- book.toml | 2 +- features.java => features.py | 0 src/SUMMARY.md | 6 ++++ src/arguments/challenges.md | 55 ++++++++++++++++++++++++++++++++ src/arguments/final_arguments.md | 4 +-- src/loops_ii/challenges.md | 48 ++++++++++++++++++++++++++++ src/loops_ii/labeled_continue.md | 2 +- src/methods/challenges.md | 37 ++++++++++++++++++++- src/methods/main.md | 9 +++++- src/retu | 1 - src/return | 1 - 11 files changed, 157 insertions(+), 8 deletions(-) rename features.java => features.py (100%) delete mode 100644 src/retu delete mode 100644 src/return diff --git a/book.toml b/book.toml index 5903260..20cbeca 100644 --- a/book.toml +++ b/book.toml @@ -15,7 +15,7 @@ enable = true # whether or not to enable section folding level = 0 # the depth to start folding [preprocessor.features] -command = "python3 features.java" +command = "python3 features.py" # Going to start writing the rest of the book # Assuming this is true toplevel_anonymous_class = false diff --git a/features.java b/features.py similarity index 100% rename from features.java rename to features.py diff --git a/src/SUMMARY.md b/src/SUMMARY.md index 8785e74..6be7c73 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -294,6 +294,12 @@ Javadoc and Documentation comments - [Inner Classes]() - [Annotations]() - [Reflection]() + +The terminal +javac +java +javadoc +jshell --> \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