From 0b4e826d3c02e2a87f88f04a153bb14639485efa Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Mon, 28 Jul 2025 09:56:56 -0400 Subject: [PATCH 001/357] Added a placeholder for the file IO chapter to test adding a new chapter to the book. Added an entry in main.ptx so this new chapter is included in the book. --- source/ch_x_filemanipulation.ptx | 11 +++++++++++ source/main.ptx | 1 + 2 files changed, 12 insertions(+) create mode 100644 source/ch_x_filemanipulation.ptx diff --git a/source/ch_x_filemanipulation.ptx b/source/ch_x_filemanipulation.ptx new file mode 100644 index 0000000..b13f2af --- /dev/null +++ b/source/ch_x_filemanipulation.ptx @@ -0,0 +1,11 @@ + + + + + File IO + +

+ This chapter will cover File IO. +

+ +
\ No newline at end of file diff --git a/source/main.ptx b/source/main.ptx index 7d8abe0..1c2123c 100644 --- a/source/main.ptx +++ b/source/main.ptx @@ -14,6 +14,7 @@ + From 2bf62eb9563778245671a76cae75eaf432da5c3f Mon Sep 17 00:00:00 2001 From: Tristan-Raz Date: Mon, 28 Jul 2025 13:22:39 -0400 Subject: [PATCH 002/357] I added typecasting, primitives, variable name, and fixes issue #32 --- source/ch_4_javadatatypes.ptx | 200 ++++++++++++++++++++-------------- 1 file changed, 121 insertions(+), 79 deletions(-) diff --git a/source/ch_4_javadatatypes.ptx b/source/ch_4_javadatatypes.ptx index 6d097a7..6992dd8 100644 --- a/source/ch_4_javadatatypes.ptx +++ b/source/ch_4_javadatatypes.ptx @@ -59,6 +59,39 @@ In older versions of Java, it was the programmers responsibility to convert back and forth from a primitive to an object whenever necessary. This process of converting a primitive to an object was called “boxing.” The reverse process is called “unboxing.” In Java 5, the compiler became smart enough to know when to convert back and forth and is called “autoboxing.” In this book, we will typically use the Object version of all the numeric data types and let the compiler do its thing.

+

+ With that distinction in mind, here are the common types you'll use, most of which are similar to Python's types: +

    +
  • +

    + int: The primitive type for integers (whole numbers), such as 3, 0, and -76. +

    +
  • +
  • +

    + double: The primitive type for floating-point numbers like 6.3 or -0.9. +

    +
  • +
  • +

    + boolean: The primitive type that can only be true or false. +

    +
  • +
  • +

    + char: The primitive type for a single character, like 'a' or 'Z'. It is represented using single quotes. +

    +
  • +
  • +

    + String: An object type that represents a sequence of characters in double quotes, like "Hello". +

    +
  • + +
+ + A data type fundamentally defines a set of values and the operations you can perform on them. For instance, you can do math with int and double values, but not with boolean values. This is simlar to Python, where you can perform arithmetic on integers and floats, but not on booleans or strings. +

Let’s look at a simple Python function which converts a Fahrenheit temperature to Celsius. @@ -117,11 +150,6 @@ public class TempConv {

-
  • -

    - Input/Output and the Scanner Class -

    -
  • @@ -202,13 +230,19 @@ public class TempConv { - - Declaring Variables + + Variable Declaration

    - Here is where we run into one of the most important differences between Java and Python. Python is a dynamically typed language. In a dynamically typed language a variable can refer to any kind of object at any time. When the variable is used, the interpreter figures out what kind of object it is. Java is a statically typed language. In a statically typed language the association between a variable and the type of object the variable can refer to is determined when the variable is declared. Once the declaration is made it is an error for a variable to refer to an object of any other type. + Here is where we run into one of the most important differences between Java and Python. Python is a dynamically typed language. In a dynamically typed language a variable can refer to any kind of object at any time. When the variable is used, the interpreter figures out what kind of object it is. Java is a statically typed language. In a statically typed language the association between a variable and the type of object the variable can refer to is determined when the variable is declared. Once the declaration is made it is an error for a variable to refer to an object of any other type.

    +

    + A valid variable name in Java can contain letters, digits, and underscores. It must begin with a letter, an underscore, or a dollar sign. It cannot start with a digit and it cannot be a reserved keyword (like class, int, or static). Variable names are case-sensitive, so fahr and Fahr are different variables. The convention is to use lower case for variable names, and to use camel case (where the first word is lowercase and subsequent words are capitalized) for multi-word variable names, such as fahrenheitTemperature. +

    +

    + An important feature of Java is that when you declare a variable of a primitive type (like int or double), the system automatically allocates a fixed amount of memory to store its value directly. This is different from reference types (like String or Scanner), where the variable holds a memory address that points to the actual object data stored elsewhere. This distinction makes operations on primitives very fast. +

    In the example above, lines 5—7 contain variable declarations. Specifically we are saying that fahr and cel are going to reference objects that are of type Double. The variable in will reference a Scanner object. This means that if we were to try an assignment like fahr = "xyz" the compiler would generate an error because "xyz" is a string and fahr is supposed to be a double.

    @@ -223,86 +257,94 @@ public class TempConv {

    - The general rule in Java is that you must decide what kind of an object your variable is going to reference and then you must declare that variable before you use it. There is much more to say about the static typing of Java, but for now this is enough. + The general rule in Java is that you must decide what kind of an object your variable is going to reference and then you must declare that variable before you use it. In our temperature converter, the calculation (fahr - 32) * 5.0/9.0 works correctly because 5.0 and 9.0 are treated as double values, preventing the integer division that would occur if we had written 5/9, which would result in 0.

    -
    - - - - Input / Output / Scanner - -

    - In the previous section we created a Scanner object. In Java, Scanner objects make getting input from the user, a file, or even over the network relatively easy. In our case we simply want to ask the user to type in a number at the command line, so in line 9 we construct a Scanner by calling the constructor and passing it the System.in object. Notice that this Scanner object is assigned to the name in, which we declared to be a Scanner on line 7. System.in is similar to System.out except, of course, it is used for input. If you are wondering why we must create a Scanner to read data from System.in when we can write data directly to System.out using println, you are not alone. We will talk about the reasons why this is so later when we talk in-depth about Java streams. You will also see in other examples that we can create a Scanner by passing the Scanner a File object. You can think of a Scanner as a kind of “adapter” that makes low level objects easier to use. -

    - -

    - On line 11 we use the Scanner object to read in a number. Here again we see the implications of Java being a strongly typed language. Notice that we must call the method nextDouble because the variable fahr was declared as a double. So, we must have a function that is guaranteed to return each kind of object we might want to read. In this case, we need to read a Double so we call the function nextDouble. The compiler matches up these assignment statments and if you try to assign the results of a method call to the wrong kind of variable it will be flagged as an error. -

    - -

    - The table below shows some commonly used methods of the Scanner class. There are many more methods supported by this class and we will talk about how to find them in our chapter about . -

    - - - - - Return type - Method name - Description - - - - boolean - hasNext() - returns true if more data is present - + + - - boolean - hasNextInt() - returns true if the next thing to read is an integer - +
    + Typecasting - - boolean - hasNextFloat() - returns true if the next thing to read is a float - +

    + Typecasting is the process of converting a variable from one type to another. In Java, this is often necessary when you want to perform operations that require different data types. For example, if you have an integer and you want to convert it to a double for more precise calculations, you would use typecasting. +

    - - boolean - hasNextDouble() - returns true if the next thing to read is a double - +

    + In Java, typecasting can be done in two ways: implicit and explicit. Implicit typecasting occurs automatically when converting from a smaller data type to a larger one (like int to double), while explicit typecasting requires you to specify the conversion manually (like double to int). +

    - - Integer - nextInt() - returns the next thing to read as an integer - +

    + Implicit typecasting happens automatically when converting a value from a smaller data type to a larger one, as there is no risk of losing information. For example, you can assign an int to a double without any special syntax. +

    +
     
    +        int myInt = 10;
    +        double myDouble = myInt; // Automatic casting from int to double
    +        
    + +

    + Explicit typecasting is required when converting from a larger data type to a smaller one, as you might lose data. You must do this manually by placing the target type in parentheses () before the value. +

    +
    +        double originalDouble = 9.78;
    +        int castedInt = (int) originalDouble; // Explicitly casts double to int. The value of castedInt is now 9.
    +        
    - - Float - nextFloat() - returns the next thing to read as a float - +

    + Besides primitive types, type casting is also a fundamental concept when working with objects, especially within an inheritance hierarchy. This involves converting an object reference from one class type to another, typically between a superclass and a subclass. This is often referred to as upcasting and downcasting. +

    +

    + Let's imagine we have a simple class hierarchy: an Animal superclass and a Dog subclass. +

    +
    +class Animal {
    +    public void makeSound() {
    +        System.out.println("The animal makes a sound.");
    +    }
    +}
     
    -                    
    -                         Double 
    -                         nextDouble() 
    -                         returns the next thing to read as a Double 
    -                    
    +class Dog extends Animal {
    +    public void bark() {
    +        System.out.println("The dog barks!");
    +    }
    +}
    +    
    + +

    + Upcasting (Implicit): Upcasting is casting a subclass instance to a superclass reference type. This is always safe because a subclass object is guaranteed to have all the methods and properties of its superclass. Therefore, upcasting is done implicitly by the compiler. +

    +
    +// A Dog object is created, but the reference is of type Animal.
    +// This is implicit upcasting.
    +Animal myAnimal = new Dog(); 
    +
    +myAnimal.makeSound(); // This is valid, as makeSound() is defined in Animal.
    +
    +// myAnimal.bark(); // This would cause a compile-time error!
    +// The compiler only knows about the methods in the Animal reference type.
    +    
    +

    + Downcasting (Explicit): Downcasting is casting a superclass reference back to its original subclass type. This is potentially unsafe because the superclass reference might not actually point to an object of the target subclass. You must perform an explicit cast. If you cast to the wrong type, Java will throw a ClassCastException at runtime. +

    +

    + To safely downcast, you should first check the object's type using the instanceof operator. +

    +
    +// 'myAnimal' is an Animal reference, but it points to a Dog object.
    +if (myAnimal instanceof Dog) {
    +    // The check passed, so this downcast is safe.
    +    Dog myDog = (Dog) myAnimal;
    +
    +    // Now we can access methods specific to the Dog class.
    +    myDog.bark(); // This is now valid.
    +}
    +    
    - - String - next() - returns the next thing to read as a String - - -
    -
    - +

    + In this example, we first create a Dog object and assign it to an Animal reference (upcasting). Then, we check if the Animal reference is actually pointing to a Dog object before downcasting it back to a Dog reference. +

    + +
    String From 19a82e183851c473268cfeca1ba391b1147a8b9d Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Mon, 28 Jul 2025 14:19:02 -0400 Subject: [PATCH 003/357] Created an introduction and a section covering library imports. For now, this chapter is chapter 8 and is listed as 'ch_x_filemanipulation.ptx' in the source folder and main.ptx. --- source/ch_x_filemanipulation.ptx | 44 +++++++++++++++++++++++++++++--- 1 file changed, 41 insertions(+), 3 deletions(-) diff --git a/source/ch_x_filemanipulation.ptx b/source/ch_x_filemanipulation.ptx index b13f2af..a2a3be3 100644 --- a/source/ch_x_filemanipulation.ptx +++ b/source/ch_x_filemanipulation.ptx @@ -4,8 +4,46 @@ File IO -

    - This chapter will cover File IO. -

    + +

    + File handling is an integral part of programming. Most programming languages have the ability to read from, write to, create, delete, move, and copy files. +

    +
    + + +
    + Class Imports + +

    + Before any code can be written to handle files, the proper classes must be imported. Java includes a class called File in the io library. The class can be imported with the following line. Be sure to capitalize File. +

    + + + +import java.io.File; + + + +

    + This class provides a lot of functionality for file hanling, however, the IOException class should also be included and used to handle file operation errors. If this class is not included and a file operation throws an exception, a compile error will occur. +

    + + + +import java.io.IOException; + + + +

    + Next, the Scanner class from the util library will need to be imported if there is any need for the program being written to read a file. It should be noted that this library is unneccesary if the program will not be reading any data from a file. +

    + + + +import java.io.IOException; + + + +
    \ No newline at end of file From 3a5ce80c1fa28fddd9333c5ef32cf16726682f14 Mon Sep 17 00:00:00 2001 From: Tristan-Raz Date: Mon, 28 Jul 2025 15:47:49 -0400 Subject: [PATCH 004/357] Adds a cheatsheet for Java fixes issue #42 --- source/ap-java-cheatsheet.ptx | 227 ++++++++++++++++++++++++++++++++++ source/main.ptx | 3 + 2 files changed, 230 insertions(+) create mode 100644 source/ap-java-cheatsheet.ptx diff --git a/source/ap-java-cheatsheet.ptx b/source/ap-java-cheatsheet.ptx new file mode 100644 index 0000000..f628368 --- /dev/null +++ b/source/ap-java-cheatsheet.ptx @@ -0,0 +1,227 @@ + + +
    + Java Cheat Sheet + + Purpose of this Cheat Sheet +

    +

    +

    + The following is intended to be useful in better understanding Java functions coming from a Python background. +

    +
    + + + + + Python Function + Java Equivalent + Description + + + print() + System.out.println() + Prints output to the console. + + + len() + array.length + Returns the length of an array. + + + range() + for (int i = 0; i < n; i++) + Used in loops to iterate a specific number of times. + + + str() + String.valueOf() + Converts an object to a string. + + + int() + Integer.parseInt() + Converts a string to an integer. + + + float() + Float.parseFloat() + Converts a string to a float. + + + list.append() + ArrayList.add() + Adds an element to the end of a list. + + + list.pop() + ArrayList.remove(index) + Removes and returns the element at the specified index. + + + list.sort() + Collections.sort(list) + Sorts a list in ascending order. + + + list.reverse() + Collections.reverse(list) + Reverses the order of elements in a list. + + + dict.get() + Map.get(key) + Retrieves the value associated with a key in a map. + + + dict.keys() + Map.keySet() + Returns a set of keys in a map. + + + dict.values() + Map.values() + Returns a collection of values in a map. + + + dict.items() + Map.entrySet() + Returns a set of key-value pairs in a map. + + + input() + Scanner.nextLine() + Reads a line of input from the console. + + + open() + FileReader, BufferedReader + Used to read from files. + + + enumerate() + for (int i = 0; i < list.size(); i++) { ... } + Used to iterate over a list with an index. + + +
    + + + + Operator Type + Operator + Description + Example + + + Arithmetic + +, -, *, / + Addition, Subtraction, Multiplication, Division + 5 + 2 + + + Arithmetic + // + Floor Division (rounds down) + 7 // 2 → 3 + + + Arithmetic + % + Modulus (remainder) + 7 % 2 → 1 + + + Arithmetic + ** + Exponent + 2 ** 3 → 8 + + + Comparison + ==, != + Equal to, Not equal to + x == y + + + Comparison + >, <, >=, <= + Greater/Less than, or equal to + x > 5 + + + Logical + and, or, not + Logical AND, OR, NOT + x > 1 and y < 10 + + + Assignment + +=, -=, *=, /= + Adds, subtracts, multiplies, or divides and assigns + x += 1 + + + Bitwise + <<, >>, >>> + Left, right, and unsigned right shift. + x << 2 + + + Ternary + ? : + One-line if-else expression. + condition ? val1 : val2 + + +
    + +

    +

      +
    • +

      + Short-Circuiting: The logical operators && (AND) and || (OR) are efficient. They stop evaluating as soon as the outcome is known. For example, in if (user != null && user.isAdmin()), the code will not attempt to call .isAdmin() if user is null, preventing an error. +

      +
    • +
    • +

      + Streams: Java's Stream API provides a powerful way to process collections of objects. A stream can be used to filter, map, and reduce data in a sequence of steps, similar to Python's list comprehensions but more powerful. +

      +
    • +
    • +

      + The Ternary Operator provides a compact, one-line if-else statement. For instance, result = "Pass" if score >= 60 else "Fail" is much shorter than a full if-else block. +

      +
    • + +
    • +

      + List Comprehension offers a concise and readable way to create new lists based on existing sequences. Instead of a multi-line loop, you can write squares = [i**2 for i in range(10)] to generate a list of squares. +

      +
    • + +
    • +

      + F-Strings (Formatted String Literals) simplify embedding expressions and variables directly inside strings. This makes code like print(f"Hello, {name}!") much cleaner than traditional string concatenation. +

      +
    • + +
    • +

      + Tuple and List Unpacking allows for assigning elements of a sequence to multiple variables in a single line, such as name, age = ["Alice", 30]. This also enables simple variable swapping with a, b = b, a. +

      +
    • + +
    • +

      + Chained Comparisons make range checks more intuitive and mathematical. You can write if 18 <= age < 65: instead of the more verbose if age >= 18 and age < 65:. +

      +
    • +
    +

    + +
    +
    + + + diff --git a/source/main.ptx b/source/main.ptx index 7d8abe0..8c06021 100644 --- a/source/main.ptx +++ b/source/main.ptx @@ -18,5 +18,8 @@ + + + \ No newline at end of file From 5988c862598b37756d498459646884732becbdf5 Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Mon, 28 Jul 2025 16:06:10 -0400 Subject: [PATCH 005/357] Added a second section on creating files. Will have others review section and make changes if needed. --- source/ch_x_filemanipulation.ptx | 153 ++++++++++++++++++++++++++++++- 1 file changed, 149 insertions(+), 4 deletions(-) diff --git a/source/ch_x_filemanipulation.ptx b/source/ch_x_filemanipulation.ptx index a2a3be3..8127811 100644 --- a/source/ch_x_filemanipulation.ptx +++ b/source/ch_x_filemanipulation.ptx @@ -2,7 +2,7 @@ - File IO + File Handling

    @@ -20,7 +20,7 @@ -import java.io.File; + import java.io.File; @@ -30,7 +30,7 @@ import java.io.File; -import java.io.IOException; + import java.io.IOException; @@ -40,10 +40,155 @@ import java.io.IOException; -import java.io.IOException; + import java.util.Scanner;

    +
    + Creating Files + +

    + Before we can write code that creates a file, we must first import the necessary classes mentioned in the previous section (Scanner is not needed for creating files) and create a class. We will call this class CreateFile(). +

    + + + + import java.io.File; + import java.io.IOException; + + public class CreateFile { + public static void main(String[] args) { + + } + } + + + +

    + Next, within the main function, we will create a File object. It is important to create a meaningful name for the File object. We will call ours myFile. +

    + + + + File myFile = new File("myfile.txt"); + + + +
    +            Note: myFile is the name of the object within the program, while "myfile.txt" 
    +            is the name of the file itself and will be the file name if the operation 
    +            that creates the file is successful.
    +        
    + +

    + Now that we have created a new File object, we can create a file using the createNewFile() method from the File class. While the previous line of code creates an object within the program for the file, this method actually does the work of creating a file and saving it in the current working directory. This method returns a boolean value. If the method returns true, the file was successfully created. If the method returns false, there is already a file using the chosen file name. We can use this method's possible return values in tandem with an if/else selection to determine if the file was created, or if a file with that file name already exists in the directory. +

    + + + + if (myFile.createNewFile()) { // If the file was created successfully + System.out.println("The file " + myFile.getName() + " was created sucessfully."); + } else { // If a file with the file name chosen already exists + System.out.println("The file " + myFile.getName() + " already exists."); + } + + + +
    +            Note: You may have noticed the use of another mthod from the File class; 
    +            getName(). This method returns a string containing the name of 
    +            the file. 
    +        
    + +

    + The code may seem complete at this point, but if you remember from the previous section, error handling using the IOException is required for program to compile. Let's utilize best practices and add in try/catch blocks to handle exceptions thrown by the IOException class. +

    + + + + try { + if (myFile.createNewFile()) { // If the file was created successfully + System.out.println("The file " + myFile.getName() + " was created sucessfully."); + } else { // If a file with the file name chosen already exists + System.out.println("The file " + myFile.getName() + " already exists."); + } + } catch (IOException e) { + System.out.println("An error occurred."); + e.printStackTrace(); + } + + + +

    + You may have noticed the IOException e part in the parenthesis next to the catch. This creates a variable called e that refers to an IOException object. In other words, e refers to the error created if the try block fails. The line e.printStackTrace(); prints the stack trace to the console. This is what the console may output if the program tries to create a file, but is blocked by the Operating System due to insufficient permissions: +

    + + + + An error occurred. + java.io.IOException: Permission denied + at java.base/java.io.File.createNewFile(File.java:1040) + at CreateFile.main(CreateFile.java:7) + + + + +

    + At this point, the program will function correctly. Let's add the try/catch blocks to the foundational code written before to get a complete program: +

    + + + + import java.io.File; + import java.io.IOException; + + public class CreateFile { + public static void main(String[] args) { + try { + if (myFile.createNewFile()) { // If the file was created successfully + System.out.println("The file " + myFile.getName() + " was created sucessfully."); + } else { // If a file with the file name chosen already exists + System.out.println("The file " + myFile.getName() + " already exists."); + } + } catch (IOException e) { + System.out.println("An error occurred."); + e.printStackTrace(); + } + + } + } + + + +

    + You may be wondering; "What if I don't want to create a file in the current working directory?" Good question! In Windows environments, you can specify the file path using two back slashes for each back slash in the file path. For each pair of back slashes, the first backslash acts as an escape character. So, if you want to save a file to this directory: +

    + +
    +            C:\Users\UserName\Documents
    +        
    + +

    + The line of code that creates a File object will look like this: +

    + + + + File myFile = new File("C:\\Users\\UserName\\Documents\\myfile.txt"); + + + +

    + If you are working in a Linux or Apple environment, you can simply use the file path with single forward slashes: +

    + + + + File myFile = new File("/home/UserName/Documents/myfile.txt"); + + +
    + \ No newline at end of file From 4fc6ea1027173a01d90631376c472c1bff86819a Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Tue, 29 Jul 2025 09:28:47 -0400 Subject: [PATCH 006/357] Made some minor code and spelling corrections to x.2. Started adding a section on writing to files. --- source/ch_x_filemanipulation.ptx | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/source/ch_x_filemanipulation.ptx b/source/ch_x_filemanipulation.ptx index 8127811..2106aba 100644 --- a/source/ch_x_filemanipulation.ptx +++ b/source/ch_x_filemanipulation.ptx @@ -25,7 +25,7 @@

    - This class provides a lot of functionality for file hanling, however, the IOException class should also be included and used to handle file operation errors. If this class is not included and a file operation throws an exception, a compile error will occur. + This class provides a lot of functionality for file handling, however, the IOException class should also be included and used to handle file operation errors. If this class is not included and a file operation throws an exception, a compile error will occur.

    @@ -35,7 +35,7 @@

    - Next, the Scanner class from the util library will need to be imported if there is any need for the program being written to read a file. It should be noted that this library is unneccesary if the program will not be reading any data from a file. + Next, the Scanner class from the util library will need to be imported if there is any need for the program being written to read a file. It should be noted that this library is unnecessary if the program will not be reading any data from a file.

    @@ -97,7 +97,7 @@
    -            Note: You may have noticed the use of another mthod from the File class; 
    +            Note: You may have noticed the use of another method from the File class; 
                 getName(). This method returns a string containing the name of 
                 the file. 
             
    @@ -147,6 +147,7 @@ public class CreateFile { public static void main(String[] args) { try { + File myFile = new File("myfile.txt"); if (myFile.createNewFile()) { // If the file was created successfully System.out.println("The file " + myFile.getName() + " was created sucessfully."); } else { // If a file with the file name chosen already exists @@ -163,7 +164,7 @@

    - You may be wondering; "What if I don't want to create a file in the current working directory?" Good question! In Windows environments, you can specify the file path using two back slashes for each back slash in the file path. For each pair of back slashes, the first backslash acts as an escape character. So, if you want to save a file to this directory: + You may be wondering: "What if I don't want to create a file in the current working directory?" Good question! In Windows environments, you can specify the file path using two back slashes for each back slash in the file path. For each pair of back slashes, the first backslash acts as an escape character. So, if you want to save a file to this directory:

    @@ -191,4 +192,13 @@
             
         
     
    +    
    + Writing to Files + +

    + The createNewFile() method is useful for attempting to create files and reporting if the operation was successful, however, createNewFile() does not write anything to files it creates. In fact, if you use createNewFile() to create a .txt file and then open the file, the file will be blank. +

    + +
    + \ No newline at end of file From 5f70b7edb2d745dac22ae50785fdcf991cfe54f4 Mon Sep 17 00:00:00 2001 From: Tristan-Raz Date: Tue, 29 Jul 2025 09:29:45 -0400 Subject: [PATCH 007/357] Moves the cheat sheet to the appendix --- source/main.ptx | 1 - source/meta_backmatter.ptx | 6 +++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/source/main.ptx b/source/main.ptx index 8c06021..1fc6f4a 100644 --- a/source/main.ptx +++ b/source/main.ptx @@ -20,6 +20,5 @@ - \ No newline at end of file diff --git a/source/meta_backmatter.ptx b/source/meta_backmatter.ptx index 34e1c60..316b40f 100644 --- a/source/meta_backmatter.ptx +++ b/source/meta_backmatter.ptx @@ -1,7 +1,7 @@ - + Appendices @@ -16,6 +16,10 @@

    + + Java Cheatsheet + + Shameless Plug From 32823aaa2f49edc7142107da19a50c099c5fa623 Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Tue, 29 Jul 2025 13:08:42 -0400 Subject: [PATCH 008/357] Added a section on writing to files. Added an additional library import to the libraries section. Updated name of ptx file and made appropriate changes in main.ptx. --- source/ch_x_filehandling.ptx | 393 +++++++++++++++++++++++++++++++++++ source/main.ptx | 2 +- 2 files changed, 394 insertions(+), 1 deletion(-) create mode 100644 source/ch_x_filehandling.ptx diff --git a/source/ch_x_filehandling.ptx b/source/ch_x_filehandling.ptx new file mode 100644 index 0000000..b1dab7e --- /dev/null +++ b/source/ch_x_filehandling.ptx @@ -0,0 +1,393 @@ + + + + + File Handling + + +

    + File handling is an integral part of programming. Most programming languages have the ability to read from, write to, create, delete, move, and copy files. +

    +
    + + +
    + Class Imports + +

    + Before any code can be written to handle files, the proper classes must be imported. Java includes a class called File in the io library. The class can be imported with the following line. Be sure to capitalize File. +

    + + + + import java.io.File; + + + +

    + This class provides a lot of functionality for file handling, however, the IOException class should also be included and used to handle file operation errors. If this class is not included and a file operation throws an exception, a compile error will occur. +

    + + + + import java.io.IOException; + + + +

    + Next, the Scanner class from the util library will need to be imported if there is any need for the program being written to read a file. It should be noted that this library is unnecessary if the program will not be reading any data from a file. +

    + + + + import java.util.Scanner; + + + +

    + Finally, the FileWriter class can be used to write to files. In the same way that the Scanner class isn't needed unless the program will read from a file, the FileWriter class isn't needed unless the program will write to a file. +

    + + + + import java.io.FileWriter; + + + +
    + +
    + Creating Files + +

    + Before we can write code that creates a file, we must first import the necessary classes mentioned in the previous section (Scanner and FileWriter is not needed for a class that creates files and does nothing else) and create a class. We will call this class CreateFile(). +

    + + + + import java.io.File; + import java.io.IOException; + + public class CreateFile { + public static void main(String[] args) { + + } + } + + + +

    + Next, within the main function, we will create a File object. It is important to create a meaningful name for the File object. We will call ours myFile. +

    + + + + File myFile = new File("myfile.txt"); + + + +
    +            Note: myFile is the name of the object within the program, while "myfile.txt" 
    +            is the name of the file itself and will be the file name if the operation 
    +            that creates the file is successful.
    +        
    + +

    + Now that we have created a new File object, we can create a file using the createNewFile() method from the File class. While the previous line of code creates an object within the program for the file, this method actually does the work of creating a file and saving it in the current working directory. This method returns a boolean value. If the method returns true, the file was successfully created. If the method returns false, there is already a file using the chosen file name. We can use this method's possible return values in tandem with an if/else selection to determine if the file was created, or if a file with that file name already exists in the directory. +

    + + + + if (myFile.createNewFile()) { // If the file was created successfully + System.out.println("The file " + myFile.getName() + " was created sucessfully."); + } else { // If a file with the file name chosen already exists + System.out.println("The file " + myFile.getName() + " already exists."); + } + + + +
    +            Note: You may have noticed the use of another method from the File class; 
    +            getName(). This method returns a string containing the name of 
    +            the file. 
    +        
    + +

    + The code may seem complete at this point, but if you remember from the previous section, error handling using the IOException is required for program to compile. Let's utilize best practices and add in try/catch blocks to handle exceptions thrown by the IOException class. +

    + + + + try { + if (myFile.createNewFile()) { // If the file was created successfully + System.out.println("The file " + myFile.getName() + " was created sucessfully."); + } else { // If a file with the file name chosen already exists + System.out.println("The file " + myFile.getName() + " already exists."); + } + } catch (IOException e) { + System.out.println("An error occurred."); + e.printStackTrace(); + } + + + +

    + You may have noticed the IOException e part in the parenthesis next to the catch. This creates a variable called e that refers to an IOException object. In other words, e refers to the error created if the try block fails. The line e.printStackTrace(); prints the stack trace to the console. This is what the console may output if the program tries to create a file, but is blocked by the Operating System due to insufficient permissions: +

    + + + + An error occurred. + java.io.IOException: Permission denied + at java.base/java.io.File.createNewFile(File.java:1040) + at CreateFile.main(CreateFile.java:7) + + + + +

    + At this point, the program will function correctly. Let's add the try/catch blocks to the foundational code written before to get a complete program: +

    + + + + import java.io.File; + import java.io.IOException; + + public class CreateFile { + public static void main(String[] args) { + try { + File myFile = new File("myfile.txt"); + if (myFile.createNewFile()) { // If the file was created successfully + System.out.println("The file " + myFile.getName() + " was created sucessfully."); + } else { // If a file with the file name chosen already exists + System.out.println("The file " + myFile.getName() + " already exists."); + } + } catch (IOException e) { + System.out.println("An error occurred."); + e.printStackTrace(); + } + + } + } + + + +

    + You may be wondering: "What if I don't want to create a file in the current working directory?" Good question! In Windows environments, you can specify the file path using two back slashes for each back slash in the file path. For each pair of back slashes, the first backslash acts as an escape character. So, if you want to save a file to this directory: +

    + +
    +            C:\Users\UserName\Documents
    +        
    + +

    + The line of code that creates a File object will look like this: +

    + + + + File myFile = new File("C:\\Users\\UserName\\Documents\\myfile.txt"); + + + +

    + If you are working in a Linux or Apple environment, you can simply use the file path with single forward slashes: +

    + + + + File myFile = new File("/home/UserName/Documents/myfile.txt"); + + +
    + +
    + Writing to Files + +

    + The createNewFile() method is useful for attempting to create files and reporting if the operation was successful, however, createNewFile() does not write anything to files it creates. In fact, if you use createNewFile() to create a .txt file and then open the file, the file will be blank. +

    + +

    + To write to a file, we will need to create a different class. We will do the same setup as the previous section. First, we will import the classes (File and Scanner are not needed) and create the framework for a class that will write to a file. Let's call this class WriteFile: +

    + + + + import java.io.FileWriter; + import java.io.IOException; + + public class WriteFile { + public static void main(String[] args) { + + } + } + + + +

    + Next, we will create a FileWriter object. Let's call it myWriter: +

    + + + + FileWriter myWriter = new FileWriter("myFile.txt"); + + + +

    + In this next step, we will use the write() method from the FileWriter class. This Method will take any data within the parenthesis and write that data to the file selected. The write() method takes most standard data types: +

    + + + + myWriter.write("File successfully updated!"); + myWriter.close(); + + + +

    + You may have noticed the close() function being used after writing to a file. This is a very important step and must be included when working with files! Without using this method, the file may remain active in system resources even after the program is closed. This can lead file corruption or other terrible problems that are best avoided! +

    + +

    + Next, we will again add the required try/catch blocks utilizing the IOException class. Just like with creating files, the program will not compile without these crucial additions! We will also add some print statements to inform us of the success of the file write operation: +

    + + + + try { + FileWriter myWriter = new FileWriter("myFile.txt"); + myWriter.write("File successfully updated!"); + myWriter.close(); + System.out.println("File successfully written to."); + } catch (IOException e) { + System.out.println("An error occurred."); + e.printStackTrace(); + } + + + +

    + And that's it! We will add our code to the foundational code for a complete program. +

    + + + + import java.io.FileWriter; + import java.io.IOException; + + public class WriteFile { + public static void main(String[] args) { + try { + FileWriter myWriter = new FileWriter("myFile.txt"); + myWriter.write("File successfully updated!"); + myWriter.close(); + System.out.println("File successfully written to."); + } catch (IOException e) { + System.out.println("An error occurred."); + e.printStackTrace(); + } + } + } + + + +

    + Files in a specific directory can be written to using the same technique as the last section in which file paths are specified, with two back slashes used in Windows environments. Something to note is, if a file does not already exist (for example, myfile.txt does not exist), the write() method will create the file. Despite this, it is still a good idea to create separate methods or classes for creating and writing to files. Not only is it good practice to ensure methods only accomplish one thing, but the createNewFile() method avoids overwriting files that already exist. Imagine a file with the name myfile.txt already exists and contains important information. Attempting to create a file using the write() method will delete that data forever. +

    + +

    + Speaking of overwriting data, it is important to know that the write() method will overwrite any text if there is already text in myfile.txt. What if we want to append text to the end of any text already in myfile.txt? To accomplish this, we can pass a boolean argument along with the file name when creating a new data argument: +

    + + + + FileWriter myWriter = new FileWriter("myfile.txt", true); // true enables append mode + + + +

    + Now, when we use write() method like before, the text will be appended if there is already text in the document. If we were to update our code to include the boolean argument: +

    + + + + import java.io.FileWriter; + import java.io.IOException; + + public class WriteFile { + public static void main(String[] args) { + try { + FileWriter myWriter = new FileWriter("myFile.txt", true); // true enables append mode + myWriter.write("File successfully updated!"); + myWriter.close(); + System.out.println("File successfully written to."); + } catch (IOException e) { + System.out.println("An error occurred."); + e.printStackTrace(); + } + } + } + + + +

    + and then run the program twice, the contents of myfile.txt would be: +

    + + + + File successfully updated!File successfully updated! + + + +

    + This doesn't look very good! There is no space between the first and second sentences! We can make this look a little better by simply adding a space after the exclamation mark in the string: +

    + + + + myWriter.write("File successfully updated! "); // Added space at end + myWriter.close(); + + + +

    + This works fine if you want all text to be on the same line, but what if we want each additional write to appear on a new line? The first answer may be to use the \n newline character: +

    + + + + myWriter.write("File successfully updated!\n"); // Added newline character + myWriter.close(); + + + +

    + This would work fine most of the time, but older Windows programs and operating systems use the \r\n newline character. To ensure the text appears on a new line regardless of what system the code is running on, concatenate the string with the System.lineSeparator() method: +

    + + + + myWriter.write("File successfully updated!" + System.lineseparator()); // Added newline character + myWriter.close(); + + + +

    + Running either variation used for adding new lines twice will result in the following contents in myfile.txt. Notice that an extra blank line that will always appear at the bottom of the text: +

    + + + + File successfully updated! + File successfully updated! + + + + +
    + +
    \ No newline at end of file diff --git a/source/main.ptx b/source/main.ptx index 1c2123c..6c62fed 100644 --- a/source/main.ptx +++ b/source/main.ptx @@ -14,7 +14,7 @@ - + From 59186ee6fe4d61f2a3ca2a73a4d9263794ae8c2b Mon Sep 17 00:00:00 2001 From: Tristan-Raz Date: Tue, 29 Jul 2025 15:08:19 -0400 Subject: [PATCH 009/357] Fixes merge conflicts and issue #42 --- source/main.ptx | 1 + source/meta_backmatter.ptx | 9 +++++++++ 2 files changed, 10 insertions(+) diff --git a/source/main.ptx b/source/main.ptx index a51dd2d..bddc8f2 100644 --- a/source/main.ptx +++ b/source/main.ptx @@ -22,6 +22,7 @@ Index + \ No newline at end of file diff --git a/source/meta_backmatter.ptx b/source/meta_backmatter.ptx index cc8e801..d380894 100644 --- a/source/meta_backmatter.ptx +++ b/source/meta_backmatter.ptx @@ -4,6 +4,15 @@ Appendices + + + Java Cheat Sheet +

    This is a quick reference guide for Java syntax and concepts.

    + +
    + + + Shameless Plug From 185be526f19494fa025994bad24bef298a6d2cc7 Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Tue, 29 Jul 2025 15:28:08 -0400 Subject: [PATCH 010/357] Added a section on Reading files. --- source/ch_x_filehandling.ptx | 140 +++++++++++++++++++++++++++++++---- 1 file changed, 127 insertions(+), 13 deletions(-) diff --git a/source/ch_x_filehandling.ptx b/source/ch_x_filehandling.ptx index b1dab7e..e560d5f 100644 --- a/source/ch_x_filehandling.ptx +++ b/source/ch_x_filehandling.ptx @@ -25,32 +25,38 @@

    - This class provides a lot of functionality for file handling, however, the IOException class should also be included and used to handle file operation errors. If this class is not included and a file operation throws an exception, a compile error will occur. + The Scanner class from the util library will need to be imported if there is any need for the program being written to read a file. It should be noted that this library is unnecessary if the program will not be reading any data from a file.

    - import java.io.IOException; + import java.util.Scanner;

    - Next, the Scanner class from the util library will need to be imported if there is any need for the program being written to read a file. It should be noted that this library is unnecessary if the program will not be reading any data from a file. + The FileWriter class can be used to write to files. In the same way that the Scanner class isn't needed unless the program will read from a file, the FileWriter class isn't needed unless the program will write to a file.

    - import java.util.Scanner; + import java.io.FileWriter;

    - Finally, the FileWriter class can be used to write to files. In the same way that the Scanner class isn't needed unless the program will read from a file, the FileWriter class isn't needed unless the program will write to a file. + Finally, these last two classes provide error handling and must be used in tandem with the File class. IOException handles file creation and writing errors, while FileNotFoundException handles errors when trying to read files that do not exist.

    - import java.io.FileWriter; + import java.io.IOException; + + + + + + import java.io.FileNotFoundException @@ -131,9 +137,9 @@ -

    - You may have noticed the IOException e part in the parenthesis next to the catch. This creates a variable called e that refers to an IOException object. In other words, e refers to the error created if the try block fails. The line e.printStackTrace(); prints the stack trace to the console. This is what the console may output if the program tries to create a file, but is blocked by the Operating System due to insufficient permissions: -

    +
    +            Note: The IOException e part in the parenthesis next to the catch. This creates a variable called e that refers to an IOException object. In other words, e refers to the error created if the try block fails. The line e.printStackTrace(); prints the stack trace to the console. This is what the console may output if the program tries to create a file, but is blocked by the Operating System due to insufficient permissions:
    +        
    @@ -210,7 +216,7 @@

    - To write to a file, we will need to create a different class. We will do the same setup as the previous section. First, we will import the classes (File and Scanner are not needed) and create the framework for a class that will write to a file. Let's call this class WriteFile: + To write to a file, we will need to create a different class. We will do the same setup as the previous section. First, we will import the classes (File and Scanner are not needed) and create the framework for a class that will write to a file. Let's call this class WriteFile:

    @@ -247,9 +253,9 @@ -

    - You may have noticed the close() function being used after writing to a file. This is a very important step and must be included when working with files! Without using this method, the file may remain active in system resources even after the program is closed. This can lead file corruption or other terrible problems that are best avoided! -

    +
    +            Note: the close() function being used after writing to a file. This is a very important step and must be included when working with files! Without using this method, the file may remain active in system resources even after the program is closed. This can lead file corruption or other terrible problems that are best avoided!
    +        

    Next, we will again add the required try/catch blocks utilizing the IOException class. Just like with creating files, the program will not compile without these crucial additions! We will also add some print statements to inform us of the success of the file write operation: @@ -387,7 +393,115 @@ + + +

    + Reading Files + +

    + Let's take a look at how we can use Java to read file contents. We'll start again with library imports and building a class, this time importing the Scanner and FileNotFoundException classes. We will call this class ReadFile: +

    + + + + import java.io.File; + import java.io.FileNotFoundException; + import java.util.Scanner + + public class ReadFile { + public static void main(String[] args) { + + } + } + + + +

    + We will then create both a new File exactly the same as the one from the section on creating files. Additionally, we will create a Scanner object. The Scanner object is the object that does the file reading. We will call this scanner fileReader: +

    + + + + File myFile = new File("myfile.txt"); + Scanner fileReader = new Scanner(myFile); + + + +
    +            Note: The myFile File object we created on the first line was passed to the Scanner object created on the second line.
    +        
    +

    + The next lines consist of a while loop that reads each line of the file passed to the Scanner object and reads them: +

    + + + + while (fileReader.hasNextLine()) { + String data = fileReader.nextLine(); + System.out.println(data); + } + fileReader.close(); + + + +

    + The hasNextLine() method checks checks if the line below the current line has any data. This will evaluate to true even if the next line only contains blank spaces. Within the while loop, a string variable called data is used to store the current line that the Scanner object is pointing to. The nextLine() method does two things. Firstly, it reads the current line. Secondly, it moves the Scanner's position to the next line. In other words, for each iteration of the while loop, each line in the text is read, stored temporarily in the data variable, and printed to the console. Finally, the close() method accomplishes and holds the same importance as the same method discussed in the section on writing to files. +

    + +

    + Alternatively, the following code can be used to store the all lines of myfile.txt to one variable: +

    + + + + String data = ""; + while (fileReader.hasNextLine()) { + data = data + fileReader.nextLine() + System.lineSeparator(); + } + System.out.println(data); + fileReader.close(); + + + +

    + Pay close attention to the details of this code. data must be declared using an empty string or it may not work correctly within the while loop. Additionally, care must be given to reassigning data in the while loop. data is concatinated (to ensure all lines are included) with fileReader.nextLine() and a lineSeparator. Each step of this process ensures what is stored in data matches exactly what is in myfile.txt. +

    + +

    + Using the second method of storing all file contents to one file, the resulting full code including try/catch blocks (this time using FileNotFoundException instead of IOException) will look like this: +

    + + + + import java.io.File; + import java.io.FileNotFoundException; + import java.util.Scanner + + public class ReadFile { + public static void main(String[] args) { + try { + File myFile = new File("myfile.txt"); + Scanner fileReader = new Scanner(myFile); + String data = ""; + while (fileReader.hasNextLine()) { + data = data + fileReader.nextLine() + System.lineSeparator(); + } + System.out.println(data); + fileReader.close(); + } catch (FileNotFoundException e) { + System.out.println("An error occurred."); + e.printStackTrace(); + } + } + } + + + +

    + In this code, we simply print the contents of the file to the console, but it is easy to imagine how the data variable could be used in conjunction with the write class created in the previous section to create a copy of myfile.txt. +

    +
    \ No newline at end of file From 37c0a1c68177b995c3748dcfd8a063afc41e3b24 Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Tue, 29 Jul 2025 15:30:22 -0400 Subject: [PATCH 011/357] Forgot to save changes for last commit. --- source/ch_x_filehandling.ptx | 2 +- source/ch_x_filemanipulation.ptx | 204 ------------------------------- 2 files changed, 1 insertion(+), 205 deletions(-) delete mode 100644 source/ch_x_filemanipulation.ptx diff --git a/source/ch_x_filehandling.ptx b/source/ch_x_filehandling.ptx index e560d5f..689bda7 100644 --- a/source/ch_x_filehandling.ptx +++ b/source/ch_x_filehandling.ptx @@ -417,7 +417,7 @@

    - We will then create both a new File exactly the same as the one from the section on creating files. Additionally, we will create a Scanner object. The Scanner object is the object that does the file reading. We will call this scanner fileReader: + We will then create a new File exactly the same as the one from the section on creating files. Additionally, we will create a Scanner object. The Scanner object is the object that does the file reading. We will call this scanner fileReader:

    diff --git a/source/ch_x_filemanipulation.ptx b/source/ch_x_filemanipulation.ptx deleted file mode 100644 index 2106aba..0000000 --- a/source/ch_x_filemanipulation.ptx +++ /dev/null @@ -1,204 +0,0 @@ - - - - - File Handling - - -

    - File handling is an integral part of programming. Most programming languages have the ability to read from, write to, create, delete, move, and copy files. -

    -
    - - -
    - Class Imports - -

    - Before any code can be written to handle files, the proper classes must be imported. Java includes a class called File in the io library. The class can be imported with the following line. Be sure to capitalize File. -

    - - - - import java.io.File; - - - -

    - This class provides a lot of functionality for file handling, however, the IOException class should also be included and used to handle file operation errors. If this class is not included and a file operation throws an exception, a compile error will occur. -

    - - - - import java.io.IOException; - - - -

    - Next, the Scanner class from the util library will need to be imported if there is any need for the program being written to read a file. It should be noted that this library is unnecessary if the program will not be reading any data from a file. -

    - - - - import java.util.Scanner; - - - -
    - -
    - Creating Files - -

    - Before we can write code that creates a file, we must first import the necessary classes mentioned in the previous section (Scanner is not needed for creating files) and create a class. We will call this class CreateFile(). -

    - - - - import java.io.File; - import java.io.IOException; - - public class CreateFile { - public static void main(String[] args) { - - } - } - - - -

    - Next, within the main function, we will create a File object. It is important to create a meaningful name for the File object. We will call ours myFile. -

    - - - - File myFile = new File("myfile.txt"); - - - -
    -            Note: myFile is the name of the object within the program, while "myfile.txt" 
    -            is the name of the file itself and will be the file name if the operation 
    -            that creates the file is successful.
    -        
    - -

    - Now that we have created a new File object, we can create a file using the createNewFile() method from the File class. While the previous line of code creates an object within the program for the file, this method actually does the work of creating a file and saving it in the current working directory. This method returns a boolean value. If the method returns true, the file was successfully created. If the method returns false, there is already a file using the chosen file name. We can use this method's possible return values in tandem with an if/else selection to determine if the file was created, or if a file with that file name already exists in the directory. -

    - - - - if (myFile.createNewFile()) { // If the file was created successfully - System.out.println("The file " + myFile.getName() + " was created sucessfully."); - } else { // If a file with the file name chosen already exists - System.out.println("The file " + myFile.getName() + " already exists."); - } - - - -
    -            Note: You may have noticed the use of another method from the File class; 
    -            getName(). This method returns a string containing the name of 
    -            the file. 
    -        
    - -

    - The code may seem complete at this point, but if you remember from the previous section, error handling using the IOException is required for program to compile. Let's utilize best practices and add in try/catch blocks to handle exceptions thrown by the IOException class. -

    - - - - try { - if (myFile.createNewFile()) { // If the file was created successfully - System.out.println("The file " + myFile.getName() + " was created sucessfully."); - } else { // If a file with the file name chosen already exists - System.out.println("The file " + myFile.getName() + " already exists."); - } - } catch (IOException e) { - System.out.println("An error occurred."); - e.printStackTrace(); - } - - - -

    - You may have noticed the IOException e part in the parenthesis next to the catch. This creates a variable called e that refers to an IOException object. In other words, e refers to the error created if the try block fails. The line e.printStackTrace(); prints the stack trace to the console. This is what the console may output if the program tries to create a file, but is blocked by the Operating System due to insufficient permissions: -

    - - - - An error occurred. - java.io.IOException: Permission denied - at java.base/java.io.File.createNewFile(File.java:1040) - at CreateFile.main(CreateFile.java:7) - - - - -

    - At this point, the program will function correctly. Let's add the try/catch blocks to the foundational code written before to get a complete program: -

    - - - - import java.io.File; - import java.io.IOException; - - public class CreateFile { - public static void main(String[] args) { - try { - File myFile = new File("myfile.txt"); - if (myFile.createNewFile()) { // If the file was created successfully - System.out.println("The file " + myFile.getName() + " was created sucessfully."); - } else { // If a file with the file name chosen already exists - System.out.println("The file " + myFile.getName() + " already exists."); - } - } catch (IOException e) { - System.out.println("An error occurred."); - e.printStackTrace(); - } - - } - } - - - -

    - You may be wondering: "What if I don't want to create a file in the current working directory?" Good question! In Windows environments, you can specify the file path using two back slashes for each back slash in the file path. For each pair of back slashes, the first backslash acts as an escape character. So, if you want to save a file to this directory: -

    - -
    -            C:\Users\UserName\Documents
    -        
    - -

    - The line of code that creates a File object will look like this: -

    - - - - File myFile = new File("C:\\Users\\UserName\\Documents\\myfile.txt"); - - - -

    - If you are working in a Linux or Apple environment, you can simply use the file path with single forward slashes: -

    - - - - File myFile = new File("/home/UserName/Documents/myfile.txt"); - - -
    - -
    - Writing to Files - -

    - The createNewFile() method is useful for attempting to create files and reporting if the operation was successful, however, createNewFile() does not write anything to files it creates. In fact, if you use createNewFile() to create a .txt file and then open the file, the file will be blank. -

    - -
    - -
    \ No newline at end of file From 01246fbdc5aa3d407b15d33db29f28940539fa1d Mon Sep 17 00:00:00 2001 From: Elijah Babayemi Date: Wed, 30 Jul 2025 09:22:57 -0400 Subject: [PATCH 012/357] Added summary and review questions for chapter 2 --- source/ch_2_whylearnjava.ptx | 91 ++++++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) diff --git a/source/ch_2_whylearnjava.ptx b/source/ch_2_whylearnjava.ptx index 9d95fc5..d9a95ac 100644 --- a/source/ch_2_whylearnjava.ptx +++ b/source/ch_2_whylearnjava.ptx @@ -91,4 +91,95 @@

    +
    + Summary & Reading Questions +

      +
    1. +

      Learning multiple programming languages helps programmers adapt to different styles and environments.

      +
    2. +
    3. +

      Python is a dynamic scripting language that is beginner-friendly, but it is less strict with types and generally slower than compiled languages.

      +
    4. +
    5. +

      Languages like Java and C++ are statically typed and offer better performance and maintainability for large-scale projects.

      +
    6. +
    7. +

      Java has a simpler syntax than C++ and includes automatic garbage collection, which reduces the complexity of memory management.

      +
    8. +
    9. +

      Java’s extensive standard library enables the development of sophisticated programs without relying on external dependencies.

      +
    10. +

    + + + +

    Which of the following best describes Python as a programming language?

    +
    + + +

    Statically typed and high-performance

    +

    No. This better describes languages like Java or C++.

    +
    + +

    Dynamically typed and beginner-friendly

    +

    That’s right! Python is dynamically typed and easy for beginners.

    +
    + +

    Industrial strength and verbose

    +

    No. Python is more informal and concise.

    +
    + +

    Memory-managed and pointer-based

    +

    No. That describes lower-level languages like C or C++.

    +
    +
    +
    + + +

    Why is Java a better language for beginners compared to C++?

    +
    + + +

    It requires more manual memory management

    +

    No. Java manages memory automatically.

    +
    + +

    It has a smaller standard library

    +

    No. Java has a very large standard library.

    +
    + +

    It avoids complex syntax and has automatic garbage collection

    +

    Correct! These features make Java easier for beginners.

    +
    + +

    It supports operator overloading

    +

    No. That's a C++ feature and it adds complexity.

    +
    +
    +
    + + +

    What is a major benefit of learning multiple programming languages?

    +
    + + +

    You will only need to code in Python

    +

    No. Relying on just one language is limiting.

    +
    + +

    You will avoid working on large projects

    +

    No. That’s not related to learning multiple languages.

    +
    + +

    You gain exposure to different language features and paradigms

    +

    Great choice! This helps you become a more adaptable programmer.

    +
    + +

    You will never have to learn new libraries

    +

    No. Libraries are often language-specific and still need to be learned.

    +
    +
    +
    +
    +
    \ No newline at end of file From c00c8aa58f74801f51b0761a7ce43ea2b7e40a35 Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Wed, 30 Jul 2025 11:13:38 -0400 Subject: [PATCH 013/357] Added a section on deleting files uing Java. --- source/ch_x_filehandling.ptx | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/source/ch_x_filehandling.ptx b/source/ch_x_filehandling.ptx index 689bda7..59eac25 100644 --- a/source/ch_x_filehandling.ptx +++ b/source/ch_x_filehandling.ptx @@ -501,7 +501,35 @@

    In this code, we simply print the contents of the file to the console, but it is easy to imagine how the data variable could be used in conjunction with the write class created in the previous section to create a copy of myfile.txt.

    + + +
    + Deleting Files + +

    + Finally, we will take a look at using Java to delete files. This one is pretty straight-forward and follows the structure used to create files. This time, however, try/catch blocks are not needed for the program to compile. We will call this class DeleteFile. The completed code should look something like this: +

    + + + import java.io.File; + + public class DeleteFile { + public static void main(String[] args) { + File myFile = new File("myfile.txt"); + if (myFile.delete()) { + System.out.println("Deleted " + myFile.getName()); + } else { + System.out.println("File could not be deleted."); + } + } + } + + + +

    + This is almost identical to the code within the try block of the CreateFile class we made earlier. The main difference is the use of the delete() method. This method will delete any file with the name provided when creating the myFile object. Similarly to the createNewFile() method, it will return true if the file existed and could be deleted, and false if the file could not be deleted. +

    \ No newline at end of file From 5711d752aa96cb705a723a70ade7d57c9264de8c Mon Sep 17 00:00:00 2001 From: Tristan-Raz Date: Wed, 30 Jul 2025 11:46:22 -0400 Subject: [PATCH 014/357] Fixes syntax errors and explains a bit more. Still keeps one line loops/conditionals --- source/ap-java-cheatsheet.ptx | 51 +++++++++++++---------------------- 1 file changed, 19 insertions(+), 32 deletions(-) diff --git a/source/ap-java-cheatsheet.ptx b/source/ap-java-cheatsheet.ptx index f628368..a0041b6 100644 --- a/source/ap-java-cheatsheet.ptx +++ b/source/ap-java-cheatsheet.ptx @@ -12,6 +12,7 @@ + Function/Method Equivalents: Python to Java Python Function @@ -25,8 +26,8 @@ len() - array.length - Returns the length of an array. + array.length or list.size() + Returns the length of an array or size of a list. range() @@ -56,7 +57,7 @@ list.pop() ArrayList.remove(index) - Removes and returns the element at the specified index. + Removes and returns the element at an index. Assign the return value to use it. list.sort() @@ -106,6 +107,7 @@
    + Operator Equivalents and Usage Operator Type @@ -121,9 +123,9 @@ Arithmetic - // - Floor Division (rounds down) - 7 // 2 → 3 + / + Integer Division (truncates toward zero) + 7 / 2 → 3 Arithmetic @@ -133,14 +135,14 @@ Arithmetic - ** + Math.pow() Exponent - 2 ** 3 → 8 + Math.pow(2, 3) → 8.0 Comparison ==, != - Equal to, Not equal to + Equal to, Not equal to (use .equals() for objects) x == y @@ -151,9 +153,9 @@ Logical - and, or, not + &&, ||, ! Logical AND, OR, NOT - x > 1 and y < 10 + x > 1 && y < 10 Assignment @@ -161,18 +163,6 @@ Adds, subtracts, multiplies, or divides and assigns x += 1 - - Bitwise - <<, >>, >>> - Left, right, and unsigned right shift. - x << 2 - - - Ternary - ? : - One-line if-else expression. - condition ? val1 : val2 -
    @@ -190,38 +180,35 @@
  • - The Ternary Operator provides a compact, one-line if-else statement. For instance, result = "Pass" if score >= 60 else "Fail" is much shorter than a full if-else block. + The Ternary Operator provides a compact, one-line if-else statement. For instance, String result = (score >= 60) ? "Pass" : "Fail"; is much shorter than a full if-else block.

  • - List Comprehension offers a concise and readable way to create new lists based on existing sequences. Instead of a multi-line loop, you can write squares = [i**2 for i in range(10)] to generate a list of squares. + Java's Stream API is the idiomatic alternative to Python's List Comprehension. Instead of a multi-line loop, you can write List<Integer> squares = IntStream.range(0, 10).map(i -> i * i).boxed().collect(Collectors.toList()); to generate a list of squares.

  • - F-Strings (Formatted String Literals) simplify embedding expressions and variables directly inside strings. This makes code like print(f"Hello, {name}!") much cleaner than traditional string concatenation. + Java uses methods like String.format() or System.out.printf() for embedding expressions in strings, similar to Python's F-Strings. This makes code like String message = String.format("Hello, %s!", name); cleaner than traditional string concatenation.

  • - Tuple and List Unpacking allows for assigning elements of a sequence to multiple variables in a single line, such as name, age = ["Alice", 30]. This also enables simple variable swapping with a, b = b, a. + Java does not have a direct equivalent to Python's tuple and list unpacking. Assignment must be done one variable at a time, such as String name = "Alice"; int age = 30;.

  • - Chained Comparisons make range checks more intuitive and mathematical. You can write if 18 <= age < 65: instead of the more verbose if age >= 18 and age < 65:. + Java does not support chained comparisons. Range checks must use logical operators, such as if (age >= 18 && age < 65).

  • - - - - + \ No newline at end of file From 6311e142a99128667bbc141c45024852a1c5faba Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Wed, 30 Jul 2025 14:37:34 -0400 Subject: [PATCH 015/357] The chapter is in a finished state at this point, but will be a draft pull request. Details will be given in the draft PR. --- source/ch_x_filehandling.ptx | 239 +++++++++++++++++++++++++++-------- 1 file changed, 188 insertions(+), 51 deletions(-) diff --git a/source/ch_x_filehandling.ptx b/source/ch_x_filehandling.ptx index 59eac25..17bedca 100644 --- a/source/ch_x_filehandling.ptx +++ b/source/ch_x_filehandling.ptx @@ -6,7 +6,7 @@

    - File handling is an integral part of programming. Most programming languages have the ability to read from, write to, create, delete, move, and copy files. + File handling is an integral part of programming. Most programming languages have the ability to read from, write to, create, delete, move, and copy files.

    @@ -15,7 +15,7 @@ Class Imports

    - Before any code can be written to handle files, the proper classes must be imported. Java includes a class called File in the io library. The class can be imported with the following line. Be sure to capitalize File. + Java has several libraries included for file handling, though, they must be imported. Java includes a class called File in the io library. The class can be imported with the following line. Be sure to capitalize File.

    @@ -25,7 +25,7 @@

    - The Scanner class from the util library will need to be imported if there is any need for the program being written to read a file. It should be noted that this library is unnecessary if the program will not be reading any data from a file. + The Scanner class from the util library will need to be imported if there is any need for a program to read a file. It should be noted that this library is unnecessary if the program will not be reading any data from a file.

    @@ -45,7 +45,7 @@

    - Finally, these last two classes provide error handling and must be used in tandem with the File class. IOException handles file creation and writing errors, while FileNotFoundException handles errors when trying to read files that do not exist. + Finally, these last two classes provide error handling and must be used in tandem with the File class when reading from or writing to files. IOException handles file creation and writing errors, while FileNotFoundException handles errors when trying to read files.

    @@ -66,7 +66,7 @@ Creating Files

    - Before we can write code that creates a file, we must first import the necessary classes mentioned in the previous section (Scanner and FileWriter is not needed for a class that creates files and does nothing else) and create a class. We will call this class CreateFile(). + Before we can write code that creates a file, we must first import the necessary classes mentioned in the previous section (Scanner and FileWriter are not needed for a class that only creates files) and create a class. We will call this class CreateFile.

    @@ -92,31 +92,61 @@ -
    -            Note: myFile is the name of the object within the program, while "myfile.txt" 
    -            is the name of the file itself and will be the file name if the operation 
    -            that creates the file is successful.
    -        
    + +

    + myFile is the name of the object within the program, while "myfile.txt" is the name of the file itself and will be the file name if the operation that creates the file is successful. +

    +

    Now that we have created a new File object, we can create a file using the createNewFile() method from the File class. While the previous line of code creates an object within the program for the file, this method actually does the work of creating a file and saving it in the current working directory. This method returns a boolean value. If the method returns true, the file was successfully created. If the method returns false, there is already a file using the chosen file name. We can use this method's possible return values in tandem with an if/else selection to determine if the file was created, or if a file with that file name already exists in the directory.

    +

    + First, lets look at the equivalent Python code: +

    + + + + import os + + filename = "myfile.txt" + + if not os.path.exists(filename): + with open(filename, 'x') as f: + pass + print(f"The file {filename} was created successfully.") + else: + print(f"The file {filename} already exists.") + + + +

    + Now, let's look at Java code that accomplishes the same task: +

    + - if (myFile.createNewFile()) { // If the file was created successfully - System.out.println("The file " + myFile.getName() + " was created sucessfully."); - } else { // If a file with the file name chosen already exists - System.out.println("The file " + myFile.getName() + " already exists."); + import java.io.File; + import java.io.IOException; + + public class CreateFile { + public static void main(String[] args) { + if (myFile.createNewFile()) { // If the file was created successfully + System.out.println("The file " + myFile.getName() + " was created sucessfully."); + } else { // If a file with the file name chosen already exists + System.out.println("The file " + myFile.getName() + " already exists."); + } + } } -
    -            Note: You may have noticed the use of another method from the File class; 
    -            getName(). This method returns a string containing the name of 
    -            the file. 
    -        
    + +

    + You may have noticed the use of another method from the File class; getName(). This method returns a string containing the name of the file. +

    +

    The code may seem complete at this point, but if you remember from the previous section, error handling using the IOException is required for program to compile. Let's utilize best practices and add in try/catch blocks to handle exceptions thrown by the IOException class. @@ -137,22 +167,52 @@ -

    -            Note: The IOException e part in the parenthesis next to the catch. This creates a variable called e that refers to an IOException object. In other words, e refers to the error created if the try block fails. The line e.printStackTrace(); prints the stack trace to the console. This is what the console may output if the program tries to create a file, but is blocked by the Operating System due to insufficient permissions:
    -        
    + +

    + The IOException e part in the parenthesis next to the catch. This creates a variable called e that refers to an IOException object. In other words, e refers to the error created if the try block fails. The line e.printStackTrace(); prints the stack trace to the console. This is what the console may output if the program tries to create a file, but is blocked by the Operating System due to insufficient permissions: +

    +
    - + An error occurred. java.io.IOException: Permission denied at java.base/java.io.File.createNewFile(File.java:1040) at CreateFile.main(CreateFile.java:7) - + + + +

    + At this point, the program will function correctly. Let's add the try/catch blocks to the foundational code written before to get a complete program. +

    + +

    + First, the equivalent Python code: +

    + + + + import os + + filename = "myfile.txt" + + try: + if not os.path.exists(filename): + with open(filename, 'x') as f: + pass # Create the file without writing anything + print(f"The file {filename} was created successfully.") + else: + print(f"The file {filename} already exists.") + except OSError as e: + print("An error occurred.") + import traceback + traceback.print_exc() +

    - At this point, the program will function correctly. Let's add the try/catch blocks to the foundational code written before to get a complete program: + Now, the completed Java code:

    @@ -212,7 +272,7 @@ Writing to Files

    - The createNewFile() method is useful for attempting to create files and reporting if the operation was successful, however, createNewFile() does not write anything to files it creates. In fact, if you use createNewFile() to create a .txt file and then open the file, the file will be blank. + The createNewFile() method is useful for attempting to create files and reporting if the operation was successful, however, createNewFile() does not write anything to files it creates. In fact, if you use createNewFile() to create a .txt file and then open the file, the file will be blank.

    @@ -238,7 +298,7 @@ - FileWriter myWriter = new FileWriter("myFile.txt"); + FileWriter myWriter = new FileWriter("myfile.txt"); @@ -253,18 +313,37 @@ -

    -            Note: the close() function being used after writing to a file. This is a very important step and must be included when working with files! Without using this method, the file may remain active in system resources even after the program is closed. This can lead file corruption or other terrible problems that are best avoided!
    -        
    + +

    + You may have noticed the close() function being used after writing to the file. This is a very important step and must be included when working with files! Without using this method, the file may remain active in system resources even after the program is closed. This can lead file corruption or other terrible problems that are best avoided! +

    +

    - Next, we will again add the required try/catch blocks utilizing the IOException class. Just like with creating files, the program will not compile without these crucial additions! We will also add some print statements to inform us of the success of the file write operation: + Next, we will again add the required try/catch blocks utilizing the IOException class. Just like with creating files, the program will not compile without these crucial additions! We will also add some print statements to inform us of the success of the file write operation. First, a Python example: +

    + + + + try: + with open("myfile.txt", "w") as my_writer: + my_writer.write("File successfully updated!") + print("File successfully written to.") + except OSError as e: + print("An error occurred.") + import traceback + traceback.print_exc() + + + +

    + And the equivalent Java code:

    try { - FileWriter myWriter = new FileWriter("myFile.txt"); + FileWriter myWriter = new FileWriter("myfile.txt"); myWriter.write("File successfully updated!"); myWriter.close(); System.out.println("File successfully written to."); @@ -276,7 +355,24 @@

    - And that's it! We will add our code to the foundational code for a complete program. + And that's it! We will add our code to the foundational code for a complete program. First, an example of equivalent Python code: +

    + + + + try: + with open("myfile.txt", "w") as my_writer: + my_writer.write("File successfully updated!") + print("File successfully written to.") + except OSError as e: + print("An error occurred.") + import traceback + traceback.print_exc() + + + +

    + The completed Java code:

    @@ -287,7 +383,7 @@ public class WriteFile { public static void main(String[] args) { try { - FileWriter myWriter = new FileWriter("myFile.txt"); + FileWriter myWriter = new FileWriter("myfile.txt"); myWriter.write("File successfully updated!"); myWriter.close(); System.out.println("File successfully written to."); @@ -301,11 +397,17 @@

    - Files in a specific directory can be written to using the same technique as the last section in which file paths are specified, with two back slashes used in Windows environments. Something to note is, if a file does not already exist (for example, myfile.txt does not exist), the write() method will create the file. Despite this, it is still a good idea to create separate methods or classes for creating and writing to files. Not only is it good practice to ensure methods only accomplish one thing, but the createNewFile() method avoids overwriting files that already exist. Imagine a file with the name myfile.txt already exists and contains important information. Attempting to create a file using the write() method will delete that data forever. -

    + Files in a specific directory can be written to using the same technique as the last section in which file paths are specified, with two back slashes used in Windows environments. +

    + + +

    + If a file does not already exist (for example, myfile.txt does not exist), the write() method will create the file. Despite this, it is still a good idea to create separate methods or classes for creating and writing to files. Not only is it good practice to ensure methods only accomplish one thing, but the createNewFile() method avoids overwriting files that already exist. Imagine a file with the name myfile.txt already exists and contains important information. Attempting to create a file using the write() method will delete that data forever. +

    +

    - Speaking of overwriting data, it is important to know that the write() method will overwrite any text if there is already text in myfile.txt. What if we want to append text to the end of any text already in myfile.txt? To accomplish this, we can pass a boolean argument along with the file name when creating a new data argument: + Speaking of overwriting data, what if we want to append text to the end of any text already in myfile.txt? To accomplish this, we can pass a boolean argument along with the file name when creating a new data argument:

    @@ -326,7 +428,7 @@ public class WriteFile { public static void main(String[] args) { try { - FileWriter myWriter = new FileWriter("myFile.txt", true); // true enables append mode + FileWriter myWriter = new FileWriter("myfile.txt", true); // true enables append mode myWriter.write("File successfully updated!"); myWriter.close(); System.out.println("File successfully written to."); @@ -361,7 +463,7 @@

    - This works fine if you want all text to be on the same line, but what if we want each additional write to appear on a new line? The first answer may be to use the \n newline character: + This works fine if you want all text to be on the same line, but what if we want each additional write to appear on a new line? The first solution may be to use the \n newline character:

    @@ -383,14 +485,13 @@

    - Running either variation used for adding new lines twice will result in the following contents in myfile.txt. Notice that an extra blank line that will always appear at the bottom of the text: + Running either variation used for adding new lines twice will result in the following contents in myfile.txt:

    File successfully updated! File successfully updated! - @@ -417,7 +518,7 @@

    - We will then create a new File exactly the same as the one from the section on creating files. Additionally, we will create a Scanner object. The Scanner object is the object that does the file reading. We will call this scanner fileReader: + We will then create a new File object exactly the same as the one from the section on creating files. Additionally, we will create a Scanner object. The Scanner object is the object that does the file reading. We will call this scanner fileReader:

    @@ -427,12 +528,26 @@
    -
    -            Note: The myFile File object we created on the first line was passed to the Scanner object created on the second line.
    -        
    + +

    + The myFile File object we created on the first line was passed to the Scanner object created on the second line. +

    +
    + +

    + The next lines consist of a while loop that reads each line of the file passed to the Scanner object and reads them. First, a Python code example. A for loop is used instead in the Python example: +

    + + + + with open("filename.txt", "r") as file_reader: + for line in file_reader: + print(line.strip()) + +

    - The next lines consist of a while loop that reads each line of the file passed to the Scanner object and reads them: + The equivalent Java code:

    @@ -446,7 +561,7 @@

    - The hasNextLine() method checks checks if the line below the current line has any data. This will evaluate to true even if the next line only contains blank spaces. Within the while loop, a string variable called data is used to store the current line that the Scanner object is pointing to. The nextLine() method does two things. Firstly, it reads the current line. Secondly, it moves the Scanner's position to the next line. In other words, for each iteration of the while loop, each line in the text is read, stored temporarily in the data variable, and printed to the console. Finally, the close() method accomplishes and holds the same importance as the same method discussed in the section on writing to files. + The hasNextLine() method checks checks if the line below the current line has any data. This will evaluate to true even if the next line only contains blank spaces. Within the while loop, a string variable called data is used to store the current line that the Scanner object is pointing to. The nextLine() method does two things. Firstly, it returns the current line when called. Secondly, it moves the Scanner's position to the next line. In other words, for each iteration of the while loop, each line in the text is read, stored temporarily in the data variable, and printed to the console. Finally, the close() method accomplishes and holds the same importance as in the section on writing to files.

    @@ -464,12 +579,34 @@ + +

    + Pay close attention to the details of this code. data must be declared using an empty string or it may not work correctly within the while loop. Additionally, care must be given to reassigning data in the while loop. data is concatinated (to ensure all lines are included) with fileReader.nextLine() and a new line operator. Each step of this process ensures what is stored in data matches exactly what is in myfile.txt. +

    + +

    - Pay close attention to the details of this code. data must be declared using an empty string or it may not work correctly within the while loop. Additionally, care must be given to reassigning data in the while loop. data is concatinated (to ensure all lines are included) with fileReader.nextLine() and a lineSeparator. Each step of this process ensures what is stored in data matches exactly what is in myfile.txt. + Using the second method of storing all file contents to one file, the resulting full code including try/catch blocks (this time using FileNotFoundException instead of IOException) will look something like this. First, the Python code:

    + + + try: + with open("myfile.txt", "r") as file_reader: + data = "" + for line in file_reader: + data += line # line already includes the newline character + print(data) + except FileNotFoundError as e: + print("An error occurred.") + import traceback + traceback.print_exc() + + + +

    - Using the second method of storing all file contents to one file, the resulting full code including try/catch blocks (this time using FileNotFoundException instead of IOException) will look like this: + And the Java equivalent:

    @@ -507,7 +644,7 @@ Deleting Files

    - Finally, we will take a look at using Java to delete files. This one is pretty straight-forward and follows the structure used to create files. This time, however, try/catch blocks are not needed for the program to compile. We will call this class DeleteFile. The completed code should look something like this: + Finally, we will take a look at using Java to delete files. This one is pretty straight-forward and follows the structure used to create files. This time, however, try/catch blocks are not needed for the program to compile. We will call this class DeleteFile. The completed code should look something like this.

    @@ -528,7 +665,7 @@

    - This is almost identical to the code within the try block of the CreateFile class we made earlier. The main difference is the use of the delete() method. This method will delete any file with the name provided when creating the myFile object. Similarly to the createNewFile() method, it will return true if the file existed and could be deleted, and false if the file could not be deleted. + This is almost identical to the code within the try block of the CreateFile class we made earlier. The main difference is the use of the delete() method. This method will delete any file with the name provided when creating the myFile object. Similar to the createNewFile() method, it will return true if the file existed and could be deleted, and false if the file could not be deleted.

    From 3e338631973f81978b1fe766a884ce380e172cb8 Mon Sep 17 00:00:00 2001 From: austing767 Date: Wed, 30 Jul 2025 14:55:43 -0500 Subject: [PATCH 016/357] Added the python code and note about code, rules for java swtich, partial issue #60 --- source/ch_5_conditionals.ptx | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/source/ch_5_conditionals.ptx b/source/ch_5_conditionals.ptx index 156049f..fd908ed 100644 --- a/source/ch_5_conditionals.ptx +++ b/source/ch_5_conditionals.ptx @@ -138,6 +138,7 @@ We can get even closer to the elif statement by taking advantage of the Java rul

    + public class ElseIf { @@ -165,6 +166,38 @@ public class ElseIf { Java also supports a switch statement that acts something like the elif statement of Python under certain conditions. To write the grade program using a switch statement we would use the following:

    + +

    + Depending on your knowledge and experience with Python you may already be familar and questioning why we are not using the match statement in our Python examples.The answer is that Unforunately, this book runs its active code examples on Python 3.7, which does not support the match statement. The match statement was introduced in Python 3.10. Below is an example of the match statement simmilar to our grade method. +

    + + Match Case example + + grade = 100 // 10 + def grading(grade): + match grade: + case 10 | 9: + return 'A' + case 8: + return 'B' + case 7: + return 'C' + case 6: + return 'D' + case _: + return 'F' + print(grading(grade)) + + +
    + +

    + The switch statement in Java provides a clean and efficient alternative to chaining multiple if-else conditions, especially when comparing a single variable against several constant values. It supports a variety of data types, including primitive types (byte, short, char, int), their wrapper classes, enumerations, and String (introduced in Java 7). Each case within a switch must be defined using a constant expression, and duplicate case values are not permitted. By default, control flow "falls through" from one case to the next unless a break, return, or throw statement is used to terminate execution. Java 14 introduced switch expressions, enhancing functionality by allowing the switch to return values and eliminating fall-through via the -> arrow syntax. These expressions can even use yield within code blocks for more complex evaluations. It’s important to note that traditional switch statements do not support null values and will throw a NullPointerException if evaluated with null. As the language evolves, newer versions of Java continue to extend switch capabilities with features like pattern matching and enhanced type handling, making it a more powerful and expressive tool for decision-making in Java programs. +

    + + + + From 945cc617fb6ba2c9454058981e38e891ae82fd5c Mon Sep 17 00:00:00 2001 From: Austing767 Date: Thu, 31 Jul 2025 09:36:35 -0500 Subject: [PATCH 017/357] Added table in binary, added example and explenation, fixes issue #60 --- source/ch_5_conditionals.ptx | 68 +++++++++++++++++++++++++++++++++++- 1 file changed, 67 insertions(+), 1 deletion(-) diff --git a/source/ch_5_conditionals.ptx b/source/ch_5_conditionals.ptx index fd908ed..c6edb1a 100644 --- a/source/ch_5_conditionals.ptx +++ b/source/ch_5_conditionals.ptx @@ -239,8 +239,74 @@ The switch statement is not used very often, and I recommend you do not u The conditionals used in the if statement can be boolean variables, simple comparisons, and compound boolean expressions.

    +

    +Java also supports the boolean expression using the ternary operator +condition ? trueValue : falseValue. This operator tests a condition as part +of an assignment statement. The following table summarizes how this works: +

    + + + Ternary Operator in Java + + + Component + Description + + + condition + The boolean expression that is evaluated (e.g., a % 2 == 0). + + + ? + This is the ternary operator that separates the condition from the trueValue. + + + trueValue + The value assigned if the condition is true (e.g., a * a). + + + : + This is the ternary operator that separates the trueValue from the falseValue. + + + falseValue + The value assigned if the condition is false (e.g., 3 * x - 1). + + + Example Usage + a = a % 2 == 0 ? a * a : 3 * x - 1 + + + Equivalent if-else Code + Can also be written with a regular if-else statement, but the ternary form is more concise. + + +
    + +

    +Using this operator can make code shorter and more readable in cases where a simple conditional assignment is needed. +

    + + + class Main { + public static void main(String[] args) { + int a = 4; + int x = 2; + + // Using the ternary operator + a = (a % 2 == 0) ? a * a : 3 * x - 1; + + System.out.println("Result: " + a); + } + } + + + +

    -Java also supports the boolean expression. condition ? trueValue : falseValue This expression can be used to test a condition as part of an assignment statement. For example a = a % 2 == 0 ? a*a : 3*x -1 In the previous assignment statement the expression a%2 ==0 is first checked. If it is true then a is assigned the value a * a if it is false then a is assigned the value of 3*x-1. Of course all of this could have been accomplished using a regular if else statement, but sometimes the convenience of a single statement is too much to resist. + In this example we are using this ternary operator to assign a value to a based on wether a is even or odd. If a is even, it will be squared; if odd, it will be instead be calculated as 3 * x - 1. This is a concise way to write conditional assignments in Java. However, it should be used reasonably, as it can make code less readable if overused or used in complex expressions.

    + + \ No newline at end of file From 9b555983ce8e22bf65b7a2dd39b2c131a7634a8b Mon Sep 17 00:00:00 2001 From: Austing767 Date: Thu, 31 Jul 2025 09:39:21 -0500 Subject: [PATCH 018/357] spelling correction --- source/ch_5_conditionals.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch_5_conditionals.ptx b/source/ch_5_conditionals.ptx index c6edb1a..1f2b1df 100644 --- a/source/ch_5_conditionals.ptx +++ b/source/ch_5_conditionals.ptx @@ -304,7 +304,7 @@ Using this operator can make code shorter and more readable in cases where a sim

    - In this example we are using this ternary operator to assign a value to a based on wether a is even or odd. If a is even, it will be squared; if odd, it will be instead be calculated as 3 * x - 1. This is a concise way to write conditional assignments in Java. However, it should be used reasonably, as it can make code less readable if overused or used in complex expressions. + In this example we are using this ternary operator to assign a value to a based on whether a is even or odd. If a is even, it will be squared; if odd, it will be instead be calculated as 3 * x - 1. This is a concise way to write conditional assignments in Java. However, it should be used reasonably, as it can make code less readable if overused or used in complex expressions.

    From 0e6b375210eaa49b1335f350b50c4fd08e0241b8 Mon Sep 17 00:00:00 2001 From: Tristan-Raz Date: Thu, 31 Jul 2025 10:45:15 -0400 Subject: [PATCH 019/357] Adds code blocks, formats, and fixes issue #42 --- source/ap-java-cheatsheet.ptx | 125 ++++++++++++++++------------------ 1 file changed, 58 insertions(+), 67 deletions(-) diff --git a/source/ap-java-cheatsheet.ptx b/source/ap-java-cheatsheet.ptx index a0041b6..46f925f 100644 --- a/source/ap-java-cheatsheet.ptx +++ b/source/ap-java-cheatsheet.ptx @@ -20,88 +20,88 @@ Description - print() - System.out.println() + print() + System.out.println() Prints output to the console. - len() - array.length or list.size() + len() + array.length or list.size() Returns the length of an array or size of a list. - range() - for (int i = 0; i < n; i++) + range() + for (int i = 0; i < n; i++) Used in loops to iterate a specific number of times. - str() - String.valueOf() + str() + String.valueOf() Converts an object to a string. - int() - Integer.parseInt() + int() + Integer.parseInt() Converts a string to an integer. - float() - Float.parseFloat() + float() + Float.parseFloat() Converts a string to a float. - list.append() - ArrayList.add() + list.append() + ArrayList.add() Adds an element to the end of a list. - list.pop() - ArrayList.remove(index) - Removes and returns the element at an index. Assign the return value to use it. + list.pop() + ArrayList.remove(index) + Removes and assign the return value to use it. - list.sort() - Collections.sort(list) + list.sort() + Collections.sort(list) Sorts a list in ascending order. - list.reverse() - Collections.reverse(list) + list.reverse() + Collections.reverse(list) Reverses the order of elements in a list. - dict.get() - Map.get(key) + dict.get() + Map.get(key) Retrieves the value associated with a key in a map. - dict.keys() - Map.keySet() + dict.keys() + Map.keySet() Returns a set of keys in a map. - dict.values() - Map.values() + dict.values() + Map.values() Returns a collection of values in a map. - dict.items() - Map.entrySet() + dict.items() + Map.entrySet() Returns a set of key-value pairs in a map. - input() - Scanner.nextLine() + input() + Scanner.nextLine() Reads a line of input from the console. - open() - FileReader, BufferedReader + open() + FileReader, BufferedReader Used to read from files. - enumerate() - for (int i = 0; i < list.size(); i++) { ... } + enumerate() + for (int i = 0; i < list.size(); i++) { ... } Used to iterate over a list with an index. @@ -117,51 +117,51 @@ Arithmetic - +, -, *, / + +, -, *, / Addition, Subtraction, Multiplication, Division - 5 + 2 + 5 + 2 Arithmetic - / + / Integer Division (truncates toward zero) - 7 / 2 → 3 + 7 / 2 → 3 Arithmetic - % + % Modulus (remainder) - 7 % 2 → 1 + 7 % 2 → 1 Arithmetic - Math.pow() + Math.pow() Exponent - Math.pow(2, 3) → 8.0 + Math.pow(2, 3) → 8.0 Comparison - ==, != - Equal to, Not equal to (use .equals() for objects) - x == y + ==, != + Equal to, Not equal to (use .equals() for objects) + x == y Comparison - >, <, >=, <= + >, <, >=, <= Greater/Less than, or equal to - x > 5 + x > 5 Logical - &&, ||, ! + &&, ||, ! Logical AND, OR, NOT - x > 1 && y < 10 + x > 1 && y < 10 Assignment - +=, -=, *=, /= + +=, -=, *=, /= Adds, subtracts, multiplies, or divides and assigns - x += 1 + x += 1 @@ -170,41 +170,32 @@
    • - Short-Circuiting: The logical operators && (AND) and || (OR) are efficient. They stop evaluating as soon as the outcome is known. For example, in if (user != null && user.isAdmin()), the code will not attempt to call .isAdmin() if user is null, preventing an error. -

      -
    • -
    • -

      - Streams: Java's Stream API provides a powerful way to process collections of objects. A stream can be used to filter, map, and reduce data in a sequence of steps, similar to Python's list comprehensions but more powerful. + Ternary Operator: Provides a compact, one-line if-else statement. For instance, String result = (score >= 60) ? "Pass" : "Fail"; is much shorter than a full if-else block.

    • - The Ternary Operator provides a compact, one-line if-else statement. For instance, String result = (score >= 60) ? "Pass" : "Fail"; is much shorter than a full if-else block. + No Chained Comparisons: Java does not support chained comparisons. Range checks must use logical operators, such as if (age >= 18 && age < 65). In Python, this could be written as if 18 <= age < 65:.

    • -
    • - Java's Stream API is the idiomatic alternative to Python's List Comprehension. Instead of a multi-line loop, you can write List<Integer> squares = IntStream.range(0, 10).map(i -> i * i).boxed().collect(Collectors.toList()); to generate a list of squares. + String Formatting: Java uses methods like String.format() or System.out.printf() for embedding expressions in strings, similar to Python's F-Strings. For example, String message = String.format("Hello, %s!", name); is cleaner than traditional string concatenation.

    • -
    • - Java uses methods like String.format() or System.out.printf() for embedding expressions in strings, similar to Python's F-Strings. This makes code like String message = String.format("Hello, %s!", name); cleaner than traditional string concatenation. + No Tuple or List Unpacking: Java does not have a direct equivalent to Python's tuple and list unpacking. Assignment must be done one variable at a time, such as String name = "Alice"; int age = 30;.

    • -
    • - Java does not have a direct equivalent to Python's tuple and list unpacking. Assignment must be done one variable at a time, such as String name = "Alice"; int age = 30;. + Short-Circuiting: The logical operators && (AND) and || (OR) are efficient. They stop evaluating as soon as the outcome is known. For example, in if (user != null && user.isAdmin()), the code will not attempt to call .isAdmin() if user is null, preventing an error.

    • -
    • - Java does not support chained comparisons. Range checks must use logical operators, such as if (age >= 18 && age < 65). + Streams API: Java's Stream API is the idiomatic alternative to Python's List Comprehensions. It can be used to filter, map, and reduce data in a sequence of steps. For example, to generate a list of squares, instead of a multi-line loop, you can write List<Integer> squares = IntStream.range(0, 10).map(i -> i * i).boxed().collect(Collectors.toList());.

    From 9360bda0a2c4a3f6061a47a50b6b6a218a62096d Mon Sep 17 00:00:00 2001 From: Elijah Babayemi Date: Thu, 31 Jul 2025 12:23:25 -0400 Subject: [PATCH 020/357] I made the answers for question 3 for the summary and reading questions section harder --- source/ch_2_whylearnjava.ptx | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/source/ch_2_whylearnjava.ptx b/source/ch_2_whylearnjava.ptx index 2aa3e1c..818117f 100644 --- a/source/ch_2_whylearnjava.ptx +++ b/source/ch_2_whylearnjava.ptx @@ -167,24 +167,24 @@

    What is a major benefit of learning multiple programming languages?

    - - -

    You will only need to code in Python

    -

    No. Relying on just one language is limiting.

    -
    - -

    You will avoid working on large projects

    -

    No. That’s not related to learning multiple languages.

    -
    - -

    You gain exposure to different language features and paradigms

    -

    Great choice! This helps you become a more adaptable programmer.

    -
    - -

    You will never have to learn new libraries

    -

    No. Libraries are often language-specific and still need to be learned.

    -
    -
    + + +

    You can standardize all projects using one universal syntax

    +

    No. Each language has its own syntax and is suited for different tasks.

    +
    + +

    You will minimize runtime errors across all platforms

    +

    No. Runtime errors depend more on logic and environment than the number of languages you know.

    +
    + +

    You gain exposure to different language features and paradigms

    +

    Great choice! This helps you become a more adaptable and well-rounded programmer.

    +
    + +

    You can bypass the need for understanding compilation and interpretation

    +

    No. Understanding how code is executed remains essential regardless of how many languages you know.

    +
    +
    From 6c501b032de4f4f6ddba7943c4f086fa083c5bd1 Mon Sep 17 00:00:00 2001 From: colin flaherty Date: Thu, 31 Jul 2025 13:31:36 -0400 Subject: [PATCH 021/357] moved paragraph out of the program tag in ch 9.2. --- source/ch_9_commonmistakes.ptx | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/source/ch_9_commonmistakes.ptx b/source/ch_9_commonmistakes.ptx index 12861c1..9b6b6ed 100644 --- a/source/ch_9_commonmistakes.ptx +++ b/source/ch_9_commonmistakes.ptx @@ -40,10 +40,11 @@
    Not importing a class - -

    +

    In Python, many classes are available by default. However, in Java, you must explicitly import most classes from external packages that you want to use.

    + + // Histo.java public class Histo { // Class declaration From f79fe09c03f0cb8a3cc8b43b187294411120aca5 Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Thu, 31 Jul 2025 13:56:03 -0400 Subject: [PATCH 022/357] Made all Python code interactive. --- source/ch_x_filehandling.ptx | 50 ++++++++++++++++++------------------ 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/source/ch_x_filehandling.ptx b/source/ch_x_filehandling.ptx index 17bedca..933b24e 100644 --- a/source/ch_x_filehandling.ptx +++ b/source/ch_x_filehandling.ptx @@ -15,7 +15,7 @@ Class Imports

    - Java has several libraries included for file handling, though, they must be imported. Java includes a class called File in the io library. The class can be imported with the following line. Be sure to capitalize File. + Java has several libraries included for file handling, though, they must be imported. Java includes a class called File in the io library. The class can be imported with the following line. Be sure to capitalize File.

    @@ -25,7 +25,7 @@

    - The Scanner class from the util library will need to be imported if there is any need for a program to read a file. It should be noted that this library is unnecessary if the program will not be reading any data from a file. + The Scanner class from the util library will need to be imported if there is any need for a program to read a file. It should be noted that this library is unnecessary if the program will not be reading any data from a file.

    @@ -35,7 +35,7 @@

    - The FileWriter class can be used to write to files. In the same way that the Scanner class isn't needed unless the program will read from a file, the FileWriter class isn't needed unless the program will write to a file. + The FileWriter class can be used to write to files. In the same way that the Scanner class isn't needed unless the program will read from a file, the FileWriter class isn't needed unless the program will write to a file.

    @@ -45,7 +45,7 @@

    - Finally, these last two classes provide error handling and must be used in tandem with the File class when reading from or writing to files. IOException handles file creation and writing errors, while FileNotFoundException handles errors when trying to read files. + Finally, these last two classes provide error handling and must be used in tandem with the File class when reading from or writing to files. IOException handles file creation and writing errors, while FileNotFoundException handles errors when trying to read files.

    @@ -66,7 +66,7 @@ Creating Files

    - Before we can write code that creates a file, we must first import the necessary classes mentioned in the previous section (Scanner and FileWriter are not needed for a class that only creates files) and create a class. We will call this class CreateFile. + Before we can write code that creates a file, we must first import the necessary classes mentioned in the previous section (Scanner and FileWriter are not needed for a class that only creates files) and create a class. We will call this class CreateFile.

    @@ -83,7 +83,7 @@

    - Next, within the main function, we will create a File object. It is important to create a meaningful name for the File object. We will call ours myFile. + Next, within the main function, we will create a File object. It is important to create a meaningful name for the File object. We will call ours myFile.

    @@ -94,19 +94,19 @@

    - myFile is the name of the object within the program, while "myfile.txt" is the name of the file itself and will be the file name if the operation that creates the file is successful. + myFile is the name of the object within the program, while myfile.txt is the name of the file itself and will be the file name if the operation that creates the file is successful.

    - Now that we have created a new File object, we can create a file using the createNewFile() method from the File class. While the previous line of code creates an object within the program for the file, this method actually does the work of creating a file and saving it in the current working directory. This method returns a boolean value. If the method returns true, the file was successfully created. If the method returns false, there is already a file using the chosen file name. We can use this method's possible return values in tandem with an if/else selection to determine if the file was created, or if a file with that file name already exists in the directory. + Now that we have created a new File object, we can create a file using the createNewFile() method from the File class. While the previous line of code creates an object within the program for the file, this method actually does the work of creating a file and saving it in the current working directory. This method returns a boolean value. If the method returns true, the file was successfully created. If the method returns false, there is already a file using the chosen file name. We can use this method's possible return values in tandem with an if/else selection to determine if the file was created, or if a file with that file name already exists in the directory.

    First, lets look at the equivalent Python code:

    - + import os @@ -149,7 +149,7 @@

    - The code may seem complete at this point, but if you remember from the previous section, error handling using the IOException is required for program to compile. Let's utilize best practices and add in try/catch blocks to handle exceptions thrown by the IOException class. + The code may seem complete at this point, but if you remember from the previous section, error handling using the IOException is required for program to compile. Let's utilize best practices and add in try/catch blocks to handle exceptions thrown by the IOException class.

    @@ -169,7 +169,7 @@

    - The IOException e part in the parenthesis next to the catch. This creates a variable called e that refers to an IOException object. In other words, e refers to the error created if the try block fails. The line e.printStackTrace(); prints the stack trace to the console. This is what the console may output if the program tries to create a file, but is blocked by the Operating System due to insufficient permissions: + The IOException e part in the parenthesis next to the catch. This creates a variable called e that refers to an IOException object. In other words, e refers to the error created if the try block fails. The line e.printStackTrace(); prints the stack trace to the console. This is what the console may output if the program tries to create a file, but is blocked by the operating system due to insufficient permissions:

    @@ -191,7 +191,7 @@ First, the equivalent Python code:

    - + import os @@ -240,7 +240,7 @@

    - You may be wondering: "What if I don't want to create a file in the current working directory?" Good question! In Windows environments, you can specify the file path using two back slashes for each back slash in the file path. For each pair of back slashes, the first backslash acts as an escape character. So, if you want to save a file to this directory: + You may be wondering: "What if I don't want to create a file in the current working directory?" Good question! In Windows environments, you can specify the file path using two back slashes for each back slash in the file path. For each pair of back slashes, the first back slash acts as an escape character. So, if you want to save a file to this directory:

    @@ -272,11 +272,11 @@
             Writing to Files
     
             

    - The createNewFile() method is useful for attempting to create files and reporting if the operation was successful, however, createNewFile() does not write anything to files it creates. In fact, if you use createNewFile() to create a .txt file and then open the file, the file will be blank. + The createNewFile() method is useful for attempting to create files and reporting if the operation was successful, however, createNewFile() does not write anything to files it creates. In fact, if you use createNewFile() to create a .txt file and then open the file, the file will be blank.

    - To write to a file, we will need to create a different class. We will do the same setup as the previous section. First, we will import the classes (File and Scanner are not needed) and create the framework for a class that will write to a file. Let's call this class WriteFile: + To write to a file, we will need to create a different class. We will do the same setup as the previous section. First, we will import the classes (File and Scanner are not needed) and create the framework for a class that will write to a file. Let's call this class WriteFile:

    @@ -293,7 +293,7 @@

    - Next, we will create a FileWriter object. Let's call it myWriter: + Next, we will create a FileWriter object. Let's call it myWriter:

    @@ -303,7 +303,7 @@

    - In this next step, we will use the write() method from the FileWriter class. This Method will take any data within the parenthesis and write that data to the file selected. The write() method takes most standard data types: + In this next step, we will use the write() method from the FileWriter class. This Method will take any data within the parenthesis and write that data to the file selected. The write() method takes most standard data types:

    @@ -320,10 +320,10 @@

    - Next, we will again add the required try/catch blocks utilizing the IOException class. Just like with creating files, the program will not compile without these crucial additions! We will also add some print statements to inform us of the success of the file write operation. First, a Python example: + Next, we will again add the required try/catch blocks utilizing the IOException class. Just like with creating files, the program will not compile without these crucial additions! We will also add some print statements to inform us of the success of the file write operation. First, a Python example:

    - + try: with open("myfile.txt", "w") as my_writer: @@ -358,7 +358,7 @@ And that's it! We will add our code to the foundational code for a complete program. First, an example of equivalent Python code:

    - + try: with open("myfile.txt", "w") as my_writer: @@ -402,12 +402,12 @@

    - If a file does not already exist (for example, myfile.txt does not exist), the write() method will create the file. Despite this, it is still a good idea to create separate methods or classes for creating and writing to files. Not only is it good practice to ensure methods only accomplish one thing, but the createNewFile() method avoids overwriting files that already exist. Imagine a file with the name myfile.txt already exists and contains important information. Attempting to create a file using the write() method will delete that data forever. + If a file does not already exist (for example, myfile.txt does not exist), the write() method will create the file. Despite this, it is still a good idea to create separate methods or classes for creating and writing to files. Not only is it good practice to ensure methods only accomplish one thing, but the createNewFile() method avoids overwriting files that already exist. Imagine a file with the name myfile.txt already exists and contains important information. Attempting to create a file using the write() method will delete that data forever.

    - Speaking of overwriting data, what if we want to append text to the end of any text already in myfile.txt? To accomplish this, we can pass a boolean argument along with the file name when creating a new data argument: + Speaking of overwriting data, what if we want to append text to the end of any text already in myfile.txt? To accomplish this, we can pass a boolean argument along with the file name when creating a new data argument:

    @@ -442,7 +442,7 @@

    - and then run the program twice, the contents of myfile.txt would be: + and then run the program twice, the contents of myfile.txt would be:

    @@ -538,7 +538,7 @@ The next lines consist of a while loop that reads each line of the file passed to the Scanner object and reads them. First, a Python code example. A for loop is used instead in the Python example:

    - + with open("filename.txt", "r") as file_reader: for line in file_reader: @@ -589,7 +589,7 @@ Using the second method of storing all file contents to one file, the resulting full code including try/catch blocks (this time using FileNotFoundException instead of IOException) will look something like this. First, the Python code:

    - + try: with open("myfile.txt", "r") as file_reader: From 92bc13e1fd68ce27c0f398bcbb9d27ec2819eeff Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Thu, 31 Jul 2025 14:42:51 -0400 Subject: [PATCH 023/357] fix typos & add code and idx tags --- source/ch_5_conditionals.ptx | 52 +++++++++++++++++++----------------- 1 file changed, 27 insertions(+), 25 deletions(-) diff --git a/source/ch_5_conditionals.ptx b/source/ch_5_conditionals.ptx index 1f2b1df..6a38a39 100644 --- a/source/ch_5_conditionals.ptx +++ b/source/ch_5_conditionals.ptx @@ -5,16 +5,15 @@ Conditionals
    - -

    + Using the Simple <c>if</c> Statement +

    conditional statements Conditional statements in Python and Java are very similar. In Python we have three patterns:

    - - Simple if +

    - In Python the simple if statement is written as: + In Python the simple if statement is written as:

    @@ -25,7 +24,7 @@ if score >= 90:

    - In Java, this same pattern requires two changes: the condition must be in parentheses (), and the code block must be enclosed in curly braces {}. + In Java, this same pattern requires two changes: the condition must be in parentheses (), and the code block must be enclosed in curly braces {}.

    @@ -41,12 +40,12 @@ if score >= 90:

    Once again you can see that in Java the curly braces define a block rather than indentation. - In Java the parenthesis around the condition are required because it is technically a function that evaluates to True or False. + In Java the parenthesis around the condition are required because it is technically a function that evaluates to True or False.

    - if else + Using the <c>if</c> - <c>else</c> Statement

    The Java equivalent follows the same syntactical rules as before.

    @@ -76,11 +75,11 @@ if score >= 90:
    - elif + Can we use <c>elif</c>? -

    - Java does not have an elif pattern like Python. - In Java you can get the functionality of an elif statement by nesting if and else. +

    elif statement + Java does not have an elif pattern like Python. + In Java you can get the functionality of an elif statement by nesting if and else. Here is a simple example in both Python and Java.

    @@ -102,7 +101,7 @@ else:

    -In Java we have a couple of ways to write this +In Java we have a couple of ways to write this.

    @@ -134,7 +133,7 @@ public class ElseIf {

    -We can get even closer to the elif statement by taking advantage of the Java rule that a single statement does not need to be enclosed in curly braces. Since the if is the only statement used in each else we can get away with the following. +We can get even closer to the elif statement by taking advantage of the Java rule that a single statement does not need to be enclosed in curly braces. Since the if is the only statement used in each else we can get away with the following.

    @@ -160,18 +159,18 @@ public class ElseIf {
    - switch + Using the <c>switch</c> Statement

    -Java also supports a switch statement that acts something like the elif statement of Python under certain conditions. To write the grade program using a switch statement we would use the following: +Java also supports a switch statement that acts something like the elif statement of Python under certain conditions. To write the grade program using a switch statement we would use the following:

    - Depending on your knowledge and experience with Python you may already be familar and questioning why we are not using the match statement in our Python examples.The answer is that Unforunately, this book runs its active code examples on Python 3.7, which does not support the match statement. The match statement was introduced in Python 3.10. Below is an example of the match statement simmilar to our grade method. + Depending on your knowledge and experience with Python you may already be familiar and questioning why we are not using the match statement in our Python examples. The answer is that this book currently runs its active code examples on Python 3.7, which does not support the match statement. The match statement was introduced in Python 3.10. Below is an example of the match statement similar to our grade method.

    - Match Case example + Match Case Example grade = 100 // 10 def grading(grade): @@ -191,8 +190,11 @@ Java also supports a switch statement that acts something like the elif s
    -

    - The switch statement in Java provides a clean and efficient alternative to chaining multiple if-else conditions, especially when comparing a single variable against several constant values. It supports a variety of data types, including primitive types (byte, short, char, int), their wrapper classes, enumerations, and String (introduced in Java 7). Each case within a switch must be defined using a constant expression, and duplicate case values are not permitted. By default, control flow "falls through" from one case to the next unless a break, return, or throw statement is used to terminate execution. Java 14 introduced switch expressions, enhancing functionality by allowing the switch to return values and eliminating fall-through via the -> arrow syntax. These expressions can even use yield within code blocks for more complex evaluations. It’s important to note that traditional switch statements do not support null values and will throw a NullPointerException if evaluated with null. As the language evolves, newer versions of Java continue to extend switch capabilities with features like pattern matching and enhanced type handling, making it a more powerful and expressive tool for decision-making in Java programs. +

    switch + The switch statement in Java provides a clean and efficient alternative to chaining multiple if-else conditions, especially when comparing a single variable against several constant values. It supports a variety of data types, including primitive types (byte, short, char, int), their wrapper classes, enumerations, and String (introduced in Java 7). Each case within a switch must be defined using a constant expression, and duplicate case values are not permitted. By default, control flow "falls through" from one case to the next unless a break, return, or throw statement is used to terminate execution. +

    +

    switch expressions + Java 14 introduced switch expressions, enhancing functionality by allowing the switch to return values and eliminating fall-through via the -> arrow syntax. These expressions can even use yield within code blocks for more complex evaluations. It’s important to note that traditional switch statements do not support null values and will throw a NullPointerException if evaluated with null. As the language evolves, newer versions of Java continue to extend switch capabilities with features like pattern matching and enhanced type handling, making it a more powerful and expressive tool for decision-making in Java programs.

    @@ -228,18 +230,18 @@ public class SwitchUp {

    -The switch statement is not used very often, and I recommend you do not use it! First, it is not as powerful as the else if model because the switch variable can only be compared for equality with an integer or enumerated constant. Second it is very easy to forget to put in the break statement. If the break statement is left out then then the next alternative will be automatically executed. For example if the grade was 95 and the break was omitted from the case 9: alternative then the program would print(out both A and B.) +The switch statement is not used very often, and we recommend you do not use it. First, it is not as powerful as the else if model because the switch variable can only be compared for equality with an integer or enumerated constant. Second, it is very easy to forget to put in the break statement, so it is more error-prone. If the break statement is left out then then the next alternative will be automatically executed. For example, if the grade was 95 and the break was omitted from the case 9: alternative then the program would print(out both A and B.)

    Boolean Operators -

    -The conditionals used in the if statement can be boolean variables, simple comparisons, and compound boolean expressions. +

    Boolean operators +The conditionals used in the if statement can be Boolean variables, simple comparisons, and compound Boolean expressions.

    -

    +

    ternary operator Java also supports the boolean expression using the ternary operator condition ? trueValue : falseValue. This operator tests a condition as part of an assignment statement. The following table summarizes how this works: @@ -254,7 +256,7 @@ of an assignment statement. The following table summarizes how this works: condition - The boolean expression that is evaluated (e.g., a % 2 == 0). + The Boolean expression that is evaluated (e.g., a % 2 == 0). ? From d5f94ab3cf10cec9191f82f4fcb804c1075d54e6 Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Thu, 31 Jul 2025 14:57:04 -0400 Subject: [PATCH 024/357] Fixed line breaks and formatting for chapter 4. --- source/ch_4_javadatatypes.ptx | 30 +++++++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/source/ch_4_javadatatypes.ptx b/source/ch_4_javadatatypes.ptx index fa591b9..7d833fc 100644 --- a/source/ch_4_javadatatypes.ptx +++ b/source/ch_4_javadatatypes.ptx @@ -212,7 +212,20 @@ public class TempConv { For Python programmers, the following error is likely to be even more common. Suppose we forgot the declaration for cel and instead left line 6 blank. What would happen when we type javac TempConv.java on the command line?

    -
    TempConv.java:13: cannot find symbol symbol  : variable cel location: class TempConv cel = (fahr - 32) * 5.0/9.0; ^ TempConv.java:14: cannot find symbol symbol  : variable cel location: class TempConv System.out.println("The temperature in C is: " + cel); ^ 2 errors
    +
    +            TempConv.java:13: cannot find symbol 
    +            symbol  : variable cel 
    +            location: class TempConv 
    +            cel = (fahr - 32) * 5.0/9.0; 
    +            ^ 
    +            TempConv.java:14: cannot find symbol 
    +            symbol  : variable cel 
    +            location: class TempConv 
    +            System.out.println("The temperature in C is: " + cel); 
    +            ^ 
    +            2 errors
    +            
    +

    When you see the first kind of error, where the symbol is on the left side of the equals sign, it usually means that you have not declared the variable. If you have ever tried to use a Python variable that you have not initialized the second error message will be familiar to you. The difference here is that we see the message before we ever try to test our program. More common error messages are discussed in the section .

    @@ -522,7 +535,11 @@ public class Histo { Technically, you don’t have to declare what is going to be in an array list. The compiler will allow you to leave the <``*Type*>`` off the declaration. If you don’t tell Java what kind of object is going to be on the list Java will give you a warning message like this:

    -
    Note: Histo.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details.
    +
    +        Note: Histo.java uses unchecked or unsafe operations. 
    +        Note: Recompile with -Xlint:unchecked for details.
    +        
    +

    Without the <Integer> part of the declaration Java simply assumes that any object can be on the list. However, without resorting to an ugly notation called casting, you cannot do anything with the objects on a list like this! So, if you forget you will surely see more errors later in your code. (Try it and see what you get)

    @@ -531,7 +548,14 @@ public class Histo { Lines 13—20 are required to open the file. Why so many lines to open a file in Java? The additional code mainly comes from the fact that Java forces you to reckon with the possibility that the file you want to open is not going to be there. If you attempt to open a file that is not there you will get an error. A try/catch construct allows us to try things that are risky, and gracefully recover from an error if one occurs. The following example shows the general structure of a try/catch block.

    -
    try { Put some risky code in here, like opening a file } catch (Exception e) { If an error happens in the try block an exception is thrown. We will catch that exception here! }
    +
    +        try { 
    +            Put some risky code in here, like opening a file 
    +        } catch (Exception e) { 
    +            If an error happens in the try block an exception is thrown. We will catch that exception here! 
    +        }
    +        
    +

    Notice that in line 16 we are catching an IOException. In fact, we will see later that we can have multiple catch blocks to catch different types of exceptions. If we want to be lazy and catch any old exception we can catch an Exception which is the parent of all exceptions. However, catching Exception is a terrible practice, since you may inadvertently catch exceptions you do not intend to, making it harder to identify bugs in your program.

    From f1f0dcdeb68d21a7497bb1b13cf711f4f9f5b10b Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Thu, 31 Jul 2025 15:00:18 -0400 Subject: [PATCH 025/357] Changed the formatting of the pre tags in chapter 6. The content wasn't changed in any way, but I made the code look a little cleaner. --- source/ch_6_loopsanditeration.ptx | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/source/ch_6_loopsanditeration.ptx b/source/ch_6_loopsanditeration.ptx index a0650f4..0ca4441 100644 --- a/source/ch_6_loopsanditeration.ptx +++ b/source/ch_6_loopsanditeration.ptx @@ -42,20 +42,24 @@ public class DefiniteLoopExample { Recall that the range function provides you with a wide variety of options for controlling the value of the loop variable.

    -
    range(stop)
    -range(start,stop)
    -range(start,stop,step)
    +
    +        range(stop)
    +        range(start,stop)
    +        range(start,stop,step)
    +        

    The Java for loop is really analogous to the last option giving you explicit control over the starting, stopping, and stepping in the three clauses inside the parenthesis. You can think of it this way:

    -
    for (start clause; stop clause; step clause) {
    -    statement1
    -    statement2
    -    ...
    -}
    +
    +        for (start clause; stop clause; step clause) {
    +            statement1
    +            statement2
    +        ...
    +        }
    +        

    If you want to start at 100, stop at 0 and count backward by 5, the Python loop would be written as: From 85ed8f3e2be10752267ef2912b8f9bf61c53fd10 Mon Sep 17 00:00:00 2001 From: Eun Sung Wang <156254694+esw0624@users.noreply.github.com> Date: Fri, 1 Aug 2025 09:17:04 -0400 Subject: [PATCH 026/357] Merging Chapter 1 and 2 into an Overview --- ...h_1_introduction.ptx => ch_1_overview.ptx} | 188 +++++++++++++++++- source/main.ptx | 3 +- 2 files changed, 187 insertions(+), 4 deletions(-) rename source/{ch_1_introduction.ptx => ch_1_overview.ptx} (55%) diff --git a/source/ch_1_introduction.ptx b/source/ch_1_overview.ptx similarity index 55% rename from source/ch_1_introduction.ptx rename to source/ch_1_overview.ptx index 29c52a0..d781f7c 100644 --- a/source/ch_1_introduction.ptx +++ b/source/ch_1_overview.ptx @@ -1,8 +1,8 @@ - - Introduction + + Overview

    @@ -306,5 +306,189 @@
    +
    + Why Learn another programming Language? + +

    + Python is a nice language for beginning programming for several reasons. + First the syntax is sparse, and clear. + Second, the underlying model of how objects and variables work is very consistent. + Third, you can write powerful and interesting programs without a lot of work. + However, Python is representative of one kind of language, called a dynamic language. + You might think of Python as being fairly informal. + There are other languages, like Java and C++ that are more formal. +

    + +

    + These languages have some advantages of their own. + First, is speed: Java and C++ code will generally give better performance than Python code. (See .) + Second is their maintainability. + A lot of what makes Python easy to use is that you must remember certain things. + For example if you set variable x to reference a turtle, and forget later that x is a turtle but try to invoke a string method on it, you will get an error. + Java and C++ protect you by forcing you to be upfront and formal about the kind of object each variable is going to refer to. +

    + +

    + In one sense Python is representative of a whole class of languages, sometimes referred to as “scripting languages.” Other languages in the same category as Python are Ruby and Perl. + Java is representative of what I will call industrial strength languages. + Industrial strength languages are good for projects with several people working on the project where being formal and careful about what you do may impact lots of other people. + Languages in this category include Rust, C++, C#, and Ada. +

    + +

    + Programming languages will always change. + As the field of computer science advances there will be new programming languages and you will need to learn them. + It is important to learn several programming languages so that you know what to expect. + There are certain features that most programming languages have in common; variables, loops, conditionals, functions. + And there are some features that are unique. + If you know what is common in languages that is a good place to start. +

    + + A Note about Python Performance + + +

    + + Although Python code is generally slower than Java and C++ code, in practice Python programs can achieve equivalent performance. + This can be done by compiling Python code to C code (see: Cython) or by calling high-performance libraries from Python (e.g., NumPy, scikit-learn, etc.). + So native language performance is just one criteria to consider when deciding which language to use for a program. +

    +
    + +
    + +
    + Why Learn Java? Why not C or C++? + +

    + It is easier to learn to create interesting programs in Java than in C or C++, for several reasons: +

    + +

    +

      +
    • +

      + Java includes a larger standard library than C or C++, which means that sophisticated programs can be created in Java without including external dependencies. + Java has over 4,000 different classes included in the Java 14 Standard Edition. + We could not begin to scratch the surface of these classes even if we devoted all of class time! However, we will cover many useful and powerful features of the Java standard library this semester. +

      +
    • + +
    • +

      + Java incorporates automatic garbage collection of memory, whereas C and C++ programs typically include some degree of manual memory management. + This makes programming in those languages more challenging. +

      +
    • + +
    • +

      + C++’s syntax is more complicated than Java’s, making it more difficult to learn. + For example, C++ supports a feature called operator overloading, which makes it possible to change the behavior of operators like +. + This can make it more difficult to understand what a C++ program is doing. +

      +
    • +
    +

    + +

    + Certainly, C and C++ are important languages, and are worth learning. + But for these and other reasons, we’ve decided to use Java for this course. + Learning Java will be a good preparation for learning these and other languages! +

    + + +
    +
    + Summary & Reading Questions +

      +
    1. +

      Learning multiple programming languages helps programmers adapt to different styles and environments.

      +
    2. +
    3. +

      Python is a dynamic scripting language that is beginner-friendly, but it is less strict with types and generally slower than compiled languages.

      +
    4. +
    5. +

      Languages like Java and C++ are statically typed and offer better performance and maintainability for large-scale projects.

      +
    6. +
    7. +

      Java has a simpler syntax than C++ and includes automatic garbage collection, which reduces the complexity of memory management.

      +
    8. +
    9. +

      Java’s extensive standard library enables the development of sophisticated programs without relying on external dependencies.

      +
    10. +

    + + + +

    Which of the following best describes Python as a programming language?

    +
    + + +

    Statically typed and high-performance

    +

    No. This better describes languages like Java or C++.

    +
    + +

    Dynamically typed and beginner-friendly

    +

    That’s right! Python is dynamically typed and easy for beginners.

    +
    + +

    Industrial strength and verbose

    +

    No. Python is more informal and concise.

    +
    + +

    Memory-managed and pointer-based

    +

    No. That describes lower-level languages like C or C++.

    +
    +
    +
    + + +

    Why is Java a better language for beginners compared to C++?

    +
    + + +

    It requires more manual memory management

    +

    No. Java manages memory automatically.

    +
    + +

    It has a smaller standard library

    +

    No. Java has a very large standard library.

    +
    + +

    It avoids complex syntax and has automatic garbage collection

    +

    Correct! These features make Java easier for beginners.

    +
    + +

    It supports operator overloading

    +

    No. That's a C++ feature and it adds complexity.

    +
    +
    +
    + + +

    What is a major benefit of learning multiple programming languages?

    +
    + + +

    You can standardize all projects using one universal syntax

    +

    No. Each language has its own syntax and is suited for different tasks.

    +
    + +

    You will minimize runtime errors across all platforms

    +

    No. Runtime errors depend more on logic and environment than the number of languages you know.

    +
    + +

    You gain exposure to different language features and paradigms

    +

    Great choice! This helps you become a more adaptable and well-rounded programmer.

    +
    + +

    You can bypass the need for understanding compilation and interpretation

    +

    No. Understanding how code is executed remains essential regardless of how many languages you know.

    +
    +
    +
    +
    +
    \ No newline at end of file diff --git a/source/main.ptx b/source/main.ptx index bddc8f2..50caef7 100644 --- a/source/main.ptx +++ b/source/main.ptx @@ -7,8 +7,7 @@ The PreTeXt Interactive Edition - - + From 3127c70bce401fe577b9c302868a1f7adaa85e4d Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Fri, 1 Aug 2025 09:49:14 -0400 Subject: [PATCH 027/357] Added a index terms for 7.1, 7.2, and part of 7.3. --- source/ch_7_definingclasses.ptx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/source/ch_7_definingclasses.ptx b/source/ch_7_definingclasses.ptx index c867871..f101f00 100644 --- a/source/ch_7_definingclasses.ptx +++ b/source/ch_7_definingclasses.ptx @@ -128,7 +128,7 @@

    - The instance variables (data members) we will need for our fraction class are the numerator and denominator. Of course in Python we can add instance variables to a class at any time by simply assigning a value to objectReference.variableName, whereas in Java all data members must be declared up front. + The instance variables (data membersdata members) we will need for our fraction class are the numerator and denominator. Of course in Python we can add instance variables to a class at any time by simply assigning a value to objectReference.variableName, whereas in Java all data members must be declared up front.

    @@ -146,7 +146,7 @@

    - Notice that we have declared the numerator and denominator to be private. + Notice that we have declared the numerator and denominator to be privateprivate. This means that the compiler will generate an error if another method tries to write code like the following:

    @@ -161,7 +161,7 @@

    Direct access to instance variables is not allowed. Therefore if we legitimately want to be able to access information such as the numerator or denominator for a particular fraction we must have getter methods. - It is very common programming practice to provide getter and setter methods for instance variables in Java. + It is very common programming practice to provide getget and setset methods for instance variables in Java.

    From df5ff3908df931dc0f73a4832d1195d04e984e40 Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Fri, 1 Aug 2025 09:50:24 -0400 Subject: [PATCH 028/357] Forgot to save my work in the last commit. --- source/ch_7_definingclasses.ptx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/ch_7_definingclasses.ptx b/source/ch_7_definingclasses.ptx index f101f00..7bf18b3 100644 --- a/source/ch_7_definingclasses.ptx +++ b/source/ch_7_definingclasses.ptx @@ -189,7 +189,7 @@ public void setDenominator(Integer denominator) {

    Once you have identified the instance variables for your class the next thing to consider is the constructor. - In Java, constructors have the same name as the class and are declared public. + In Java, constructorsconstructors have the same name as the class and are declared public. They are declared without a return type. So any method that is named the same as the class and has no return type is a constructor. Our constructor will take two parameters: the numerator and the denominator. @@ -210,7 +210,7 @@ public Fraction(Integer top, Integer bottom) { First, you will notice that the constructor does not have a self parameter. You will also notice that we can simply refer to the instance variables by name without the self prefix, because they have already been declared. This allows the Java compiler to do the work of dereferencing the current Java object. - Java does provide a special variable called this that works like the self variable. + Java does provide a special variable called thisthis that works like the self variable. In Java, this is typically only used when it is needed to differentiate between a parameter or local variable and an instance variable. For example this alternate definition of the the Fraction constructor uses this to differentiate between parameters and instance variables.

    From 3d14e42e581ba4756ed05c6915f5a3923d0d14c9 Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Fri, 1 Aug 2025 10:45:37 -0400 Subject: [PATCH 029/357] Added index terms for 7.3 --- source/ch_7_definingclasses.ptx | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/source/ch_7_definingclasses.ptx b/source/ch_7_definingclasses.ptx index 7bf18b3..8109bff 100644 --- a/source/ch_7_definingclasses.ptx +++ b/source/ch_7_definingclasses.ptx @@ -233,7 +233,7 @@ public Fraction(Integer num, Integer den) {

    Now we come to one of the major differences between Java and Python. The Python class definition used the special methods for addition and comparison that have the effect of redefining how the standard operators behave: in Python, __add__ and __lt__ change the behavior of + and <, respectively. - In Java there is no operator overloading. + In Java there is no operator overloading. So we will have to write the method for addition a little differently.

    @@ -248,12 +248,12 @@ public Fraction(Integer num, Integer den) {
    • - Java is strictly pass-by-value. For primitive types (like int), a copy of the value is passed. For object types (like our Fraction), a copy of the value of the reference (the memory address) is passed. + pass-by-valueJava is strictly pass-by-value. For primitive types (like int), a copy of the value is passed. For object types (like our Fraction), a copy of the value of the referencevalue of the reference (the memory address) is passed.

    • - Python is pass-by-assignment (or pass-by-object-reference). Since everything in Python is an object, the rule is consistent: a copy of the reference to the object is passed. + pass-by-assignmentPython is pass-by-assignment (or pass-by-object-reference). Since everything in Python is an object, the rule is consistent: a copy of the reference to the object is passed.

    @@ -282,7 +282,7 @@ public Fraction add(Fraction otherFrac) {

    - First you will notice that the add method is declared as public Fraction The public part means that any other method may call the add method. + First you will notice that the add method is declared as public Fraction The publicpublic part means that any other method may call the add method. The Fraction part means that add will return a fraction as its result.

    @@ -333,14 +333,14 @@ public Fraction add(Fraction otherFrac) {

    In Java we can do runtime type checking, but the compiler will not allow us to pass an Integer to the add method since the parameter has been declared to be a Fraction. The way that we solve this problem is by writing another add method with a different set of parameters. - In Java this practice is legal and common we call this practice method overloading. + In Java this practice is legal and common we call this practice method overloadingmethod overloading.

    This idea of method overloading raises a very important difference between Python and Java. In Python a method is known by its name only. In Java a method is known by its signature. - The signature of a method includes its name, and the types of all of its parameters. + The signaturesignature of a method includes its name, and the types of all of its parameters. The name and the types of the parameters are enough information for the Java compiler to decide which method to call at runtime.

    From cf0979b6c4f83b09da53f52e668c6133393b6ca0 Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Fri, 1 Aug 2025 11:18:14 -0400 Subject: [PATCH 030/357] added index terms for 7.4. --- source/ch_7_definingclasses.ptx | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/source/ch_7_definingclasses.ptx b/source/ch_7_definingclasses.ptx index 8109bff..c89dd3b 100644 --- a/source/ch_7_definingclasses.ptx +++ b/source/ch_7_definingclasses.ptx @@ -128,7 +128,7 @@

    - The instance variables (data membersdata members) we will need for our fraction class are the numerator and denominator. Of course in Python we can add instance variables to a class at any time by simply assigning a value to objectReference.variableName, whereas in Java all data members must be declared up front. + The instance variables (data membersdata members) we will need for our fraction class are the numerator and denominator. Of course in Python we can add instance variables to a class at any time by simply assigning a value to objectReference.variableName, whereas in Java all data members must be declared up front.

    @@ -488,7 +488,8 @@ Fraction@6ff3c5b5 The <c>Object</c> Class

    - In Java, the equivalent of __str__ is the toString method. + Object class + In Java, the equivalent of __str__ is the toStringtoString method. Every object in Java already has a toString method defined for it because every class in Java automatically inherits from the Object class. The Object class provides default implementations for the following methods.

    @@ -625,7 +626,7 @@ public boolean equals(Fraction other) { If we want to make our Fraction class behave like Integer, Double, and the other numeric classes in Java then we need to make a couple of additional modifications to the class. The first thing we will do is plug Fraction into the Java class hierarchy at the same place as Integer and its siblings. If you look at the documentation for Integer you will see that Integer’s parent class is Number. - Number is an abstract class that specifies several methods that all of its children must implement. + Number is an abstract classabstract class that specifies several methods that all of its children must implement. In Java an abstract class is more than just a placeholder for common methods. In Java an abstract class has the power to specify certain methods that all of its children must implement. You can trace this power back to the strong typing nature of Java. @@ -645,7 +646,7 @@ public class Fraction extends Number {

    - The keyword extends tells the compiler that the class Fraction extends, or adds new functionality to the Number class. + The keyword extendsextends tells the compiler that the class Fraction extends, or adds new functionality to the Number class. A child class always extends its parent.

    @@ -706,7 +707,7 @@ public long longValue() {

    By having the Fraction class extend the Number class we can now pass a Fraction to any Java method that specifies it can receive a Number as one of its parameters. For example many Java user interface methods accept any object that is a subclass of Number as a parameter. - In Java the class hierarchy and the “is-a” relationships are very important. + In Java the class hierarchy and the “is-ais-a” relationships are very important. Whereas in Python you can pass any kind of object as a parameter to any method or function, the strong typing of Java makes sure that you only pass an object as a parameter that is of the type specified in the method signature, or one of the children of the type specified. When you see a parameter of type Number it’s important to remember that an Integer is-a Number and a Double is-a Number and a Fraction is-a Number, because these classes are children of Number.

    From 7e587670e4155f060432572efad076fcce037fc0 Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Fri, 1 Aug 2025 11:24:59 -0400 Subject: [PATCH 031/357] Added index terms for 7.5. --- source/ch_7_definingclasses.ptx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/source/ch_7_definingclasses.ptx b/source/ch_7_definingclasses.ptx index c89dd3b..04456ed 100644 --- a/source/ch_7_definingclasses.ptx +++ b/source/ch_7_definingclasses.ptx @@ -743,16 +743,16 @@ public void test(Number a, Number b) { Lets turn our attention to making a list of fractions sortable by the standard Java sorting method Collections.sort. In Python, we would just need to implement the __cmp__ method. But in Java we cannot be that informal. - In Java, things that are sortable must be Comparable. + In Java, things that are sortable must be ComparableComparable. Your first thought might be that Comparable is superclass of Number, but that is actually not the case. - Java only supports single inheritance, that is, a class can have only one parent. + Java only supports single inheritancesingle inheritance, that is, a class can have only one parent. Although it would be possible to add an additional layer to the class hierarchy it would also complicate things dramatically, because not only are Numbers comparable, but Strings are also Comparable as would many other types. For example, we might have a Student class and we want to be able to sort students by their GPA. But Student might already extends the class Person for which there would be no natural comparison method.

    - Java’s answer to this problem is the Interface mechanism. + Java’s answer to this problem is the InterfaceInterface mechanism. Interfaces are like a combination of “inheritance” and “contracts” all rolled into one. An interface is a specification that says any object that claims it implements this interface must provide the following methods. It sounds a little bit like an abstract class, however it is outside the inheritance mechanism. From 96ed98a198966aef6a011624a5c755c88411efeb Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Fri, 1 Aug 2025 11:28:50 -0400 Subject: [PATCH 032/357] Added an index term for 7.6. --- source/ch_7_definingclasses.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch_7_definingclasses.ptx b/source/ch_7_definingclasses.ptx index 04456ed..36f73b3 100644 --- a/source/ch_7_definingclasses.ptx +++ b/source/ch_7_definingclasses.ptx @@ -864,7 +864,7 @@ public class Student {

    - In this example notice that we create a static member variable by using the static modifier on the variable declaration. Once a variable has been declared static in Java it can be accessed from inside the class without prefixing the name of the class as we had to do in Python. + In this example notice that we create a static member variablestatic member variable by using the static modifier on the variable declaration. Once a variable has been declared static in Java it can be accessed from inside the class without prefixing the name of the class as we had to do in Python.

    From d953ea86ab680ea798d90a5c1a8c20c740633acb Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Fri, 1 Aug 2025 11:58:44 -0400 Subject: [PATCH 033/357] Removed duplicate indexes. Moved all idx tags to beginning of paragraphs. Encased some terms that are code in c tags. Fixed errors. --- source/ch_7_definingclasses.ptx | 56 ++++++++++++++++++++++----------- 1 file changed, 37 insertions(+), 19 deletions(-) diff --git a/source/ch_7_definingclasses.ptx b/source/ch_7_definingclasses.ptx index 36f73b3..c58e11f 100644 --- a/source/ch_7_definingclasses.ptx +++ b/source/ch_7_definingclasses.ptx @@ -128,7 +128,8 @@

    - The instance variables (data membersdata members) we will need for our fraction class are the numerator and denominator. Of course in Python we can add instance variables to a class at any time by simply assigning a value to objectReference.variableName, whereas in Java all data members must be declared up front. + data members + The instance variables (data members) we will need for our fraction class are the numerator and denominator. Of course in Python we can add instance variables to a class at any time by simply assigning a value to objectReference.variableName, whereas in Java all data members must be declared up front.

    @@ -146,7 +147,7 @@

    - Notice that we have declared the numerator and denominator to be privateprivate. + Notice that we have declared the numerator and denominator to be private. This means that the compiler will generate an error if another method tries to write code like the following:

    @@ -159,9 +160,11 @@

    + get + set Direct access to instance variables is not allowed. Therefore if we legitimately want to be able to access information such as the numerator or denominator for a particular fraction we must have getter methods. - It is very common programming practice to provide getget and setset methods for instance variables in Java. + It is very common programming practice to provide get and set methods for instance variables in Java.

    @@ -188,8 +191,9 @@ public void setDenominator(Integer denominator) { Writing a constructor

    + constructors Once you have identified the instance variables for your class the next thing to consider is the constructor. - In Java, constructorsconstructors have the same name as the class and are declared public. + In Java, constructors have the same name as the class and are declared public. They are declared without a return type. So any method that is named the same as the class and has no return type is a constructor. Our constructor will take two parameters: the numerator and the denominator. @@ -206,11 +210,12 @@ public Fraction(Integer top, Integer bottom) {

    + this There are a couple of important things to notice here. First, you will notice that the constructor does not have a self parameter. You will also notice that we can simply refer to the instance variables by name without the self prefix, because they have already been declared. This allows the Java compiler to do the work of dereferencing the current Java object. - Java does provide a special variable called thisthis that works like the self variable. + Java does provide a special variable called this that works like the self variable. In Java, this is typically only used when it is needed to differentiate between a parameter or local variable and an instance variable. For example this alternate definition of the the Fraction constructor uses this to differentiate between parameters and instance variables.

    @@ -248,12 +253,15 @@ public Fraction(Integer num, Integer den) {
    • - pass-by-valueJava is strictly pass-by-value. For primitive types (like int), a copy of the value is passed. For object types (like our Fraction), a copy of the value of the referencevalue of the reference (the memory address) is passed. + pass-by-value + value of the reference + Java is strictly pass-by-value. For primitive types (like int), a copy of the value is passed. For object types (like our Fraction), a copy of the value of the reference (the memory address) is passed.

    • - pass-by-assignmentPython is pass-by-assignment (or pass-by-object-reference). Since everything in Python is an object, the rule is consistent: a copy of the reference to the object is passed. + pass-by-assignment + Python is pass-by-assignment (or pass-by-object-reference). Since everything in Python is an object, the rule is consistent: a copy of the reference to the object is passed.

    @@ -282,7 +290,7 @@ public Fraction add(Fraction otherFrac) {

    - First you will notice that the add method is declared as public Fraction The publicpublic part means that any other method may call the add method. + First you will notice that the add method is declared as public Fraction The public part means that any other method may call the add method. The Fraction part means that add will return a fraction as its result.

    @@ -331,16 +339,18 @@ public Fraction add(Fraction otherFrac) {

    + method overloading In Java we can do runtime type checking, but the compiler will not allow us to pass an Integer to the add method since the parameter has been declared to be a Fraction. The way that we solve this problem is by writing another add method with a different set of parameters. - In Java this practice is legal and common we call this practice method overloadingmethod overloading. + In Java this practice is legal and common we call this practice method overloading.

    + signature This idea of method overloading raises a very important difference between Python and Java. In Python a method is known by its name only. In Java a method is known by its signature. - The signaturesignature of a method includes its name, and the types of all of its parameters. + The signature of a method includes its name, and the types of all of its parameters. The name and the types of the parameters are enough information for the Java compiler to decide which method to call at runtime.

    @@ -488,8 +498,9 @@ Fraction@6ff3c5b5 The <c>Object</c> Class

    - Object class - In Java, the equivalent of __str__ is the toStringtoString method. + object class + toString + In Java, the equivalent of __str__ is the toString method. Every object in Java already has a toString method defined for it because every class in Java automatically inherits from the Object class. The Object class provides default implementations for the following methods.

    @@ -623,10 +634,11 @@ public boolean equals(Fraction other) { Abstract Classes and Methods

    + abstract class If we want to make our Fraction class behave like Integer, Double, and the other numeric classes in Java then we need to make a couple of additional modifications to the class. The first thing we will do is plug Fraction into the Java class hierarchy at the same place as Integer and its siblings. If you look at the documentation for Integer you will see that Integer’s parent class is Number. - Number is an abstract classabstract class that specifies several methods that all of its children must implement. + Number is an abstract class that specifies several methods that all of its children must implement. In Java an abstract class is more than just a placeholder for common methods. In Java an abstract class has the power to specify certain methods that all of its children must implement. You can trace this power back to the strong typing nature of Java. @@ -646,7 +658,8 @@ public class Fraction extends Number {

    - The keyword extendsextends tells the compiler that the class Fraction extends, or adds new functionality to the Number class. + extends + The keyword extends tells the compiler that the class Fraction extends, or adds new functionality to the Number class. A child class always extends its parent.

    @@ -705,9 +718,10 @@ public long longValue() {

    + is-a By having the Fraction class extend the Number class we can now pass a Fraction to any Java method that specifies it can receive a Number as one of its parameters. For example many Java user interface methods accept any object that is a subclass of Number as a parameter. - In Java the class hierarchy and the “is-ais-a” relationships are very important. + In Java the class hierarchy and the “is-a” relationships are very important. Whereas in Python you can pass any kind of object as a parameter to any method or function, the strong typing of Java makes sure that you only pass an object as a parameter that is of the type specified in the method signature, or one of the children of the type specified. When you see a parameter of type Number it’s important to remember that an Integer is-a Number and a Double is-a Number and a Fraction is-a Number, because these classes are children of Number.

    @@ -740,19 +754,22 @@ public void test(Number a, Number b) { Interfaces

    + Comparable + single inheritance Lets turn our attention to making a list of fractions sortable by the standard Java sorting method Collections.sort. In Python, we would just need to implement the __cmp__ method. But in Java we cannot be that informal. - In Java, things that are sortable must be ComparableComparable. + In Java, things that are sortable must be Comparable. Your first thought might be that Comparable is superclass of Number, but that is actually not the case. - Java only supports single inheritancesingle inheritance, that is, a class can have only one parent. + Java only supports single inheritance, that is, a class can have only one parent. Although it would be possible to add an additional layer to the class hierarchy it would also complicate things dramatically, because not only are Numbers comparable, but Strings are also Comparable as would many other types. For example, we might have a Student class and we want to be able to sort students by their GPA. But Student might already extends the class Person for which there would be no natural comparison method.

    - Java’s answer to this problem is the InterfaceInterface mechanism. + Interface + Java’s answer to this problem is the Interface mechanism. Interfaces are like a combination of “inheritance” and “contracts” all rolled into one. An interface is a specification that says any object that claims it implements this interface must provide the following methods. It sounds a little bit like an abstract class, however it is outside the inheritance mechanism. @@ -864,7 +881,8 @@ public class Student {

    - In this example notice that we create a static member variablestatic member variable by using the static modifier on the variable declaration. Once a variable has been declared static in Java it can be accessed from inside the class without prefixing the name of the class as we had to do in Python. + static member variable + In this example notice that we create a static member variable by using the static modifier on the variable declaration. Once a variable has been declared static in Java it can be accessed from inside the class without prefixing the name of the class as we had to do in Python.

    From 9905a08883ab5bfd82e4304bf68d41691e9a8b47 Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Sun, 3 Aug 2025 13:14:36 -0400 Subject: [PATCH 034/357] add .cache folder to .gitignore --- .gitignore | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitignore b/.gitignore index 194fce6..341f520 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,9 @@ # don't track unpublished builds or stage output +# don't track .cache directory +.cache/* + # don't track assets generated from source generated-assets **/*.pkl From 189ef9b12ccb41349c49f254122aad9b731328b8 Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Sun, 3 Aug 2025 13:31:42 -0400 Subject: [PATCH 035/357] fix introduced pretext warnings --- source/ch_7_definingclasses.ptx | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/source/ch_7_definingclasses.ptx b/source/ch_7_definingclasses.ptx index c58e11f..6bd0ea5 100644 --- a/source/ch_7_definingclasses.ptx +++ b/source/ch_7_definingclasses.ptx @@ -215,7 +215,7 @@ public Fraction(Integer top, Integer bottom) { First, you will notice that the constructor does not have a self parameter. You will also notice that we can simply refer to the instance variables by name without the self prefix, because they have already been declared. This allows the Java compiler to do the work of dereferencing the current Java object. - Java does provide a special variable called this that works like the self variable. + Java does provide a special variable called this that works like the self variable. In Java, this is typically only used when it is needed to differentiate between a parameter or local variable and an instance variable. For example this alternate definition of the the Fraction constructor uses this to differentiate between parameters and instance variables.

    @@ -290,7 +290,7 @@ public Fraction add(Fraction otherFrac) {

    - First you will notice that the add method is declared as public Fraction The public part means that any other method may call the add method. + First you will notice that the add method is declared as public Fraction The public part means that any other method may call the add method. The Fraction part means that add will return a fraction as its result.

    @@ -500,7 +500,7 @@ Fraction@6ff3c5b5

    object class toString - In Java, the equivalent of __str__ is the toString method. + In Java, the equivalent of __str__ is the toString method. Every object in Java already has a toString method defined for it because every class in Java automatically inherits from the Object class. The Object class provides default implementations for the following methods.

    @@ -659,7 +659,7 @@ public class Fraction extends Number {

    extends - The keyword extends tells the compiler that the class Fraction extends, or adds new functionality to the Number class. + The keyword extends tells the compiler that the class Fraction extends, or adds new functionality to the Number class. A child class always extends its parent.

    @@ -759,7 +759,7 @@ public void test(Number a, Number b) { Lets turn our attention to making a list of fractions sortable by the standard Java sorting method Collections.sort. In Python, we would just need to implement the __cmp__ method. But in Java we cannot be that informal. - In Java, things that are sortable must be Comparable. + In Java, things that are sortable must be Comparable. Your first thought might be that Comparable is superclass of Number, but that is actually not the case. Java only supports single inheritance, that is, a class can have only one parent. Although it would be possible to add an additional layer to the class hierarchy it would also complicate things dramatically, because not only are Numbers comparable, but Strings are also Comparable as would many other types. @@ -769,7 +769,7 @@ public void test(Number a, Number b) {

    Interface - Java’s answer to this problem is the Interface mechanism. + Java’s answer to this problem is the Interface mechanism. Interfaces are like a combination of “inheritance” and “contracts” all rolled into one. An interface is a specification that says any object that claims it implements this interface must provide the following methods. It sounds a little bit like an abstract class, however it is outside the inheritance mechanism. From a23e698122c041e0c5b8abd3ff61bfa80f74bd22 Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Sun, 3 Aug 2025 13:40:22 -0400 Subject: [PATCH 036/357] correct introduced errors --- source/ch_7_definingclasses.ptx | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/source/ch_7_definingclasses.ptx b/source/ch_7_definingclasses.ptx index 6bd0ea5..7a95433 100644 --- a/source/ch_7_definingclasses.ptx +++ b/source/ch_7_definingclasses.ptx @@ -160,11 +160,11 @@

    - get - set - Direct access to instance variables is not allowed. - Therefore if we legitimately want to be able to access information such as the numerator or denominator for a particular fraction we must have getter methods. - It is very common programming practice to provide get and set methods for instance variables in Java. + getter method + setter method + Direct access to instance variables is not allowed in Java. + Therefore if we legitimately want to be able to access information such as the numerator or the denominator for a particular fraction we must have a getter method that returns the needed value. + Hence, it is a very common programming practice to both provide getter methods and setter methods when needed for instance variables in Java.

    From 3acbf412a11b6e2ac752787e946b98b80a178f04 Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Sun, 3 Aug 2025 18:39:02 -0400 Subject: [PATCH 037/357] restructure chapters --- ...ntation.ptx => ch10_moredocumentation.ptx} | 0 .../{ch_1_overview.ptx => ch1_overview.ptx} | 0 ..._whylearnjava.ptx => ch2_whylearnjava.ptx} | 0 ...vaprogram.ptx => ch3_firstjavaprogram.ptx} | 2 +- ...avadatatypes.ptx => ch4_javadatatypes.ptx} | 0 ..._conditionals.ptx => ch5_conditionals.ptx} | 0 ...teration.ptx => ch6_loopsanditeration.ptx} | 0 ...ingclasses.ptx => ch7_definingclasses.ptx} | 0 ..._filehandling.ptx => ch8_filehandling.ptx} | 0 ...ventions.ptx => ch8_namingconventions.ptx} | 0 ...monmistakes.ptx => ch9_commonmistakes.ptx} | 0 source/main.ptx | 19 +++++++++---------- 12 files changed, 10 insertions(+), 11 deletions(-) rename source/{ch_10_moredocumentation.ptx => ch10_moredocumentation.ptx} (100%) rename source/{ch_1_overview.ptx => ch1_overview.ptx} (100%) rename source/{ch_2_whylearnjava.ptx => ch2_whylearnjava.ptx} (100%) rename source/{ch_3_firstjavaprogram.ptx => ch3_firstjavaprogram.ptx} (99%) rename source/{ch_4_javadatatypes.ptx => ch4_javadatatypes.ptx} (100%) rename source/{ch_5_conditionals.ptx => ch5_conditionals.ptx} (100%) rename source/{ch_6_loopsanditeration.ptx => ch6_loopsanditeration.ptx} (100%) rename source/{ch_7_definingclasses.ptx => ch7_definingclasses.ptx} (100%) rename source/{ch_x_filehandling.ptx => ch8_filehandling.ptx} (100%) rename source/{ch_8_namingconventions.ptx => ch8_namingconventions.ptx} (100%) rename source/{ch_9_commonmistakes.ptx => ch9_commonmistakes.ptx} (100%) diff --git a/source/ch_10_moredocumentation.ptx b/source/ch10_moredocumentation.ptx similarity index 100% rename from source/ch_10_moredocumentation.ptx rename to source/ch10_moredocumentation.ptx diff --git a/source/ch_1_overview.ptx b/source/ch1_overview.ptx similarity index 100% rename from source/ch_1_overview.ptx rename to source/ch1_overview.ptx diff --git a/source/ch_2_whylearnjava.ptx b/source/ch2_whylearnjava.ptx similarity index 100% rename from source/ch_2_whylearnjava.ptx rename to source/ch2_whylearnjava.ptx diff --git a/source/ch_3_firstjavaprogram.ptx b/source/ch3_firstjavaprogram.ptx similarity index 99% rename from source/ch_3_firstjavaprogram.ptx rename to source/ch3_firstjavaprogram.ptx index 7d80a61..a485e61 100644 --- a/source/ch_3_firstjavaprogram.ptx +++ b/source/ch3_firstjavaprogram.ptx @@ -33,7 +33,7 @@ public class Hello {

    - What we see is that at the core there are a few similarities, such as a main and the string “Hello World”. However, there is a lot more stuff around the edges that make it harder to see the core of the program. Do not worry! An important skill for a computer scientist is to learn what to ignore and what to look at carefully. You will soon find that there are some elements of Java that will fade into the background as you become used to seeing them. One thing that will help you is to learn a little bit about Java . + What we see is that at the core there are a few similarities, such as a main and the string “Hello World”. However, there is a lot more stuff around the edges that make it harder to see the core of the program. Do not worry! An important skill for a computer scientist is to learn what to ignore and what to look at carefully. You will soon find that there are some elements of Java that will fade into the background as you become used to seeing them.

    diff --git a/source/ch_4_javadatatypes.ptx b/source/ch4_javadatatypes.ptx similarity index 100% rename from source/ch_4_javadatatypes.ptx rename to source/ch4_javadatatypes.ptx diff --git a/source/ch_5_conditionals.ptx b/source/ch5_conditionals.ptx similarity index 100% rename from source/ch_5_conditionals.ptx rename to source/ch5_conditionals.ptx diff --git a/source/ch_6_loopsanditeration.ptx b/source/ch6_loopsanditeration.ptx similarity index 100% rename from source/ch_6_loopsanditeration.ptx rename to source/ch6_loopsanditeration.ptx diff --git a/source/ch_7_definingclasses.ptx b/source/ch7_definingclasses.ptx similarity index 100% rename from source/ch_7_definingclasses.ptx rename to source/ch7_definingclasses.ptx diff --git a/source/ch_x_filehandling.ptx b/source/ch8_filehandling.ptx similarity index 100% rename from source/ch_x_filehandling.ptx rename to source/ch8_filehandling.ptx diff --git a/source/ch_8_namingconventions.ptx b/source/ch8_namingconventions.ptx similarity index 100% rename from source/ch_8_namingconventions.ptx rename to source/ch8_namingconventions.ptx diff --git a/source/ch_9_commonmistakes.ptx b/source/ch9_commonmistakes.ptx similarity index 100% rename from source/ch_9_commonmistakes.ptx rename to source/ch9_commonmistakes.ptx diff --git a/source/main.ptx b/source/main.ptx index 2d2899a..3b05012 100644 --- a/source/main.ptx +++ b/source/main.ptx @@ -7,16 +7,15 @@ The PreTeXt Interactive Edition - - - - - - - - - - + + + + + + + + + From bc27ab40ba8b33ed9fed77c3471274bf6bd09366 Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Mon, 4 Aug 2025 10:06:03 -0400 Subject: [PATCH 038/357] remove extra namingconventions file --- source/ch8_namingconventions.ptx | 41 -------------------------------- 1 file changed, 41 deletions(-) delete mode 100644 source/ch8_namingconventions.ptx diff --git a/source/ch8_namingconventions.ptx b/source/ch8_namingconventions.ptx deleted file mode 100644 index 08b90f9..0000000 --- a/source/ch8_namingconventions.ptx +++ /dev/null @@ -1,41 +0,0 @@ - - - - - Naming Conventions - -

    - Java has some very handy naming conventions. -

    - -

    -

      -
    • -

      - Class names always start with an upper case letter. - For example, Scanner, System, Hello -

      -
    • - -
    • -

      - Method names always start with a lower case letter, and use camelCase to represent multiword method names. - for example nextInt() -

      -
    • - -
    • -

      - Instance variables of a class start with a lower case letter and use camelCase -

      -
    • - -
    • -

      - Constants are in all upper case letters. - for example Math.MAXINT -

      -
    • -
    -

    - \ No newline at end of file From 44a21e1197ddcd289384885ceb22b81ce28beda5 Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Mon, 4 Aug 2025 10:39:31 -0400 Subject: [PATCH 039/357] add missing chapters --- source/ch_10_moredocumentation.ptx | 77 +++++++++ source/chx_recursion.ptx | 250 +++++++++++++++++++++++++++++ source/main.ptx | 1 + 3 files changed, 328 insertions(+) create mode 100644 source/ch_10_moredocumentation.ptx create mode 100644 source/chx_recursion.ptx diff --git a/source/ch_10_moredocumentation.ptx b/source/ch_10_moredocumentation.ptx new file mode 100644 index 0000000..942fd2d --- /dev/null +++ b/source/ch_10_moredocumentation.ptx @@ -0,0 +1,77 @@ + + + + + Java Documentation + +

    + All Java class libraries are documented and available online. + Here are two good resources for you to use: +

    + +

    +

      +
    • +

      + JavaDoc The Javadoconline website provides a nice searchable interface. Search for a classname and you will get the documentation you are looking for. +

      +
    • + +
    • +

      + JavaAPI contains the same information but in a browsable format. If you don’t know the class name exactly this is a good way to see what is close. +

      +
    • +
    +

    + +

    + In general the Javadoc page for any class contains information about: +

    + +

    +

      +
    • +

      + Where this class falls in the class hierarchy. + What classes are its parents and what classes are its decendents. +

      +
    • + +
    • +

      + A summary and some examples of using the class. +

      +
    • + +
    • +

      + A summary listing of instance variables +

      +
    • + +
    • +

      + A summary listing of Constructors +

      +
    • + +
    • +

      + A summary listing of Methods +

      +
    • + +
    • +

      + Detailed documentation on constructors and methods. +

      +
    • +
    +

    + +

    + Typically the Javadoc pages are constructed from the source code where the class is implemented. + This encourages Java programmers to do a good job of documenting their code, while providing a user friendly way to read the documentation without looking at the code directly. +

    +
    \ No newline at end of file diff --git a/source/chx_recursion.ptx b/source/chx_recursion.ptx new file mode 100644 index 0000000..4304a89 --- /dev/null +++ b/source/chx_recursion.ptx @@ -0,0 +1,250 @@ + + + Recursion in Java + + +
    + Basic Recursion +

    + In this chapter, we will explore how to translate your recursive logic from Python to Java. While the core concepts of recursion remain the same, the syntax and structure of your code will change somewhat. +

    +

    recursion + As you may know from Python, recursion is a powerful problem-solving technique involving base cases and recursive steps in which a function or method calls itself. When moving to Java, the core logic you've learned remains identical. The challenge is adapting that logic to Java's statically-typed, class-based syntax. +

    +

    + Let's take the familiar factorial function (which calculates the factorial of a number, namely the product of all positive integers from 1 to n). The logical steps in the code are the same, but the implementation details change. +

    +

    + Here is the standard implementation in Python: +

    + + + class MathTools: + """A utility class for mathematical operations.""" + def factorial(n: int) -> int: + """Calculates the factorial of n using recursion.""" + # A check for negative numbers is good practice. + if n < 0: + raise ValueError("Factorial is not defined for negative numbers.") # Base Case: 0! or 1! is 1 + if n <= 1: + return 1 # Recursive Step: n * (n-1)! + # The call is now to the method within the class. + return n * MathTools.factorial(n - 1)# This block shows how to use the class method. + if __name__ == "__main__": + number = 5 + result = MathTools.factorial(number) # Call the method on the class + print(f"{number}! is {result}") + + +

    + The Java version follows the same recursive logic but requires three key syntax changes: the method must be inside a class, you must declare the parameter and return types (int n and int return), and you use public static to make it callable from main. The base case and recursive step remain conceptually identical. +

    +

    + Here is the equivalent Java code: +

    + + + public class MathTools { /** + * Calculates the factorial of n using recursion. + * This is a static method, like Python's @staticmethod. + * @param n The non-negative integer. + * @return The factorial of n as a long to prevent overflow for larger numbers. + */ + public static int factorial(int n) { + // A check for negative numbers is good practice. + if (n < 0) { + throw new IllegalArgumentException("Factorial is not defined for negative numbers."); + } // Base Case: 0! or 1! is 1 + if (n <= 1) { + return 1; + } // Recursive Step: n * (n-1)! + return n * factorial(n - 1); + } /** + * The main entry point for the application. + * This is the Java equivalent of Python's 'if __name__ == "__main__":' + */ + public static void main(String[] args) { + int number = 5; + // The static method is called directly on the class. + long result = MathTools.factorial(number); System.out.println(number + "! is " + result); + } + } + + +

    + Notice the key differences: instead of def, the method signature public static int declares its scope, that it belongs to the class rather than an object, and that it returns an int. All logic is contained within curly braces {}. +

    +
    +
    + Common Recursive Patterns + +

    + In many recursive algorithms, the recursive calls need extra information that the original caller shouldn't have to provide. For example, to recursively process an array, you need to keep track of the current position (index). To traverse a tree, you need to know the current node. This extra information clutters the public-facing method signature. +

    +

    + A common pattern to solve this is using a private helper method. This pattern lets you create a clean, simple public method that users will call, while the private helper method handles the complex details of the recursion. The public method typically makes the initial call to the private helper, providing the necessary starting values for the extra parameters. +

    +

    + Let's see this pattern in action with an example that calculates the sum of all elements in an integer array. The public sum method only takes the array, but the private sumHelper method also takes an index to track its progress through the array. +

    + +

    + You're likely familiar with how some recursive algorithms, like the naive Fibonacci implementation, + are elegant but inefficient, due to branching recursive calls filling the call stack. A common pattern to solve + this is using a private helper method. +

    +

    + The following example demonstrates this pattern. The public fib method provides a simple entry point, while the private fibHelper method performs the efficient recursion by carrying its state (the previous two numbers) in its parameters. +

    +

    + The following Java code demonstrates a similar pattern. +

    + + + + public class FibonacciExample { + public int fib(int n) { + if (n < 0) { + throw new IllegalArgumentException("Input cannot be negative."); + } + // Initial call to the recursive helper with depth 0. + return this._fibHelper(n, 0, 1, 0); + } + private int _fibHelper(int count, int a, int b, int depth) { + // Create an indent string based on the recursion depth. + String indent = " ".repeat(depth); + // Print when the method is entered (pushed onto the stack). + System.out.printf("%s[>>] ENTERING _fibHelper(count=%d, a=%d, b=%d)%n", indent, count, a, b); + // Base Case: When the count reaches 0, 'a' holds the result. + if (count == 0) { + System.out.printf("%s[<<] EXITING (Base Case) -> returns %d%n", indent, a); + return a; + } + // Recursive Step. + int result = this._fibHelper(count - 1, b, a + b, depth + 1); + // Print when the method exits (popped from the stack). + System.out.printf("%s[<<] EXITING (Recursive Step) -> passing %d%n", indent, result); + return result; + } + public static void main(String[] args) { + FibonacciExample calculator = new FibonacciExample(); + int n = 4; // Let's calculate the 4th Fibonacci number. + System.out.printf("--- Calculating fib(%d) ---%n", n); + int result = calculator.fib(n); + System.out.println("--------------------------"); + System.out.printf("The %dth Fibonacci number is: %d%n", n, result); + } + } + + +

    + This helper method approach is significantly more efficient in terms of time than the classic branching recursion (where fib(n) calls fib(n-1) and fib(n-2)). The branching model has an exponential time complexity of roughly O(2^n) because it re-calculates the same values many times. In contrast, our helper method has a linear time complexity of O(n), as it avoids re-computation by carrying the previous two results (a and b) forward into the next call. +

    +

    + However, regarding memory efficiency, the comparison is different. The maximum depth of the call stack for both the naive and the helper method is proportional to n, giving them both a space complexity of O(n). This means that while the helper method is much faster, it is equally vulnerable to a StackOverflowError for very large values of n. Because Java does not perform tail-call optimization, any recursive solution that goes too deep will exhaust the stack memory, regardless of its time efficiency. For true memory efficiency (O(1) space), an iterative loop-based solution is superior. +

    +

    + The following Python code demonstrates the same pattern, using a public method to initiate the calculation and a private helper method to perform the recursion. +

    + + + class FibonacciExample: + def fib(self, n: int) -> int: + """ + Public method to start the Fibonacci calculation. + """ + if n < 0: + raise ValueError("Input cannot be negative.") + # Initial call to the recursive helper with depth 0. + return self._fib_helper(n, 0, 1, 0) + + def _fib_helper(self, count: int, a: int, b: int, depth: int) -> int: + """ + Private helper that performs the tail recursion to find the number. + """ + # Create an indent string based on the recursion depth. + indent = " " * depth + # Print when the method is entered (pushed onto the stack). + print(f"{indent}[>>] ENTERING _fib_helper(count={count}, a={a}, b={b})") + + # Base Case: When the count reaches 0, 'a' holds the result. + if count == 0: + print(f"{indent}[<<] EXITING (Base Case) -> returns {a}") + return a + + # Recursive Step. + result = self._fib_helper(count - 1, b, a + b, depth + 1) + # Print when the method exits (popped from the stack). + print(f"{indent}[<<] EXITING (Recursive Step) -> passing {result}") + return result + + # The standard Python entry point, equivalent to Java's `main` method. + if __name__ == "__main__": + calculator = FibonacciExample() + n = 4 # Let's calculate the 4th Fibonacci number. + print(f"--- Calculating fib({n}) ---") + result = calculator.fib(n) + print("--------------------------") + print(f"The {n}th Fibonacci number is: {result}") + + +
    +
    + Recursion Limits: Python vs. Java +

    + The consequence of deep recursion, running out of stack space, is a concept you've already encountered in Python. Java handles this in a very similar way, throwing an error when the call stack depth is exceeded. +

    +

    + The key difference is the name of the error: +

    +
      +
    • In Python, this raises a RecursionError.
    • +
    • In Java, this throws a StackOverflowError.
    • +
    +

    + Neither language supports tail call optimization tail call optimization, so the practical limits on recursion depth are a factor in both. If an algorithm requires thousands of recursive calls, an iterative (loop-based) approach is the preferred solution in both Python and Java. +

    +

    + The following Python code demonstrates a situation where a function calls itself indefinitely without a base case, leading to aRecursionError. +

    + + + def cause_recursion_error(): + """ + This function calls itself without a base case, guaranteeing an error. + """ + cause_recursion_error() + + # Standard Python entry point + if __name__ == "__main__": + print("Calling the recursive function... this will end in an error!") + + # This line starts the infinite recursion. + # Python will stop it and raise a RecursionError automatically. + cause_recursion_error() + + + +

    + The following Java code demonstrates a similar situation, where a method calls itself indefinitely without a base case, leading to a StackOverflowError. +

    + + + public class Crash { + public static void causeStackOverflow() { + // This method calls itself endlessly without a stopping condition (a base case). + // Each call adds a new layer to the program's call stack. + // Eventually, the stack runs out of space, causing the error. + causeStackOverflow(); + } + // A main method is required to run the program. + public static void main(String[] args) { + System.out.println("Calling the recursive method... this will end in an error!"); + // This line starts the infinite recursion. + causeStackOverflow(); + } + } + + +
    +
    \ No newline at end of file diff --git a/source/main.ptx b/source/main.ptx index 3b05012..fd70e99 100644 --- a/source/main.ptx +++ b/source/main.ptx @@ -13,6 +13,7 @@ + From e7b05619a07cee74f0f59f9389d1768ea5566b0d Mon Sep 17 00:00:00 2001 From: Eun Sung Wang <156254694+esw0624@users.noreply.github.com> Date: Mon, 4 Aug 2025 11:53:16 -0400 Subject: [PATCH 040/357] Updating Section 1.4 and Removing Chapter 2 file --- source/ch1_overview.ptx | 2 +- source/ch2_whylearnjava.ptx | 191 ------------------------------------ 2 files changed, 1 insertion(+), 192 deletions(-) delete mode 100644 source/ch2_whylearnjava.ptx diff --git a/source/ch1_overview.ptx b/source/ch1_overview.ptx index d781f7c..7c1da79 100644 --- a/source/ch1_overview.ptx +++ b/source/ch1_overview.ptx @@ -369,7 +369,7 @@
  • Java includes a larger standard library than C or C++, which means that sophisticated programs can be created in Java without including external dependencies. - Java has over 4,000 different classes included in the Java 14 Standard Edition. + The Java Standard Edition contains thousands of built-in classes that support tasks like file input/output, networking, data structures, and graphical interfaces. We could not begin to scratch the surface of these classes even if we devoted all of class time! However, we will cover many useful and powerful features of the Java standard library this semester.

  • diff --git a/source/ch2_whylearnjava.ptx b/source/ch2_whylearnjava.ptx deleted file mode 100644 index 818117f..0000000 --- a/source/ch2_whylearnjava.ptx +++ /dev/null @@ -1,191 +0,0 @@ - - - - - Exploring Other Programming Languages - -
    - Why Learn another programming Language? - -

    - Python is a nice language for beginning programming for several reasons. - First the syntax is sparse, and clear. - Second, the underlying model of how objects and variables work is very consistent. - Third, you can write powerful and interesting programs without a lot of work. - However, Python is representative of one kind of language, called a dynamic language. - You might think of Python as being fairly informal. - There are other languages, like Java and C++ that are more formal. -

    - -

    - These languages have some advantages of their own. - First, is speed: Java and C++ code will generally give better performance than Python code. (See .) - Second is their maintainability. - A lot of what makes Python easy to use is that you must remember certain things. - For example if you set variable x to reference a turtle, and forget later that x is a turtle but try to invoke a string method on it, you will get an error. - Java and C++ protect you by forcing you to be upfront and formal about the kind of object each variable is going to refer to. -

    - -

    - In one sense Python is representative of a whole class of languages, sometimes referred to as “scripting languages.” Other languages in the same category as Python are Ruby and Perl. - Java is representative of what I will call industrial strength languages. - Industrial strength languages are good for projects with several people working on the project where being formal and careful about what you do may impact lots of other people. - Languages in this category include Rust, C++, C#, and Ada. -

    - -

    - Programming languages will always change. - As the field of computer science advances there will be new programming languages and you will need to learn them. - It is important to learn several programming languages so that you know what to expect. - There are certain features that most programming languages have in common; variables, loops, conditionals, functions. - And there are some features that are unique. - If you know what is common in languages that is a good place to start. -

    - - A Note about Python Performance - - -

    - - Although Python code is generally slower than Java and C++ code, in practice Python programs can achieve equivalent performance. - This can be done by compiling Python code to C code (see: Cython) or by calling high-performance libraries from Python (e.g., NumPy, scikit-learn, etc.). - So native language performance is just one criteria to consider when deciding which language to use for a program. -

    -
    - -
    - -
    - Why Learn Java? Why not C or C++? - -

    - It is easier to learn to create interesting programs in Java than in C or C++, for several reasons: -

    - -

    -

      -
    • -

      - Java includes a larger standard library than C or C++, which means that sophisticated programs can be created in Java without including external dependencies. - Java has over 4,000 different classes included in the Java 14 Standard Edition. - We could not begin to scratch the surface of these classes even if we devoted all of class time! However, we will cover many useful and powerful features of the Java standard library this semester. -

      -
    • - -
    • -

      - Java incorporates automatic garbage collection of memory, whereas C and C++ programs typically include some degree of manual memory management. - This makes programming in those languages more challenging. -

      -
    • - -
    • -

      - C++’s syntax is more complicated than Java’s, making it more difficult to learn. - For example, C++ supports a feature called operator overloading, which makes it possible to change the behavior of operators like +. - This can make it more difficult to understand what a C++ program is doing. -

      -
    • -
    -

    - -

    - Certainly, C and C++ are important languages, and are worth learning. - But for these and other reasons, we’ve decided to use Java for this course. - Learning Java will be a good preparation for learning these and other languages! -

    - - -
    -
    - Summary & Reading Questions -

      -
    1. -

      Learning multiple programming languages helps programmers adapt to different styles and environments.

      -
    2. -
    3. -

      Python is a dynamic scripting language that is beginner-friendly, but it is less strict with types and generally slower than compiled languages.

      -
    4. -
    5. -

      Languages like Java and C++ are statically typed and offer better performance and maintainability for large-scale projects.

      -
    6. -
    7. -

      Java has a simpler syntax than C++ and includes automatic garbage collection, which reduces the complexity of memory management.

      -
    8. -
    9. -

      Java’s extensive standard library enables the development of sophisticated programs without relying on external dependencies.

      -
    10. -

    - - - -

    Which of the following best describes Python as a programming language?

    -
    - - -

    Statically typed and high-performance

    -

    No. This better describes languages like Java or C++.

    -
    - -

    Dynamically typed and beginner-friendly

    -

    That’s right! Python is dynamically typed and easy for beginners.

    -
    - -

    Industrial strength and verbose

    -

    No. Python is more informal and concise.

    -
    - -

    Memory-managed and pointer-based

    -

    No. That describes lower-level languages like C or C++.

    -
    -
    -
    - - -

    Why is Java a better language for beginners compared to C++?

    -
    - - -

    It requires more manual memory management

    -

    No. Java manages memory automatically.

    -
    - -

    It has a smaller standard library

    -

    No. Java has a very large standard library.

    -
    - -

    It avoids complex syntax and has automatic garbage collection

    -

    Correct! These features make Java easier for beginners.

    -
    - -

    It supports operator overloading

    -

    No. That's a C++ feature and it adds complexity.

    -
    -
    -
    - - -

    What is a major benefit of learning multiple programming languages?

    -
    - - -

    You can standardize all projects using one universal syntax

    -

    No. Each language has its own syntax and is suited for different tasks.

    -
    - -

    You will minimize runtime errors across all platforms

    -

    No. Runtime errors depend more on logic and environment than the number of languages you know.

    -
    - -

    You gain exposure to different language features and paradigms

    -

    Great choice! This helps you become a more adaptable and well-rounded programmer.

    -
    - -

    You can bypass the need for understanding compilation and interpretation

    -

    No. Understanding how code is executed remains essential regardless of how many languages you know.

    -
    -
    -
    -
    -
    -
    \ No newline at end of file From 9dff49d50c21b53ce2b1a7cc4e438a9047d1462b Mon Sep 17 00:00:00 2001 From: Tristan-Raz Date: Mon, 4 Aug 2025 16:04:40 -0400 Subject: [PATCH 041/357] Formats chapter syntax and makes one liner easier for cheatsheet --- source/ap-java-cheatsheet.ptx | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/source/ap-java-cheatsheet.ptx b/source/ap-java-cheatsheet.ptx index 46f925f..f272981 100644 --- a/source/ap-java-cheatsheet.ptx +++ b/source/ap-java-cheatsheet.ptx @@ -119,49 +119,49 @@ Arithmetic +, -, *, / Addition, Subtraction, Multiplication, Division - 5 + 2 + 5 + 2 7 Arithmetic / Integer Division (truncates toward zero) - 7 / 2 → 3 + 7 / 2 3 Arithmetic % Modulus (remainder) - 7 % 2 → 1 + 7 % 2 1 Arithmetic Math.pow() Exponent - Math.pow(2, 3) → 8.0 + Math.pow(2, 3) 8.0 + + + Assignment + +=, -=, *=, /= + Adds, subtracts, multiplies, or divides and assigns + x += 1x = x + 1 Comparison ==, != Equal to, Not equal to (use .equals() for objects) - x == y + x == yTrue or False Comparison >, <, >=, <= Greater/Less than, or equal to - x > 5 + x > 5True or False Logical &&, ||, ! Logical AND, OR, NOT - x > 1 && y < 10 - - - Assignment - +=, -=, *=, /= - Adds, subtracts, multiplies, or divides and assigns - x += 1 + x > 1 && y < 10True or False @@ -195,7 +195,7 @@
  • - Streams API: Java's Stream API is the idiomatic alternative to Python's List Comprehensions. It can be used to filter, map, and reduce data in a sequence of steps. For example, to generate a list of squares, instead of a multi-line loop, you can write List<Integer> squares = IntStream.range(0, 10).map(i -> i * i).boxed().collect(Collectors.toList());. + Streams API: Java's Stream API is the idiomatic alternative to Python's List Comprehensions. It can be used to filter, map, and reduce data in a sequence of steps. For a simpler example, to generate a basic list of numbers, instead of a multi-line loop, you can write List<Integer> numbers = IntStream.range(0, 5).boxed().toList(); This single line creates a stream of numbers from 0 to 4, prepares them for the list with the `.boxed()` method, and collects them into the final result.

  • From bfca746fc03de0e3e2e90f9b62d51db95816edfc Mon Sep 17 00:00:00 2001 From: Elijah Babayemi Date: Mon, 4 Aug 2025 16:05:07 -0400 Subject: [PATCH 042/357] Added Summary and Reading Questions section to Chapter 5 --- source/ch6_loopsanditeration.ptx | 101 +++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) diff --git a/source/ch6_loopsanditeration.ptx b/source/ch6_loopsanditeration.ptx index 0ca4441..fd10c12 100644 --- a/source/ch6_loopsanditeration.ptx +++ b/source/ch6_loopsanditeration.ptx @@ -223,4 +223,105 @@ public class DoWhileExample {
    +
    + Summary & Reading Questions +

    +

      +
    1. +

      Java’s for loop syntax allows you to control loop initialization, condition, and update in one line using the format for (init; condition; update).

      +
    2. +
    3. +

      To loop over lists or arrays in Java, the enhanced for-each loop uses the syntax for (type var : collection), which is similar to Python’s for item in list.

      +
    4. +
    5. +

      Python’s range() function supports start, stop, and step, which directly maps to the three components of a Java for loop.

      +
    6. +
    7. +

      Java also supports the while loop, which executes a block of code while a condition is true, similar to Python’s while loop.

      +
    8. +
    9. +

      Java’s do-while loop guarantees the loop body executes at least once, because the condition is evaluated after the loop body.

      +
    10. +
    11. +

      To iterate through characters in a Java String, use toCharArray() along with a for-each loop.

      +
    12. +
    +

    + + + + + +

    Which of the following is the correct format for a definite loop in Java that runs 10 times?

    +
    + + +

    for i in range(10):

    +

    No, that is Python syntax.

    +
    + +

    for (int i = 0; i < 10; i++)

    +

    Correct! That’s the proper Java syntax for a definite loop.

    +
    + +

    loop i from 0 to 10

    +

    No, this is not valid syntax in Java.

    +
    + +

    for (i < 10; i++)

    +

    No, the initialization part is missing in this Java loop.

    +
    +
    +
    + + + +

    Which loop correctly iterates through all elements in a Java array of integers?

    +
    + + +

    for (int i : array)

    +

    Yes! This is Java's enhanced for-each loop for arrays.

    +
    + +

    for (i in array)

    +

    No, that's closer to Python syntax.

    +
    + +

    for (int i = 0; i < array; i++)

    +

    No, array is not a valid condition; use array.length.

    +
    + +

    foreach i in array:

    +

    No, this is not valid Java syntax.

    +
    +
    +
    + + + +

    What is a unique characteristic of the Java do-while loop compared to the while loop?

    +
    + + +

    It checks the condition before the loop body runs.

    +

    No, that describes a regular while loop.

    +
    + +

    It always runs infinitely.

    +

    No, a do-while loop will stop when its condition becomes false.

    +
    + +

    It guarantees the loop body runs at least once.

    +

    Correct! The do-while loop checks the condition after running the loop body.

    +
    + +

    It is not supported in Java.

    +

    No, Java does support do-while loops.

    +
    +
    +
    + +
    +
    \ No newline at end of file From 2fb17535ff2728e88f987909f3493d47c7f7b8d1 Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Mon, 4 Aug 2025 21:16:20 -0400 Subject: [PATCH 043/357] renumber early chapters --- ...3_firstjavaprogram.ptx => ch2_firstjavaprogram.ptx} | 0 .../{ch4_javadatatypes.ptx => ch3_javadatatypes.ptx} | 0 source/{ch5_conditionals.ptx => ch4_conditionals.ptx} | 0 ...loopsanditeration.ptx => ch5_loopsanditeration.ptx} | 0 ...ch7_definingclasses.ptx => ch6_definingclasses.ptx} | 0 source/main.ptx | 10 +++++----- 6 files changed, 5 insertions(+), 5 deletions(-) rename source/{ch3_firstjavaprogram.ptx => ch2_firstjavaprogram.ptx} (100%) rename source/{ch4_javadatatypes.ptx => ch3_javadatatypes.ptx} (100%) rename source/{ch5_conditionals.ptx => ch4_conditionals.ptx} (100%) rename source/{ch6_loopsanditeration.ptx => ch5_loopsanditeration.ptx} (100%) rename source/{ch7_definingclasses.ptx => ch6_definingclasses.ptx} (100%) diff --git a/source/ch3_firstjavaprogram.ptx b/source/ch2_firstjavaprogram.ptx similarity index 100% rename from source/ch3_firstjavaprogram.ptx rename to source/ch2_firstjavaprogram.ptx diff --git a/source/ch4_javadatatypes.ptx b/source/ch3_javadatatypes.ptx similarity index 100% rename from source/ch4_javadatatypes.ptx rename to source/ch3_javadatatypes.ptx diff --git a/source/ch5_conditionals.ptx b/source/ch4_conditionals.ptx similarity index 100% rename from source/ch5_conditionals.ptx rename to source/ch4_conditionals.ptx diff --git a/source/ch6_loopsanditeration.ptx b/source/ch5_loopsanditeration.ptx similarity index 100% rename from source/ch6_loopsanditeration.ptx rename to source/ch5_loopsanditeration.ptx diff --git a/source/ch7_definingclasses.ptx b/source/ch6_definingclasses.ptx similarity index 100% rename from source/ch7_definingclasses.ptx rename to source/ch6_definingclasses.ptx diff --git a/source/main.ptx b/source/main.ptx index fd70e99..6a3df61 100644 --- a/source/main.ptx +++ b/source/main.ptx @@ -8,11 +8,11 @@ The PreTeXt Interactive Edition - - - - - + + + git + + From a11cbe4aac672d49b553ae18322567f31e0bc23c Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Tue, 5 Aug 2025 08:30:32 -0400 Subject: [PATCH 044/357] remove extra file --- source/ch_10_moredocumentation.ptx | 77 ------------------------------ 1 file changed, 77 deletions(-) delete mode 100644 source/ch_10_moredocumentation.ptx diff --git a/source/ch_10_moredocumentation.ptx b/source/ch_10_moredocumentation.ptx deleted file mode 100644 index 942fd2d..0000000 --- a/source/ch_10_moredocumentation.ptx +++ /dev/null @@ -1,77 +0,0 @@ - - - - - Java Documentation - -

    - All Java class libraries are documented and available online. - Here are two good resources for you to use: -

    - -

    -

      -
    • -

      - JavaDoc The Javadoconline website provides a nice searchable interface. Search for a classname and you will get the documentation you are looking for. -

      -
    • - -
    • -

      - JavaAPI contains the same information but in a browsable format. If you don’t know the class name exactly this is a good way to see what is close. -

      -
    • -
    -

    - -

    - In general the Javadoc page for any class contains information about: -

    - -

    -

      -
    • -

      - Where this class falls in the class hierarchy. - What classes are its parents and what classes are its decendents. -

      -
    • - -
    • -

      - A summary and some examples of using the class. -

      -
    • - -
    • -

      - A summary listing of instance variables -

      -
    • - -
    • -

      - A summary listing of Constructors -

      -
    • - -
    • -

      - A summary listing of Methods -

      -
    • - -
    • -

      - Detailed documentation on constructors and methods. -

      -
    • -
    -

    - -

    - Typically the Javadoc pages are constructed from the source code where the class is implemented. - This encourages Java programmers to do a good job of documenting their code, while providing a user friendly way to read the documentation without looking at the code directly. -

    -
    \ No newline at end of file From 843d4703ccb274e41b57d53c1346167a58417823 Mon Sep 17 00:00:00 2001 From: Tristan-Raz Date: Tue, 5 Aug 2025 11:29:23 -0400 Subject: [PATCH 045/357] Fixes formatting to read better and fixes grammar mistakes. --- source/ch8_filehandling.ptx | 370 ++++++++++++++++-------------------- 1 file changed, 167 insertions(+), 203 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 933b24e..242c1d9 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -21,7 +21,7 @@ import java.io.File; - +

    @@ -31,7 +31,7 @@ import java.util.Scanner; - +

    @@ -41,7 +41,7 @@ import java.io.FileWriter; - +

    @@ -51,45 +51,166 @@ import java.io.IOException; - + import java.io.FileNotFoundException - + -

    - Creating Files - +
    + Reading Files +

    - Before we can write code that creates a file, we must first import the necessary classes mentioned in the previous section (Scanner and FileWriter are not needed for a class that only creates files) and create a class. We will call this class CreateFile. + Let's take a look at how we can use Java to read file contents. We'll start again with library imports and building a class, this time importing the Scanner and FileNotFoundException classes. We will call this class ReadFile:

    import java.io.File; - import java.io.IOException; + import java.io.FileNotFoundException; + import java.util.Scanner - public class CreateFile { + public class ReadFile { public static void main(String[] args) { } } - +

    - Next, within the main function, we will create a File object. It is important to create a meaningful name for the File object. We will call ours myFile. + We will then create a new File object exactly the same as the one from the section on creating files. Additionally, we will create a Scanner object. The Scanner object is the object that does the file reading. We will call this scanner fileReader:

    File myFile = new File("myfile.txt"); - + Scanner fileReader = new Scanner(myFile); + + + +

    + The next lines consists of a Python code examplethat reads each line of the file passed to the Scanner object.: +

    + + + + with open("filename.txt", "r") as file_reader: + for line in file_reader: + print(line.strip()) + + + +

    + The equivalent Java code: +

    + + + + while (fileReader.hasNextLine()) { + String data = fileReader.nextLine(); + System.out.println(data); + } + fileReader.close(); + + + +

    + The hasNextLine() method checks checks if the line below the current line has any data. This will evaluate to true even if the next line only contains blank spaces. Within the while loop, a string variable called data is used to store the current line that the Scanner object is pointing to. The nextLine() method does two things. Firstly, it returns the current line when called. Secondly, it moves the Scanner's position to the next line. In other words, for each iteration of the while loop, each line in the text is read, stored temporarily in the data variable, and printed to the console. Finally, the close() method accomplishes and holds the same importance as in the section on writing to files. +

    + +

    + Alternatively, the following code can be used to store the all lines of myfile.txt to one variable: +

    + + + + String data = ""; + while (fileReader.hasNextLine()) { + data = data + fileReader.nextLine() + System.lineSeparator(); + } + System.out.println(data); + fileReader.close(); + + + + +

    + Pay close attention to the details of this code. data must be declared using an empty string or it may not work correctly within the while loop. Additionally, care must be given to reassigning data in the while loop. data is concatinated (to ensure all lines are included) with fileReader.nextLine() and a new line operator. Each step of this process ensures what is stored in data matches exactly what is in myfile.txt. +

    +
    + +

    + Using the second method of storing all file contents to one file, the resulting full code including try/catch blocks (this time using FileNotFoundException instead of IOException) will look something like this. First, the Python code: +

    + + + + try: + with open("myfile.txt", "r") as file_reader: + data = "" + for line in file_reader: + data += line # line already includes the newline character + print(data) + except FileNotFoundError as e: + print("An error occurred.") + import traceback + traceback.print_exc() + + + + +

    + And the Java equivalent: +

    + + + + import java.io.File; + import java.io.FileNotFoundException; + import java.util.Scanner + + public class ReadFile { + public static void main(String[] args) { + try { + File myFile = new File("myfile.txt"); + Scanner fileReader = new Scanner(myFile); + String data = ""; + while (fileReader.hasNextLine()) { + data = data + fileReader.nextLine() + System.lineSeparator(); + } + System.out.println(data); + fileReader.close(); + } catch (FileNotFoundException e) { + System.out.println("An error occurred."); + e.printStackTrace(); + } + } + } + + + +

    + In this code, we simply print the contents of the file to the console, but it is easy to imagine how the data variable could be used in conjunction with the write class created in the previous section to create a copy of myfile.txt. +

    +
    + +
    + Creating Files + +

    + We will now create a File object. It is important to create a meaningful name for the File object. We will call ours myFile. +

    + + + + File myFile = new File("myfile.txt"); + @@ -118,7 +239,7 @@ print(f"The file {filename} was created successfully.") else: print(f"The file {filename} already exists.") - +

    @@ -139,7 +260,7 @@ } } } - + @@ -164,7 +285,7 @@ System.out.println("An error occurred."); e.printStackTrace(); } - + @@ -208,7 +329,7 @@ print("An error occurred.") import traceback traceback.print_exc() - +

    @@ -236,7 +357,7 @@ } } - +

    @@ -254,7 +375,7 @@ File myFile = new File("C:\\Users\\UserName\\Documents\\myfile.txt"); - +

    @@ -264,7 +385,7 @@ File myFile = new File("/home/UserName/Documents/myfile.txt"); - +

    @@ -276,7 +397,7 @@

    - To write to a file, we will need to create a different class. We will do the same setup as the previous section. First, we will import the classes (File and Scanner are not needed) and create the framework for a class that will write to a file. Let's call this class WriteFile: + Let us create the framework for a class that will write to a file. Let's call this class WriteFile:

    @@ -289,7 +410,7 @@ } } - +

    @@ -299,7 +420,7 @@ FileWriter myWriter = new FileWriter("myfile.txt"); - +

    @@ -310,7 +431,7 @@ myWriter.write("File successfully updated!"); myWriter.close(); - + @@ -325,14 +446,12 @@ - try: - with open("myfile.txt", "w") as my_writer: - my_writer.write("File successfully updated!") - print("File successfully written to.") - except OSError as e: - print("An error occurred.") - import traceback - traceback.print_exc() + with open("filename.txt", "r") as file_reader: + while True: + line = file_reader.readline() + if not line: # End of file + break + print(line.strip()) @@ -351,7 +470,7 @@ System.out.println("An error occurred."); e.printStackTrace(); } - +

    @@ -368,7 +487,7 @@ print("An error occurred.") import traceback traceback.print_exc() - +

    @@ -393,7 +512,7 @@ } } } - +

    @@ -413,7 +532,7 @@ FileWriter myWriter = new FileWriter("myfile.txt", true); // true enables append mode - +

    @@ -438,206 +557,51 @@ } } } - +

    - and then run the program twice, the contents of myfile.txt would be: + Then if we run the program twice, the contents of myfile.txt would be:

    File successfully updated!File successfully updated! - - - -

    - This doesn't look very good! There is no space between the first and second sentences! We can make this look a little better by simply adding a space after the exclamation mark in the string: -

    - - - - myWriter.write("File successfully updated! "); // Added space at end - myWriter.close(); - +

    - This works fine if you want all text to be on the same line, but what if we want each additional write to appear on a new line? The first solution may be to use the \n newline character: + This doesn't look very good! If we want each additional write to appear on a new line? The first solution may be to use the \n newline character:

    myWriter.write("File successfully updated!\n"); // Added newline character myWriter.close(); - + - +

    - This would work fine most of the time, but older Windows programs and operating systems use the \r\n newline character. To ensure the text appears on a new line regardless of what system the code is running on, concatenate the string with the System.lineSeparator() method: + The System.lineseseparator() method is a better solution. This method returns the system's default line separator, which is platform-dependent. For example, on Windows, it returns \n, while on Linux and macOS, it returns \n. Using this method ensures that your code works correctly across different operating systems:

    myWriter.write("File successfully updated!" + System.lineseparator()); // Added newline character myWriter.close(); - +

    - Running either variation used for adding new lines twice will result in the following contents in myfile.txt: + Running it twice will result in the following contents in myfile.txt:

    File successfully updated! File successfully updated! - - -
    - -
    - Reading Files - -

    - Let's take a look at how we can use Java to read file contents. We'll start again with library imports and building a class, this time importing the Scanner and FileNotFoundException classes. We will call this class ReadFile: -

    - - - - import java.io.File; - import java.io.FileNotFoundException; - import java.util.Scanner - - public class ReadFile { - public static void main(String[] args) { - - } - } - - - -

    - We will then create a new File object exactly the same as the one from the section on creating files. Additionally, we will create a Scanner object. The Scanner object is the object that does the file reading. We will call this scanner fileReader: -

    - - - - File myFile = new File("myfile.txt"); - Scanner fileReader = new Scanner(myFile); - - - - -

    - The myFile File object we created on the first line was passed to the Scanner object created on the second line. -

    -
    - -

    - The next lines consist of a while loop that reads each line of the file passed to the Scanner object and reads them. First, a Python code example. A for loop is used instead in the Python example: -

    - - - - with open("filename.txt", "r") as file_reader: - for line in file_reader: - print(line.strip()) - + - -

    - The equivalent Java code: -

    - - - - while (fileReader.hasNextLine()) { - String data = fileReader.nextLine(); - System.out.println(data); - } - fileReader.close(); - - - -

    - The hasNextLine() method checks checks if the line below the current line has any data. This will evaluate to true even if the next line only contains blank spaces. Within the while loop, a string variable called data is used to store the current line that the Scanner object is pointing to. The nextLine() method does two things. Firstly, it returns the current line when called. Secondly, it moves the Scanner's position to the next line. In other words, for each iteration of the while loop, each line in the text is read, stored temporarily in the data variable, and printed to the console. Finally, the close() method accomplishes and holds the same importance as in the section on writing to files. -

    - -

    - Alternatively, the following code can be used to store the all lines of myfile.txt to one variable: -

    - - - - String data = ""; - while (fileReader.hasNextLine()) { - data = data + fileReader.nextLine() + System.lineSeparator(); - } - System.out.println(data); - fileReader.close(); - - - - -

    - Pay close attention to the details of this code. data must be declared using an empty string or it may not work correctly within the while loop. Additionally, care must be given to reassigning data in the while loop. data is concatinated (to ensure all lines are included) with fileReader.nextLine() and a new line operator. Each step of this process ensures what is stored in data matches exactly what is in myfile.txt. -

    -
    - -

    - Using the second method of storing all file contents to one file, the resulting full code including try/catch blocks (this time using FileNotFoundException instead of IOException) will look something like this. First, the Python code: -

    - - - - try: - with open("myfile.txt", "r") as file_reader: - data = "" - for line in file_reader: - data += line # line already includes the newline character - print(data) - except FileNotFoundError as e: - print("An error occurred.") - import traceback - traceback.print_exc() - - - - -

    - And the Java equivalent: -

    - - - - import java.io.File; - import java.io.FileNotFoundException; - import java.util.Scanner - - public class ReadFile { - public static void main(String[] args) { - try { - File myFile = new File("myfile.txt"); - Scanner fileReader = new Scanner(myFile); - String data = ""; - while (fileReader.hasNextLine()) { - data = data + fileReader.nextLine() + System.lineSeparator(); - } - System.out.println(data); - fileReader.close(); - } catch (FileNotFoundException e) { - System.out.println("An error occurred."); - e.printStackTrace(); - } - } - } - - - -

    - In this code, we simply print the contents of the file to the console, but it is easy to imagine how the data variable could be used in conjunction with the write class created in the previous section to create a copy of myfile.txt. -

    @@ -661,7 +625,7 @@ } } } - +

    From 3cd5d5a8f7e24d5b7e0535b7ffb7990d53891db2 Mon Sep 17 00:00:00 2001 From: Tristan-Raz Date: Tue, 5 Aug 2025 11:33:47 -0400 Subject: [PATCH 046/357] Moved the section too far previous push, fixing it to infront of writing files --- source/ch8_filehandling.ptx | 276 ++++++++++++++++++------------------ 1 file changed, 138 insertions(+), 138 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 242c1d9..c0f2e91 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -62,144 +62,6 @@

    -
    - Reading Files - -

    - Let's take a look at how we can use Java to read file contents. We'll start again with library imports and building a class, this time importing the Scanner and FileNotFoundException classes. We will call this class ReadFile: -

    - - - - import java.io.File; - import java.io.FileNotFoundException; - import java.util.Scanner - - public class ReadFile { - public static void main(String[] args) { - - } - } - - - -

    - We will then create a new File object exactly the same as the one from the section on creating files. Additionally, we will create a Scanner object. The Scanner object is the object that does the file reading. We will call this scanner fileReader: -

    - - - - File myFile = new File("myfile.txt"); - Scanner fileReader = new Scanner(myFile); - - - -

    - The next lines consists of a Python code examplethat reads each line of the file passed to the Scanner object.: -

    - - - - with open("filename.txt", "r") as file_reader: - for line in file_reader: - print(line.strip()) - - - -

    - The equivalent Java code: -

    - - - - while (fileReader.hasNextLine()) { - String data = fileReader.nextLine(); - System.out.println(data); - } - fileReader.close(); - - - -

    - The hasNextLine() method checks checks if the line below the current line has any data. This will evaluate to true even if the next line only contains blank spaces. Within the while loop, a string variable called data is used to store the current line that the Scanner object is pointing to. The nextLine() method does two things. Firstly, it returns the current line when called. Secondly, it moves the Scanner's position to the next line. In other words, for each iteration of the while loop, each line in the text is read, stored temporarily in the data variable, and printed to the console. Finally, the close() method accomplishes and holds the same importance as in the section on writing to files. -

    - -

    - Alternatively, the following code can be used to store the all lines of myfile.txt to one variable: -

    - - - - String data = ""; - while (fileReader.hasNextLine()) { - data = data + fileReader.nextLine() + System.lineSeparator(); - } - System.out.println(data); - fileReader.close(); - - - - -

    - Pay close attention to the details of this code. data must be declared using an empty string or it may not work correctly within the while loop. Additionally, care must be given to reassigning data in the while loop. data is concatinated (to ensure all lines are included) with fileReader.nextLine() and a new line operator. Each step of this process ensures what is stored in data matches exactly what is in myfile.txt. -

    -
    - -

    - Using the second method of storing all file contents to one file, the resulting full code including try/catch blocks (this time using FileNotFoundException instead of IOException) will look something like this. First, the Python code: -

    - - - - try: - with open("myfile.txt", "r") as file_reader: - data = "" - for line in file_reader: - data += line # line already includes the newline character - print(data) - except FileNotFoundError as e: - print("An error occurred.") - import traceback - traceback.print_exc() - - - - -

    - And the Java equivalent: -

    - - - - import java.io.File; - import java.io.FileNotFoundException; - import java.util.Scanner - - public class ReadFile { - public static void main(String[] args) { - try { - File myFile = new File("myfile.txt"); - Scanner fileReader = new Scanner(myFile); - String data = ""; - while (fileReader.hasNextLine()) { - data = data + fileReader.nextLine() + System.lineSeparator(); - } - System.out.println(data); - fileReader.close(); - } catch (FileNotFoundException e) { - System.out.println("An error occurred."); - e.printStackTrace(); - } - } - } - - - -

    - In this code, we simply print the contents of the file to the console, but it is easy to imagine how the data variable could be used in conjunction with the write class created in the previous section to create a copy of myfile.txt. -

    -
    -
    Creating Files @@ -389,6 +251,144 @@
    +
    + Reading Files + +

    + Let's take a look at how we can use Java to read file contents. We'll start again with library imports and building a class, this time importing the Scanner and FileNotFoundException classes. We will call this class ReadFile: +

    + + + + import java.io.File; + import java.io.FileNotFoundException; + import java.util.Scanner + + public class ReadFile { + public static void main(String[] args) { + + } + } + + + +

    + We will then create a new File object exactly the same as the one from the section on creating files. Additionally, we will create a Scanner object. The Scanner object is the object that does the file reading. We will call this scanner fileReader: +

    + + + + File myFile = new File("myfile.txt"); + Scanner fileReader = new Scanner(myFile); + + + +

    + The next lines consists of a Python code examplethat reads each line of the file passed to the Scanner object.: +

    + + + + with open("filename.txt", "r") as file_reader: + for line in file_reader: + print(line.strip()) + + + +

    + The equivalent Java code: +

    + + + + while (fileReader.hasNextLine()) { + String data = fileReader.nextLine(); + System.out.println(data); + } + fileReader.close(); + + + +

    + The hasNextLine() method checks checks if the line below the current line has any data. This will evaluate to true even if the next line only contains blank spaces. Within the while loop, a string variable called data is used to store the current line that the Scanner object is pointing to. The nextLine() method does two things. Firstly, it returns the current line when called. Secondly, it moves the Scanner's position to the next line. In other words, for each iteration of the while loop, each line in the text is read, stored temporarily in the data variable, and printed to the console. Finally, the close() method accomplishes and holds the same importance as in the section on writing to files. +

    + +

    + Alternatively, the following code can be used to store the all lines of myfile.txt to one variable: +

    + + + + String data = ""; + while (fileReader.hasNextLine()) { + data = data + fileReader.nextLine() + System.lineSeparator(); + } + System.out.println(data); + fileReader.close(); + + + + +

    + Pay close attention to the details of this code. data must be declared using an empty string or it may not work correctly within the while loop. Additionally, care must be given to reassigning data in the while loop. data is concatinated (to ensure all lines are included) with fileReader.nextLine() and a new line operator. Each step of this process ensures what is stored in data matches exactly what is in myfile.txt. +

    +
    + +

    + Using the second method of storing all file contents to one file, the resulting full code including try/catch blocks (this time using FileNotFoundException instead of IOException) will look something like this. First, the Python code: +

    + + + + try: + with open("myfile.txt", "r") as file_reader: + data = "" + for line in file_reader: + data += line # line already includes the newline character + print(data) + except FileNotFoundError as e: + print("An error occurred.") + import traceback + traceback.print_exc() + + + + +

    + And the Java equivalent: +

    + + + + import java.io.File; + import java.io.FileNotFoundException; + import java.util.Scanner + + public class ReadFile { + public static void main(String[] args) { + try { + File myFile = new File("myfile.txt"); + Scanner fileReader = new Scanner(myFile); + String data = ""; + while (fileReader.hasNextLine()) { + data = data + fileReader.nextLine() + System.lineSeparator(); + } + System.out.println(data); + fileReader.close(); + } catch (FileNotFoundException e) { + System.out.println("An error occurred."); + e.printStackTrace(); + } + } + } + + + +

    + In this code, we simply print the contents of the file to the console, but it is easy to imagine how the data variable could be used in conjunction with the write class created in the previous section to create a copy of myfile.txt. +

    +
    +
    Writing to Files From 915ba01504af4877d3abf900f824e28adc95f676 Mon Sep 17 00:00:00 2001 From: Eun Sung Wang <156254694+esw0624@users.noreply.github.com> Date: Tue, 5 Aug 2025 13:20:33 -0400 Subject: [PATCH 047/357] Adding Summary and Reading Questions Section on Chapter 9 --- source/ch9_commonmistakes.ptx | 141 ++++++++++++++++++++++++++++++++++ 1 file changed, 141 insertions(+) diff --git a/source/ch9_commonmistakes.ptx b/source/ch9_commonmistakes.ptx index 9b6b6ed..81a25f0 100644 --- a/source/ch9_commonmistakes.ptx +++ b/source/ch9_commonmistakes.ptx @@ -154,4 +154,145 @@

    + +
    + Summary & Reading Questions +

      +
    1. +

      In Java, every variable must be declared with its type before use; undeclared variables cause compilation errors.

      +
    2. +
    3. +

      Java requires explicit import statements for classes from external packages (e.g., java.util.Scanner); otherwise, you get "cannot find symbol" errors.

      +
    4. +
    5. +

      The new keyword is mandatory when creating new objects; forgetting it leads to errors as Java treats the constructor call incorrectly.

      +
    6. +
    7. +

      Every Java statement must end with a semicolon (;); missing semicolons cause syntax errors.

      +
    8. +
    9. +

      Java uses generics for type safety in containers like ArrayList; forgetting to specify the contained type leads to compiler warnings about unchecked operations.

      +
    10. +
    11. +

      Compiler error messages may sometimes be misleading; understanding common mistakes helps quickly identify the root cause.

      +
    12. +

    + + + +

    What happens if you use a variable in Java without declaring it first?

    +
    + + +

    The compiler gives an error indicating the variable cannot be found.

    +

    Correct! Java requires all variables to be declared before use.

    +
    + +

    The variable is automatically declared as type Object.

    +

    No. Java does not implicitly declare variables.

    +
    + +

    The program compiles but throws an error at runtime.

    +

    No. This is a compile-time error.

    +
    + +

    Java ignores the variable and continues compiling.

    +

    No. Java will stop compiling with an error.

    +
    +
    +
    + + +

    Why must you include import statements for classes like Scanner?

    +
    + + +

    Because these classes belong to external packages and are not automatically available.

    +

    Correct! Java requires explicit imports for external classes.

    +
    + +

    Because Java does not support standard input without imports.

    +

    No. Standard input is supported but needs the Scanner class explicitly imported.

    +
    + +

    Because the classes are only available in Python, not Java.

    +

    No. This is a Java-specific requirement.

    +
    + +

    Because the compiler ignores unknown classes without imports.

    +

    No. It causes a compile error instead.

    +
    +
    +
    + + +

    What is the correct way to instantiate a new object of class Scanner?

    +
    + + +

    new Scanner(...)

    +

    Correct! The new keyword must be used to create new objects.

    +
    + +

    Scanner(...) without new

    +

    No. Omitting new causes errors.

    +
    + +

    Scanner.create(...)

    +

    No. This method does not exist for object creation.

    +
    + +

    Scanner = new Scanner()

    +

    No. The syntax is incorrect; the variable name must be assigned the new object.

    +
    +
    +
    + + +

    What causes a "';' expected" error in Java?

    +
    + + +

    A missing semicolon at the end of a statement.

    +

    Correct! Java statements must end with a semicolon.

    +
    + +

    Using too many semicolons in a line.

    +

    No. Extra semicolons do not cause this error.

    +
    + +

    Missing braces {}.

    +

    No. This error specifically refers to missing semicolons.

    +
    + +

    Using single quotes instead of double quotes.

    +

    No. This is unrelated to semicolon errors.

    +
    +
    +
    + + +

    What warning occurs when you use an ArrayList without specifying a type?

    +
    + + +

    An "unchecked" warning indicating potential type safety issues.

    +

    Correct! Using raw types disables generic type checks.

    +
    + +

    A syntax error.

    +

    No. This is a compiler warning, not an error.

    +
    + +

    A runtime exception.

    +

    No. It only warns about possible runtime errors.

    +
    + +

    A logical error in the program.

    +

    No. The warning points out type safety concerns.

    +
    +
    +
    +
    +
    From 08e3325b24c30e8ecc9fd7ab0318817d199f08ef Mon Sep 17 00:00:00 2001 From: colin flaherty Date: Tue, 5 Aug 2025 13:26:06 -0400 Subject: [PATCH 048/357] making file reading activecode run. Issue #102 --- source/ch8_filehandling.ptx | 47 +++++++++++++++++++++++++++++-------- 1 file changed, 37 insertions(+), 10 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index c0f2e91..51d1db0 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -256,17 +256,30 @@

    Let's take a look at how we can use Java to read file contents. We'll start again with library imports and building a class, this time importing the Scanner and FileNotFoundException classes. We will call this class ReadFile: -

    - - +

    + +
    +                    1
    +                    2
    +                    3
    +                    4
    +                    5
    +                    6
    +                    7
    +                    8
    +                
    +
    + + + import java.io.File; import java.io.FileNotFoundException; - import java.util.Scanner + import java.util.Scanner; public class ReadFile { public static void main(String[] args) { - + } } @@ -280,6 +293,8 @@ File myFile = new File("myfile.txt"); Scanner fileReader = new Scanner(myFile); + + @@ -299,13 +314,25 @@ The equivalent Java code:

    - + - while (fileReader.hasNextLine()) { - String data = fileReader.nextLine(); - System.out.println(data); + import java.io.File; + import java.io.FileNotFoundException; + import java.util.Scanner; + + public class ReadFile { + public static void main(String[] args) { + File myFile = new File("myfile.txt"); + Scanner fileReader = new Scanner(myFile); + + while (fileReader.hasNextLine()) { + String data = fileReader.nextLine(); + System.out.println(data); + } + fileReader.close(); + + } } - fileReader.close(); From 4fa8d7e076781cd23ddd5511bfcfbe0d49e12095 Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Tue, 5 Aug 2025 13:30:50 -0400 Subject: [PATCH 049/357] improve section 1 of the new recursion chapter --- source/chx_recursion.ptx | 160 +++++++++++++++++++++++---------------- 1 file changed, 93 insertions(+), 67 deletions(-) diff --git a/source/chx_recursion.ptx b/source/chx_recursion.ptx index 4304a89..4f3601e 100644 --- a/source/chx_recursion.ptx +++ b/source/chx_recursion.ptx @@ -3,78 +3,104 @@ Recursion in Java -
    + +
    Basic Recursion

    In this chapter, we will explore how to translate your recursive logic from Python to Java. While the core concepts of recursion remain the same, the syntax and structure of your code will change somewhat.

    -

    recursion - As you may know from Python, recursion is a powerful problem-solving technique involving base cases and recursive steps in which a function or method calls itself. When moving to Java, the core logic you've learned remains identical. The challenge is adapting that logic to Java's statically-typed, class-based syntax. -

    -

    - Let's take the familiar factorial function (which calculates the factorial of a number, namely the product of all positive integers from 1 to n). The logical steps in the code are the same, but the implementation details change. -

    -

    - Here is the standard implementation in Python: -

    - - - class MathTools: - """A utility class for mathematical operations.""" - def factorial(n: int) -> int: - """Calculates the factorial of n using recursion.""" - # A check for negative numbers is good practice. - if n < 0: - raise ValueError("Factorial is not defined for negative numbers.") # Base Case: 0! or 1! is 1 - if n <= 1: - return 1 # Recursive Step: n * (n-1)! - # The call is now to the method within the class. - return n * MathTools.factorial(n - 1)# This block shows how to use the class method. - if __name__ == "__main__": - number = 5 - result = MathTools.factorial(number) # Call the method on the class - print(f"{number}! is {result}") - - -

    - The Java version follows the same recursive logic but requires three key syntax changes: the method must be inside a class, you must declare the parameter and return types (int n and int return), and you use public static to make it callable from main. The base case and recursive step remain conceptually identical. -

    -

    - Here is the equivalent Java code: -

    - - - public class MathTools { /** - * Calculates the factorial of n using recursion. - * This is a static method, like Python's @staticmethod. - * @param n The non-negative integer. - * @return The factorial of n as a long to prevent overflow for larger numbers. - */ - public static int factorial(int n) { - // A check for negative numbers is good practice. - if (n < 0) { - throw new IllegalArgumentException("Factorial is not defined for negative numbers."); - } // Base Case: 0! or 1! is 1 - if (n <= 1) { - return 1; - } // Recursive Step: n * (n-1)! - return n * factorial(n - 1); - } /** - * The main entry point for the application. - * This is the Java equivalent of Python's 'if __name__ == "__main__":' - */ - public static void main(String[] args) { - int number = 5; - // The static method is called directly on the class. - long result = MathTools.factorial(number); System.out.println(number + "! is " + result); - } - } - - -

    - Notice the key differences: instead of def, the method signature public static int declares its scope, that it belongs to the class rather than an object, and that it returns an int. All logic is contained within curly braces {}. -

    +

    recursion + As you may know from Python, recursion is a powerful problem-solving technique involving base cases and recursive steps in which a function or method calls itself. When moving to Java, the core logic you've learned remains identical. The challenge is adapting that logic to Java's statically-typed, class-based syntax. +

    +

    + Let's take the familiar factorial function (which calculates the factorial of a number, namely the product of all positive integers from 1 to n). The logical steps in the code are the same, but the implementation details change. +

    +

    + Here is a simple Python function implementation: +

    + + +def factorial(n): + # Check for negative numbers + if n < 0: + print("Factorials are only defined on non-negative integers.") + return + # Base Case: 0! or 1! is 1 + if n <= 1: + return 1 + # Recursive Step: n * (n-1)! + return n * factorial(n - 1) + +def main(): + number = 5 + print(str(number) + "! is " + str(factorial(number))) + +main() + + + +

    + Many Python programs organize related functions into classes. The same factorial function can be placed inside a class as a method. Then you need to create an instance of the class to call the method. There we create the class MathTools with a method factorial, and we call it from the main function. +

    + + +class MathTools: + def factorial(self, n): + # Check for negative numbers + if n < 0: + print("Factorials are only defined on non-negative integers.") + return + # Base Case: 0! or 1! is 1 + if n <= 1: + return 1 + # Recursive Step: n * (n-1)! + return n * self.factorial(n - 1) + +def main(): + # Create an instance of the class and call the method + math_tools = MathTools() + number = 5 + print(str(number) + "! is " + str(math_tools.factorial(number))) + +main() + + + +

    + See if you can spot the differences in the Java version below. +

    +

    + Here is the equivalent Java code: +

    + + +public class MathTools { + public static int factorial(int n) { + // Check for negative numbers + if (n < 0) { + System.out.println("Factorials are only defined on non-negative integers."); + return -1; // Return -1 to indicate error + } + // Base Case: 0! or 1! is 1 + if (n <= 1) { + return 1; + } + // Recursive Step: n * (n-1)! + return n * factorial(n - 1); + } + + public static void main(String[] args) { + int number = 5; + System.out.println(number + "! is " + factorial(number)); + } +} + + +

    + Notice the key differences from Python: instead of def factorial(n):, Java uses public static int factorial(int n) which declares the method's visibility as public, that it belongs to the class rather than an instance (hence, static), the return type as integer, and the parameter type also as integer. The recursive logic—base case and recursive step—remains identical to Python, but all code blocks use curly braces {} instead of indentation. +

    +
    Common Recursive Patterns From 5c8f5fbcb207393708f9aac8c29ccba8cb723e05 Mon Sep 17 00:00:00 2001 From: Eun Sung Wang <156254694+esw0624@users.noreply.github.com> Date: Tue, 5 Aug 2025 14:46:32 -0400 Subject: [PATCH 050/357] Removed question 3 and 4 --- source/ch9_commonmistakes.ptx | 46 ----------------------------------- 1 file changed, 46 deletions(-) diff --git a/source/ch9_commonmistakes.ptx b/source/ch9_commonmistakes.ptx index 81a25f0..0bbd78a 100644 --- a/source/ch9_commonmistakes.ptx +++ b/source/ch9_commonmistakes.ptx @@ -225,52 +225,6 @@ - -

    What is the correct way to instantiate a new object of class Scanner?

    -
    - - -

    new Scanner(...)

    -

    Correct! The new keyword must be used to create new objects.

    -
    - -

    Scanner(...) without new

    -

    No. Omitting new causes errors.

    -
    - -

    Scanner.create(...)

    -

    No. This method does not exist for object creation.

    -
    - -

    Scanner = new Scanner()

    -

    No. The syntax is incorrect; the variable name must be assigned the new object.

    -
    -
    -
    - - -

    What causes a "';' expected" error in Java?

    -
    - - -

    A missing semicolon at the end of a statement.

    -

    Correct! Java statements must end with a semicolon.

    -
    - -

    Using too many semicolons in a line.

    -

    No. Extra semicolons do not cause this error.

    -
    - -

    Missing braces {}.

    -

    No. This error specifically refers to missing semicolons.

    -
    - -

    Using single quotes instead of double quotes.

    -

    No. This is unrelated to semicolon errors.

    -
    -
    -
    -

    What warning occurs when you use an ArrayList without specifying a type?

    From c7cffd62b3b0bcfad777c3a110d8872c70b84ba2 Mon Sep 17 00:00:00 2001 From: colin flaherty Date: Tue, 5 Aug 2025 15:18:54 -0400 Subject: [PATCH 051/357] commiting running code for the file reading section. Issue #102 --- source/ch8_filehandling.ptx | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 51d1db0..4609482 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -318,19 +318,21 @@ import java.io.File; import java.io.FileNotFoundException; - import java.util.Scanner; - - public class ReadFile { + import java.util.Scanner;public class Main { public static void main(String[] args) { - File myFile = new File("myfile.txt"); - Scanner fileReader = new Scanner(myFile); - - while (fileReader.hasNextLine()) { - String data = fileReader.nextLine(); - System.out.println(data); + try { + File myFile = new File("myfile.txt"); + Scanner fileReader = new Scanner(myFile); + System.out.println("Reading from file: " + myFile.getName()); + while (fileReader.hasNextLine()) { + String data = fileReader.nextLine(); + System.out.println(data); + } + fileReader.close(); // Close the scanner to release the file + } catch (FileNotFoundException e) { + System.out.println("An error occurred: The file was not found."); + e.printStackTrace(); } - fileReader.close(); - } } From f96da7f1b5d310e62f2c50b53195ca03ab3c5e2a Mon Sep 17 00:00:00 2001 From: Elijah Babayemi Date: Tue, 5 Aug 2025 15:35:12 -0400 Subject: [PATCH 052/357] Added Summary and Reading Questions section to Chapter 6 --- source/ch6_definingclasses.ptx | 147 +++++++++++++++++++++++++++++++++ 1 file changed, 147 insertions(+) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index 7a95433..2d97e94 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -1012,4 +1012,151 @@ public class Fraction extends Number implements Comparable<Fraction> {
    + +
    + Summary & Reading Questions +

      +
    1. +

      In Java, instance variables must be declared at the top of the class, unlike Python which allows dynamic creation of instance variables anywhere.

      +
    2. +
    3. +

      Java uses access modifiers like private to enforce encapsulation, encouraging data hiding and controlled access through getter and setter methods.

      +
    4. +
    5. +

      Java requires a separate constructor method to initialize objects, using the class name and defining parameters explicitly, whereas Python uses the __init__ method.

      +
    6. +
    7. +

      Every Java class inherits from the Object class, which provides default methods like toString() and equals(). Overriding toString() allows for more meaningful output when printing objects (similar to Python’s __str__).

      +
    8. +
    9. +

      Java’s equals() method checks object equivalence based on memory reference by default. To compare objects based on content (like Fraction values), you must override equals() and use it directly — object1.equals(object2) is not the same as object1 == object2.

      +
    10. +
    11. +

      Java supports inheritance through abstract classes like Number, which require subclasses (like Fraction) to implement specific methods such as intValue(), doubleValue(), etc., allowing Fraction to be used where a Number is expected.

      +
    12. +

    + + + + +

    How must instance variables be declared in Java compared to Python?

    +
    + + +

    They can be created dynamically anywhere in the class like Python.

    +

    No, Java does not allow dynamic creation of instance variables.

    +
    + +

    Instance variables are declared inside methods only.

    +

    No, instance variables belong to the class and are declared outside methods.

    +
    + +

    They must be declared at the top of the class before use.

    +

    Correct! Java requires upfront declaration of instance variables.

    +
    + +

    Java does not use instance variables.

    +

    No, instance variables are fundamental in Java classes.

    +
    +
    +
    + + + +

    What Java feature encourages encapsulation and controlled access to instance variables?

    +
    + + +

    Declaring all variables as public.

    +

    No, that would expose data and reduce encapsulation.

    +
    + +

    Using access modifiers like private and providing getter/setter methods.

    +

    Right! This is how Java enforces encapsulation.

    +
    + +

    Using global variables.

    +

    No, Java does not support global variables and this reduces encapsulation.

    +
    + +

    Avoiding the use of classes altogether.

    +

    No, encapsulation is a class-based concept in Java.

    +
    +
    +
    + + + +

    How does Java initialize objects differently than Python?

    +
    + + +

    Java uses a constructor method named after the class with explicit parameters.

    +

    Correct! Unlike Python's __init__, Java constructors share the class name.

    +
    + +

    Java uses the __init__ method like Python.

    +

    No, Java does not have __init__.

    +
    + +

    Java initializes objects automatically without constructors.

    +

    No, Java requires constructors for explicit initialization.

    +
    + +

    Java uses global initialization functions instead of constructors.

    +

    No, Java uses constructors, not global functions, for object initialization.

    +
    +
    +
    + + + +

    What must you do to get meaningful printed output and proper equality comparison for Java objects?

    +
    + + +

    Use == for content comparison and no need to override toString().

    +

    No, == compares memory references, not content.

    +
    + +

    Only override toString() and use == for equality.

    +

    No, you should override equals() to compare content correctly.

    +
    + +

    Java automatically handles content comparison without overrides.

    +

    No, default equals() compares references, not content.

    +
    + +

    Override toString() for printing and override equals() to compare object contents.

    +

    Yes! This improves output and content-based comparison.

    +
    +
    +
    + + + +

    Why does the Fraction class extend the abstract Number class in Java?

    +
    + + +

    To require implementation of methods like intValue() and allow Fraction to be used wherever Number is expected.

    +

    Correct! This integrates Fraction into Java’s numeric hierarchy.

    +
    + +

    Because Number implements operator overloading for Fraction.

    +

    No, Java does not support operator overloading.

    +
    + +

    To avoid writing constructors.

    +

    No, constructors are still needed in subclasses.

    +
    + +

    Because Number provides default sorting methods.

    +

    No, sorting is handled by interfaces like Comparable, not Number.

    +
    +
    +
    +
    +
    + \ No newline at end of file From 758bf7908bad15acca86597a2a052793cc143763 Mon Sep 17 00:00:00 2001 From: colin flaherty Date: Tue, 5 Aug 2025 15:42:47 -0400 Subject: [PATCH 053/357] fixes the second code block in 8.3. issue #102 --- source/ch8_filehandling.ptx | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 4609482..e89021f 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -291,10 +291,25 @@ - File myFile = new File("myfile.txt"); - Scanner fileReader = new Scanner(myFile); + import java.io.File; + import java.io.FileNotFoundException; + import java.util.Scanner;// Code generated on: 2025-08-05 + public class Main { + public static void main(String[] args) { + // This 'try-with-resources' statement handles opening the file + // and guarantees it is closed automatically, which is best practice. + try (Scanner fileReader = new Scanner(new File("myfile.txt"))) { - + // If this line is reached, the file was opened successfully. + System.out.println("Success! The file 'myfile.txt' is now open."); + + } catch (FileNotFoundException e) { + + // This block runs only if 'myfile.txt' does not exist. + System.out.println("Error: The file 'myfile.txt' could not be found."); + } + } + } From 892048e4990bca1e857e6965f969bd02b337c98e Mon Sep 17 00:00:00 2001 From: colin flaherty Date: Tue, 5 Aug 2025 15:49:19 -0400 Subject: [PATCH 054/357] Adds a working active code for the first code block. Issue #102 --- source/ch8_filehandling.ptx | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index e89021f..3378995 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -275,11 +275,22 @@ import java.io.File; import java.io.FileNotFoundException; - import java.util.Scanner; + import java.util.Scanner;// Code generated on: 2025-08-05 + public class Main { + public static void main(String[] args) { - public class ReadFile { - public static void main(String[] args) { - + // This 'try-with-resources' statement handles opening the file + // and guarantees it is closed automatically, which is best practice. + try (Scanner fileReader = new Scanner(new File("myfile.txt"))) { + + // If this line is reached, the file was opened successfully. + System.out.println("Success! The file 'myfile.txt' is now open."); + + } catch (FileNotFoundException e) { + + // This block runs only if 'myfile.txt' does not exist. + System.out.println("Error: The file 'myfile.txt' could not be found."); + } } } @@ -314,7 +325,7 @@

    - The next lines consists of a Python code examplethat reads each line of the file passed to the Scanner object.: + The next lines consists of a Python code example that reads each line of the file passed to the Scanner object.:

    @@ -406,7 +417,7 @@ import java.io.File; import java.io.FileNotFoundException; - import java.util.Scanner + import java.util.Scanner; public class ReadFile { public static void main(String[] args) { From aaa5fc18783c4b70bd437cedec24ede946272cac Mon Sep 17 00:00:00 2001 From: Elijah Babayemi Date: Tue, 5 Aug 2025 15:50:05 -0400 Subject: [PATCH 055/357] Added Summary and Reading Questions section to Chapter 4 --- source/ch3_javadatatypes.ptx | 4 +- source/ch4_conditionals.ptx | 138 +++++++++++++++++++++++++++++++++++ 2 files changed, 140 insertions(+), 2 deletions(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index ab3a790..b0b41ec 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -788,7 +788,7 @@ public class HistoMap { Improve the program above to remove the punctuation.

    -
    +
    Summary & Reading Questions

    1. @@ -813,7 +813,7 @@ public class HistoMap {

      Maps (HashMap and TreeMap) are Java's equivalent to Python dictionaries for storing key-value pairs.

    - +

    What is the correct way to declare an ArrayList that will hold String objects in Java?

    diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 6a38a39..6066ee1 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -310,5 +310,143 @@ Using this operator can make code shorter and more readable in cases where a sim

    +
    +
    + Summary & Reading Questions +

      +
    1. +

      Java requires parentheses around the condition and curly braces for code blocks in if statements, unlike Python which uses indentation alone.

      +
    2. +
    3. +

      Java uses else if instead of Python's elif, and allows optional curly braces for single-line blocks.

      +
    4. +
    5. +

      Java includes a switch statement for checking equality against constant values, which can replace long if-else chains for specific scenarios.

      +
    6. +
    7. +

      + Java uses the boolean data type to represent logical values true or false, commonly used in conditionals and control flow. +

      +
    8. +

    + + + +

    Which is a correct Java if statement syntax?

    +
    + + + +

    if (x > 0) { System.out.println("Positive"); }

    +
    + +

    Correct! Java requires parentheses and curly braces.

    +
    +
    + + +

    if x > 0: print("Positive")

    +
    + +

    No, that's Python syntax, not Java.

    +
    +
    + + +

    if x > 0 { System.out.println("Positive"); }

    +
    + +

    No, Java requires parentheses around the condition.

    +
    +
    + + +

    if (x > 0) print("Positive");

    +
    + +

    No, print is not a valid method in Java. Use System.out.println.

    +
    +
    +
    +
    + + +

    How do you write Python’s elif equivalent in Java?

    +
    + + + +

    elif (score > 90)

    +
    + +

    No, elif is used in Python, not Java.

    +
    +
    + + +

    else: if (score > 90)

    +
    + +

    Incorrect syntax; no colon in Java and not the right structure.

    +
    +
    + + +

    else if (score > 90)

    +
    + +

    Right! Java uses else if.

    +
    +
    + + +

    ifelse (score > 90)

    +
    + +

    No, ifelse is not a valid construct in Java.

    +
    +
    +
    +
    + + +

    What is one limitation of Java's switch statement?

    +
    + + + +

    It allows complex boolean expressions in case statements.

    +
    + +

    No, switch does not support complex expressions like if does.

    +
    +
    + + +

    It can be used with any type of object, including null.

    +
    + +

    No, using null in switch causes a runtime error.

    +
    +
    + + +

    It supports dynamic pattern matching by default.

    +
    + +

    No, Java switch supports limited pattern matching starting only in later versions.

    +
    +
    + + +

    It can only compare a variable to constant values using equality.

    +
    + +

    Correct! switch is limited to constant comparisons only.

    +
    +
    +
    +
    +
    \ No newline at end of file From 0173e451ab9fdd1ca226b102fa02dc59db7c0e59 Mon Sep 17 00:00:00 2001 From: colin flaherty Date: Tue, 5 Aug 2025 15:57:40 -0400 Subject: [PATCH 056/357] fixes all code in 8.3.fixed mistake due to not being able to build. issue #102 --- source/ch8_filehandling.ptx | 67 ++++++++++++++++++++----------------- 1 file changed, 37 insertions(+), 30 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 3378995..7de97b2 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -275,21 +275,20 @@ import java.io.File; import java.io.FileNotFoundException; - import java.util.Scanner;// Code generated on: 2025-08-05 - public class Main { - public static void main(String[] args) { - - // This 'try-with-resources' statement handles opening the file - // and guarantees it is closed automatically, which is best practice. - try (Scanner fileReader = new Scanner(new File("myfile.txt"))) { - - // If this line is reached, the file was opened successfully. - System.out.println("Success! The file 'myfile.txt' is now open."); - - } catch (FileNotFoundException e) { - - // This block runs only if 'myfile.txt' does not exist. - System.out.println("Error: The file 'myfile.txt' could not be found."); + import java.util.Scanner;public class Main { + public static void main(String[] args) { + try { + File myFile = new File("myfile.txt"); + Scanner fileReader = new Scanner(myFile); + System.out.println("Reading from file: " + myFile.getName()); + while (fileReader.hasNextLine()) { + String data = fileReader.nextLine(); + System.out.println(data); + } + fileReader.close(); // Close the scanner to release the file + } catch (FileNotFoundException e) { + System.out.println("An error occurred: The file was not found."); + e.printStackTrace(); } } } @@ -304,7 +303,7 @@ import java.io.File; import java.io.FileNotFoundException; - import java.util.Scanner;// Code generated on: 2025-08-05 + import java.util.Scanner; public class Main { public static void main(String[] args) { // This 'try-with-resources' statement handles opening the file @@ -346,18 +345,15 @@ import java.io.FileNotFoundException; import java.util.Scanner;public class Main { public static void main(String[] args) { - try { - File myFile = new File("myfile.txt"); - Scanner fileReader = new Scanner(myFile); - System.out.println("Reading from file: " + myFile.getName()); + String filename = "myfile.txt"; + try (Scanner fileReader = new Scanner(new File(filename))) { while (fileReader.hasNextLine()) { String data = fileReader.nextLine(); System.out.println(data); } - fileReader.close(); // Close the scanner to release the file - } catch (FileNotFoundException e) { - System.out.println("An error occurred: The file was not found."); - e.printStackTrace(); + } + catch (FileNotFoundException e) { + System.out.println("Error: The file '" + filename + "' was not found."); } } } @@ -374,12 +370,23 @@ - String data = ""; - while (fileReader.hasNextLine()) { - data = data + fileReader.nextLine() + System.lineSeparator(); - } - System.out.println(data); - fileReader.close(); + import java.io.File; + import java.io.FileNotFoundException; + import java.util.Scanner;public class Main { + public static void main(String[] args) { + String filename = "myfile.txt"; + try (Scanner fileReader = new Scanner(new File(filename))) { + String data = ""; + while (fileReader.hasNextLine()) { + data = data + fileReader.nextLine() + System.lineSeparator(); + } + System.out.println(data); + } + catch (FileNotFoundException e) { + System.out.println("Error: The file '" + filename + "' was not found."); + } + } + } From cfc4bef3eab1496a2e98e693935137b06db2d5de Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Wed, 6 Aug 2025 09:52:40 -0400 Subject: [PATCH 057/357] improve summary and questions --- source/ch6_definingclasses.ptx | 269 +++++++++++++++------------------ 1 file changed, 124 insertions(+), 145 deletions(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index 2d97e94..77547dc 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -1013,150 +1013,129 @@ public class Fraction extends Number implements Comparable<Fraction> {
    -
    - Summary & Reading Questions -

      -
    1. -

      In Java, instance variables must be declared at the top of the class, unlike Python which allows dynamic creation of instance variables anywhere.

      -
    2. -
    3. -

      Java uses access modifiers like private to enforce encapsulation, encouraging data hiding and controlled access through getter and setter methods.

      -
    4. -
    5. -

      Java requires a separate constructor method to initialize objects, using the class name and defining parameters explicitly, whereas Python uses the __init__ method.

      -
    6. -
    7. -

      Every Java class inherits from the Object class, which provides default methods like toString() and equals(). Overriding toString() allows for more meaningful output when printing objects (similar to Python’s __str__).

      -
    8. -
    9. -

      Java’s equals() method checks object equivalence based on memory reference by default. To compare objects based on content (like Fraction values), you must override equals() and use it directly — object1.equals(object2) is not the same as object1 == object2.

      -
    10. -
    11. -

      Java supports inheritance through abstract classes like Number, which require subclasses (like Fraction) to implement specific methods such as intValue(), doubleValue(), etc., allowing Fraction to be used where a Number is expected.

      -
    12. -

    - - - - -

    How must instance variables be declared in Java compared to Python?

    -
    - - -

    They can be created dynamically anywhere in the class like Python.

    -

    No, Java does not allow dynamic creation of instance variables.

    -
    - -

    Instance variables are declared inside methods only.

    -

    No, instance variables belong to the class and are declared outside methods.

    -
    - -

    They must be declared at the top of the class before use.

    -

    Correct! Java requires upfront declaration of instance variables.

    -
    - -

    Java does not use instance variables.

    -

    No, instance variables are fundamental in Java classes.

    -
    -
    -
    - - - -

    What Java feature encourages encapsulation and controlled access to instance variables?

    -
    - - -

    Declaring all variables as public.

    -

    No, that would expose data and reduce encapsulation.

    -
    - -

    Using access modifiers like private and providing getter/setter methods.

    -

    Right! This is how Java enforces encapsulation.

    -
    - -

    Using global variables.

    -

    No, Java does not support global variables and this reduces encapsulation.

    -
    - -

    Avoiding the use of classes altogether.

    -

    No, encapsulation is a class-based concept in Java.

    -
    -
    -
    - - - -

    How does Java initialize objects differently than Python?

    -
    - - -

    Java uses a constructor method named after the class with explicit parameters.

    -

    Correct! Unlike Python's __init__, Java constructors share the class name.

    -
    - -

    Java uses the __init__ method like Python.

    -

    No, Java does not have __init__.

    -
    - -

    Java initializes objects automatically without constructors.

    -

    No, Java requires constructors for explicit initialization.

    -
    - -

    Java uses global initialization functions instead of constructors.

    -

    No, Java uses constructors, not global functions, for object initialization.

    -
    -
    -
    - - - -

    What must you do to get meaningful printed output and proper equality comparison for Java objects?

    -
    - - -

    Use == for content comparison and no need to override toString().

    -

    No, == compares memory references, not content.

    -
    - -

    Only override toString() and use == for equality.

    -

    No, you should override equals() to compare content correctly.

    -
    - -

    Java automatically handles content comparison without overrides.

    -

    No, default equals() compares references, not content.

    -
    - -

    Override toString() for printing and override equals() to compare object contents.

    -

    Yes! This improves output and content-based comparison.

    -
    -
    -
    - - - -

    Why does the Fraction class extend the abstract Number class in Java?

    -
    - - -

    To require implementation of methods like intValue() and allow Fraction to be used wherever Number is expected.

    -

    Correct! This integrates Fraction into Java’s numeric hierarchy.

    -
    - -

    Because Number implements operator overloading for Fraction.

    -

    No, Java does not support operator overloading.

    -
    - -

    To avoid writing constructors.

    -

    No, constructors are still needed in subclasses.

    -
    - -

    Because Number provides default sorting methods.

    -

    No, sorting is handled by interfaces like Comparable, not Number.

    -
    -
    -
    -
    -
    +
    + Summary & Reading Questions +

      +
    1. +

      In Java, instance variables (fields) must be declared in the class body before they are used. Unlike Python, you cannot dynamically add new instance variables to an object at runtime.

      +
    2. +
    3. +

      Java uses access modifiers like private to enforce encapsulation, encouraging data hiding and controlled access through getter and setter methods.

      +
    4. +
    5. +

      Java requires a constructor method to initialize objects. A constructor has the same name as the class and defines its parameters explicitly, whereas Python uses the __init__ method.

      +
    6. +
    7. +

      Every Java class inherits from the Object class, which provides default methods like toString() and equals(). Overriding toString() gives more meaningful output when printing objects (similar to Python’s __str__).

      +
    8. +
    9. +

      By default, Java’s equals() method checks reference equality, just like == for objects. To compare objects based on content (like Fraction values), you must override equals() and call it explicitly.

      +
    10. +
    11. +

      Java supports inheritance through abstract classes (like Number) and interfaces. Extending an abstract class requires implementing its abstract methods, allowing objects like Fraction to be used where a Number is expected.

      +
    12. +

    + + + + + +

    How are instance variables declared in Java compared to Python?

    +
    + + +

    They can be created dynamically anywhere in the class like Python.

    +

    No, Java does not allow dynamic creation of instance variables at runtime.

    +
    + +

    Instance variables are declared inside methods only.

    +

    No, instance variables are declared in the class body, not in methods.

    +
    + +

    They must be declared in the class body before use.

    +

    Correct! Java requires instance variables (fields) to be declared in the class body.

    +
    + +

    Java does not use instance variables.

    +

    No, instance variables are fundamental in Java classes.

    +
    +
    +
    + + + +

    What Java feature encourages encapsulation and controlled access to instance variables?

    +
    + + +

    Declaring all variables as public.

    +

    No, that would expose data and reduce encapsulation.

    +
    + +

    Using access modifiers like private and providing getter/setter methods.

    +

    Right! This is how Java enforces encapsulation.

    +
    + +

    Using global variables.

    +

    No, Java does not support global variables and this reduces encapsulation.

    +
    + +

    Avoiding the use of classes altogether.

    +

    No, encapsulation is a class-based concept in Java.

    +
    +
    +
    + + + +

    How does Java initialize objects differently than Python?

    +
    + + +

    Java uses a constructor method named after the class with explicit parameters.

    +

    Correct! Unlike Python's __init__, Java constructors share the class name.

    +
    + +

    Java uses the __init__ method like Python.

    +

    No, Java does not have __init__.

    +
    + +

    Java initializes objects automatically without constructors.

    +

    No, Java requires constructors for explicit initialization.

    +
    + +

    Java uses global initialization functions instead of constructors.

    +

    No, Java uses constructors, not global functions, for object initialization.

    +
    +
    +
    + + + +

    What must you do to get meaningful printed output and proper equality comparison for Java objects?

    +
    + + +

    Use == for content comparison and no need to override toString().

    +

    No, == compares memory references, not content.

    +
    + +

    Only override toString() and use == for equality.

    +

    No, you should override equals() to compare content correctly.

    +
    + +

    Java automatically handles content comparison without overrides.

    +

    No, default equals() compares references, not content.

    +
    + +

    Override toString() for printing and override equals() to compare object contents.

    +

    Yes! This improves output and content-based comparison.

    +
    +
    +
    + +
    +
    + \ No newline at end of file From e45a743a33259c1d970fce98cd4066121f433898 Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Wed, 6 Aug 2025 09:55:51 -0400 Subject: [PATCH 058/357] clarify question --- source/ch6_definingclasses.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index 77547dc..78d27f0 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -1112,7 +1112,7 @@ public class Fraction extends Number implements Comparable<Fraction> { -

    What must you do to get meaningful printed output and proper equality comparison for Java objects?

    +

    What must you do in Java to print objects in a readable way and compare two objects based on their contents rather than their memory references?

    From 09056ac14c64b09542b84328248d7f23805abbe3 Mon Sep 17 00:00:00 2001 From: colin flaherty Date: Wed, 6 Aug 2025 11:28:24 -0400 Subject: [PATCH 059/357] adds working code block in 8.1 and partial fix for 8.2. Issue #102 --- source/ch8_filehandling.ptx | 99 +++++++++++++++++-------------------- 1 file changed, 46 insertions(+), 53 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 7de97b2..0fd0e4e 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -17,10 +17,20 @@

    Java has several libraries included for file handling, though, they must be imported. Java includes a class called File in the io library. The class can be imported with the following line. Be sure to capitalize File.

    - import java.io.File; + import java.io.IOException;public class Main { + public static void main(String[] args) { + try { + File myFile = new File("newfile.txt"); + myFile.createNewFile(); + System.out.println("File Made."); + } catch (IOException e) { + System.out.println("An error occurred."); + } + } + } @@ -28,37 +38,29 @@ The Scanner class from the util library will need to be imported if there is any need for a program to read a file. It should be noted that this library is unnecessary if the program will not be reading any data from a file.

    - - - import java.util.Scanner; - - +
    +            import java.util.Scanner; 
    +        

    The FileWriter class can be used to write to files. In the same way that the Scanner class isn't needed unless the program will read from a file, the FileWriter class isn't needed unless the program will write to a file.

    - - +
                 import java.io.FileWriter;
    -             
    -        
    +        

    Finally, these last two classes provide error handling and must be used in tandem with the File class when reading from or writing to files. IOException handles file creation and writing errors, while FileNotFoundException handles errors when trying to read files.

    - - +
                 import java.io.IOException;
    -             
    -        
    +        
    - - - import java.io.FileNotFoundException - - +
    +            import java.io.FileNotFoundException 
    +        
    @@ -68,10 +70,19 @@

    We will now create a File object. It is important to create a meaningful name for the File object. We will call ours myFile.

    - + +
    +                    empty file
    +                
    +
    - File myFile = new File("myfile.txt"); + import java.io.File;public class Main { + public static void main(String[] args) { + File myFile = new File("myfile.txt"); + System.out.println(myFile); + } + } @@ -88,19 +99,22 @@

    First, lets look at the equivalent Python code:

    - + +
    +                    empty file
    +                
    +
    - import os - - filename = "myfile.txt" - - if not os.path.exists(filename): - with open(filename, 'x') as f: - pass - print(f"The file {filename} was created successfully.") - else: - print(f"The file {filename} already exists.") + filename = "newfile.txt" + print(f"Attempting to write to '{filename}' using 'w' mode...") + try: + with open(filename, 'w') as f: + f.write("This file was created using 'w' mode.") + print(f"SUCCESS: The file '{filename}' was created or overwritten.") + except Exception as e: + # This would only catch other unexpected errors + print(f"An unexpected error occurred during write: {e}") @@ -135,27 +149,6 @@ The code may seem complete at this point, but if you remember from the previous section, error handling using the IOException is required for program to compile. Let's utilize best practices and add in try/catch blocks to handle exceptions thrown by the IOException class.

    - - - try { - if (myFile.createNewFile()) { // If the file was created successfully - System.out.println("The file " + myFile.getName() + " was created sucessfully."); - } else { // If a file with the file name chosen already exists - System.out.println("The file " + myFile.getName() + " already exists."); - } - } catch (IOException e) { - System.out.println("An error occurred."); - e.printStackTrace(); - } - - - - -

    - The IOException e part in the parenthesis next to the catch. This creates a variable called e that refers to an IOException object. In other words, e refers to the error created if the try block fails. The line e.printStackTrace(); prints the stack trace to the console. This is what the console may output if the program tries to create a file, but is blocked by the operating system due to insufficient permissions: -

    -
    - An error occurred. From e6bc43a1244798a5ac97e0f128a9964c7b5a8dcb Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Wed, 6 Aug 2025 11:33:40 -0400 Subject: [PATCH 060/357] Added a class definition. Will add interactive code that uses this class to create an object. --- source/ch2_firstjavaprogram.ptx | 62 +++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/source/ch2_firstjavaprogram.ptx b/source/ch2_firstjavaprogram.ptx index a485e61..e53fb37 100644 --- a/source/ch2_firstjavaprogram.ptx +++ b/source/ch2_firstjavaprogram.ptx @@ -3,6 +3,68 @@ Lets look at a Java Program + +
    + Classes and Objects + +

    + Depending on how deep your knowledge is of Python and programming in general, you may or may not be familiar with classes and objects. These two important Object-Oriented Programming (OOP) concepts will briefly be discussed. +

    + +

    + Objects in the context of programming are instances of classes. Objects contain attributes, which are details that describe the object, and methods, which are things the object can do. +

    + +

    + Classes can be thought of as being similar to blueprints or a recipe; they hold details of how to create an instance of an object. Classes contain a special method called a constructor that is used to create an instance of an object. Once the object is created, it will use the class definition to define its attributes and call methods. +

    + +

    + The best way to understand classes and objects is to see them in action. Let's define a Dog class in Python: +

    + + + + class Dog: + def __init__(self, name, breed, fur_color): + self.name = name + self.breed = breed + self.fur_color = fur_color + self.trained = False + + def bark(self): + print(f"{self.name} says woof!") + + def sit(self): + if self.trained: + print(f"{self.name} sits") + else: + print(f"{self.name} has not been trained.") + + def train(self): + self.trained = True + + + +

    + Let's unpack what is going on in this code. The first line is where we declare the class definition and name it Dog. Next, we have a special method called __init__. This __init__ method is the constructor and is required for every Python class definition. Within the __init__ method, attributes are defined. As you can see, the attributes name, breed, and fur_color must be defined when creating a Dog object using this class definition, but the trained attribute is not defined and is initialized as False. +

    + +

    + The next three blocks of code are the class's methods. These include bark(self), sit(self), and train(self). As you can see, the class defines attributes (the variables in the __init__ method) and methods for instances of the Dog class. +

    + +

    + Next, we will use this class to create a new Dog object. We will call this new Dog object my_dog: +

    + + + + + + + +
    Lets look at a Java Program

    From 3b1ecd23ffeaf579ed77334f43b669cbea9d43f4 Mon Sep 17 00:00:00 2001 From: colin flaherty Date: Wed, 6 Aug 2025 11:49:31 -0400 Subject: [PATCH 061/357] finnished adding code to 8.2, but it still needs tested. added some to 8.4 as well. Issue #102 --- source/ch8_filehandling.ptx | 58 ++++++++++++++++++++++++------------- 1 file changed, 38 insertions(+), 20 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 0fd0e4e..d913675 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -457,12 +457,28 @@ + import java.io.File; import java.io.FileWriter; import java.io.IOException; - - public class WriteFile { + import java.util.Scanner; + public class Main { public static void main(String[] args) { - + String filename = "test_file.txt"; + try (FileWriter writer = new FileWriter(filename)) { + writer.write("This line was written by the program."); + System.out.println("Successfully wrote to the file."); + } + catch (IOException e) { + System.out.println("An error occurred during writing."); + } System.out.println("--- Reading file back ---"); + try (Scanner reader = new Scanner(new File(filename))) { + while (reader.hasNextLine()) { + System.out.println(reader.nextLine()); + } + } + catch (IOException e) { + System.out.println("An error occurred during reading."); + } } } @@ -472,22 +488,18 @@ Next, we will create a FileWriter object. Let's call it myWriter:

    - - +
                 FileWriter myWriter = new FileWriter("myfile.txt");
    -             
    -        
    +        

    In this next step, we will use the write() method from the FileWriter class. This Method will take any data within the parenthesis and write that data to the file selected. The write() method takes most standard data types:

    - - +
                 myWriter.write("File successfully updated!");
                 myWriter.close();
    -             
    -        
    +        

    @@ -501,7 +513,7 @@ - with open("filename.txt", "r") as file_reader: + with open("myfile.txt", "r") as file_reader: while True: line = file_reader.readline() if not line: # End of file @@ -516,14 +528,20 @@ - try { - FileWriter myWriter = new FileWriter("myfile.txt"); - myWriter.write("File successfully updated!"); - myWriter.close(); - System.out.println("File successfully written to."); - } catch (IOException e) { - System.out.println("An error occurred."); - e.printStackTrace(); + import java.io.File; + import java.io.IOException; + import java.util.Scanner;public class Main { + public static void main(String[] args) { + String filename = "myfile.txt"; + try (Scanner reader = new Scanner(new File(filename))) { + while (reader.hasNextLine()) { + String line = reader.nextLine(); + System.out.println(line.trim()); + } + } catch (IOException e) { + System.out.println("An error occurred."); + } + } } From c799d3f49b7f2db818c084ce316dd9b66871d892 Mon Sep 17 00:00:00 2001 From: colin flaherty Date: Wed, 6 Aug 2025 11:50:22 -0400 Subject: [PATCH 062/357] unsaved changes --- source/ch8_filehandling.ptx | 105 +++--------------------------------- 1 file changed, 6 insertions(+), 99 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index d913675..16911b6 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -121,7 +121,11 @@

    Now, let's look at Java code that accomplishes the same task:

    - + +
    +                    empty file
    +                
    +
    import java.io.File; @@ -145,104 +149,7 @@

    -

    - The code may seem complete at this point, but if you remember from the previous section, error handling using the IOException is required for program to compile. Let's utilize best practices and add in try/catch blocks to handle exceptions thrown by the IOException class. -

    - - - - An error occurred. - java.io.IOException: Permission denied - at java.base/java.io.File.createNewFile(File.java:1040) - at CreateFile.main(CreateFile.java:7) - - - - -

    - At this point, the program will function correctly. Let's add the try/catch blocks to the foundational code written before to get a complete program. -

    - -

    - First, the equivalent Python code: -

    - - - - import os - - filename = "myfile.txt" - - try: - if not os.path.exists(filename): - with open(filename, 'x') as f: - pass # Create the file without writing anything - print(f"The file {filename} was created successfully.") - else: - print(f"The file {filename} already exists.") - except OSError as e: - print("An error occurred.") - import traceback - traceback.print_exc() - - - -

    - Now, the completed Java code: -

    - - - - import java.io.File; - import java.io.IOException; - - public class CreateFile { - public static void main(String[] args) { - try { - File myFile = new File("myfile.txt"); - if (myFile.createNewFile()) { // If the file was created successfully - System.out.println("The file " + myFile.getName() + " was created sucessfully."); - } else { // If a file with the file name chosen already exists - System.out.println("The file " + myFile.getName() + " already exists."); - } - } catch (IOException e) { - System.out.println("An error occurred."); - e.printStackTrace(); - } - - } - } - - - -

    - You may be wondering: "What if I don't want to create a file in the current working directory?" Good question! In Windows environments, you can specify the file path using two back slashes for each back slash in the file path. For each pair of back slashes, the first back slash acts as an escape character. So, if you want to save a file to this directory: -

    - -
    -            C:\Users\UserName\Documents
    -        
    - -

    - The line of code that creates a File object will look like this: -

    - - - - File myFile = new File("C:\\Users\\UserName\\Documents\\myfile.txt"); - - - -

    - If you are working in a Linux or Apple environment, you can simply use the file path with single forward slashes: -

    - - - - File myFile = new File("/home/UserName/Documents/myfile.txt"); - - -
    +
    Reading Files From 207cc7e6892f564b6b0d992bebf79ce40d8de7ae Mon Sep 17 00:00:00 2001 From: colin flaherty Date: Wed, 6 Aug 2025 11:52:19 -0400 Subject: [PATCH 063/357] fixed typo --- source/ch8_filehandling.ptx | 1 - 1 file changed, 1 deletion(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 16911b6..bae5ae7 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -345,7 +345,6 @@ } -

    In this code, we simply print the contents of the file to the console, but it is easy to imagine how the data variable could be used in conjunction with the write class created in the previous section to create a copy of myfile.txt.

    From 486579e19dcc047981b2ebf34b7d82431dab80c1 Mon Sep 17 00:00:00 2001 From: colin flaherty Date: Wed, 6 Aug 2025 11:57:12 -0400 Subject: [PATCH 064/357] adds datafiles to the first three codeblocks in 8.3. Issue #102 --- source/ch8_filehandling.ptx | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index bae5ae7..78d4f6d 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -360,7 +360,11 @@

    Let us create the framework for a class that will write to a file. Let's call this class WriteFile:

    - + +
    +                    
    +                
    +
    import java.io.File; @@ -416,7 +420,11 @@

    Next, we will again add the required try/catch blocks utilizing the IOException class. Just like with creating files, the program will not compile without these crucial additions! We will also add some print statements to inform us of the success of the file write operation. First, a Python example:

    - + +
    +                    
    +                
    +
    with open("myfile.txt", "r") as file_reader: @@ -431,7 +439,11 @@

    And the equivalent Java code:

    - + +
    +                    
    +                
    +
    import java.io.File; From 0c4d2d5c191ceb2d6fc6bca77d6676fa9b941e98 Mon Sep 17 00:00:00 2001 From: Elijah Babayemi Date: Tue, 5 Aug 2025 15:35:12 -0400 Subject: [PATCH 065/357] Added Summary and Reading Questions section to Chapter 6 --- source/ch6_definingclasses.ptx | 147 +++++++++++++++++++++++++++++++++ 1 file changed, 147 insertions(+) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index 7a95433..2d97e94 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -1012,4 +1012,151 @@ public class Fraction extends Number implements Comparable<Fraction> {
    + +
    + Summary & Reading Questions +

      +
    1. +

      In Java, instance variables must be declared at the top of the class, unlike Python which allows dynamic creation of instance variables anywhere.

      +
    2. +
    3. +

      Java uses access modifiers like private to enforce encapsulation, encouraging data hiding and controlled access through getter and setter methods.

      +
    4. +
    5. +

      Java requires a separate constructor method to initialize objects, using the class name and defining parameters explicitly, whereas Python uses the __init__ method.

      +
    6. +
    7. +

      Every Java class inherits from the Object class, which provides default methods like toString() and equals(). Overriding toString() allows for more meaningful output when printing objects (similar to Python’s __str__).

      +
    8. +
    9. +

      Java’s equals() method checks object equivalence based on memory reference by default. To compare objects based on content (like Fraction values), you must override equals() and use it directly — object1.equals(object2) is not the same as object1 == object2.

      +
    10. +
    11. +

      Java supports inheritance through abstract classes like Number, which require subclasses (like Fraction) to implement specific methods such as intValue(), doubleValue(), etc., allowing Fraction to be used where a Number is expected.

      +
    12. +

    + + + + +

    How must instance variables be declared in Java compared to Python?

    +
    + + +

    They can be created dynamically anywhere in the class like Python.

    +

    No, Java does not allow dynamic creation of instance variables.

    +
    + +

    Instance variables are declared inside methods only.

    +

    No, instance variables belong to the class and are declared outside methods.

    +
    + +

    They must be declared at the top of the class before use.

    +

    Correct! Java requires upfront declaration of instance variables.

    +
    + +

    Java does not use instance variables.

    +

    No, instance variables are fundamental in Java classes.

    +
    +
    +
    + + + +

    What Java feature encourages encapsulation and controlled access to instance variables?

    +
    + + +

    Declaring all variables as public.

    +

    No, that would expose data and reduce encapsulation.

    +
    + +

    Using access modifiers like private and providing getter/setter methods.

    +

    Right! This is how Java enforces encapsulation.

    +
    + +

    Using global variables.

    +

    No, Java does not support global variables and this reduces encapsulation.

    +
    + +

    Avoiding the use of classes altogether.

    +

    No, encapsulation is a class-based concept in Java.

    +
    +
    +
    + + + +

    How does Java initialize objects differently than Python?

    +
    + + +

    Java uses a constructor method named after the class with explicit parameters.

    +

    Correct! Unlike Python's __init__, Java constructors share the class name.

    +
    + +

    Java uses the __init__ method like Python.

    +

    No, Java does not have __init__.

    +
    + +

    Java initializes objects automatically without constructors.

    +

    No, Java requires constructors for explicit initialization.

    +
    + +

    Java uses global initialization functions instead of constructors.

    +

    No, Java uses constructors, not global functions, for object initialization.

    +
    +
    +
    + + + +

    What must you do to get meaningful printed output and proper equality comparison for Java objects?

    +
    + + +

    Use == for content comparison and no need to override toString().

    +

    No, == compares memory references, not content.

    +
    + +

    Only override toString() and use == for equality.

    +

    No, you should override equals() to compare content correctly.

    +
    + +

    Java automatically handles content comparison without overrides.

    +

    No, default equals() compares references, not content.

    +
    + +

    Override toString() for printing and override equals() to compare object contents.

    +

    Yes! This improves output and content-based comparison.

    +
    +
    +
    + + + +

    Why does the Fraction class extend the abstract Number class in Java?

    +
    + + +

    To require implementation of methods like intValue() and allow Fraction to be used wherever Number is expected.

    +

    Correct! This integrates Fraction into Java’s numeric hierarchy.

    +
    + +

    Because Number implements operator overloading for Fraction.

    +

    No, Java does not support operator overloading.

    +
    + +

    To avoid writing constructors.

    +

    No, constructors are still needed in subclasses.

    +
    + +

    Because Number provides default sorting methods.

    +

    No, sorting is handled by interfaces like Comparable, not Number.

    +
    +
    +
    +
    +
    +
    \ No newline at end of file From 789a1c41e7119efa3db8e3c1cadf21851935517f Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Wed, 6 Aug 2025 09:52:40 -0400 Subject: [PATCH 066/357] improve summary and questions --- source/ch6_definingclasses.ptx | 269 +++++++++++++++------------------ 1 file changed, 124 insertions(+), 145 deletions(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index 2d97e94..77547dc 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -1013,150 +1013,129 @@ public class Fraction extends Number implements Comparable<Fraction> {
    -
    - Summary & Reading Questions -

      -
    1. -

      In Java, instance variables must be declared at the top of the class, unlike Python which allows dynamic creation of instance variables anywhere.

      -
    2. -
    3. -

      Java uses access modifiers like private to enforce encapsulation, encouraging data hiding and controlled access through getter and setter methods.

      -
    4. -
    5. -

      Java requires a separate constructor method to initialize objects, using the class name and defining parameters explicitly, whereas Python uses the __init__ method.

      -
    6. -
    7. -

      Every Java class inherits from the Object class, which provides default methods like toString() and equals(). Overriding toString() allows for more meaningful output when printing objects (similar to Python’s __str__).

      -
    8. -
    9. -

      Java’s equals() method checks object equivalence based on memory reference by default. To compare objects based on content (like Fraction values), you must override equals() and use it directly — object1.equals(object2) is not the same as object1 == object2.

      -
    10. -
    11. -

      Java supports inheritance through abstract classes like Number, which require subclasses (like Fraction) to implement specific methods such as intValue(), doubleValue(), etc., allowing Fraction to be used where a Number is expected.

      -
    12. -

    - - - - -

    How must instance variables be declared in Java compared to Python?

    -
    - - -

    They can be created dynamically anywhere in the class like Python.

    -

    No, Java does not allow dynamic creation of instance variables.

    -
    - -

    Instance variables are declared inside methods only.

    -

    No, instance variables belong to the class and are declared outside methods.

    -
    - -

    They must be declared at the top of the class before use.

    -

    Correct! Java requires upfront declaration of instance variables.

    -
    - -

    Java does not use instance variables.

    -

    No, instance variables are fundamental in Java classes.

    -
    -
    -
    - - - -

    What Java feature encourages encapsulation and controlled access to instance variables?

    -
    - - -

    Declaring all variables as public.

    -

    No, that would expose data and reduce encapsulation.

    -
    - -

    Using access modifiers like private and providing getter/setter methods.

    -

    Right! This is how Java enforces encapsulation.

    -
    - -

    Using global variables.

    -

    No, Java does not support global variables and this reduces encapsulation.

    -
    - -

    Avoiding the use of classes altogether.

    -

    No, encapsulation is a class-based concept in Java.

    -
    -
    -
    - - - -

    How does Java initialize objects differently than Python?

    -
    - - -

    Java uses a constructor method named after the class with explicit parameters.

    -

    Correct! Unlike Python's __init__, Java constructors share the class name.

    -
    - -

    Java uses the __init__ method like Python.

    -

    No, Java does not have __init__.

    -
    - -

    Java initializes objects automatically without constructors.

    -

    No, Java requires constructors for explicit initialization.

    -
    - -

    Java uses global initialization functions instead of constructors.

    -

    No, Java uses constructors, not global functions, for object initialization.

    -
    -
    -
    - - - -

    What must you do to get meaningful printed output and proper equality comparison for Java objects?

    -
    - - -

    Use == for content comparison and no need to override toString().

    -

    No, == compares memory references, not content.

    -
    - -

    Only override toString() and use == for equality.

    -

    No, you should override equals() to compare content correctly.

    -
    - -

    Java automatically handles content comparison without overrides.

    -

    No, default equals() compares references, not content.

    -
    - -

    Override toString() for printing and override equals() to compare object contents.

    -

    Yes! This improves output and content-based comparison.

    -
    -
    -
    - - - -

    Why does the Fraction class extend the abstract Number class in Java?

    -
    - - -

    To require implementation of methods like intValue() and allow Fraction to be used wherever Number is expected.

    -

    Correct! This integrates Fraction into Java’s numeric hierarchy.

    -
    - -

    Because Number implements operator overloading for Fraction.

    -

    No, Java does not support operator overloading.

    -
    - -

    To avoid writing constructors.

    -

    No, constructors are still needed in subclasses.

    -
    - -

    Because Number provides default sorting methods.

    -

    No, sorting is handled by interfaces like Comparable, not Number.

    -
    -
    -
    -
    -
    +
    + Summary & Reading Questions +

      +
    1. +

      In Java, instance variables (fields) must be declared in the class body before they are used. Unlike Python, you cannot dynamically add new instance variables to an object at runtime.

      +
    2. +
    3. +

      Java uses access modifiers like private to enforce encapsulation, encouraging data hiding and controlled access through getter and setter methods.

      +
    4. +
    5. +

      Java requires a constructor method to initialize objects. A constructor has the same name as the class and defines its parameters explicitly, whereas Python uses the __init__ method.

      +
    6. +
    7. +

      Every Java class inherits from the Object class, which provides default methods like toString() and equals(). Overriding toString() gives more meaningful output when printing objects (similar to Python’s __str__).

      +
    8. +
    9. +

      By default, Java’s equals() method checks reference equality, just like == for objects. To compare objects based on content (like Fraction values), you must override equals() and call it explicitly.

      +
    10. +
    11. +

      Java supports inheritance through abstract classes (like Number) and interfaces. Extending an abstract class requires implementing its abstract methods, allowing objects like Fraction to be used where a Number is expected.

      +
    12. +

    + + + + + +

    How are instance variables declared in Java compared to Python?

    +
    + + +

    They can be created dynamically anywhere in the class like Python.

    +

    No, Java does not allow dynamic creation of instance variables at runtime.

    +
    + +

    Instance variables are declared inside methods only.

    +

    No, instance variables are declared in the class body, not in methods.

    +
    + +

    They must be declared in the class body before use.

    +

    Correct! Java requires instance variables (fields) to be declared in the class body.

    +
    + +

    Java does not use instance variables.

    +

    No, instance variables are fundamental in Java classes.

    +
    +
    +
    + + + +

    What Java feature encourages encapsulation and controlled access to instance variables?

    +
    + + +

    Declaring all variables as public.

    +

    No, that would expose data and reduce encapsulation.

    +
    + +

    Using access modifiers like private and providing getter/setter methods.

    +

    Right! This is how Java enforces encapsulation.

    +
    + +

    Using global variables.

    +

    No, Java does not support global variables and this reduces encapsulation.

    +
    + +

    Avoiding the use of classes altogether.

    +

    No, encapsulation is a class-based concept in Java.

    +
    +
    +
    + + + +

    How does Java initialize objects differently than Python?

    +
    + + +

    Java uses a constructor method named after the class with explicit parameters.

    +

    Correct! Unlike Python's __init__, Java constructors share the class name.

    +
    + +

    Java uses the __init__ method like Python.

    +

    No, Java does not have __init__.

    +
    + +

    Java initializes objects automatically without constructors.

    +

    No, Java requires constructors for explicit initialization.

    +
    + +

    Java uses global initialization functions instead of constructors.

    +

    No, Java uses constructors, not global functions, for object initialization.

    +
    +
    +
    + + + +

    What must you do to get meaningful printed output and proper equality comparison for Java objects?

    +
    + + +

    Use == for content comparison and no need to override toString().

    +

    No, == compares memory references, not content.

    +
    + +

    Only override toString() and use == for equality.

    +

    No, you should override equals() to compare content correctly.

    +
    + +

    Java automatically handles content comparison without overrides.

    +

    No, default equals() compares references, not content.

    +
    + +

    Override toString() for printing and override equals() to compare object contents.

    +

    Yes! This improves output and content-based comparison.

    +
    +
    +
    + +
    +
    + \ No newline at end of file From b43db0835831e608b90d9f21913076085339dfa8 Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Wed, 6 Aug 2025 09:55:51 -0400 Subject: [PATCH 067/357] clarify question --- source/ch6_definingclasses.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index 77547dc..78d27f0 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -1112,7 +1112,7 @@ public class Fraction extends Number implements Comparable<Fraction> { -

    What must you do to get meaningful printed output and proper equality comparison for Java objects?

    +

    What must you do in Java to print objects in a readable way and compare two objects based on their contents rather than their memory references?

    From 83f88dd8bbe200551b26039809170c6c81c20510 Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Wed, 6 Aug 2025 13:12:59 -0400 Subject: [PATCH 068/357] The section on classes and objects is in a draft form at this point. Will make some necessary changes. --- source/ch2_firstjavaprogram.ptx | 111 ++++++++++++++++++++++++++------ 1 file changed, 91 insertions(+), 20 deletions(-) diff --git a/source/ch2_firstjavaprogram.ptx b/source/ch2_firstjavaprogram.ptx index e53fb37..b805db6 100644 --- a/source/ch2_firstjavaprogram.ptx +++ b/source/ch2_firstjavaprogram.ptx @@ -23,31 +23,32 @@ The best way to understand classes and objects is to see them in action. Let's define a Dog class in Python:

    - + class Dog: - def __init__(self, name, breed, fur_color): - self.name = name - self.breed = breed - self.fur_color = fur_color - self.trained = False - - def bark(self): - print(f"{self.name} says woof!") - - def sit(self): - if self.trained: - print(f"{self.name} sits") - else: - print(f"{self.name} has not been trained.") + def __init__(self, name, breed, fur_color): + self.name = name + self.breed = breed + self.fur_color = fur_color + self.trained = False + print("Dog named " + self.name + " created!") + + def bark(self): + print(self.name + " says woof!") - def train(self): - self.trained = True + def sit(self): + if self.trained: + print(self.name + " sits.") + else: + print(self.name + " has not been trained.") + + def train(self): + self.trained = True

    - Let's unpack what is going on in this code. The first line is where we declare the class definition and name it Dog. Next, we have a special method called __init__. This __init__ method is the constructor and is required for every Python class definition. Within the __init__ method, attributes are defined. As you can see, the attributes name, breed, and fur_color must be defined when creating a Dog object using this class definition, but the trained attribute is not defined and is initialized as False. + Let's unpack what is going on in this code. The first line is where we declare the class definition and name it Dog. Next, we have a special method called __init__. This __init__ method is the constructor and is required for every Python class definition. Within the __init__ method, attributes are defined. As you can see, the attributes name, breed, and fur_color must be defined when creating a Dog object using this class definition, but the trained attribute is not defined and is initialized as False. We can also have the __init__ method run any code, such as a print statement informing us that a Dog object was created.

    @@ -58,11 +59,81 @@ Next, we will use this class to create a new Dog object. We will call this new Dog object my_dog:

    - + - + class Dog: + def __init__(self, name, breed, fur_color): + self.name = name + self.breed = breed + self.fur_color = fur_color + self.trained = False + print("Dog named " + self.name + " created!") + + def bark(self): + print(self.name + " says woof!") + + def sit(self): + if self.trained: + print(self.name + " sits.") + else: + print(self.name + " has not been trained.") + + def train(self): + self.trained = True + + + my_dog = Dog("Rex", "pug", "tan") + + + +

    + In the final line of code, we have created an object called my_dog. We have initialized its attributes, setting name to Rex, breed to pug, and fur_color to tan. +

    + +

    + Now that we have created a Dog object using the class we defined, we can utilize the class's methods: +

    + + + + class Dog: + def __init__(self, name, breed, fur_color): + self.name = name + self.breed = breed + self.fur_color = fur_color + self.trained = False + print("Dog named " + self.name + " created!") + + def bark(self): + print(self.name + " says woof!") + + def sit(self): + if self.trained: + print(self.name + " sits.") + else: + print(self.name + " has not been trained.") + + def train(self): + self.trained = True + + + my_dog = Dog("Rex", "pug", "tan") + my_dog.bark() + my_dog.sit() + + +

    + When running the code above, the line Rex has not ben trained. will appear in the output when calling the sit() method. Try adding a one or more lines of code so that Rex sits. appears in the output! +

    +
    + +

    + Now, we have a full class definition and have utilized its methods. Class definitions in Java will be covered in chapter 6. For now, it is important to know that Python programs can be entirely written without using classes at all. Java, on the other hand, requires all code to reside in a class. This will be discussed in the next section. +

    + +
    From c3e89a2001c7d07841aee8ba66c15572c3a31ffb Mon Sep 17 00:00:00 2001 From: colin flaherty Date: Wed, 6 Aug 2025 13:14:18 -0400 Subject: [PATCH 069/357] added missing end tag to section --- source/ch8_filehandling.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 78d4f6d..a70c0b2 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -148,7 +148,7 @@ You may have noticed the use of another method from the File class; getName(). This method returns a string containing the name of the file.

    - +
    From 7bcec04662dec32e9faa3326c3556b2263e97c7e Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Wed, 6 Aug 2025 13:36:21 -0400 Subject: [PATCH 070/357] Made some minor changes and added a paragraph on the use of self in Python classes. --- source/ch2_firstjavaprogram.ptx | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/source/ch2_firstjavaprogram.ptx b/source/ch2_firstjavaprogram.ptx index b805db6..1c19e14 100644 --- a/source/ch2_firstjavaprogram.ptx +++ b/source/ch2_firstjavaprogram.ptx @@ -8,11 +8,11 @@ Classes and Objects

    - Depending on how deep your knowledge is of Python and programming in general, you may or may not be familiar with classes and objects. These two important Object-Oriented Programming (OOP) concepts will briefly be discussed. + Depending on how deep your knowledge of Python and programming in general is, you may or may not be familiar with classes and objects. These two important Object-Oriented Programming (OOP) concepts will briefly be discussed. If you already have a good understanding of classes and objects in Python, this section may be skipped.

    - Objects in the context of programming are instances of classes. Objects contain attributes, which are details that describe the object, and methods, which are things the object can do. + Objects in the context of programming are instances of classes. Objects contain attributes, which are data that describe the object or are associated with the object, and methods, which are special functions used by the object. Methods are typically actions the object can perform, or can be used to make changes to the object's attributes.

    @@ -48,13 +48,17 @@

    - Let's unpack what is going on in this code. The first line is where we declare the class definition and name it Dog. Next, we have a special method called __init__. This __init__ method is the constructor and is required for every Python class definition. Within the __init__ method, attributes are defined. As you can see, the attributes name, breed, and fur_color must be defined when creating a Dog object using this class definition, but the trained attribute is not defined and is initialized as False. We can also have the __init__ method run any code, such as a print statement informing us that a Dog object was created. + Let's unpack what is going on in this code. The first line is where we declare the class definition and name it Dog. Next, we have a special method called __init__. This __init__ method is the constructor and is required for every Python class definition. Within the __init__ method, attributes are defined. As you can see, the attributes name, breed, and fur_color must be defined when creating a Dog object using this class definition, but the trained attribute is defined within the constructor and is initialized as False. We can also have the __init__ method run any code, such as the print statement informing us that a Dog object was created.

    The next three blocks of code are the class's methods. These include bark(self), sit(self), and train(self). As you can see, the class defines attributes (the variables in the __init__ method) and methods for instances of the Dog class.

    +

    + Within each method, and for each attribute, you will notice the use of self. This is required in Python. self simply indicates that an attribute or method is being used for a specific instance of an object created with a class. +

    +

    Next, we will use this class to create a new Dog object. We will call this new Dog object my_dog:

    @@ -82,12 +86,12 @@ self.trained = True - my_dog = Dog("Rex", "pug", "tan") + my_dog = Dog("Rex", "pug", "brown")

    - In the final line of code, we have created an object called my_dog. We have initialized its attributes, setting name to Rex, breed to pug, and fur_color to tan. + In the final line of code, we have created an object called my_dog. We have initialized its attributes, setting name to Rex, breed to pug, and fur_color to brown.

    @@ -117,7 +121,7 @@ self.trained = True - my_dog = Dog("Rex", "pug", "tan") + my_dog = Dog("Rex", "pug", "brown") my_dog.bark() my_dog.sit() @@ -130,7 +134,7 @@

    - Now, we have a full class definition and have utilized its methods. Class definitions in Java will be covered in chapter 6. For now, it is important to know that Python programs can be entirely written without using classes at all. Java, on the other hand, requires all code to reside in a class. This will be discussed in the next section. + Now, we have a full class definition and have utilized its methods. Class definitions in Java will be covered thoroughly in chapter 6. For now, it is important to know that Python programs can be written without using classes at all. Java, on the other hand, requires all code to reside in a class. This will be discussed in the next section.

    From b35295faa8e5b42e5e8bad3332ae78792167c626 Mon Sep 17 00:00:00 2001 From: colin flaherty Date: Wed, 6 Aug 2025 13:37:25 -0400 Subject: [PATCH 071/357] 8.4 all codeblocks work in an ide, and added data files to each code block. --- source/ch8_filehandling.ptx | 50 +++++++++++++++++++------------------ 1 file changed, 26 insertions(+), 24 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index a70c0b2..bf778c0 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -467,7 +467,11 @@

    And that's it! We will add our code to the foundational code for a complete program. First, an example of equivalent Python code:

    - + +
    +                    
    +                
    +
    try: @@ -484,7 +488,11 @@

    The completed Java code:

    - + +
    +                    
    +                
    +
    import java.io.FileWriter; @@ -520,16 +528,18 @@ Speaking of overwriting data, what if we want to append text to the end of any text already in myfile.txt? To accomplish this, we can pass a boolean argument along with the file name when creating a new data argument:

    - - +
                 FileWriter myWriter = new FileWriter("myfile.txt", true); // true enables append mode
    -             
    -        
    +        

    Now, when we use write() method like before, the text will be appended if there is already text in the document. If we were to update our code to include the boolean argument:

    - + +
    +                    
    +                
    +
    import java.io.FileWriter; @@ -555,44 +565,36 @@ Then if we run the program twice, the contents of myfile.txt would be:

    - - +
                 File successfully updated!File successfully updated!
    -             
    -        
    +        

    This doesn't look very good! If we want each additional write to appear on a new line? The first solution may be to use the \n newline character:

    - - +
                 myWriter.write("File successfully updated!\n"); // Added newline character 
    -            myWriter.close();
    -             
    -        
    +            myWriter.close(); 
    +        

    The System.lineseseparator() method is a better solution. This method returns the system's default line separator, which is platform-dependent. For example, on Windows, it returns \n, while on Linux and macOS, it returns \n. Using this method ensures that your code works correctly across different operating systems:

    - - +
                 myWriter.write("File successfully updated!" + System.lineseparator()); // Added newline character 
                 myWriter.close();
    -             
    -        
    +        

    Running it twice will result in the following contents in myfile.txt:

    - - +
                 File successfully updated!
                 File successfully updated!
    -             
    -        
    +        
    From 16a6c782cda6a5f55e7ecd940cd8a798e55c8dbb Mon Sep 17 00:00:00 2001 From: colin flaherty Date: Wed, 6 Aug 2025 13:55:24 -0400 Subject: [PATCH 072/357] fixed missbehaving python block --- source/ch8_filehandling.ptx | 38 ++++++++++++++++++------------------- 1 file changed, 18 insertions(+), 20 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index bf778c0..cea1792 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -360,11 +360,7 @@

    Let us create the framework for a class that will write to a file. Let's call this class WriteFile:

    - -
    -                    
    -                
    -
    + import java.io.File; @@ -420,37 +416,39 @@

    Next, we will again add the required try/catch blocks utilizing the IOException class. Just like with creating files, the program will not compile without these crucial additions! We will also add some print statements to inform us of the success of the file write operation. First, a Python example:

    - +
    -                    
    +                    1
    +                    2
    +                    3
                     
    - + - with open("myfile.txt", "r") as file_reader: - while True: - line = file_reader.readline() - if not line: # End of file - break - print(line.strip()) + with open("myfile8-4-2.txt", "r") as file_reader: + while True: + line = file_reader.readline() + if not line: # End of file + break + print(line.strip())

    And the equivalent Java code:

    - +
                         
                     
    - + import java.io.File; import java.io.IOException; import java.util.Scanner;public class Main { public static void main(String[] args) { - String filename = "myfile.txt"; + String filename = "myfile8-4-3.txt"; try (Scanner reader = new Scanner(new File(filename))) { while (reader.hasNextLine()) { String line = reader.nextLine(); @@ -472,7 +470,7 @@
    - + try: with open("myfile.txt", "w") as my_writer: @@ -493,7 +491,7 @@ - + import java.io.FileWriter; import java.io.IOException; @@ -540,7 +538,7 @@ - + import java.io.FileWriter; import java.io.IOException; From d93f2ae293172c582d60498f2fa726aae06e00a2 Mon Sep 17 00:00:00 2001 From: Elijah Babayemi Date: Wed, 6 Aug 2025 14:00:50 -0400 Subject: [PATCH 073/357] Made the answers for Question 3 harder --- source/ch4_conditionals.ptx | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 6066ee1..256595f 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -415,26 +415,26 @@ Using this operator can make code shorter and more readable in cases where a sim -

    It allows complex boolean expressions in case statements.

    +

    It cannot evaluate relational expressions like greater than or less than.

    -

    No, switch does not support complex expressions like if does.

    +

    No, while switch can compare values, it does not support relational expressions like > or <.

    -

    It can be used with any type of object, including null.

    +

    It cannot handle more than five case labels.

    -

    No, using null in switch causes a runtime error.

    +

    No, there is no such limit. You can have many case labels in a switch statement.

    -

    It supports dynamic pattern matching by default.

    +

    It allows fall-through behavior when break is omitted.

    -

    No, Java switch supports limited pattern matching starting only in later versions.

    +

    Incorrect. This is actually a feature of switch, not a limitation.

    @@ -442,7 +442,7 @@ Using this operator can make code shorter and more readable in cases where a sim

    It can only compare a variable to constant values using equality.

    -

    Correct! switch is limited to constant comparisons only.

    +

    Correct! Java's switch is limited to constant comparisons using equality.

    From 3c546399d6241578a408a81247e0dd80064f8808 Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Wed, 6 Aug 2025 14:26:14 -0400 Subject: [PATCH 074/357] Added index terms to the new section 2.1 and removed duplicates from chapter 6. --- source/ch2_firstjavaprogram.ptx | 40 ++++++++++++++++++++------------- source/ch6_definingclasses.ptx | 2 -- 2 files changed, 24 insertions(+), 18 deletions(-) diff --git a/source/ch2_firstjavaprogram.ptx b/source/ch2_firstjavaprogram.ptx index 1c19e14..12d4b68 100644 --- a/source/ch2_firstjavaprogram.ptx +++ b/source/ch2_firstjavaprogram.ptx @@ -8,15 +8,22 @@ Classes and Objects

    - Depending on how deep your knowledge of Python and programming in general is, you may or may not be familiar with classes and objects. These two important Object-Oriented Programming (OOP) concepts will briefly be discussed. If you already have a good understanding of classes and objects in Python, this section may be skipped. + Object-Oriented Programming (OOP) + Depending on how deep your knowledge of Python and programming in general is, you may or may not be familiar with classes and objects. These two important Object-Oriented Programming (OOP) concepts will briefly be discussed. If you already have a good understanding of classes and objects in Python, this section may be skipped.

    - Objects in the context of programming are instances of classes. Objects contain attributes, which are data that describe the object or are associated with the object, and methods, which are special functions used by the object. Methods are typically actions the object can perform, or can be used to make changes to the object's attributes. + object + attribute + instance variable + method + Objects in the context of programming are instances of classes. Objects contain attributes (also referred to as instance variables), which are data that describe the object or are associated with the object, and methods, which are special functions used by the object. Methods are typically actions the object can perform, or can be used to make changes to the object's attributes.

    - Classes can be thought of as being similar to blueprints or a recipe; they hold details of how to create an instance of an object. Classes contain a special method called a constructor that is used to create an instance of an object. Once the object is created, it will use the class definition to define its attributes and call methods. + class + constructor + Classes can be thought of as being similar to blueprints or a recipe; they hold details of how to create an instance of an object. Classes contain a special method called a constructor that is used to create an instance of an object. Once the object is created, it will use the class definition to define its attributes and call methods.

    @@ -31,16 +38,16 @@ self.breed = breed self.fur_color = fur_color self.trained = False - print("Dog named " + self.name + " created!") + print(f"Dog named {self.name} created!") def bark(self): - print(self.name + " says woof!") + print(f"{self.name} says woof!") def sit(self): if self.trained: - print(self.name + " sits.") + print(f"{self.name} sits.") else: - print(self.name + " has not been trained.") + print(f"{self.name} has not been trained.") def train(self): self.trained = True @@ -56,7 +63,8 @@

    - Within each method, and for each attribute, you will notice the use of self. This is required in Python. self simply indicates that an attribute or method is being used for a specific instance of an object created with a class. + self + Within each method, and for each attribute, you will notice the use of self. This is required in Python. self simply indicates that an attribute or method is being used for a specific instance of an object created with a class.

    @@ -71,16 +79,16 @@ self.breed = breed self.fur_color = fur_color self.trained = False - print("Dog named " + self.name + " created!") + print(f"Dog named {self.name} created!") def bark(self): - print(self.name + " says woof!") + print(f"{self.name} says woof!") def sit(self): if self.trained: - print(self.name + " sits.") + print(f"{self.name} sits.") else: - print(self.name + " has not been trained.") + print(f"{self.name} has not been trained.") def train(self): self.trained = True @@ -106,16 +114,16 @@ self.breed = breed self.fur_color = fur_color self.trained = False - print("Dog named " + self.name + " created!") + print(f"Dog named {self.name} created!") def bark(self): - print(self.name + " says woof!") + print(f"{self.name} says woof!") def sit(self): if self.trained: - print(self.name + " sits.") + print(f"{self.name} sits.") else: - print(self.name + " has not been trained.") + print(f"{self.name} has not been trained.") def train(self): self.trained = True diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index 7a95433..45e2d8c 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -191,7 +191,6 @@ public void setDenominator(Integer denominator) { Writing a constructor

    - constructors Once you have identified the instance variables for your class the next thing to consider is the constructor. In Java, constructors have the same name as the class and are declared public. They are declared without a return type. @@ -498,7 +497,6 @@ Fraction@6ff3c5b5 The <c>Object</c> Class

    - object class toString In Java, the equivalent of __str__ is the toString method. Every object in Java already has a toString method defined for it because every class in Java automatically inherits from the Object class. From a96e7d7a826bc8f89c985b5eaf9d6d9531990031 Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Wed, 6 Aug 2025 14:56:50 -0400 Subject: [PATCH 075/357] Added xml ids to each code block. --- source/ch2_firstjavaprogram.ptx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/source/ch2_firstjavaprogram.ptx b/source/ch2_firstjavaprogram.ptx index 12d4b68..4b3da63 100644 --- a/source/ch2_firstjavaprogram.ptx +++ b/source/ch2_firstjavaprogram.ptx @@ -30,7 +30,7 @@ The best way to understand classes and objects is to see them in action. Let's define a Dog class in Python:

    - + class Dog: def __init__(self, name, breed, fur_color): @@ -71,7 +71,7 @@ Next, we will use this class to create a new Dog object. We will call this new Dog object my_dog:

    - + class Dog: def __init__(self, name, breed, fur_color): @@ -106,7 +106,7 @@ Now that we have created a Dog object using the class we defined, we can utilize the class's methods:

    - + class Dog: def __init__(self, name, breed, fur_color): From be3d9f7f8e744440869c2af60e5b6883123c2c8d Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Wed, 6 Aug 2025 15:30:27 -0400 Subject: [PATCH 076/357] correct older Java statements --- source/ch4_conditionals.ptx | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 256595f..1f2a59b 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -318,10 +318,13 @@ Using this operator can make code shorter and more readable in cases where a sim

    Java requires parentheses around the condition and curly braces for code blocks in if statements, unlike Python which uses indentation alone.

  • -

    Java uses else if instead of Python's elif, and allows optional curly braces for single-line blocks.

    +

    Java uses else if instead of Python's elif, and allows optional curly braces for single-line blocks. However, it is considered good practice to use curly braces even for single-line blocks to improve readability.

  • -

    Java includes a switch statement for checking equality against constant values, which can replace long if-else chains for specific scenarios.

    +

    + Java's switch statement is similar to Python's match statement, but it only supports equality checks against constant values and does not evaluate relational expressions like greater than or less than. +

    +
  • @@ -408,9 +411,9 @@ Using this operator can make code shorter and more readable in cases where a sim - + -

    What is one limitation of Java's switch statement?

    +

    What is one limitation of Java's switch statement, including in its modern versions?

    @@ -418,7 +421,7 @@ Using this operator can make code shorter and more readable in cases where a sim

    It cannot evaluate relational expressions like greater than or less than.

    -

    No, while switch can compare values, it does not support relational expressions like > or <.

    +

    No, while switch can compare values, it does not support relational expressions like > or <, even with modern enhancements of Java 14+

    @@ -431,10 +434,10 @@ Using this operator can make code shorter and more readable in cases where a sim -

    It allows fall-through behavior when break is omitted.

    +

    It always requires a break statement.

    -

    Incorrect. This is actually a feature of switch, not a limitation.

    +

    Incorrect. The break statement is actually an optional feature of switch, not a limitation.

    From d929770b140fa8fb4364c3f8ad2b10c1d8535338 Mon Sep 17 00:00:00 2001 From: Elijah Babayemi Date: Wed, 6 Aug 2025 15:33:17 -0400 Subject: [PATCH 077/357] Added Summary and Reanding Questions section to chapter 8 --- source/ch8_filehandling.ptx | 140 ++++++++++++++++++++++++++++++++++++ 1 file changed, 140 insertions(+) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index cea1792..fa5aa72 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -624,4 +624,144 @@

    +
    + Summary & Reading Questions +

      +
    1. +

      To work with files in Java, you must import specific classes like java.io.File, java.io.FileWriter, and handle exceptions such as IOException.

      +
    2. +
    3. +

      You can create a new file using File.createNewFile(), which returns true if the file is created and false if it already exists.

      +
    4. +
    5. +

      Reading from files is done using a Scanner attached to a File, often with a loop using hasNextLine() and nextLine().

      +
    6. +
    7. +

      To write to a file, use a FileWriter object and call methods like write() and close() to save and finish the output.

      +
    8. +
    9. +

      You can delete a file using the delete() method on a File object, which returns true if successful.

      +
    10. +

    + + + +

    Which import is needed to create and manipulate files in Java?

    +
    + + + +

    import java.util.File;

    +
    + +

    No, File is part of the java.io package, not java.util.

    +
    +
    + + +

    import java.io.File;

    +
    + +

    Correct! File is found in the java.io package.

    +
    +
    + + +

    import java.file.Input;

    +
    + +

    No, this is not a valid import for file operations.

    +
    +
    + + +

    import java.system.io.*;

    +
    + +

    No, there is no such package in Java.

    +
    +
    +
    +
    + + +

    What does myFile.createNewFile() return if the file already exists?

    +
    + + + +

    It throws an exception.

    +
    + +

    No, it only throws an exception for access errors, not for existing files.

    +
    +
    + + +

    false

    +
    + +

    Correct! It returns false if the file already exists.

    +
    +
    + + +

    true

    +
    + +

    No, true is returned only when the file is successfully created.

    +
    +
    + + +

    null

    +
    + +

    No, null is not a valid return value for this method.

    +
    +
    +
    +
    + + +

    Which method checks if a file has more lines to read using a Scanner?

    +
    + + + +

    nextLine()

    +
    + +

    No, nextLine() retrieves the next line, but does not check for availability.

    +
    +
    + + +

    hasMore()

    +
    + +

    No, this is not a method of Scanner.

    +
    +
    + + +

    hasNextLine()

    +
    + +

    Correct! This checks if there is another line available to read.

    +
    +
    + + +

    canReadLine()

    +
    + +

    No, this is not a standard method in the Scanner class.

    +
    +
    +
    +
    +
    +
    + \ No newline at end of file From da8bf06300044bfde35bbf088f5425d0e6220e39 Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Wed, 6 Aug 2025 15:36:26 -0400 Subject: [PATCH 078/357] Added an empty section on Exception Handling to get started. --- source/ch4_conditionals.ptx | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 6a38a39..2ec26a8 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -234,6 +234,11 @@ The switch statement is not used very often, and we recommend you do not

    +
    + Exception Handling + +
    +
    Boolean Operators From ce966dbc4744f36012bb31ebe3a3a80750839a3a Mon Sep 17 00:00:00 2001 From: colin flaherty Date: Wed, 6 Aug 2025 15:36:59 -0400 Subject: [PATCH 079/357] 8.1 adds python example of importing and a java comparison. Also added xml ids and joined the last two pretags --- source/ch8_filehandling.ptx | 34 +++++++++++++++++++++++++++++----- 1 file changed, 29 insertions(+), 5 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index cea1792..e2036c9 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -13,11 +13,38 @@
    Class Imports +

    + In Python, most built-in libraries are available without needing to explicitly import additional packages, but some libraries like math do need to be imported. Consider the following. +

    +

    + Python: +

    + + + import math + print(math.sqrt(25)) + + + +

    + Java: +

    + + + import java.lang.Math; + + public class Main { + public static void main(String[] args) { + System.out.println(Math.sqrt(25)); + } + } + +

    Java has several libraries included for file handling, though, they must be imported. Java includes a class called File in the io library. The class can be imported with the following line. Be sure to capitalize File.

    - + import java.io.File; import java.io.IOException;public class Main { @@ -56,10 +83,7 @@
                 import java.io.IOException;
    -        
    - -
    -            import java.io.FileNotFoundException 
    +            import java.io.FileNotFoundException;
             
    From f83eb6c17e1a7a492f6b722c7b29d9635f0d20e9 Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Wed, 6 Aug 2025 15:38:21 -0400 Subject: [PATCH 080/357] Added an empty section on Exception Handling to get started. --- source/ch4_conditionals.ptx | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 2ec26a8..aedb61b 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -237,6 +237,10 @@ The switch statement is not used very often, and we recommend you do not
    Exception Handling +

    + +

    +
    From cc539f31e016c70cf1d77a9b14666390bc61fed1 Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Wed, 6 Aug 2025 15:40:37 -0400 Subject: [PATCH 081/357] Changed outdated input tags to code tags. --- source/ch2_firstjavaprogram.ptx | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/source/ch2_firstjavaprogram.ptx b/source/ch2_firstjavaprogram.ptx index 4b3da63..289eeee 100644 --- a/source/ch2_firstjavaprogram.ptx +++ b/source/ch2_firstjavaprogram.ptx @@ -31,7 +31,7 @@

    - + class Dog: def __init__(self, name, breed, fur_color): self.name = name @@ -51,7 +51,7 @@ def train(self): self.trained = True - +

    @@ -72,7 +72,7 @@

    - + class Dog: def __init__(self, name, breed, fur_color): self.name = name @@ -95,7 +95,7 @@ my_dog = Dog("Rex", "pug", "brown") - +

    @@ -107,7 +107,7 @@

    - + class Dog: def __init__(self, name, breed, fur_color): self.name = name @@ -132,7 +132,7 @@ my_dog = Dog("Rex", "pug", "brown") my_dog.bark() my_dog.sit() - + From ab0d429b2db26822362918d9c84096a9ea63f741 Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Wed, 6 Aug 2025 15:44:03 -0400 Subject: [PATCH 082/357] Changed print statements so they use more beginner-friendly formatting. --- source/ch2_firstjavaprogram.ptx | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/source/ch2_firstjavaprogram.ptx b/source/ch2_firstjavaprogram.ptx index 289eeee..a156fcc 100644 --- a/source/ch2_firstjavaprogram.ptx +++ b/source/ch2_firstjavaprogram.ptx @@ -38,16 +38,16 @@ self.breed = breed self.fur_color = fur_color self.trained = False - print(f"Dog named {self.name} created!") + print("Dog named " + self.name + " created!") def bark(self): - print(f"{self.name} says woof!") + print(self.name + " says woof!") def sit(self): if self.trained: - print(f"{self.name} sits.") + print(self.name + " sits.") else: - print(f"{self.name} has not been trained.") + print(self.name + " has not been trained.") def train(self): self.trained = True @@ -79,16 +79,16 @@ self.breed = breed self.fur_color = fur_color self.trained = False - print(f"Dog named {self.name} created!") + print("Dog named " + self.name + " created!") def bark(self): - print(f"{self.name} says woof!") + print(self.name + " says woof!") def sit(self): if self.trained: - print(f"{self.name} sits.") + print(self.name + " sits.") else: - print(f"{self.name} has not been trained.") + print(self.name + " has not been trained.") def train(self): self.trained = True @@ -114,16 +114,16 @@ self.breed = breed self.fur_color = fur_color self.trained = False - print(f"Dog named {self.name} created!") + print("Dog named " + self.name + " created!") def bark(self): - print(f"{self.name} says woof!") + print(self.name + " says woof!") def sit(self): if self.trained: - print(f"{self.name} sits.") + print(self.name + " sits.") else: - print(f"{self.name} has not been trained.") + print(self.name + " has not been trained.") def train(self): self.trained = True From c7b894553c71952ad5774ebbac5e94b72c73c3a0 Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Wed, 6 Aug 2025 15:47:19 -0400 Subject: [PATCH 083/357] Changed chapter title and xml id to java programs. --- source/ch2_firstjavaprogram.ptx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/ch2_firstjavaprogram.ptx b/source/ch2_firstjavaprogram.ptx index a156fcc..f233cc0 100644 --- a/source/ch2_firstjavaprogram.ptx +++ b/source/ch2_firstjavaprogram.ptx @@ -1,8 +1,8 @@ - - Lets look at a Java Program + + Java Programs
    Classes and Objects From c58cd4e9e41443cdc5348960b6962a829f6a0f19 Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Wed, 6 Aug 2025 15:47:53 -0400 Subject: [PATCH 084/357] add transition between codeblocks --- source/ch8_filehandling.ptx | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index e2036c9..082b069 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -16,9 +16,6 @@

    In Python, most built-in libraries are available without needing to explicitly import additional packages, but some libraries like math do need to be imported. Consider the following.

    -

    - Python: -

    import math @@ -27,7 +24,7 @@

    - Java: + The same program in Java would look like this:

    From a2f429e2e0a8db20655d7c062e8ceb8a155ae314 Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Wed, 6 Aug 2025 15:51:08 -0400 Subject: [PATCH 085/357] add statement about imports in Java --- source/ch8_filehandling.ptx | 3 +++ 1 file changed, 3 insertions(+) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 082b069..d87b7e5 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -37,6 +37,9 @@ } +

    + Note the use of import java.lang.Math; in the above to import the Math class. Unlike Python, Java requires explicit imports for most libraries, including the Math class and many different classes for file handling. +

    Java has several libraries included for file handling, though, they must be imported. Java includes a class called File in the io library. The class can be imported with the following line. Be sure to capitalize File. From bf84c8ca25f635f44819c4fac815af3c8df1ed1f Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Wed, 6 Aug 2025 15:52:55 -0400 Subject: [PATCH 086/357] remove redundency --- source/ch8_filehandling.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index d87b7e5..6664838 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -42,7 +42,7 @@

    - Java has several libraries included for file handling, though, they must be imported. Java includes a class called File in the io library. The class can be imported with the following line. Be sure to capitalize File. + Java includes a class called File in the io library. The class can be imported with the following line. Be sure to capitalize File.

    From 63256d44c1ef964729a51b0b801dc0db214ea7a6 Mon Sep 17 00:00:00 2001 From: Eun Sung Wang <156254694+esw0624@users.noreply.github.com> Date: Wed, 6 Aug 2025 16:12:13 -0400 Subject: [PATCH 087/357] Restructing the sections in Chapter 9 --- source/ch9_commonmistakes.ptx | 50 +++++++++++++++++------------------ 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/source/ch9_commonmistakes.ptx b/source/ch9_commonmistakes.ptx index 0bbd78a..c8ef187 100644 --- a/source/ch9_commonmistakes.ptx +++ b/source/ch9_commonmistakes.ptx @@ -7,6 +7,31 @@ +
    + Forgetting a Semicolon +

    + A common mistake in Java is to forget that every statement must end with a semicolon (;). +

    + + + // Histo.java + import java.util.Scanner; // Imports Scanner + + public class Histo { // Class declaration + + public static void main(String[] args) { // Main method declaration + Scanner data = null // The error will point here + System.out.println("This line will not compile."); + }// End of main method + }//End of class + + +

    + The error "';' expected" on line 7 of Histo.java means that a semicolon is missing at the end of the statement Scanner data = null. In Java, every statement must be terminated with a semicolon (;) to indicate its completion. The arrow points to null because that's where the compiler expected to find the semicolon. +

    + +
    +
    Forgetting to declare your variables

    @@ -96,31 +121,6 @@

    -
    - Forgetting a Semicolon -

    - A common mistake in Java is to forget that every statement must end with a semicolon (;). -

    - - - // Histo.java - import java.util.Scanner; // Imports Scanner - - public class Histo { // Class declaration - - public static void main(String[] args) { // Main method declaration - Scanner data = null // The error will point here - System.out.println("This line will not compile."); - }// End of main method - }//End of class - - -

    - The error "';' expected" on line 7 of Histo.java means that a semicolon is missing at the end of the statement Scanner data = null. In Java, every statement must be terminated with a semicolon (;) to indicate its completion. The arrow points to null because that's where the compiler expected to find the semicolon. -

    - -
    -
    Forgetting to declare the kind of object in a container

    From 97e32a3aa29ad417c33364b99a523b05dd9ba043 Mon Sep 17 00:00:00 2001 From: colin flaherty Date: Wed, 6 Aug 2025 15:56:45 -0400 Subject: [PATCH 088/357] storing changes before pulling from main --- source/ch8_filehandling.ptx | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 49bf932..f5aac3b 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -44,7 +44,7 @@

    Java includes a class called File in the io library. The class can be imported with the following line. Be sure to capitalize File.

    - + import java.io.File; import java.io.IOException;public class Main { @@ -94,14 +94,15 @@

    We will now create a File object. It is important to create a meaningful name for the File object. We will call ours myFile.

    - +
                         empty file
                     
    - + - import java.io.File;public class Main { + import java.io.File; + public class Main { public static void main(String[] args) { File myFile = new File("myfile.txt"); System.out.println(myFile); @@ -123,12 +124,12 @@

    First, lets look at the equivalent Python code:

    - +
                         empty file
                     
    - + filename = "newfile.txt" print(f"Attempting to write to '{filename}' using 'w' mode...") @@ -145,12 +146,12 @@

    Now, let's look at Java code that accomplishes the same task:

    - +
                         empty file
                     
    - + import java.io.File; import java.io.IOException; @@ -181,7 +182,7 @@

    Let's take a look at how we can use Java to read file contents. We'll start again with library imports and building a class, this time importing the Scanner and FileNotFoundException classes. We will call this class ReadFile:

    - +
                         1
                         2
    
    From b4a029351c0d067af8a8960559a51d900ae3a47d Mon Sep 17 00:00:00 2001
    From: colin flaherty 
    Date: Thu, 7 Aug 2025 09:41:25 -0400
    Subject: [PATCH 089/357] added files to 8.3 and finished 8.2. commiting before
     updating branch.
    
    ---
     source/ch8_filehandling.ptx | 10 +++-------
     1 file changed, 3 insertions(+), 7 deletions(-)
    
    diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx
    index f5aac3b..8cca43d 100644
    --- a/source/ch8_filehandling.ptx
    +++ b/source/ch8_filehandling.ptx
    @@ -124,11 +124,7 @@
             

    First, lets look at the equivalent Python code:

    - -
    -                    empty file
    -                
    -
    + filename = "newfile.txt" @@ -293,7 +289,7 @@ Alternatively, the following code can be used to store the all lines of myfile.txt to one variable:

    - + import java.io.File; import java.io.FileNotFoundException; @@ -345,7 +341,7 @@ And the Java equivalent:

    - + import java.io.File; import java.io.FileNotFoundException; From 97dc160da29942c461032669d18963f459fcaacf Mon Sep 17 00:00:00 2001 From: colin flaherty Date: Thu, 7 Aug 2025 09:52:31 -0400 Subject: [PATCH 090/357] fixed python block in 8.3 --- source/ch8_filehandling.ptx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 8cca43d..87a4f29 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -125,7 +125,7 @@ First, lets look at the equivalent Python code:

    - + filename = "newfile.txt" print(f"Attempting to write to '{filename}' using 'w' mode...") @@ -248,9 +248,9 @@ The next lines consists of a Python code example that reads each line of the file passed to the Scanner object.:

    - + - with open("filename.txt", "r") as file_reader: + with open("myfile.txt", "r") as file_reader: for line in file_reader: print(line.strip()) From 370f9d8511172904de9b5f935ad42a1ba6eff5b7 Mon Sep 17 00:00:00 2001 From: colin flaherty Date: Thu, 7 Aug 2025 10:03:13 -0400 Subject: [PATCH 091/357] added xmlids to all of the code blocks from 8.1-8.4 --- source/ch8_filehandling.ptx | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 87a4f29..a202942 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -192,7 +192,7 @@ - + import java.io.File; import java.io.FileNotFoundException; @@ -220,7 +220,7 @@ We will then create a new File object exactly the same as the one from the section on creating files. Additionally, we will create a Scanner object. The Scanner object is the object that does the file reading. We will call this scanner fileReader:

    - + import java.io.File; import java.io.FileNotFoundException; @@ -248,7 +248,7 @@ The next lines consists of a Python code example that reads each line of the file passed to the Scanner object.:

    - + with open("myfile.txt", "r") as file_reader: for line in file_reader: @@ -260,7 +260,7 @@ The equivalent Java code:

    - + import java.io.File; import java.io.FileNotFoundException; @@ -289,7 +289,7 @@ Alternatively, the following code can be used to store the all lines of myfile.txt to one variable:

    - + import java.io.File; import java.io.FileNotFoundException; @@ -321,7 +321,7 @@ Using the second method of storing all file contents to one file, the resulting full code including try/catch blocks (this time using FileNotFoundException instead of IOException) will look something like this. First, the Python code:

    - + try: with open("myfile.txt", "r") as file_reader: @@ -341,7 +341,7 @@ And the Java equivalent:

    - + import java.io.File; import java.io.FileNotFoundException; @@ -382,7 +382,7 @@ Let us create the framework for a class that will write to a file. Let's call this class WriteFile:

    - + import java.io.File; import java.io.FileWriter; @@ -444,7 +444,7 @@ 3
    - + with open("myfile8-4-2.txt", "r") as file_reader: while True: @@ -463,7 +463,7 @@
    - + import java.io.File; import java.io.IOException; @@ -491,7 +491,7 @@
    - + try: with open("myfile.txt", "w") as my_writer: @@ -512,7 +512,7 @@
    - + import java.io.FileWriter; import java.io.IOException; @@ -559,7 +559,7 @@
    - + import java.io.FileWriter; import java.io.IOException; From 18a2305602c497cd40f9fe0d374b0e5d56f5e07a Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Thu, 7 Aug 2025 11:29:22 -0400 Subject: [PATCH 092/357] simplify helper method section --- source/ch7_recursion.ptx | 319 +++++++++++++++++++++++++++++++++++++++ source/chx_recursion.ptx | 276 --------------------------------- source/main.ptx | 2 +- 3 files changed, 320 insertions(+), 277 deletions(-) create mode 100644 source/ch7_recursion.ptx delete mode 100644 source/chx_recursion.ptx diff --git a/source/ch7_recursion.ptx b/source/ch7_recursion.ptx new file mode 100644 index 0000000..08afdc4 --- /dev/null +++ b/source/ch7_recursion.ptx @@ -0,0 +1,319 @@ + + + Recursion in Java + + + +
    + Basic Recursion +

    + In this chapter, we will explore how to translate your recursive logic from Python to Java. While the core concepts of recursion remain the same, the syntax and structure of your code will change somewhat. +

    +

    recursion + As you may know from Python, recursion is a powerful problem-solving technique involving base cases and recursive steps in which a function or method calls itself. When moving to Java, the core logic you've learned remains identical. The challenge is adapting that logic to Java's statically-typed, class-based syntax. +

    +

    + Let's take the familiar factorial function (which calculates the factorial of a number, namely the product of all positive integers from 1 to n). The logical steps in the code are the same, but the implementation details change. +

    +

    + Here is a Python implementation using functions: +

    + + +def factorial(n): + # Check for negative numbers + if n < 0: + print("Factorials are only defined on non-negative integers.") + return + # Base Case: 0! or 1! is 1 + if n <= 1: + return 1 + # Recursive Step: n * (n-1)! + return n * factorial(n - 1) + +def main(): + number = 5 + print(str(number) + "! is " + str(factorial(number))) + +main() + + + +

    + Many Python programs organize related functions into classes. The same factorial function can be placed inside a class as a method. Then you need to create an instance of the class to call the method. There we create the class MathTools with a method factorial, and we call it from the main function. +

    + + +class MathTools: + def factorial(self, n): + # Check for negative numbers + if n < 0: + print("Factorials are only defined on non-negative integers.") + return + # Base Case: 0! or 1! is 1 + if n <= 1: + return 1 + # Recursive Step: n * (n-1)! + return n * self.factorial(n - 1) + +def main(): + # Create an instance of the class and call the method + math_tools = MathTools() + number = 5 + print(str(number) + "! is " + str(math_tools.factorial(number))) + +main() + + + +

    + See if you can spot the differences in the Java version below. +

    +

    + Here is the equivalent Java code: +

    + + +public class MathTools { + public static int factorial(int n) { + // Check for negative numbers + if (n < 0) { + System.out.println("Factorials are only defined on non-negative integers."); + return -1; // Return -1 to indicate error + } + // Base Case: 0! or 1! is 1 + if (n <= 1) { + return 1; + } + // Recursive Step: n * (n-1)! + return n * factorial(n - 1); + } + + public static void main(String[] args) { + int number = 5; + System.out.println(number + "! is " + factorial(number)); + } +} + + +

    + Notice the key differences from Python: instead of def factorial(n):, Java uses public static int factorial(int n) which declares the method's visibility as public, that it belongs to the class rather than an instance (hence, static), the return type as integer, and the parameter type also as integer. The recursive logic—base case and recursive step—remains identical to Python, but all code blocks use curly braces {} instead of indentation. +

    +
    + +
    + Using Helper Methods + +

    + In many recursive algorithms, the recursive calls need extra information that the original caller shouldn't have to provide. For example, to recursively process an array, you need to keep track of the current position (index). This extra information clutters the public-facing method signature and forces users to provide implementation details they shouldn't need to know about. +

    +

    helper method pattern in recursion + A common pattern to solve this is using a helper method. This pattern lets you create a clean, simple public method that users will call, while the private helper method handles the complex details of the recursion. The public method typically makes the initial call to the private helper, providing the necessary starting values for the extra parameters. +

    +

    + Let's see this pattern in action with an example that calculates the sum of all elements in an integer array. Notice how the public method only requires the array, but the recursive logic needs to track the current index position. +

    + +

    + First, let's see what happens if we try to write a recursive array sum function without using a helper method. In this approach, the user must provide the starting index, which is awkward and exposes implementation details: +

    + + +class ArrayProcessor: + def sum_array(self, arr, index): + """ + This version forces users to provide the index parameter. + This is inconvenient and exposes implementation details. + """ + # Base case: we've processed all elements + if index >= len(arr): + return 0 + + # Recursive step: current element + sum of remaining elements + return arr[index] + self.sum_array(arr, index + 1) + +def main(): + processor = ArrayProcessor() + numbers = [1, 2, 3, 4, 5] + # Users must remember to start at index 0 - this is confusing! + result = processor.sum_array(numbers, 0) + print("The sum of " + str(numbers) + " is " + str(result)) + +main() + + + +

    + This approach has several problems: users must remember to start with index 0, the method signature is cluttered with implementation details, and it's easy to make mistakes by passing the wrong starting index. The same awkward pattern appears in Java: +

    + + +public class ArrayProcessor { + public static int sumArray(int[] arr, int index) { + // Base case: we've processed all elements + if (index >= arr.length) { + return 0; + } + + // Recursive step: current element + sum of remaining elements + return arr[index] + sumArray(arr, index + 1); + } + + public static void main(String[] args) { + int[] numbers = {1, 2, 3, 4, 5}; + // Users must remember to start at index 0 - this is confusing! + int result = sumArray(numbers, 0); + System.out.println("The sum of [1, 2, 3, 4, 5] is " + result); + } +} + + + +

    + Both versions force users to understand and provide implementation details they shouldn't need to know about. Now let's see how helper methods solve this problem by providing a clean, user-friendly interface. +

    + +

    + Here's the improved Python version using a helper method: +

    + + +class ArrayProcessor: + def sum_array(self, arr): + """ + Public method that provides a clean interface for summing array elements. + Users only need to provide the array - no implementation details required. + """ + if not arr: # Handle empty array + return 0 + # Start the recursion at index 0 + return self._sum_helper(arr, 0) + + def _sum_helper(self, arr, index): + """ + Private helper method that does the actual recursive work. + Tracks the current index position through the array. + """ + # Base case: we've processed all elements + if index >= len(arr): + return 0 + + # Recursive step: current element + sum of remaining elements + return arr[index] + self._sum_helper(arr, index + 1) + +def main(): + processor = ArrayProcessor() + numbers = [1, 2, 3, 4, 5] + result = processor.sum_array(numbers) + print("The sum of " + str(numbers) + " is " + str(result)) + +main() + + + +

    separation of concerns + The key insight here is called the separation of concerns. The public sum_array method provides a user-friendly interface—callers just pass an array and get the sum. They don't need to know about indexes or how the recursion works internally. The private _sum_helper method handles the recursive logic with the extra parameter needed to track progress through the array. +

    + +

    + Now let's see the improved Java version using a helper method: +

    + + +public class ArrayProcessor { + public static int sumArray(int[] arr) { + // Handle empty array + if (arr.length == 0) { + return 0; + } + // Start the recursion at index 0 + return sumHelper(arr, 0); + } + + private static int sumHelper(int[] arr, int index) { + // Base case: we've processed all elements + if (index >= arr.length) { + return 0; + } + + // Recursive step: current element + sum of remaining elements + return arr[index] + sumHelper(arr, index + 1); + } + + public static void main(String[] args) { + int[] numbers = {1, 2, 3, 4, 5}; + int result = sumArray(numbers); + System.out.println("The sum of [1, 2, 3, 4, 5] is " + result); + } +} + + + +

    + Compare these improved versions with the earlier problematic ones. Notice how much cleaner the method calls become: processor.sum_array(numbers) in Python and sumArray(numbers) in Java. Users no longer need to worry about providing the correct starting index or understanding the internal mechanics of the recursion. The helper method pattern creates a clear separation between what users need to know (just pass an array) and the implementation details (tracking the index through recursion). +

    + +

    + This helper method pattern is essential when your recursive algorithm needs to track additional state (like array positions, accumulated values, or depth counters) that the original caller shouldn't need to provide. It's a fundamental technique you'll use frequently in recursive problem solving. +

    +
    + +
    + Recursion Limits: Python vs. Java +

    + The consequence of deep recursion, running out of stack space, is a concept you've already encountered in Python. Java handles this in a very similar way, throwing an error when the call stack depth is exceeded. +

    +

    + The key difference is the name of the error: +

    +
      +
    • In Python, this raises a RecursionError.
    • +
    • In Java, this throws a StackOverflowError.
    • +
    +

    + Neither language supports tail call optimization tail call optimization, so the practical limits on recursion depth are a factor in both. If an algorithm requires thousands of recursive calls, an iterative (loop-based) approach is the preferred solution in both Python and Java. +

    +

    + The following Python code demonstrates a situation where a function calls itself indefinitely without a base case, leading to aRecursionError. +

    + + + def cause_recursion_error(): + """ + This function calls itself without a base case, guaranteeing an error. + """ + cause_recursion_error() + + # Standard Python entry point + if __name__ == "__main__": + print("Calling the recursive function... this will end in an error!") + + # This line starts the infinite recursion. + # Python will stop it and raise a RecursionError automatically. + cause_recursion_error() + + + +

    + The following Java code demonstrates a similar situation, where a method calls itself indefinitely without a base case, leading to a StackOverflowError. +

    + + + public class Crash { + public static void causeStackOverflow() { + // This method calls itself endlessly without a stopping condition (a base case). + // Each call adds a new layer to the program's call stack. + // Eventually, the stack runs out of space, causing the error. + causeStackOverflow(); + } + // A main method is required to run the program. + public static void main(String[] args) { + System.out.println("Calling the recursive method... this will end in an error!"); + // This line starts the infinite recursion. + causeStackOverflow(); + } + } + + +
    +
    \ No newline at end of file diff --git a/source/chx_recursion.ptx b/source/chx_recursion.ptx deleted file mode 100644 index 4f3601e..0000000 --- a/source/chx_recursion.ptx +++ /dev/null @@ -1,276 +0,0 @@ - - - Recursion in Java - - - -
    - Basic Recursion -

    - In this chapter, we will explore how to translate your recursive logic from Python to Java. While the core concepts of recursion remain the same, the syntax and structure of your code will change somewhat. -

    -

    recursion - As you may know from Python, recursion is a powerful problem-solving technique involving base cases and recursive steps in which a function or method calls itself. When moving to Java, the core logic you've learned remains identical. The challenge is adapting that logic to Java's statically-typed, class-based syntax. -

    -

    - Let's take the familiar factorial function (which calculates the factorial of a number, namely the product of all positive integers from 1 to n). The logical steps in the code are the same, but the implementation details change. -

    -

    - Here is a simple Python function implementation: -

    - - -def factorial(n): - # Check for negative numbers - if n < 0: - print("Factorials are only defined on non-negative integers.") - return - # Base Case: 0! or 1! is 1 - if n <= 1: - return 1 - # Recursive Step: n * (n-1)! - return n * factorial(n - 1) - -def main(): - number = 5 - print(str(number) + "! is " + str(factorial(number))) - -main() - - - -

    - Many Python programs organize related functions into classes. The same factorial function can be placed inside a class as a method. Then you need to create an instance of the class to call the method. There we create the class MathTools with a method factorial, and we call it from the main function. -

    - - -class MathTools: - def factorial(self, n): - # Check for negative numbers - if n < 0: - print("Factorials are only defined on non-negative integers.") - return - # Base Case: 0! or 1! is 1 - if n <= 1: - return 1 - # Recursive Step: n * (n-1)! - return n * self.factorial(n - 1) - -def main(): - # Create an instance of the class and call the method - math_tools = MathTools() - number = 5 - print(str(number) + "! is " + str(math_tools.factorial(number))) - -main() - - - -

    - See if you can spot the differences in the Java version below. -

    -

    - Here is the equivalent Java code: -

    - - -public class MathTools { - public static int factorial(int n) { - // Check for negative numbers - if (n < 0) { - System.out.println("Factorials are only defined on non-negative integers."); - return -1; // Return -1 to indicate error - } - // Base Case: 0! or 1! is 1 - if (n <= 1) { - return 1; - } - // Recursive Step: n * (n-1)! - return n * factorial(n - 1); - } - - public static void main(String[] args) { - int number = 5; - System.out.println(number + "! is " + factorial(number)); - } -} - - -

    - Notice the key differences from Python: instead of def factorial(n):, Java uses public static int factorial(int n) which declares the method's visibility as public, that it belongs to the class rather than an instance (hence, static), the return type as integer, and the parameter type also as integer. The recursive logic—base case and recursive step—remains identical to Python, but all code blocks use curly braces {} instead of indentation. -

    -
    - -
    - Common Recursive Patterns - -

    - In many recursive algorithms, the recursive calls need extra information that the original caller shouldn't have to provide. For example, to recursively process an array, you need to keep track of the current position (index). To traverse a tree, you need to know the current node. This extra information clutters the public-facing method signature. -

    -

    - A common pattern to solve this is using a private helper method. This pattern lets you create a clean, simple public method that users will call, while the private helper method handles the complex details of the recursion. The public method typically makes the initial call to the private helper, providing the necessary starting values for the extra parameters. -

    -

    - Let's see this pattern in action with an example that calculates the sum of all elements in an integer array. The public sum method only takes the array, but the private sumHelper method also takes an index to track its progress through the array. -

    - -

    - You're likely familiar with how some recursive algorithms, like the naive Fibonacci implementation, - are elegant but inefficient, due to branching recursive calls filling the call stack. A common pattern to solve - this is using a private helper method. -

    -

    - The following example demonstrates this pattern. The public fib method provides a simple entry point, while the private fibHelper method performs the efficient recursion by carrying its state (the previous two numbers) in its parameters. -

    -

    - The following Java code demonstrates a similar pattern. -

    - - - - public class FibonacciExample { - public int fib(int n) { - if (n < 0) { - throw new IllegalArgumentException("Input cannot be negative."); - } - // Initial call to the recursive helper with depth 0. - return this._fibHelper(n, 0, 1, 0); - } - private int _fibHelper(int count, int a, int b, int depth) { - // Create an indent string based on the recursion depth. - String indent = " ".repeat(depth); - // Print when the method is entered (pushed onto the stack). - System.out.printf("%s[>>] ENTERING _fibHelper(count=%d, a=%d, b=%d)%n", indent, count, a, b); - // Base Case: When the count reaches 0, 'a' holds the result. - if (count == 0) { - System.out.printf("%s[<<] EXITING (Base Case) -> returns %d%n", indent, a); - return a; - } - // Recursive Step. - int result = this._fibHelper(count - 1, b, a + b, depth + 1); - // Print when the method exits (popped from the stack). - System.out.printf("%s[<<] EXITING (Recursive Step) -> passing %d%n", indent, result); - return result; - } - public static void main(String[] args) { - FibonacciExample calculator = new FibonacciExample(); - int n = 4; // Let's calculate the 4th Fibonacci number. - System.out.printf("--- Calculating fib(%d) ---%n", n); - int result = calculator.fib(n); - System.out.println("--------------------------"); - System.out.printf("The %dth Fibonacci number is: %d%n", n, result); - } - } - - -

    - This helper method approach is significantly more efficient in terms of time than the classic branching recursion (where fib(n) calls fib(n-1) and fib(n-2)). The branching model has an exponential time complexity of roughly O(2^n) because it re-calculates the same values many times. In contrast, our helper method has a linear time complexity of O(n), as it avoids re-computation by carrying the previous two results (a and b) forward into the next call. -

    -

    - However, regarding memory efficiency, the comparison is different. The maximum depth of the call stack for both the naive and the helper method is proportional to n, giving them both a space complexity of O(n). This means that while the helper method is much faster, it is equally vulnerable to a StackOverflowError for very large values of n. Because Java does not perform tail-call optimization, any recursive solution that goes too deep will exhaust the stack memory, regardless of its time efficiency. For true memory efficiency (O(1) space), an iterative loop-based solution is superior. -

    -

    - The following Python code demonstrates the same pattern, using a public method to initiate the calculation and a private helper method to perform the recursion. -

    - - - class FibonacciExample: - def fib(self, n: int) -> int: - """ - Public method to start the Fibonacci calculation. - """ - if n < 0: - raise ValueError("Input cannot be negative.") - # Initial call to the recursive helper with depth 0. - return self._fib_helper(n, 0, 1, 0) - - def _fib_helper(self, count: int, a: int, b: int, depth: int) -> int: - """ - Private helper that performs the tail recursion to find the number. - """ - # Create an indent string based on the recursion depth. - indent = " " * depth - # Print when the method is entered (pushed onto the stack). - print(f"{indent}[>>] ENTERING _fib_helper(count={count}, a={a}, b={b})") - - # Base Case: When the count reaches 0, 'a' holds the result. - if count == 0: - print(f"{indent}[<<] EXITING (Base Case) -> returns {a}") - return a - - # Recursive Step. - result = self._fib_helper(count - 1, b, a + b, depth + 1) - # Print when the method exits (popped from the stack). - print(f"{indent}[<<] EXITING (Recursive Step) -> passing {result}") - return result - - # The standard Python entry point, equivalent to Java's `main` method. - if __name__ == "__main__": - calculator = FibonacciExample() - n = 4 # Let's calculate the 4th Fibonacci number. - print(f"--- Calculating fib({n}) ---") - result = calculator.fib(n) - print("--------------------------") - print(f"The {n}th Fibonacci number is: {result}") - - -
    -
    - Recursion Limits: Python vs. Java -

    - The consequence of deep recursion, running out of stack space, is a concept you've already encountered in Python. Java handles this in a very similar way, throwing an error when the call stack depth is exceeded. -

    -

    - The key difference is the name of the error: -

    -
      -
    • In Python, this raises a RecursionError.
    • -
    • In Java, this throws a StackOverflowError.
    • -
    -

    - Neither language supports tail call optimization tail call optimization, so the practical limits on recursion depth are a factor in both. If an algorithm requires thousands of recursive calls, an iterative (loop-based) approach is the preferred solution in both Python and Java. -

    -

    - The following Python code demonstrates a situation where a function calls itself indefinitely without a base case, leading to aRecursionError. -

    - - - def cause_recursion_error(): - """ - This function calls itself without a base case, guaranteeing an error. - """ - cause_recursion_error() - - # Standard Python entry point - if __name__ == "__main__": - print("Calling the recursive function... this will end in an error!") - - # This line starts the infinite recursion. - # Python will stop it and raise a RecursionError automatically. - cause_recursion_error() - - - -

    - The following Java code demonstrates a similar situation, where a method calls itself indefinitely without a base case, leading to a StackOverflowError. -

    - - - public class Crash { - public static void causeStackOverflow() { - // This method calls itself endlessly without a stopping condition (a base case). - // Each call adds a new layer to the program's call stack. - // Eventually, the stack runs out of space, causing the error. - causeStackOverflow(); - } - // A main method is required to run the program. - public static void main(String[] args) { - System.out.println("Calling the recursive method... this will end in an error!"); - // This line starts the infinite recursion. - causeStackOverflow(); - } - } - - -
    -
    \ No newline at end of file diff --git a/source/main.ptx b/source/main.ptx index 6a3df61..ec616d0 100644 --- a/source/main.ptx +++ b/source/main.ptx @@ -13,7 +13,7 @@ git - + From 849982dc486d1869f4655eadc0b26e98159d0fc5 Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Thu, 7 Aug 2025 11:33:15 -0400 Subject: [PATCH 093/357] fix title --- source/main.ptx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/main.ptx b/source/main.ptx index ec616d0..6f4f823 100644 --- a/source/main.ptx +++ b/source/main.ptx @@ -3,9 +3,9 @@ - Java For Python Programmer + Java For Python Programmers - The PreTeXt Interactive Edition + Edition 2 From 5ab0d747d64303fb67965a25e40db99bcbd1913b Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Thu, 7 Aug 2025 11:57:27 -0400 Subject: [PATCH 094/357] Removed the work completed in the last commit as it did not include Python code. All Code blocks are completed. Need to add explanation of Java code. --- source/ch4_conditionals.ptx | 91 ++++++++++++++++++++++++++++--------- 1 file changed, 69 insertions(+), 22 deletions(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index abc77ae..8b53c5b 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -163,7 +163,17 @@ public class ElseIf {

    Java also supports a switch statement that acts something like the elif statement of Python under certain conditions. To write the grade program using a switch statement we would use the following: -

    +

    while True: + + try: + + x = int(input("Please enter a whole number: ")) + + break + + except ValueError: + + print("Oops! That was no valid number. Try again...")

    @@ -234,48 +244,85 @@ The switch statement is not used very often, and we recommend you do not

    -
    +
    Exception Handling

    - Errors and bugs when writing programs are nearly impossible to avoid. As a programmer, you may have spent a considerable amount of time debugging code. Sometimes, even when we have done everything right and ensured a program will function as it is intended to, errors are still unavoidable especially when user input is necessary. + In Python, if you want a program to continue running when an error has occurred, you can use try/except blocks to handle exceptions. If you wanted to write a program that asks the user to enter a whole number and then squares that number, you could use the following code to do so:

    + + + number = int(input("Please enter a whole number: ")) + squared = number ** 2 + print("Your number squared is " + str(squared)) + + +

    - Let's look at an example of code that may lead to user error. This Java program will ask the user to input the year they were born. It will then tell them how old they will be in the year 2050. We will use the Scanner class from the util library to ask the user for input. + The Java code that would perform the same task is a little more complex and utilizes the Scanner class for input.

    - + import java.util.Scanner; - public class Main - { + public class SquareNumber { public static void main(String[] args) { + Scanner user_input = new Scanner(System.in); - // Update to current year if needed - int current_year = 2025; - - // Scanner object is created to get input - Scanner userInput = new Scanner(System.in); - System.out.println("Enter your age: "); - - // Reads user input - int age = Integer.parseInt(userInput.nextLine()); + System.out.print("Please enter a whole number: "); + int number = user_input.nextInt(); + int squared = number * number; - // Arithmatic to find age in 2050 - int birth_year = current_year - age; - int age_in_2050 = 2050 - birth_year; - - System.out.println("Your age in 2050 will be " + age_in_2050); + System.out.println("Your number squared is " + squared); } }

    - This program seems to work pretty well. The user can enter their age and get the desired result. Large numbers such as 10,000 and negative numbers such as -75 work fine with this program, meaning we have accommodated both vampires and time travelers! Despite this, our program can still run into issues. You may have noticed that the age variable is an integer. What happens if a user takes into account that their birthday was six months ago and types 20.5 into the console? What happens if the user spells out their age and types twelve instead of 12? Try these two inputs and see what happens! + This code works well, but will end with an exception if the user types anything other than a whole number (such as 12.5 or two). If we wanted to ensure the code will continue to run until the user enters the correct format, we could add try/except (Python) or try/catch (Java) blocks within a while loop that iterates until the user enter the correct code. Adding try/except blocks and a while loop will look something like this:

    + + + + while True: + try: + number = int(input("Please enter a whole number: ")) + squared = number ** 2 + print("Your number squared is " + str(squared)) + break + except ValueError: + print("That was not a valid number. Please try again: ") + + + + + + import java.util.Scanner; + import java.util.InputMismatchException; + + public class SquareNumberWithValidation { + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + + while (true) { + try { + System.out.print("Please enter a whole number: "); + int number = scanner.nextInt(); + int squared = number * number; + System.out.println("Your number squared is " + squared); + break; + } catch (InputMismatchException e) { + System.out.println("That was not a valid number. Please try again: "); + scanner.nextLine(); // Clear the invalid input + } + } + } + } + +
    From 5cde97ef742ba27ea87594bbeb247a983643f8f6 Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Thu, 7 Aug 2025 12:15:47 -0400 Subject: [PATCH 095/357] add xml:ids to codeblocks and improve clarity --- source/ch7_recursion.ptx | 61 +++++++++++++++++++++++++--------------- 1 file changed, 38 insertions(+), 23 deletions(-) diff --git a/source/ch7_recursion.ptx b/source/ch7_recursion.ptx index 08afdc4..156f9a3 100644 --- a/source/ch7_recursion.ptx +++ b/source/ch7_recursion.ptx @@ -12,13 +12,31 @@

    recursion As you may know from Python, recursion is a powerful problem-solving technique involving base cases and recursive steps in which a function or method calls itself. When moving to Java, the core logic you've learned remains identical. The challenge is adapting that logic to Java's statically-typed, class-based syntax.

    + +

    + Let's take the familiar factorial function, which calculates n! (read as "n factorial"), so for example 5! = 5 × 4 × 3 × 2 × 1 = 120. Factorial is a classic example of recursion, where the function calls itself with a smaller value until it reaches a base case. + In general, n! = n \times (n-1) \times (n-2) \times \cdots \times 2 \times 1, + or recursively defined as n! = n \times (n-1)! with base cases 0! = 1 and 1! = 1. +

    +

    + You may recall mathematical notation using the symbol \sum (Greek letter sigma) + to represent "sum." For example, when we sum all elements in an array, we write + \sum_{i=0}^{n-1} a_i, where i=0 below the symbol indicates we start at index 0, + n-1 above it means we end at index n-1, and a_i represents the array + element at each index i. Similarly, \sum_{i=1}^{n} i means "sum all integers + i from 1 to n." +

    +

    + Factorial involves multiplication rather than addition, so we use the product symbol + \prod (Greek letter pi): n! = \prod_{i=1}^{n} i, which means "multiply + all integers i from 1 to n." Both summation and factorial can be expressed + recursively—summation as the first element plus the sum of remaining elements, and factorial + as n \times (n-1)!. +

    - Let's take the familiar factorial function (which calculates the factorial of a number, namely the product of all positive integers from 1 to n). The logical steps in the code are the same, but the implementation details change. -

    -

    - Here is a Python implementation using functions: + Here is a Python implementation of factorial using functions:

    - + def factorial(n): # Check for negative numbers @@ -42,7 +60,7 @@ main()

    Many Python programs organize related functions into classes. The same factorial function can be placed inside a class as a method. Then you need to create an instance of the class to call the method. There we create the class MathTools with a method factorial, and we call it from the main function.

    - + class MathTools: def factorial(self, n): @@ -72,7 +90,7 @@ main()

    Here is the equivalent Java code:

    - + public class MathTools { public static int factorial(int n) { @@ -105,19 +123,17 @@ public class MathTools { Using Helper Methods

    - In many recursive algorithms, the recursive calls need extra information that the original caller shouldn't have to provide. For example, to recursively process an array, you need to keep track of the current position (index). This extra information clutters the public-facing method signature and forces users to provide implementation details they shouldn't need to know about. + In many recursive algorithms, the recursive calls need extra information that the original caller shouldn't have to provide. For example, to recursively process an array, you need to keep track of the index of the current position. This extra information clutters the public-facing signature by forcing users to provide implementation details they shouldn't actually need to know about.

    helper method pattern in recursion - A common pattern to solve this is using a helper method. This pattern lets you create a clean, simple public method that users will call, while the private helper method handles the complex details of the recursion. The public method typically makes the initial call to the private helper, providing the necessary starting values for the extra parameters. -

    -

    - Let's see this pattern in action with an example that calculates the sum of all elements in an integer array. Notice how the public method only requires the array, but the recursive logic needs to track the current index position. + A common pattern to solve this problem is by using a helper method. This pattern lets you create a clean, simple function or public method that users can call, while the private helper function or method handles the complex details of the recursion. The function or public method typically makes an initial call to the private helper method or function, providing the necessary starting values for the extra parameters.

    +

    First, let's see what happens if we try to write a recursive array sum function without using a helper method. In this approach, the user must provide the starting index, which is awkward and exposes implementation details:

    - + class ArrayProcessor: def sum_array(self, arr, index): @@ -144,9 +160,9 @@ main()

    - This approach has several problems: users must remember to start with index 0, the method signature is cluttered with implementation details, and it's easy to make mistakes by passing the wrong starting index. The same awkward pattern appears in Java: + This approach has a significant problem, namely that users must remember to start with index 0. Hence, the method signature is cluttered with an implementation detail, and it's easy to make a mistake by passing the wrong starting index. The same awkward pattern appears in Java:

    - + public class ArrayProcessor { public static int sumArray(int[] arr, int index) { @@ -170,13 +186,12 @@ public class ArrayProcessor {

    - Both versions force users to understand and provide implementation details they shouldn't need to know about. Now let's see how helper methods solve this problem by providing a clean, user-friendly interface. + Both versions force users to understand and provide implementation details they shouldn't need to know about. Now let's see how helper methods solve this problem by providing a clean, user-friendly interface. Notice how the public method only requires the array itself, and the hidden recursive logic tracks the current index position.

    -

    Here's the improved Python version using a helper method:

    - + class ArrayProcessor: def sum_array(self, arr): @@ -212,13 +227,13 @@ main()

    separation of concerns - The key insight here is called the separation of concerns. The public sum_array method provides a user-friendly interface—callers just pass an array and get the sum. They don't need to know about indexes or how the recursion works internally. The private _sum_helper method handles the recursive logic with the extra parameter needed to track progress through the array. + The key insight here is called the separation of concerns. The public sum_array method provides a user-friendly interface—callers just pass an array and get the sum. Users don't need to know about indexes or how the recursion works internally. The private _sum_helper method handles the recursive logic with the extra parameter needed to track progress through the array.

    Now let's see the improved Java version using a helper method:

    - + public class ArrayProcessor { public static int sumArray(int[] arr) { @@ -254,7 +269,7 @@ public class ArrayProcessor {

    - This helper method pattern is essential when your recursive algorithm needs to track additional state (like array positions, accumulated values, or depth counters) that the original caller shouldn't need to provide. It's a fundamental technique you'll use frequently in recursive problem solving. + This helper method pattern is essential when your recursive algorithm needs to track additional state (like array positions, accumulated values, or depth counters) that the original caller shouldn't need to provide or care about. It's a fundamental pattern and technique you'll likely use frequently in recursive problem solving.

    @@ -276,7 +291,7 @@ public class ArrayProcessor {

    The following Python code demonstrates a situation where a function calls itself indefinitely without a base case, leading to aRecursionError.

    - + def cause_recursion_error(): """ @@ -297,7 +312,7 @@ public class ArrayProcessor {

    The following Java code demonstrates a similar situation, where a method calls itself indefinitely without a base case, leading to a StackOverflowError.

    - + public class Crash { public static void causeStackOverflow() { From a14e85d2b460c51e3a48129bc2970992fee6b563 Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Thu, 7 Aug 2025 12:57:25 -0400 Subject: [PATCH 096/357] fix early xml:ids --- source/ch1_overview.ptx | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/source/ch1_overview.ptx b/source/ch1_overview.ptx index 7c1da79..4a589a9 100644 --- a/source/ch1_overview.ptx +++ b/source/ch1_overview.ptx @@ -5,8 +5,8 @@ Overview -
    - Introduction to Java for Python Programmers +
    + Prerequisites

    This book assumes that you are already familiar with the Python programming language. @@ -87,7 +87,7 @@

    -
    +
    Java Development Environment @@ -306,8 +306,8 @@
    -
    - Why Learn another programming Language? +
    + Why Another Programming Language?

    Python is a nice language for beginning programming for several reasons. @@ -357,7 +357,7 @@

    -
    +
    Why Learn Java? Why not C or C++?

    @@ -399,9 +399,9 @@

    -
    +
    Summary & Reading Questions -

      +

      1. Learning multiple programming languages helps programmers adapt to different styles and environments.

      2. From c090273ce85b51e8ec724e76e6aeaa4f3d38c9f0 Mon Sep 17 00:00:00 2001 From: colin flaherty Date: Thu, 7 Aug 2025 13:21:37 -0400 Subject: [PATCH 097/357] fixed remaining issues after testing, and removed sourcecode for data files. --- source/ch8_filehandling.ptx | 41 ++++++++++++++++++++----------------- 1 file changed, 22 insertions(+), 19 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index a202942..8d804f7 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -118,7 +118,7 @@

        - Now that we have created a new File object, we can create a file using the createNewFile() method from the File class. While the previous line of code creates an object within the program for the file, this method actually does the work of creating a file and saving it in the current working directory. This method returns a boolean value. If the method returns true, the file was successfully created. If the method returns false, there is already a file using the chosen file name. We can use this method's possible return values in tandem with an if/else selection to determine if the file was created, or if a file with that file name already exists in the directory. + Now that we have created a new File object, we can create a file using the createNewFile() method from the File class. While the previous line of code creates an object within the program for the file, this method actually does the work of creating a file and saving it in the current working directory. This method returns a boolean value. If the method returns true, the file was successfully created. If the method returns false, there is already a file using the chosen file name. We can use this method's possible return values in tandem with an try/catch structure to determine if the file was created, or catch the error if a file with that file name already exists in the directory.

        @@ -142,22 +142,25 @@

        Now, let's look at Java code that accomplishes the same task:

        - -
        -                    empty file
        -                
        -
        - + + import java.io.File; import java.io.IOException; public class CreateFile { public static void main(String[] args) { - if (myFile.createNewFile()) { // If the file was created successfully - System.out.println("The file " + myFile.getName() + " was created sucessfully."); - } else { // If a file with the file name chosen already exists - System.out.println("The file " + myFile.getName() + " already exists."); + File myFile = new File("newfile.txt"); + try { + if (myFile.createNewFile()) { + System.out.println("The file " + myFile.getName() + " was created successfully."); + } else { + System.out.println("The file " + myFile.getName() + " already exists."); + } + } catch (IOException e) { + // This code runs if an IOException occurs + System.out.println("An error occurred while creating the file."); + e.printStackTrace(); // This prints the stack trace for more detailed error info } } } @@ -220,7 +223,7 @@ We will then create a new File object exactly the same as the one from the section on creating files. Additionally, we will create a Scanner object. The Scanner object is the object that does the file reading. We will call this scanner fileReader:

        - + import java.io.File; import java.io.FileNotFoundException; @@ -329,7 +332,7 @@ for line in file_reader: data += line # line already includes the newline character print(data) - except FileNotFoundError as e: + except FileNotFoundError: print("An error occurred.") import traceback traceback.print_exc() @@ -341,7 +344,7 @@ And the Java equivalent:

        - + import java.io.File; import java.io.FileNotFoundException; @@ -437,7 +440,7 @@

        Next, we will again add the required try/catch blocks utilizing the IOException class. Just like with creating files, the program will not compile without these crucial additions! We will also add some print statements to inform us of the success of the file write operation. First, a Python example:

        - +
                             1
                             2
        @@ -458,7 +461,7 @@
                 

        And the equivalent Java code:

        - +
                             
                         
        @@ -486,7 +489,7 @@

        And that's it! We will add our code to the foundational code for a complete program. First, an example of equivalent Python code:

        - +
                             
                         
        @@ -507,7 +510,7 @@

        The completed Java code:

        - +
                             
                         
        @@ -554,7 +557,7 @@

        Now, when we use write() method like before, the text will be appended if there is already text in the document. If we were to update our code to include the boolean argument:

        - +
                             
                         
        From e950f9765882b01cb122c61b2b036cca04fa2cd2 Mon Sep 17 00:00:00 2001 From: colin flaherty Date: Thu, 7 Aug 2025 14:49:05 -0400 Subject: [PATCH 098/357] fixes file not found errors in 8.4 --- source/ch8_filehandling.ptx | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 8d804f7..3169b36 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -489,7 +489,11 @@

        And that's it! We will add our code to the foundational code for a complete program. First, an example of equivalent Python code:

        +<<<<<<< HEAD +======= + +>>>>>>> 0633649 (fixes file not found errors in 8.4)
                             
                         
        @@ -500,7 +504,7 @@ with open("myfile.txt", "w") as my_writer: my_writer.write("File successfully updated!") print("File successfully written to.") - except OSError as e: + except OSError: print("An error occurred.") import traceback traceback.print_exc() @@ -510,12 +514,16 @@

        The completed Java code:

        +<<<<<<< HEAD
                             
                         
        +======= + +>>>>>>> 0633649 (fixes file not found errors in 8.4) import java.io.FileWriter; import java.io.IOException; @@ -523,7 +531,7 @@ public class WriteFile { public static void main(String[] args) { try { - FileWriter myWriter = new FileWriter("myfile.txt"); + FileWriter myWriter = new FileWriter("newfile.txt"); myWriter.write("File successfully updated!"); myWriter.close(); System.out.println("File successfully written to."); @@ -557,12 +565,17 @@

        Now, when we use write() method like before, the text will be appended if there is already text in the document. If we were to update our code to include the boolean argument:

        +<<<<<<< HEAD
                             
                         
        +======= + + +>>>>>>> 0633649 (fixes file not found errors in 8.4) import java.io.FileWriter; import java.io.IOException; @@ -570,7 +583,7 @@ public class WriteFile { public static void main(String[] args) { try { - FileWriter myWriter = new FileWriter("myfile.txt", true); // true enables append mode + FileWriter myWriter = new FileWriter("newfile.txt", true); // true enables append mode myWriter.write("File successfully updated!"); myWriter.close(); System.out.println("File successfully written to."); From 1186f640889c59e662f8e2c6d316f4f4c044c47d Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Thu, 7 Aug 2025 15:20:26 -0400 Subject: [PATCH 099/357] Finished adding content. Awaiting review before making addtional changes. --- source/ch4_conditionals.ptx | 81 +++++++++++++++++++++++++++++++++++-- 1 file changed, 78 insertions(+), 3 deletions(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 8b53c5b..1a8eb5e 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -282,7 +282,7 @@ The switch statement is not used very often, and we recommend you do not

        - This code works well, but will end with an exception if the user types anything other than a whole number (such as 12.5 or two). If we wanted to ensure the code will continue to run until the user enters the correct format, we could add try/except (Python) or try/catch (Java) blocks within a while loop that iterates until the user enter the correct code. Adding try/except blocks and a while loop will look something like this: + This code works well, but will end with an exception if the user types anything other than a whole number (such as 12.5 or two). If we wanted to ensure the code will continue to run until the user enters the correct format, we could add try/except (Python) or try/catch (Java) blocks within a while loop that iterates until the user enter the correct code. Adding try/except blocks and a while loop to the Python code will look something like this:

        @@ -298,6 +298,10 @@ The switch statement is not used very often, and we recommend you do not
        +

        + Now that we have Python code that will continuously prompt the user until they enter a whole number, let's look at Java code that accomplishes the same task. Like most other equivalent Java code blocks, this code has a lot of extra bits that are necessary to get working code. +

        + import java.util.Scanner; @@ -316,14 +320,85 @@ The switch statement is not used very often, and we recommend you do not break; } catch (InputMismatchException e) { System.out.println("That was not a valid number. Please try again: "); - scanner.nextLine(); // Clear the invalid input + scanner.nextLine(); } } } } - + +

        + Firstly, let's talk about the extra import alongside the Scanner import. In Java, any exception that isn't part of the java.lang class or is a checked exception must be explicitly imported to be used with try/catch blocks. If you ran the previous Java codeblock without try/catch blocks and entered an erroneous input, you would have got an InputMismatchException exception despite not having imported this class. That being said, removing the explicit import of this library for the try/catch code block above will lead to compilation errors. +

        + +

        + checked exception + unchecked exception + Exceptions in Java fall under two categories: checked and unchecked. Checked exceptions must be explicitly imported and declared along with try/catch blocks for a program to compile. Unchecked exceptions do not need to be imported unless try/catch blocks are implemented for them (except for java.lang exceptions). InputMismatchException is an unchecked exception that is not part of the java.lang library, so it is only included if try/catch blocks declare it. Here are some common exceptions used with try/catch blocks: +

        + + + Exceptions + + + Exception + Package + Description + + + IOException + java.io + Thrown when an I/O operation fails (e.g., reading or writing a file). + + + FileNotFoundException + java.io + Thrown when an attempt to open a file denoted by a pathname has failed. + + + ParseException + java.text + Thrown when parsing a string into a date, number, etc. fails (e.g., wrong format). + + + NoSuchMethodException + java.lang + Thrown when a particular method cannot be found via reflection. + + + InputMismatchException + java.util + Thrown when Scanner input doesn’t match the expected data type. + + + SQLException + java.sql + Thrown when a database access error occurs (e.g., invalid SQL query, bad connection). + + + InstantiationException + java.lang + Thrown when trying to create an instance of an abstract class or interface. + + + IllegalAccessException + java.lang + Thrown when a reflection operation tries to access a field or method it doesn't have permission for. + + +
        + +

        + Next, we will look into the try/catch blocks themselves. As with most other structures in Java, the blocks must be encased with braces {}. The most important part of this code is, after catch, there is a set of parenthesis with an exception type and a variable name catch (InputMismatchException e). This is where we declare a InputMismatchException exception and name it with the variable name e. It is common practice to name exception variables e in this manner. +

        + + +

        + Typically, Java is more "strict" than Python. Variable data types must be declared along with the variable, braces must be used, etc. A notable exception occurs in print statements as seen in the code in this section. In Python, strings can only be concatenated with other strings, but in Java, strings can be concatenated with other data types. +

        +
        +
    From 282c172e2f69ed9e80667612c804eb919d864b83 Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Thu, 7 Aug 2025 15:24:57 -0400 Subject: [PATCH 100/357] Removed an unnecessary note at the end of the new section. --- source/ch4_conditionals.ptx | 6 ------ 1 file changed, 6 deletions(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 1a8eb5e..3c3ae12 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -393,12 +393,6 @@ The switch statement is not used very often, and we recommend you do not Next, we will look into the try/catch blocks themselves. As with most other structures in Java, the blocks must be encased with braces {}. The most important part of this code is, after catch, there is a set of parenthesis with an exception type and a variable name catch (InputMismatchException e). This is where we declare a InputMismatchException exception and name it with the variable name e. It is common practice to name exception variables e in this manner.

    - -

    - Typically, Java is more "strict" than Python. Variable data types must be declared along with the variable, braces must be used, etc. A notable exception occurs in print statements as seen in the code in this section. In Python, strings can only be concatenated with other strings, but in Java, strings can be concatenated with other data types. -

    -
    -
    From e8798bc750455749ffae2075b8506a9d9e5aa568 Mon Sep 17 00:00:00 2001 From: flahertyc <122467714+coco3427@users.noreply.github.com> Date: Thu, 7 Aug 2025 16:35:37 -0400 Subject: [PATCH 101/357] removing conflicts --- source/ch8_filehandling.ptx | 15 +-------------- 1 file changed, 1 insertion(+), 14 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 3169b36..05a8ca7 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -489,11 +489,7 @@

    And that's it! We will add our code to the foundational code for a complete program. First, an example of equivalent Python code:

    -<<<<<<< HEAD -======= - ->>>>>>> 0633649 (fixes file not found errors in 8.4)
                         
                     
    @@ -514,16 +510,12 @@

    The completed Java code:

    -<<<<<<< HEAD
                         
                     
    -======= - ->>>>>>> 0633649 (fixes file not found errors in 8.4) import java.io.FileWriter; import java.io.IOException; @@ -565,17 +557,12 @@

    Now, when we use write() method like before, the text will be appended if there is already text in the document. If we were to update our code to include the boolean argument:

    -<<<<<<< HEAD
                         
                     
    -======= - - ->>>>>>> 0633649 (fixes file not found errors in 8.4) import java.io.FileWriter; import java.io.IOException; @@ -801,4 +788,4 @@
    - \ No newline at end of file + From dea854bbb197772f55bbe48827464f14a51de43f Mon Sep 17 00:00:00 2001 From: Eun Sung Wang <156254694+esw0624@users.noreply.github.com> Date: Thu, 7 Aug 2025 19:09:26 -0400 Subject: [PATCH 102/357] Adding Introduction and Debugging Section in Chapter 9 --- source/ch9_commonmistakes.ptx | 39 +++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/source/ch9_commonmistakes.ptx b/source/ch9_commonmistakes.ptx index c8ef187..4d22f7f 100644 --- a/source/ch9_commonmistakes.ptx +++ b/source/ch9_commonmistakes.ptx @@ -7,6 +7,45 @@ +
    + How to Avoid Making Mistakes +

    + Making mistakes is a natural part of learning Java—or any programming language. The good news is that most errors happen for just a few common reasons, and once you recognize the patterns, they become much easier to fix. This chapter focuses on those typical mistakes and how to understand and correct them. +

    +

    + One of the best ways to avoid these errors is to slow down and test your code in small pieces. Write a few lines, compile, and check the output before moving on. If something goes wrong, read the error message carefully and focus on fixing one problem at a time. Often, solving the first error helps fix others that follow. +

    +

    + A simple debugging technique is to use System.out.println() to print out variable values and program flow. If you're not sure whether a part of your code is running or what a variable contains, print it out. This helps you check your assumptions and narrow down where something is going wrong. +

    + + + // DebugExample.java + public class DebugExample { + + public static void main(String[] args) { + int number = 10; + int result = multiplyByTwo(number); + // Debugging: print the result to verify the method worked + System.out.println("Result after multiplying: " + result); + } + + public static int multiplyByTwo(int value) { + // Debugging: print the input value to check it's being passed correctly + System.out.println("multiplyByTwo received: " + value); + return value * 2; + } + }//End of class + + +

    + In the example above, System.out.println() is used inside both main and multiplyByTwo() to trace what values are being passed and returned. This kind of print-based debugging can quickly reveal logic errors, unexpected behavior, or whether a method is even being called. +

    +

    + Above all, be patient with yourself. Every mistake you make is an opportunity to understand Java more deeply. +

    +
    +
    Forgetting a Semicolon

    From 9f0ab256ea13b2afa5352a602b687ecceb025d65 Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Fri, 8 Aug 2025 08:46:34 -0400 Subject: [PATCH 103/357] change section title and mention debugging tools --- source/ch9_commonmistakes.ptx | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/source/ch9_commonmistakes.ptx b/source/ch9_commonmistakes.ptx index 4d22f7f..1a041b9 100644 --- a/source/ch9_commonmistakes.ptx +++ b/source/ch9_commonmistakes.ptx @@ -7,16 +7,23 @@ -

    - How to Avoid Making Mistakes +
    + Mistakes Happen!

    - Making mistakes is a natural part of learning Java—or any programming language. The good news is that most errors happen for just a few common reasons, and once you recognize the patterns, they become much easier to fix. This chapter focuses on those typical mistakes and how to understand and correct them. + Making mistakes is a very natural part of learning Java—or any other programming language. In fact, mistakes are an absolutely essential part of the learning process! So, try not to feel discouraged when you encounter errors in your code. Instead, view each mistake as an opportunity to deepen your understanding. Every programmer, no matter how experienced, encounters errors in their code. The key is to learn how to identify and correct these errors while also learning from them.

    - One of the best ways to avoid these errors is to slow down and test your code in small pieces. Write a few lines, compile, and check the output before moving on. If something goes wrong, read the error message carefully and focus on fixing one problem at a time. Often, solving the first error helps fix others that follow. + The good news is that most errors happen for just a few common reasons, and once you recognize the patterns, they become much easier to fix. This chapter focuses on those typical mistakes and how to understand and correct them.

    - A simple debugging technique is to use System.out.println() to print out variable values and program flow. If you're not sure whether a part of your code is running or what a variable contains, print it out. This helps you check your assumptions and narrow down where something is going wrong. + One of the best ways to correct these errors is to slow down and test your code in small pieces. Write a few lines, compile, and check the output before moving on. If something goes wrong, read the first error message very carefully, and focus on fixing one problem at a time. Often, solving the first error helps fix others that follow. +

    +

    + A simple debugging technique is to use System.out.println() to print out variable values. If you're not sure whether a part of your code is running correctly or what a variable contains, you can print it out. This can help you to check your assumptions and narrow down where something is going wrong. +

    + +

    + Consider the following example where we have a method that multiplies a number by two. We can add print statements to help us debug the code:

    @@ -39,10 +46,13 @@

    - In the example above, System.out.println() is used inside both main and multiplyByTwo() to trace what values are being passed and returned. This kind of print-based debugging can quickly reveal logic errors, unexpected behavior, or whether a method is even being called. + In the example above, System.out.println() is used inside both main and multiplyByTwo() to trace what values are being passed and returned. This kind of print-based debugging can quickly reveal logic errors, unexpected behavior, or whether a method is even being called. However, overuse of this technique will often take more time than using the debugging tools that are built into your IDE. +

    +

    + Useful tools in the built-in Java debugger can help you step through your code, inspect variables, and evaluate expressions at runtime. Familiarizing yourself with these tools can greatly enhance your debugging efficiency.

    - Above all, be patient with yourself. Every mistake you make is an opportunity to understand Java more deeply. + Above all, when you encounter an error, be patient with yourself. Every mistake you make is an opportunity to learn.

    From 14a208a5b832ea4e566c9d7261aba27fe6bdc870 Mon Sep 17 00:00:00 2001 From: colin flaherty Date: Fri, 8 Aug 2025 10:15:24 -0400 Subject: [PATCH 104/357] moved the introduction to 8.1 and added a section describes the code in the third code block. --- source/ch8_filehandling.ptx | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 05a8ca7..e2b96b4 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -4,17 +4,10 @@ File Handling - -

    - File handling is an integral part of programming. Most programming languages have the ability to read from, write to, create, delete, move, and copy files. -

    -
    - -
    Class Imports

    - In Python, most built-in libraries are available without needing to explicitly import additional packages, but some libraries like math do need to be imported. Consider the following. + File handling is an integral part of programming. Most programming languages have the ability to read from, write to, create, delete, move, and copy files. In Python, most built-in libraries are available without needing to explicitly import additional packages, but some libraries like math do need to be imported. Consider the following.

    @@ -42,12 +35,13 @@

    - Java includes a class called File in the io library. The class can be imported with the following line. Be sure to capitalize File. + Much like the Math class, in order for your program to work with files you need to import classes from libraries. Java includes a class called File in the io library. This class allows you to create File objects, and use its public methods. the following code imports the File class and creates a File object called myFile. for now focus on how the class is imported and used in the program; We will cover the IOException class and createNewFile method later.

    import java.io.File; - import java.io.IOException;public class Main { + import java.io.IOException; + public class Main { public static void main(String[] args) { try { File myFile = new File("newfile.txt"); From 6e2388a0c0835fda1eb27214d29c762c99332fb7 Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Fri, 8 Aug 2025 10:35:27 -0400 Subject: [PATCH 105/357] remove stray code and some minor fixes --- source/ch4_conditionals.ptx | 33 ++++++++++++--------------------- 1 file changed, 12 insertions(+), 21 deletions(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 3c3ae12..3d1459a 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -163,27 +163,18 @@ public class ElseIf {

    Java also supports a switch statement that acts something like the elif statement of Python under certain conditions. To write the grade program using a switch statement we would use the following: -

    while True: - - try: - - x = int(input("Please enter a whole number: ")) - - break - - except ValueError: - - print("Oops! That was no valid number. Try again...") +

    - Depending on your knowledge and experience with Python you may already be familiar and questioning why we are not using the match statement in our Python examples. The answer is that this book currently runs its active code examples on Python 3.7, which does not support the match statement. The match statement was introduced in Python 3.10. Below is an example of the match statement similar to our grade method. + Depending on your knowledge and experience with Python you may already be familiar and questioning why we are not using the match statement in our Python examples. The answer is that this book currently runs its active code examples using Python 3.7, which does not support the match statement which was introduced in Python 3.10. Below is an example of the match statement similar to our grade method.

    Match Case Example - grade = 100 // 10 - def grading(grade): + grade = 85 + tempgrade = grade // 10 + def grading(tempgrade): match grade: case 10 | 9: return 'A' @@ -195,7 +186,7 @@ Java also supports a switch statement that acts something like the eli return 'D' case _: return 'F' - print(grading(grade)) + print(grading(tempgrade))
    @@ -248,7 +239,7 @@ The switch statement is not used very often, and we recommend you do not Exception Handling

    - In Python, if you want a program to continue running when an error has occurred, you can use try/except blocks to handle exceptions. If you wanted to write a program that asks the user to enter a whole number and then squares that number, you could use the following code to do so: + In Python, if you want a program to continue running when an error has occurred, you can use try-except blocks to handle exceptions. If you wanted to write a program that asks the user to enter a whole number and then squares that number, you could use the following code to do so:

    @@ -282,7 +273,7 @@ The switch statement is not used very often, and we recommend you do not

    - This code works well, but will end with an exception if the user types anything other than a whole number (such as 12.5 or two). If we wanted to ensure the code will continue to run until the user enters the correct format, we could add try/except (Python) or try/catch (Java) blocks within a while loop that iterates until the user enter the correct code. Adding try/except blocks and a while loop to the Python code will look something like this: + This code works well, but will end with an exception if the user types anything other than a whole number (such as 12.5 or two). If we wanted to ensure the code will continue to run until the user enters the correct format, we could add try-except (Python) or try-catch (Java) blocks within a while loop that iterates until the user enter the correct code. Adding try-except blocks and a while loop to the Python code will look something like this:

    @@ -320,7 +311,7 @@ The switch statement is not used very often, and we recommend you do not break; } catch (InputMismatchException e) { System.out.println("That was not a valid number. Please try again: "); - scanner.nextLine(); + scanner.nextLine(); // Clear the invalid input from the scanner } } } @@ -329,13 +320,13 @@ The switch statement is not used very often, and we recommend you do not

    - Firstly, let's talk about the extra import alongside the Scanner import. In Java, any exception that isn't part of the java.lang class or is a checked exception must be explicitly imported to be used with try/catch blocks. If you ran the previous Java codeblock without try/catch blocks and entered an erroneous input, you would have got an InputMismatchException exception despite not having imported this class. That being said, removing the explicit import of this library for the try/catch code block above will lead to compilation errors. + Firstly, let's talk about the extra import alongside the Scanner import. In Java, we need to import InputMismatchException because it's not automatically available like basic exceptions. This is different from Python where most exceptions are readily accessible. If you ran the previous Java codeblock without try-catch blocks and entered an erroneous input, you would have got an InputMismatchException exception despite not having imported this class. That being said, removing the explicit import of this library for the try-catch code block above will lead to compilation errors.

    checked exception unchecked exception - Exceptions in Java fall under two categories: checked and unchecked. Checked exceptions must be explicitly imported and declared along with try/catch blocks for a program to compile. Unchecked exceptions do not need to be imported unless try/catch blocks are implemented for them (except for java.lang exceptions). InputMismatchException is an unchecked exception that is not part of the java.lang library, so it is only included if try/catch blocks declare it. Here are some common exceptions used with try/catch blocks: + Exceptions in Java fall under two categories: checked and unchecked. Checked exceptions must be explicitly imported and declared along with try-catch blocks for a program to compile. Unchecked exceptions do not need to be imported unless try-catch blocks are implemented for them (except for java.lang exceptions). InputMismatchException is an unchecked exception that is not part of the java.lang library, so it is only included if try-catch blocks declare it. Here are some common exceptions used with try-catch blocks:

    @@ -390,7 +381,7 @@ The switch statement is not used very often, and we recommend you do not

    - Next, we will look into the try/catch blocks themselves. As with most other structures in Java, the blocks must be encased with braces {}. The most important part of this code is, after catch, there is a set of parenthesis with an exception type and a variable name catch (InputMismatchException e). This is where we declare a InputMismatchException exception and name it with the variable name e. It is common practice to name exception variables e in this manner. + Next, we will look into the try-catch blocks themselves. As with most other structures in Java, the blocks must be encased with braces {}. The most important part of this code is, after catch, there is a set of parenthesis with an exception type and a variable name catch (InputMismatchException e). This is where we declare a InputMismatchException exception and name it with the variable name e. It is common practice to name exception variables e in this manner.

    From 24ba63b4183f2f5bc3b3c6c503ab301605cb16f0 Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Fri, 8 Aug 2025 10:38:57 -0400 Subject: [PATCH 106/357] clarification --- source/ch4_conditionals.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 3d1459a..7d1ed00 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -381,7 +381,7 @@ The switch statement is not used very often, and we recommend you do not

    - Next, we will look into the try-catch blocks themselves. As with most other structures in Java, the blocks must be encased with braces {}. The most important part of this code is, after catch, there is a set of parenthesis with an exception type and a variable name catch (InputMismatchException e). This is where we declare a InputMismatchException exception and name it with the variable name e. It is common practice to name exception variables e in this manner. + Note that as with other structures in Java, try-catch blocks blocks must be encased with braces {}. The most important part of this code is, after catch, there is a set of parenthesis with an exception type and a variable name catch (InputMismatchException e). This is where we declare a InputMismatchException exception and name it with the variable name e. It is common practice, though not a requirement, to name exception variables e in this manner.

    From c085b2d12efc87bc451eac440aee0d6aed0030a8 Mon Sep 17 00:00:00 2001 From: Elijah Babayemi Date: Fri, 8 Aug 2025 11:00:07 -0400 Subject: [PATCH 107/357] I made regular print statements and replaced the previous ones that used f --- source/ch8_filehandling.ptx | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 05a8ca7..73ed7d1 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -128,14 +128,15 @@ filename = "newfile.txt" - print(f"Attempting to write to '{filename}' using 'w' mode...") + print("Attempting to write to '" + filename + "' using 'w' mode...") try: with open(filename, 'w') as f: f.write("This file was created using 'w' mode.") - print(f"SUCCESS: The file '{filename}' was created or overwritten.") + print("SUCCESS: The file '" + filename + "' was created or overwritten.") except Exception as e: # This would only catch other unexpected errors - print(f"An unexpected error occurred during write: {e}") + print("An unexpected error occurred during write: " + str(e)) + From 7ae8b3f02d3a51a6d71286843fae7a30bd90a4c5 Mon Sep 17 00:00:00 2001 From: Elijah Babayemi Date: Fri, 8 Aug 2025 14:34:45 -0400 Subject: [PATCH 108/357] Added more indices to important concepts and terminology --- source/ch2_firstjavaprogram.ptx | 4 ++-- source/ch4_conditionals.ptx | 4 ++-- source/ch5_loopsanditeration.ptx | 3 +-- 3 files changed, 5 insertions(+), 6 deletions(-) diff --git a/source/ch2_firstjavaprogram.ptx b/source/ch2_firstjavaprogram.ptx index f233cc0..d911d4b 100644 --- a/source/ch2_firstjavaprogram.ptx +++ b/source/ch2_firstjavaprogram.ptx @@ -8,8 +8,8 @@ Classes and Objects

    - Object-Oriented Programming (OOP) - Depending on how deep your knowledge of Python and programming in general is, you may or may not be familiar with classes and objects. These two important Object-Oriented Programming (OOP) concepts will briefly be discussed. If you already have a good understanding of classes and objects in Python, this section may be skipped. + object-oriented programming OOP + Depending on how deep your knowledge of Python and programming in general is, you may or may not be familiar with classes and objects. These two important Object-Oriented Programming (OOP) concepts will briefly be discussed. If you already have a good understanding of classes and objects in Python, this section may be skipped.

    diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 7d1ed00..d7af30c 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -389,8 +389,8 @@ The switch statement is not used very often, and we recommend you do not

    Boolean Operators -

    Boolean operators -The conditionals used in the if statement can be Boolean variables, simple comparisons, and compound Boolean expressions. +

    boolean operators simple comparisons compound boolean expressions +The conditionals used in the if statement can be boolean variables, simple comparisons, and compound boolean expressions.

    ternary operator diff --git a/source/ch5_loopsanditeration.ptx b/source/ch5_loopsanditeration.ptx index fd10c12..7907dcc 100644 --- a/source/ch5_loopsanditeration.ptx +++ b/source/ch5_loopsanditeration.ptx @@ -173,7 +173,7 @@ public class StringIterationExample { Indefinite Loops

    while loop - Both Python and Java support the while loop, which continues to execute as long as a condition is true. + Both Python and Java support the while loop, which continues to execute as long as a condition is true. Here is a simple example in Python that counts down from 5:

    @@ -321,7 +321,6 @@ public class DoWhileExample { -
    \ No newline at end of file From ccdbe277698313d6d8bdfbb4ba2eeb7a3a3c4afd Mon Sep 17 00:00:00 2001 From: colin flaherty Date: Fri, 8 Aug 2025 14:43:12 -0400 Subject: [PATCH 109/357] made a new ch8.3 that is smaller and uses better examples. --- source/ch8_filehandling.ptx | 176 +++++------------------------------- 1 file changed, 21 insertions(+), 155 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index ae8e80e..af0fc29 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -167,16 +167,18 @@ You may have noticed the use of another method from the File class; getName(). This method returns a string containing the name of the file.

    -
    - +
    Reading Files

    - Let's take a look at how we can use Java to read file contents. We'll start again with library imports and building a class, this time importing the Scanner and FileNotFoundException classes. We will call this class ReadFile: -

    - + Let’s take a look at how we can use Python to understand how read file contents in Java.In order to read files generally you iterate through each line in the file and read its content. In Java you read files in a very similar way, however in java we will use a Scanner object in order to iterate through lines. +

    +

    + The next lines consists of a Python code example that reads each line of the file and prints it to the console. +

    +
                         1
                         2
    @@ -188,77 +190,27 @@
                         8
                     
    - - - - - import java.io.File; - import java.io.FileNotFoundException; - import java.util.Scanner;public class Main { - public static void main(String[] args) { - try { - File myFile = new File("myfile.txt"); - Scanner fileReader = new Scanner(myFile); - System.out.println("Reading from file: " + myFile.getName()); - while (fileReader.hasNextLine()) { - String data = fileReader.nextLine(); - System.out.println(data); - } - fileReader.close(); // Close the scanner to release the file - } catch (FileNotFoundException e) { - System.out.println("An error occurred: The file was not found."); - e.printStackTrace(); - } - } - } - - - -

    - We will then create a new File object exactly the same as the one from the section on creating files. Additionally, we will create a Scanner object. The Scanner object is the object that does the file reading. We will call this scanner fileReader: -

    - + - import java.io.File; - import java.io.FileNotFoundException; - import java.util.Scanner; - public class Main { - public static void main(String[] args) { - // This 'try-with-resources' statement handles opening the file - // and guarantees it is closed automatically, which is best practice. - try (Scanner fileReader = new Scanner(new File("myfile.txt"))) { - - // If this line is reached, the file was opened successfully. - System.out.println("Success! The file 'myfile.txt' is now open."); - - } catch (FileNotFoundException e) { - - // This block runs only if 'myfile.txt' does not exist. - System.out.println("Error: The file 'myfile.txt' could not be found."); - } - } - } - - - -

    - The next lines consists of a Python code example that reads each line of the file passed to the Scanner object.: -

    - - - - with open("myfile.txt", "r") as file_reader: - for line in file_reader: - print(line.strip()) + filename = "myfile.txt" + try: + # Attempt to open the file in read mode ('r') + with open(filename, "r") as file_reader: + # Iterate over each line in the file + for line in file_reader: + print(line.strip()) + except: + #catches if the file doesn't exist or can't be written to + print("file could not be opened")

    - The equivalent Java code: + The following Java code functions very similarly to the previous Python. The main difference here is that unlike Python, In Java we use the Scanner object to iterate through and read lines in the file. You will notice that the structure of the Java code is still similar to the Python; Both use a try and catch statement to read the file and catch any errors.

    - + import java.io.File; import java.io.FileNotFoundException; @@ -278,94 +230,8 @@ } - -

    - The hasNextLine() method checks checks if the line below the current line has any data. This will evaluate to true even if the next line only contains blank spaces. Within the while loop, a string variable called data is used to store the current line that the Scanner object is pointing to. The nextLine() method does two things. Firstly, it returns the current line when called. Secondly, it moves the Scanner's position to the next line. In other words, for each iteration of the while loop, each line in the text is read, stored temporarily in the data variable, and printed to the console. Finally, the close() method accomplishes and holds the same importance as in the section on writing to files. -

    - -

    - Alternatively, the following code can be used to store the all lines of myfile.txt to one variable: -

    - - - - import java.io.File; - import java.io.FileNotFoundException; - import java.util.Scanner;public class Main { - public static void main(String[] args) { - String filename = "myfile.txt"; - try (Scanner fileReader = new Scanner(new File(filename))) { - String data = ""; - while (fileReader.hasNextLine()) { - data = data + fileReader.nextLine() + System.lineSeparator(); - } - System.out.println(data); - } - catch (FileNotFoundException e) { - System.out.println("Error: The file '" + filename + "' was not found."); - } - } - } - - - - -

    - Pay close attention to the details of this code. data must be declared using an empty string or it may not work correctly within the while loop. Additionally, care must be given to reassigning data in the while loop. data is concatinated (to ensure all lines are included) with fileReader.nextLine() and a new line operator. Each step of this process ensures what is stored in data matches exactly what is in myfile.txt. -

    -
    - -

    - Using the second method of storing all file contents to one file, the resulting full code including try/catch blocks (this time using FileNotFoundException instead of IOException) will look something like this. First, the Python code: -

    - - - - try: - with open("myfile.txt", "r") as file_reader: - data = "" - for line in file_reader: - data += line # line already includes the newline character - print(data) - except FileNotFoundError: - print("An error occurred.") - import traceback - traceback.print_exc() - - - - -

    - And the Java equivalent: -

    - - - - import java.io.File; - import java.io.FileNotFoundException; - import java.util.Scanner; - - public class ReadFile { - public static void main(String[] args) { - try { - File myFile = new File("myfile.txt"); - Scanner fileReader = new Scanner(myFile); - String data = ""; - while (fileReader.hasNextLine()) { - data = data + fileReader.nextLine() + System.lineSeparator(); - } - System.out.println(data); - fileReader.close(); - } catch (FileNotFoundException e) { - System.out.println("An error occurred."); - e.printStackTrace(); - } - } - } - -

    - In this code, we simply print the contents of the file to the console, but it is easy to imagine how the data variable could be used in conjunction with the write class created in the previous section to create a copy of myfile.txt. + You may have noticed that there are some new methods you haven't seen yet. The hasNextLine() method checks if there is a next line in the file, and returns false if there isn't. This method allows us to iterate over every line till there is no next line. The nextLine() method of the Scanner object returns the next line in the file as a string.

    From be3a60d7f75dd3ef8eee11a7bf1fa16b3f758f8e Mon Sep 17 00:00:00 2001 From: colin flaherty Date: Fri, 8 Aug 2025 15:58:11 -0400 Subject: [PATCH 110/357] changes 8.2's introduction and uses a new opening paragraph --- source/ch8_filehandling.ptx | 29 +---------------------------- 1 file changed, 1 insertion(+), 28 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index ae8e80e..d4e65b5 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -84,35 +84,8 @@
    Creating Files - -

    - We will now create a File object. It is important to create a meaningful name for the File object. We will call ours myFile. -

    - -
    -                    empty file
    -                
    -
    - - - import java.io.File; - public class Main { - public static void main(String[] args) { - File myFile = new File("myfile.txt"); - System.out.println(myFile); - } - } - - - - -

    - myFile is the name of the object within the program, while myfile.txt is the name of the file itself and will be the file name if the operation that creates the file is successful. -

    -
    -

    - Now that we have created a new File object, we can create a file using the createNewFile() method from the File class. While the previous line of code creates an object within the program for the file, this method actually does the work of creating a file and saving it in the current working directory. This method returns a boolean value. If the method returns true, the file was successfully created. If the method returns false, there is already a file using the chosen file name. We can use this method's possible return values in tandem with an try/catch structure to determine if the file was created, or catch the error if a file with that file name already exists in the directory. + Now lets learn how to make a file in Java. In Python files can be made using the open() function on a file path that doesn't exist yet. Similarly, in Java you create a file by using the createNewFile() method on a File object. This method actually does the work of creating a file and saving it in the current working directory, and returns a boolean value of either true or false if the file is successfully created. We can use this method's possible return values in tandem with an try/catch structure to determine if the file was created, or catch the error if a file with that file name already exists in the directory.

    From 2b9b26705cb958051aeb497e2f1c2632dfea816c Mon Sep 17 00:00:00 2001 From: Eun Sung Wang <156254694+esw0624@users.noreply.github.com> Date: Fri, 8 Aug 2025 17:37:45 -0400 Subject: [PATCH 111/357] Fixing the margin for the Data File --- source/ch3_javadatatypes.ptx | 34 ++++++++++++++++++++++------------ 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index b0b41ec..ad28a23 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -728,18 +728,28 @@ main() This program reads the file alice30.txt (which follows), and it then splits it into a list of words. Next it creates a dictionary called count which maps each word to the number of times that word occurs in the text. Finally, it prints out the words in alphabetical order along with their frequency.

    -
     
    -            Down, down, down.  Would the fall NEVER come to an end! 
    -             'I wonder how many miles I've fallen by this time?' she said aloud. 'I must 
    -             be getting somewhere near the centre of the earth.  
    -             Let me see:  that would be four thousand miles down, I think--' 
    -             (for, you see, Alice had learnt several things of this sort in her lessons 
    -             in the schoolroom, and though this was not a VERY good opportunity for 
    -             showing off her knowledge, as there was no one to listen to her, still it 
    -             was good practice to say it over) '--yes, that's about the right distance
    -             --but then I wonder what Latitude or Longitude I've got to?'  
    -             (Alice had no idea what Latitude was, or Longitude either, 
    -             but thought they were nice grand words to say.) 
    + +
     
    +            Down, down, down. Would the fall NEVER
    +            come to an end! 'I wonder how many
    +            miles I've fallen by this time?' she
    +            said aloud. 'I must be getting somewhere
    +            near the centre of the earth. Let me see:
    +            that would be four thousand miles down,
    +            I think--' (for, you see, Alice had
    +            learnt several things of this sort in
    +            her lessons in the schoolroom, and though
    +            this was not a VERY good opportunity for
    +            showing off her knowledge, as there was no
    +            one to listen to her, still it was good
    +            practice to say it over) '--yes, that's
    +            about the right distance--but then I
    +            wonder what Latitude or Longitude I've got
    +            to?' (Alice had no idea what Latitude was,
    +            or Longitude either, but thought they were
    +            nice grand words to say.)
    +            
    +

    Notice that the structure of the program is very similar to the numeric histogram program.

    From 5d3dfe4fce2af6fcfecbe06290f13e2cdb26cd68 Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Fri, 8 Aug 2025 17:44:58 -0400 Subject: [PATCH 112/357] fix Boolean vs boolean --- source/ch4_conditionals.ptx | 6 +++--- source/ch5_loopsanditeration.ptx | 2 +- source/ch8_filehandling.ptx | 6 +++--- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index d7af30c..6b7a86b 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -389,8 +389,8 @@ The switch statement is not used very often, and we recommend you do not
    Boolean Operators -

    boolean operators simple comparisons compound boolean expressions -The conditionals used in the if statement can be boolean variables, simple comparisons, and compound boolean expressions. +

    Boolean operators simple comparisons compound Boolean expressions +The conditionals used in the if statement can be Boolean variables, simple comparisons, and compound Boolean expressions.

    ternary operator @@ -408,7 +408,7 @@ of an assignment statement. The following table summarizes how this works: condition - The Boolean expression that is evaluated (e.g., a % 2 == 0). + The boolean expression that is evaluated (e.g., a % 2 == 0). ? diff --git a/source/ch5_loopsanditeration.ptx b/source/ch5_loopsanditeration.ptx index 7907dcc..07f33c9 100644 --- a/source/ch5_loopsanditeration.ptx +++ b/source/ch5_loopsanditeration.ptx @@ -173,7 +173,7 @@ public class StringIterationExample { Indefinite Loops

    while loop - Both Python and Java support the while loop, which continues to execute as long as a condition is true. + Both Python and Java support the while loop, which continues to execute as long as a condition is true. Here is a simple example in Python that counts down from 5:

    diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index e2b96b4..72e97fb 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -112,7 +112,7 @@

    - Now that we have created a new File object, we can create a file using the createNewFile() method from the File class. While the previous line of code creates an object within the program for the file, this method actually does the work of creating a file and saving it in the current working directory. This method returns a boolean value. If the method returns true, the file was successfully created. If the method returns false, there is already a file using the chosen file name. We can use this method's possible return values in tandem with an try/catch structure to determine if the file was created, or catch the error if a file with that file name already exists in the directory. + Now that we have created a new File object, we can create a file using the createNewFile() method from the File class. While the previous line of code creates an object within the program for the file, this method actually does the work of creating a file and saving it in the current working directory. This method returns a boolean value. If the method returns true, the file was successfully created. If the method returns false, there is already a file using the chosen file name. We can use this method's possible return values in tandem with an try/catch structure to determine if the file was created, or catch the error if a file with that file name already exists in the directory.

    @@ -541,7 +541,7 @@

    - Speaking of overwriting data, what if we want to append text to the end of any text already in myfile.txt? To accomplish this, we can pass a boolean argument along with the file name when creating a new data argument: + Speaking of overwriting data, what if we want to append text to the end of any text already in myfile.txt? To accomplish this, we can pass a boolean argument along with the file name when creating a new data argument:

    @@ -549,7 +549,7 @@
             

    - Now, when we use write() method like before, the text will be appended if there is already text in the document. If we were to update our code to include the boolean argument: + Now, when we use write() method like before, the text will be appended if there is already text in the document. If we were to update our code to include the boolean argument:

    
    From eaa69a45ce0eedb0d52cfddfbae3075a22bac030 Mon Sep 17 00:00:00 2001
    From: Jan Pearce 
    Date: Fri, 8 Aug 2025 19:03:55 -0400
    Subject: [PATCH 113/357] improve ch8 with clarifications
    
    ---
     source/ch8_filehandling.ptx | 36 ++++++++++++++++++------------------
     1 file changed, 18 insertions(+), 18 deletions(-)
    
    diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx
    index af0fc29..f8eb14a 100644
    --- a/source/ch8_filehandling.ptx
    +++ b/source/ch8_filehandling.ptx
    @@ -1,13 +1,13 @@
     
     
     
    -
    +
         File Handling
     
    -    
    +
    Class Imports

    - File handling is an integral part of programming. Most programming languages have the ability to read from, write to, create, delete, move, and copy files. In Python, most built-in libraries are available without needing to explicitly import additional packages, but some libraries like math do need to be imported. Consider the following. + File handling is an integral part of programming. Most programming languages have the ability to create, read from, write to, and delete, files. In Python, most built-in libraries are available without needing to explicitly import additional packages, but some libraries like math do need to be imported. Consider the following.

    @@ -17,7 +17,7 @@

    - The same program in Java would look like this: + Delete the first line that says import math and see what happens. The import math is needed. The same program in Java would look like this:

    @@ -31,11 +31,11 @@

    - Note the use of import java.lang.Math; in the above to import the Math class. Unlike Python, Java requires explicit imports for most libraries, including the Math class and many different classes for file handling. + Note the use of import java.lang.Math; in the above to import the Math class. Unlike Python, Java requires explicit import for most libraries, including the Math class and many classes related to file handling.

    - Much like the Math class, in order for your program to work with files you need to import classes from libraries. Java includes a class called File in the io library. This class allows you to create File objects, and use its public methods. the following code imports the File class and creates a File object called myFile. for now focus on how the class is imported and used in the program; We will cover the IOException class and createNewFile method later. + Much like the Math class, in order for your program to work with files you need use import. Java includes a class called File in the io library. This class allows you to create File objects, and use its public methods. the following code imports the File class and creates a File object called myFile. for now focus on how the class is imported and used in the program; We will cover the IOException class and createNewFile method later.

    @@ -82,18 +82,18 @@
    -
    +
    Creating Files

    We will now create a File object. It is important to create a meaningful name for the File object. We will call ours myFile.

    - +
                         empty file
                     
    - + import java.io.File; public class Main { @@ -119,7 +119,7 @@ First, lets look at the equivalent Python code:

    - + filename = "newfile.txt" print("Attempting to write to '" + filename + "' using 'w' mode...") @@ -169,16 +169,16 @@
    -
    +
    Reading Files

    - Let’s take a look at how we can use Python to understand how read file contents in Java.In order to read files generally you iterate through each line in the file and read its content. In Java you read files in a very similar way, however in java we will use a Scanner object in order to iterate through lines. + Let’s take a look at how we can use Python to understand how read file contents in Java. In order to read files generally you iterate through each line in the file and read the line's content. In Java, you read files in a very similar way, however in Java we will use the Scanner class in order to iterate through the lines.

    - The next lines consists of a Python code example that reads each line of the file and prints it to the console. + Consider the following Python code example that reads each line of the file and prints it to the console.

    - +
                         1
                         2
    @@ -191,7 +191,7 @@
                     
    - + filename = "myfile.txt" try: @@ -210,7 +210,7 @@ The following Java code functions very similarly to the previous Python. The main difference here is that unlike Python, In Java we use the Scanner object to iterate through and read lines in the file. You will notice that the structure of the Java code is still similar to the Python; Both use a try and catch statement to read the file and catch any errors.

    - + import java.io.File; import java.io.FileNotFoundException; @@ -231,11 +231,11 @@

    - You may have noticed that there are some new methods you haven't seen yet. The hasNextLine() method checks if there is a next line in the file, and returns false if there isn't. This method allows us to iterate over every line till there is no next line. The nextLine() method of the Scanner object returns the next line in the file as a string. + You may have noticed that there are some new methods you haven't seen yet. The hasNextLine() method checks if there is a next line in the file, and returns false if there isn't. This method allows us to iterate over every line till there is no next line. The nextLine() method of the Scanner object returns the next line in the file as a string.

    -
    +
    Writing to Files

    From c15d0d9d4842782d5910b573850e66e404e32475 Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Sat, 9 Aug 2025 12:44:30 -0400 Subject: [PATCH 114/357] correct topics in section 1.1 to what is actually covered --- source/ch1_overview.ptx | 53 ++++++++++++++++------------------------- 1 file changed, 21 insertions(+), 32 deletions(-) diff --git a/source/ch1_overview.ptx b/source/ch1_overview.ptx index 4a589a9..f8e4253 100644 --- a/source/ch1_overview.ptx +++ b/source/ch1_overview.ptx @@ -5,17 +5,17 @@ Overview -

    - Prerequisites +
    + Prerequisites and Trajectory

    This book assumes that you are already familiar with the Python programming language. - We will use Python as a starting point for our journey into Java. + We will use Python as a starting point for our journey into Java. We will begin by looking at a very simple Java program, just to see what the language looks like and how we get a program to run. Next, we will look at the main constructs that are common to most programming languages:

    -
    +

    • @@ -26,63 +26,51 @@
    • - Loops + User input and output

    • - Reading user input + Conditionals and Exception Handling

    • -
    • - Conditionals + Loops and Iteration

    -

    - Once we have the basics of Java behind us we will move on to look at the features of Java that are both unique and powerful. + Once we have the basics of Java behind us we will move on to look at more powerful features of the language.

    -
    +

    • - Classes + Classes and Interfaces

    • -
    • - Interfaces + Recursion

    • -
    • - Collections + File Handling

    • -
    • -

      - Graphical User Interface Programming -

      -
    • -
    • -

      - Generic Programming -

      -

    -
    +

    + Finally, we will look at common errors and how to find the help you need. +

    @@ -91,11 +79,7 @@ Java Development Environment - -

    - Thank you to Beryl Hoffman for contributing to this section from her CSAwesome: AP Java Programming book. -

    -
    +

    The tool that we use to compile a Java source file into a Java class file @@ -304,6 +288,11 @@ visual="http://skylit.com/javamethods/faqs/Eclipse.pdf">http://skylit.com/javamethods/faqs/Eclipse.pdf.

    + +

    + Thank you to Beryl Hoffman for contributing to this section from her CSAwesome: AP Java Programming book. +

    +
    From 99c436c5b857301e72a535fcd9440238389f935f Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Sat, 9 Aug 2025 14:04:05 -0400 Subject: [PATCH 115/357] reorganize section on java IDEs --- source/ch1_overview.ptx | 397 ++++++++++++++++++++-------------------- 1 file changed, 201 insertions(+), 196 deletions(-) diff --git a/source/ch1_overview.ptx b/source/ch1_overview.ptx index f8e4253..be9f0de 100644 --- a/source/ch1_overview.ptx +++ b/source/ch1_overview.ptx @@ -75,224 +75,229 @@
    -
    +
    Java Development Environment - - -

    +

    compilerintegrated development environmentIDE The tool that we use to compile a Java source file into a Java class file is called a compiler. Most programmers use an - Integrated Development Environment (IDE) that has the + integrated development environment (IDE) that has the compiler built in and helps you write, compile, run, and debug programs.

    -

    +

    Active Codeload history You can learn Java by just using the interactive coding panels called Active Code in this e-book. If you are logged in, the Active Code will remember your changes and even show you a history of your - changes to the code if you click on Load History. + changes to the code if you click on Load History.

    - However, it’s a good idea to also try a Java IDE to build code outside of - this e-book, especially to try coding with user input which Active Code - cannot do. There are many Java IDEs available. + However, it's a good idea to also try a Java IDE to build code outside of + this online book. There are many Java IDEs available. If you are enrolled in a course, your instructor will likely recommend one, so you should learn to use that one.

    - - Java IDE Options + + Installing Java +

    JDKJava development kitOracleOpenJDK + Before you can use any Java IDE or compile Java programs, you need to install the Java development kit (JDK) on your computer. The JDK includes the Java compiler, the runtime environment, and essential tools for Java development. You can either download the latest version of the JDK from Oracle's website (https://www.oracle.com/java/technologies/downloads/) or use OpenJDK, which is a free and open-source implementation available at https://openjdk.org/. Most IDEs will help you configure the JDK once it's installed, but you'll need to have it on your system first. To verify your installation works, open a command prompt or terminal and type java -version - you should see version information displayed. +

    +
    + + + Github Classroom and Codespaces +

    GitHubversion controlCodespaces + GitHub is the largest source code repository host in the world, with over 300 million repositories and a global community of more than 100 million developers. Github is widely used for both open-source and private projects, making it a versatile platform for various development needs, and a great place to learn about version control and collaboration in software development. + Github provides many free opportunities for both students and teachers (https://docs.github.com/en/education/quickstart). + Github Classroom (https://classroom.github.com/) + allows teachers to set up a classroom based on Github repositories. Github + and git are both very widely used in the computer industry, so learning to use + them is great experience for students who want to showcase their skills. Github now has a cloud IDE called + Codespaces (https://github.com/features/codespaces) + which you can use for 60 hours a month for free or completely free if you + join as a school or get approved as a teacher or student. In Codespaces, + you can start from a blank template or repository, open a .java file in the + VSCode editor, follow prompts to install the Extension Pack for Java, + click on the Run and Debug (play button), follow the prompts to install + the Java debugger, and see the output of your code in the terminal. You + can also use Copilot (https://github.com/features/copilot), + which is a coding AI based on GPT, for free if you are approved for + educational use. +

    +

    - There are a lot of online cloud IDEs where you can code online in many - programming languages. Most are free to start, but offer different - features for a price. These are great options if you are using a - Chromebook or you cannot install software on your computer or you want an - easy no-installation option. Some of the Active Code samples in this - e-book also include a link to online IDEs. These projects can be copied to - make your own copy. -

    - -

    Here are some popular online IDEs:

    -

    -

      -
    • -

      - CodeHS (https://codehs.com/) has a free Sandbox online IDE - (https://codehs.com/app/sandbox) - where you can run Java and Java Swing programs. Students can share the links - to their code and the history of their code is saved. CodeHS has free and paid features. - Grading features are in the paid version. -

      -
    • -
    • -

      - PickCode (https://pickcode.io/) is another - online IDE that offers many free and paid features for setting up - classrooms. In the free version, tudents can share links to their code and - the history of their code is saved. Classroom features are in the paid version. -

      -
    • -
    • -

      - Replit (https://replit.com/) an online - IDE which recently switched to only allowing 3 projects at a time - for free. Be aware that Replit has turned on its AI feature for code - completion for all accounts (https://replit.com/ai). Each - user can turn the AI on and off at the bottom of the code window, - and use an AI chat window to ask questions of the AI. -

      -
    • + To use Github classroom, students need to sign up for a free Github account (https://github.com/signup) if + they don't already have one in order to use Codespaces. +

      + -
    • -

      - JuiceMind (https://juicemind.com/) is an - online IDE that offers many free and paid features for teachers to - set up classrooms like Coding Rooms. It has a built-in version of - CSAwesome. -

      -
    • -
    -

    -
    - - - Github Classroom and Codespaces -

    - Github provides many free opportunities for students and teachers (https://docs.github.com/en/education/quickstart). - Github Classroom (https://classroom.github.com/) - allows teachers to set up a classroom based on github repositories. Github - and git are both widely used in the computer industry, so learning to use - them is great experience for students. Github now has a cloud IDE called - Codespaces (https://github.com/features/codespaces) - which you can use for 60 hours a month for free or completely free if you - join as a school or get approved as a teacher or student. In Codespaces, - you can start from a blank template or a repo, open a .java file in the - VSCode editor, follow prompts to install the Extension Pack for Java, - click on the Run and Debug (play button), follow the prompts to install - the Java debugger, and see the output of your code in the terminal. You - can also use Copilot (https://github.com/features/copilot), - which is a coding AI based on GPT, for free if you are approved for - educational use. -

    - -

    - Students will need to sign up for a free Github account (https://github.com/signup) if - they don’t already have one in order to use Codespaces. -

    -
    - - - VSCode -

    - VSCode (https://code.visualstudio.com) - is a widely used coding editor which you can download on your local - computers. It has many useful extensions. The code can be run in a - terminal window in the editor. See https://code.visualstudio.com/docs/languages/java - for Java support. This editor is different than Microsoft Visual Studio - which is a very large IDE. -

    + + Desktop IDE Options +

    + To install Java software on your local computer, below are several popular Java IDEs and editors that you can download and install. Please be sure to use the one that is recommended by your instructor if you are enrolled in a course, as they may have specific preferences or requirements. +

    + +

    +

      +
    • +

      + VSCode (https://code.visualstudio.com) is not an IDE per se, but it + is a widely used coding editor which you can download on your local + computer with many useful extensions like debugging tools that for all practical purposes make it behave like an IDE. It is frequently used in combination with Github Classroom. See https://code.visualstudio.com/docs/languages/java + for Java support. Note that the VSCode editor is not the same as the Microsoft Visual Studio IDE which is a very large IDE that is not widely used for Java. +

      +
    • + +
    • +

      + IntelliJ IDEA (https://www.jetbrains.com/idea/) + is a free Java IDE from JetBrains which many professionals use. It is a + little easier to configure than Eclipse. Here is a guide on how to + set up IntelliJ: https://www.jetbrains.com/help/idea/install-and-set-up-product.html. +

      +
    • + +
    • +

      + Eclipse (https://www.eclipse.org/downloads/packages/installer) + is what many professional Java programmers use. It may be a little complex + for beginners. Here are some installation and configuration instructions + for Eclipse for Java beginners: http://skylit.com/javamethods/faqs/Eclipse.pdf. +

      +
    • + +
    • +

      + DrJava (http://DrJava.org) is a free, simple, + easy to install and use development environment. One nice feature is the + interactions pane at the bottom which lets you try out Java code without + having to create a class first. +

      +
    • + +
    • +

      + BlueJ (https://www.bluej.org/) is a free + Java IDE designed for beginners. It is built to explore objects and + object-oriented programming and has a teachers' community as well as a + playlist of videos online https://www.youtube.com/playlist?list=PLYPWr4ErjcnzWB95MVvlKArO6PIfv1fHd + to go with the BlueJ Object-First Java book. +

      +
    • + +
    • +

      + jGRASP (https://www.jgrasp.org/) is a free + lightweight development environment, created specifically to provide + automatic generation of software visualizations. jGRASP is implemented in + Java, and runs on all platforms with a Java Virtual Machine (Java version + 1.5 or higher). jGRASP produces Control Structure Diagrams (CSDs) for + Java, C, C++, Objective-C, Python, Ada, and VHDL; Complexity Profile + Graphs (CPGs) for Java and Ada; UML class diagrams for Java; and has + dynamic object viewers and a viewer canvas that work in conjunction with + an integrated debugger and workbench for Java. The site includes both + intro video and PDF tutorials. +

      +
    • + +
    • +

      + NetBeans (https://netbeans.org/) is one of the + original Java IDEs. Here is a tutorial on how to set it up: https://netbeans.org/kb/docs/java/quickstart. +

      +
    • +
    +

    - - Dr. Java -

    - DrJava (from http://DrJava.org) is a free, simple, - easy to install and use development environment. One nice feature is the - interactions pane at the bottom which lets you try out Java code without - having to create a class first. -

    -
    - - - BlueJ -

    - BlueJ (https://www.bluej.org/) is a free - Java IDE designed for beginners. It is built to explore objects and - object-oriented programming and has a teachers’ community as well as a - playlist of videos online https://www.youtube.com/playlist?list=PLYPWr4ErjcnzWB95MVvlKArO6PIfv1fHd - to go with the BlueJ Object-First Java book. -

    -
    - - - jGRASP -

    - jGRASP (https://www.jgrasp.org/) is a free - lightweight development environment, created specifically to provide - automatic generation of software visualizations. jGRASP is implemented in - Java, and runs on all platforms with a Java Virtual Machine (Java version - 1.5 or higher). jGRASP produces Control Structure Diagrams (CSDs) for - Java, C, C++, Objective-C, Python, Ada, and VHDL; Complexity Profile - Graphs (CPGs) for Java and Ada; UML class diagrams for Java; and has - dynamic object viewers and a viewer canvas that work in conjunction with - an integrated debugger and workbench for Java. The site includes both - intro video and PDF tutorials. -

    -
    - - - IntelliJ -

    - IntelliJ (https://www.jetbrains.com/idea/) - is a free Java IDE from JetBrains which many professionals use. It is a - little easier to configure than Eclipse below. Here is a guide on how to - set up IntelliJ: https://www.jetbrains.com/help/idea/install-and-set-up-product.html. -

    -
    - - - Netbeans -

    - Netbeans (https://netbeans.org/) is one of the - original Java IDEs. Here is a tutorial on how to set it up: https://netbeans.org/kb/docs/java/quickstart. -

    -
    - - - Eclipse -

    - Eclipse (https://www.eclipse.org/downloads/packages/installer) - is what many professional Java programmers use. It may be a little complex - for beginners. Here are some installation and configuration instructions - for Eclipse for Java beginners: http://skylit.com/javamethods/faqs/Eclipse.pdf. -

    -
    - -

    + + Java Online IDE Options +

    + There are also a lot of online cloud IDEs where you can code online in many + programming languages. Most are free to start, but offer different + features for a price. These are great options if you are using a + Chromebook or you cannot install software on your computer or you want an + easy no-installation option. +

    + +

    Here are some popular online IDEs:

    +

    +

      +
    • +

      + CodeHS (https://codehs.com/) has a free Sandbox online IDE + (https://codehs.com/app/sandbox) + where you can run Java and Java Swing programs. Students can share the links + to their code and the history of their code is saved. CodeHS has free and paid features. + Grading features are in the paid version. +

      +
    • +
    • +

      + PickCode (https://pickcode.io/) is another + online IDE that offers many free and paid features for setting up + classrooms. In the free version, students can share links to their code and + the history of their code is saved. Classroom features are in the paid version. +

      +
    • +
    • +

      + Replit (https://replit.com/) an online + IDE which recently switched to only allowing 3 projects at a time + for free. Be aware that Replit has turned on its AI feature for code + completion for all accounts (https://replit.com/ai). Each + user can turn the AI on and off at the bottom of the code window, + and use an AI chat window to ask questions of the AI. +

      +
    • +
    • +

      + JuiceMind (https://juicemind.com/) is an + online IDE that offers many free and paid features for teachers to + set up classrooms like Coding Rooms. It has a built-in version of + CSAwesome. +

      +
    • +
    +

    +
    + + +

    Thank you to Beryl Hoffman for contributing to this section from her CSAwesome: AP Java Programming book. -

    -
    +

    +
    From 95116200cf3295419d0b979d438ad716af38cc39 Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Sat, 9 Aug 2025 15:47:44 -0400 Subject: [PATCH 116/357] improve flow in ch1 and add indexing to the chapter --- source/ch1_overview.ptx | 47 +++++++++++++++++++++++------------------ 1 file changed, 26 insertions(+), 21 deletions(-) diff --git a/source/ch1_overview.ptx b/source/ch1_overview.ptx index be9f0de..59ce40e 100644 --- a/source/ch1_overview.ptx +++ b/source/ch1_overview.ptx @@ -102,7 +102,7 @@ Installing Java

    JDKJava development kitOracleOpenJDK - Before you can use any Java IDE or compile Java programs, you need to install the Java development kit (JDK) on your computer. The JDK includes the Java compiler, the runtime environment, and essential tools for Java development. You can either download the latest version of the JDK from Oracle's website (https://www.oracle.com/java/technologies/downloads/) or use OpenJDK, which is a free and open-source implementation available at https://openjdk.org/. Most IDEs will help you configure the JDK once it's installed, but you'll need to have it on your system first. To verify your installation works, open a command prompt or terminal and type java -version - you should see version information displayed. + Before you can use any Java IDE or compile Java programs, you need to install the Java development kit (JDK) on your computer. The JDK includes the Java compiler, the Java runtime environment, and many essential tools for Java development. You can either download the latest version of the JDK from Oracle's website (https://www.oracle.com/java/technologies/downloads/) or use OpenJDK, which is a free and open-source implementation available at https://openjdk.org/. Most IDEs will help you configure the JDK once it's installed, but you'll need to have it on your system first. To verify your installation works, you can open a command prompt or terminal and type java -version - you should see version information displayed.

    @@ -303,30 +303,34 @@
    Why Another Programming Language? -

    +

    dynamic languagestatic languages + Python Java Python is a nice language for beginning programming for several reasons. First the syntax is sparse, and clear. Second, the underlying model of how objects and variables work is very consistent. Third, you can write powerful and interesting programs without a lot of work. - However, Python is representative of one kind of language, called a dynamic language. - You might think of Python as being fairly informal. - There are other languages, like Java and C++ that are more formal. + However, Python is representative of one kind of language, called a dynamic language. In dynamic languages like Python, the type of a variable (whether it's a number, string, list, etc.) is determined while the program is running, not when you write the code. +

    + +

    In static languages, all variable types need to be declared upfront. + You might think of Python as being fairly informal about data types. + Java and C++ are more formal about types.

    -

    +

    performance These languages have some advantages of their own. - First, is speed: Java and C++ code will generally give better performance than Python code. (See .) - Second is their maintainability. + First, is speed: Java and C++ code will generally give better performance than Python code. (See .) + Second is their maintainability over time. Maintainability is the ease with which a program can be modified to correct faults, improve performance, or adapt to a changed environment. A lot of what makes Python easy to use is that you must remember certain things. - For example if you set variable x to reference a turtle, and forget later that x is a turtle but try to invoke a string method on it, you will get an error. + For example, if you set Python variable x to reference a turtle, and forget later that x is a turtle but try to invoke a string method on it, you will get an error. Java and C++ protect you by forcing you to be upfront and formal about the kind of object each variable is going to refer to.

    -

    - In one sense Python is representative of a whole class of languages, sometimes referred to as “scripting languages.” Other languages in the same category as Python are Ruby and Perl. - Java is representative of what I will call industrial strength languages. - Industrial strength languages are good for projects with several people working on the project where being formal and careful about what you do may impact lots of other people. - Languages in this category include Rust, C++, C#, and Ada. +

    scripting language industrial strength languages + In one sense Python is representative of a whole class of languages, sometimes referred to as scripting languages. Other languages in the same category as Python are JavaScript, Ruby, and Perl. + Java is representative of what we might call industrial strength languages. + Industrial strength languages are good for large projects with multiple programmers, where being formal and careful about code structure is important because changes made by one person can impact many others. + Other industrial strength languages include Rust, C++, C#, and Ada.

    @@ -343,7 +347,7 @@

    - Although Python code is generally slower than Java and C++ code, in practice Python programs can achieve equivalent performance. + Although Python code is generally slower than Java and C++ code, in practice Python programs can achieve equivalent performance. Performance can be defined as how efficiently software can accomplish its tasks. This can be done by compiling Python code to C code (see: Cython) or by calling high-performance libraries from Python (e.g., NumPy, scikit-learn, etc.). So native language performance is just one criteria to consider when deciding which language to use for a program.

    @@ -351,7 +355,7 @@
    -
    +
    Why Learn Java? Why not C or C++?

    @@ -361,16 +365,17 @@

    • -

      - Java includes a larger standard library than C or C++, which means that sophisticated programs can be created in Java without including external dependencies. +

      standard library + Java includes a larger standard library than C or C++, which means that sophisticated programs can be created in Java without including external dependencies. The Java Standard Edition contains thousands of built-in classes that support tasks like file input/output, networking, data structures, and graphical interfaces. - We could not begin to scratch the surface of these classes even if we devoted all of class time! However, we will cover many useful and powerful features of the Java standard library this semester. + We could not begin to scratch the surface of these classes even if we devoted many more chapters! However, we will cover many useful and powerful features of the Java standard library.

    • -

      - Java incorporates automatic garbage collection of memory, whereas C and C++ programs typically include some degree of manual memory management. +

      garbage collection + Java incorporates automatic garbage collection of memory, which is an automatic memory management process that identifies and removes unused objects from memory, helping to free up space and improve program efficiency. + C and C++ programs typically include some degree of manual memory management. This makes programming in those languages more challenging.

    • From 5baad59b31346905b66229bf5cf7618a9d13d036 Mon Sep 17 00:00:00 2001 From: Eun Sung Wang <156254694+esw0624@users.noreply.github.com> Date: Mon, 11 Aug 2025 15:51:46 -0400 Subject: [PATCH 117/357] Adding a Summary Section and fixing typo in Chapter 7 --- source/ch7_recursion.ptx | 119 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 118 insertions(+), 1 deletion(-) diff --git a/source/ch7_recursion.ptx b/source/ch7_recursion.ptx index 156f9a3..bdc102a 100644 --- a/source/ch7_recursion.ptx +++ b/source/ch7_recursion.ptx @@ -289,7 +289,7 @@ public class ArrayProcessor { Neither language supports tail call optimization tail call optimization, so the practical limits on recursion depth are a factor in both. If an algorithm requires thousands of recursive calls, an iterative (loop-based) approach is the preferred solution in both Python and Java.

      - The following Python code demonstrates a situation where a function calls itself indefinitely without a base case, leading to aRecursionError. + The following Python code demonstrates a situation where a function calls itself indefinitely without a base case, leading to a RecursionError.

      @@ -331,4 +331,121 @@ public class ArrayProcessor {
    + +
    + Summary & Reading Questions +

      +
    1. +

      Recursion solves problems by defining a base case and a recursive step; each call reduces the problem size until the base case is reached.

      +
    2. +
    3. +

      Java methods must declare visibility, static/instance context, return type, and parameter types; e.g., public static int factorial(int n).

      +
    4. +
    5. +

      The recursive logic in Java mirrors Python conceptually, but Java uses curly braces {} and explicit types instead of indentation and dynamic typing.

      +
    6. +
    7. +

      The helper-method pattern keeps public APIs clean (e.g., sumArray(int[] arr)) while a private helper (e.g., sumHelper(int[] arr, int index)) carries extra state like the current index.

      +
    8. +
    9. +

      Closing over array bounds and indexes in the helper avoids forcing callers to provide implementation details (like a starting index).

      +
    10. +
    11. +

      Deep or unbounded recursion can exhaust the call stack: Python raises RecursionError; Java throws StackOverflowError.

      +
    12. +
    13. +

      Neither Java nor Python guarantees tail call optimization; prefer iterative solutions for algorithms requiring very deep recursion.

      +
    14. +
    15. +

      Error signaling differs across languages; for example, a Java factorial that receives a negative n might return a sentinel value (e.g., -1) after printing an error message.

      +
    16. +

    + + + +

    Which method signature and behavior best match a typical Java recursive factorial implementation?

    +
    + + +

    public void factorial(int n) that prints each partial product and stops when n reaches zero.

    +

    No. Printing results is fine for testing, but a proper factorial method should return the computed value.

    +
    + +

    public static int factorial(int n) that returns 1 when n <= 1 and otherwise returns n * factorial(n - 1).

    +

    Correct. This matches the standard recursive factorial definition in Java.

    +
    + +

    private static int factorial(double n) that repeatedly multiplies n and decrements it until it reaches 1.

    +

    No. Factorials are for integers, and using double here is unnecessary and can cause rounding issues.

    +
    + +

    public int factorial() that uses a stored class field for n instead of a method parameter.

    +

    No. Relying on a class field hides the input and makes recursion less flexible.

    +
    +
    +
    + + +

    Why use a private helper method (e.g., sumHelper(int[] arr, int index)) behind a public method (e.g., sumArray(int[] arr)) in recursive array processing?

    +
    + + +

    Because it allows Java to automatically optimize the recursion for faster execution.

    +

    No. Java does not automatically optimize recursion just because you use a helper method.

    +
    + +

    To keep the public API simple while encapsulating extra recursion state (such as the current index) inside a private method.

    +

    Correct. This keeps the interface clean while hiding internal details from the caller.

    +
    + +

    Because public methods cannot take more than one parameter in recursive calls.

    +

    No. Public methods can take multiple parameters; this is about interface clarity, not parameter limits.

    +
    + +

    To eliminate the need for a base case by handling termination in the helper method automatically.

    +

    No. The helper method still needs an explicit base case to stop recursion.

    +
    +
    +
    + + +

    Which statement about recursion limits and errors is accurate?

    +
    + + + +

    Java can handle very deep or even infinite recursion if the method body is short and does not perform significant operations.

    +
    + +

    No. Regardless of the method’s complexity, each recursive call consumes stack space, and infinite recursion will always cause a stack overflow.

    +
    +
    + + +

    When the call stack is exhausted, Python raises a RecursionError whereas Java throws a StackOverflowError, and neither language applies automatic tail call optimization.

    +
    + +

    Correct. This difference in exception types and the lack of built-in tail call optimization is a key distinction between the two languages.

    +
    +
    + + +

    Declaring a recursive method as static in Java reduces memory usage per call, allowing more recursive calls before a stack overflow occurs.

    +
    + +

    No. The static modifier changes method context (class vs. instance) but does not meaningfully affect per-call stack memory usage.

    +
    +
    + + +

    Increasing a method’s parameter type from int to long in Java can prevent stack overflows for large input values by storing bigger numbers more efficiently.

    +
    + +

    No. The size of the number type does not influence the maximum recursion depth; stack space usage depends on the number of active calls, not numeric range.

    +
    +
    +
    +
    +
    +
    \ No newline at end of file From af8153123edb8d9bad5983160df2d9bc5bafdfb7 Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Mon, 11 Aug 2025 19:09:10 -0400 Subject: [PATCH 118/357] small improvements to 7.1 & 7.2 --- source/ch7_recursion.ptx | 28 +++++++++++++--------------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/source/ch7_recursion.ptx b/source/ch7_recursion.ptx index bdc102a..34462f3 100644 --- a/source/ch7_recursion.ptx +++ b/source/ch7_recursion.ptx @@ -7,10 +7,10 @@
    Basic Recursion

    - In this chapter, we will explore how to translate your recursive logic from Python to Java. While the core concepts of recursion remain the same, the syntax and structure of your code will change somewhat. + In this chapter, we will explore how to translate your recursive logic from Python to Java. While the core concepts of recursion remain the same, the syntax and a bit of the structure of your code will change somewhat.

    -

    recursion - As you may know from Python, recursion is a powerful problem-solving technique involving base cases and recursive steps in which a function or method calls itself. When moving to Java, the core logic you've learned remains identical. The challenge is adapting that logic to Java's statically-typed, class-based syntax. +

    recursionbase caserecursive step + As you may know from Python, recursion is a powerful problem-solving technique involving one or more base cases and recursive steps in which a function or method calls itself while moving towards a base case. When moving to Java, the core logic you've learned remains identical. The challenge is adapting that logic to Java's statically-typed, class-based syntax.

    @@ -34,7 +34,7 @@ as n \times (n-1)!.

    - Here is a Python implementation of factorial using functions: + Here is a Python implementation of factorial using just one function:

    @@ -49,20 +49,18 @@ def factorial(n): # Recursive Step: n * (n-1)! return n * factorial(n - 1) -def main(): - number = 5 - print(str(number) + "! is " + str(factorial(number))) +number = 5 +print(str(number) + "! is " + str(factorial(number))) -main() - +

    - Many Python programs organize related functions into classes. The same factorial function can be placed inside a class as a method. Then you need to create an instance of the class to call the method. There we create the class MathTools with a method factorial, and we call it from the main function. + Many Python programs organize related functions into classes. The same factorial function can be placed inside a class as a method instead of as a function. When this is done, you need to create an instance of the class in order to call the method. Below, we create the class MathTools with a method factorial, and we call it from the main function.

    -class MathTools: +class MTools: def factorial(self, n): # Check for negative numbers if n < 0: @@ -76,9 +74,9 @@ class MathTools: def main(): # Create an instance of the class and call the method - math_tools = MathTools() + mtools_instance = MTools() number = 5 - print(str(number) + "! is " + str(math_tools.factorial(number))) + print(str(number) + "! is " + str(mtools_instance.factorial(number))) main() @@ -92,7 +90,7 @@ main()

    -public class MathTools { +public class MTools { public static int factorial(int n) { // Check for negative numbers if (n < 0) { @@ -115,7 +113,7 @@ public class MathTools {

    - Notice the key differences from Python: instead of def factorial(n):, Java uses public static int factorial(int n) which declares the method's visibility as public, that it belongs to the class rather than an instance (hence, static), the return type as integer, and the parameter type also as integer. The recursive logic—base case and recursive step—remains identical to Python, but all code blocks use curly braces {} instead of indentation. + Notice the key differences from Python: instead of def factorial(n):, Java uses public static int factorial(int n) which declares the method's visibility as public, that it belongs to the class rather than an instance (hence, static), the return type as integer, and the parameter type also as integer. The recursive logic—base case and recursive step—remains identical to Python, and, of course, all code blocks use curly braces {} instead of indentation.

    From 3e78cb02c5ac0c190ddc535fb762b17711e4e723 Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Mon, 11 Aug 2025 19:31:42 -0400 Subject: [PATCH 119/357] make code in 7.3 more parallel --- source/ch7_recursion.ptx | 35 ++++++++++++++++++----------------- 1 file changed, 18 insertions(+), 17 deletions(-) diff --git a/source/ch7_recursion.ptx b/source/ch7_recursion.ptx index 34462f3..2971013 100644 --- a/source/ch7_recursion.ptx +++ b/source/ch7_recursion.ptx @@ -256,7 +256,7 @@ public class ArrayProcessor { public static void main(String[] args) { int[] numbers = {1, 2, 3, 4, 5}; int result = sumArray(numbers); - System.out.println("The sum of [1, 2, 3, 4, 5] is " + result); + System.out.println("The sum of " + Arrays.toString(numbers) + " is " + result); } }
    @@ -274,7 +274,7 @@ public class ArrayProcessor {
    Recursion Limits: Python vs. Java

    - The consequence of deep recursion, running out of stack space, is a concept you've already encountered in Python. Java handles this in a very similar way, throwing an error when the call stack depth is exceeded. + The consequence of deep recursion, running out of stack space, is a concept you may have already encountered in Python. Java handles this in a very similar way to Python, throwing an error when the call stack depth is exceeded.

    The key difference is the name of the error: @@ -284,10 +284,10 @@ public class ArrayProcessor {

  • In Java, this throws a StackOverflowError.
  • - Neither language supports tail call optimization tail call optimization, so the practical limits on recursion depth are a factor in both. If an algorithm requires thousands of recursive calls, an iterative (loop-based) approach is the preferred solution in both Python and Java. + Neither language supports tail call optimization tail call optimization, so the practical limits on recursion depth are a factor in both. If an algorithm requires thousands of recursive calls, an iterative, loop-based, approach is likely going to be the preferred solution in both Python and Java.

    - The following Python code demonstrates a situation where a function calls itself indefinitely without a base case, leading to a RecursionError. + The following Python code demonstrates a situation where a function calls itself indefinitely without a base case, leading to a RecursionError.

    @@ -297,32 +297,33 @@ public class ArrayProcessor { """ cause_recursion_error() - # Standard Python entry point - if __name__ == "__main__": - print("Calling the recursive function... this will end in an error!") - - # This line starts the infinite recursion. - # Python will stop it and raise a RecursionError automatically. - cause_recursion_error() + print("Calling the recursive function... this will end in an error!") + + # The line below will start the infinite recursion. + # Python will stop it and raise a RecursionError automatically. + # Each call adds a new layer to the program's call stack. + # Eventually, the call stack runs out of space, causing the error. + cause_recursion_error()

    - The following Java code demonstrates a similar situation, where a method calls itself indefinitely without a base case, leading to a StackOverflowError. + The following Java code demonstrates a similar situation, where a method calls itself indefinitely without a base case, leading to a StackOverflowError.

    public class Crash { public static void causeStackOverflow() { - // This method calls itself endlessly without a stopping condition (a base case). - // Each call adds a new layer to the program's call stack. - // Eventually, the stack runs out of space, causing the error. + // The line below will start the infinite recursion. + // Java will stop it and raise a StackOverflowError automatically. + // Each call adds a new layer to the program's call stack. + // Eventually, the call stack runs out of space, causing the error. causeStackOverflow(); } - // A main method is required to run the program. + // A main method is required to run the Java program. public static void main(String[] args) { System.out.println("Calling the recursive method... this will end in an error!"); - // This line starts the infinite recursion. + causeStackOverflow(); } } From 5ddc2d5980c3149c60f96fd8180c627559a969d2 Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Mon, 11 Aug 2025 19:50:55 -0400 Subject: [PATCH 120/357] use meaningful xml:ids --- source/ch6_definingclasses.ptx | 2 +- source/ch7_recursion.ptx | 19 ++++++++----------- 2 files changed, 9 insertions(+), 12 deletions(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index 3652c74..77f82be 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -1011,7 +1011,7 @@ public class Fraction extends Number implements Comparable<Fraction> {
    -
    +
    Summary & Reading Questions

    1. diff --git a/source/ch7_recursion.ptx b/source/ch7_recursion.ptx index 2971013..1d56783 100644 --- a/source/ch7_recursion.ptx +++ b/source/ch7_recursion.ptx @@ -324,14 +324,14 @@ public class ArrayProcessor { public static void main(String[] args) { System.out.println("Calling the recursive method... this will end in an error!"); - causeStackOverflow(); + causeStackOverflow(); } }
    -
    +
    Summary & Reading Questions

    1. @@ -344,23 +344,20 @@ public class ArrayProcessor {

      The recursive logic in Java mirrors Python conceptually, but Java uses curly braces {} and explicit types instead of indentation and dynamic typing.

    2. -

      The helper-method pattern keeps public APIs clean (e.g., sumArray(int[] arr)) while a private helper (e.g., sumHelper(int[] arr, int index)) carries extra state like the current index.

      -
    3. -
    4. -

      Closing over array bounds and indexes in the helper avoids forcing callers to provide implementation details (like a starting index).

      +

      The helper method pattern hides implementation details (like array indices) from callers, providing clean public interfaces while managing recursive state privately.

    5. Deep or unbounded recursion can exhaust the call stack: Python raises RecursionError; Java throws StackOverflowError.

    6. -

      Neither Java nor Python guarantees tail call optimization; prefer iterative solutions for algorithms requiring very deep recursion.

      +

      Neither Java nor Python guarantees tail call optimization, so programmers should use iterative solutions for algorithms that would require very deep recursion.

    7. -

      Error signaling differs across languages; for example, a Java factorial that receives a negative n might return a sentinel value (e.g., -1) after printing an error message.

      +

      Recursive methods in Java must specify return types explicitly, unlike Python's dynamic typing, which affects how you handle error cases and return values.

    - +

    Which method signature and behavior best match a typical Java recursive factorial implementation?

    @@ -383,7 +380,7 @@ public class ArrayProcessor {
    - +

    Why use a private helper method (e.g., sumHelper(int[] arr, int index)) behind a public method (e.g., sumArray(int[] arr)) in recursive array processing?

    @@ -406,7 +403,7 @@ public class ArrayProcessor {
    - +

    Which statement about recursion limits and errors is accurate?

    From ee5d2314d625306e66d915c1a84c318b639771b8 Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Mon, 11 Aug 2025 20:15:51 -0400 Subject: [PATCH 121/357] improve summary and reading question --- source/ch7_recursion.ptx | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/source/ch7_recursion.ptx b/source/ch7_recursion.ptx index 1d56783..f09149f 100644 --- a/source/ch7_recursion.ptx +++ b/source/ch7_recursion.ptx @@ -356,12 +356,16 @@ public class ArrayProcessor {

    Recursive methods in Java must specify return types explicitly, unlike Python's dynamic typing, which affects how you handle error cases and return values.

  • - +

    Which method signature and behavior best match a typical Java recursive factorial implementation?

    + +

    public static int factorial(int n) that returns 0 when n <= 0 and otherwise returns n * factorial(n - 1).

    +

    No. While this handles negative numbers, the base case is incorrect - factorial of 0 should be 1, not 0.

    +

    public void factorial(int n) that prints each partial product and stops when n reaches zero.

    No. Printing results is fine for testing, but a proper factorial method should return the computed value.

    @@ -371,12 +375,8 @@ public class ArrayProcessor {

    Correct. This matches the standard recursive factorial definition in Java.

    -

    private static int factorial(double n) that repeatedly multiplies n and decrements it until it reaches 1.

    -

    No. Factorials are for integers, and using double here is unnecessary and can cause rounding issues.

    -
    - -

    public int factorial() that uses a stored class field for n instead of a method parameter.

    -

    No. Relying on a class field hides the input and makes recursion less flexible.

    +

    public static long factorial(int n) that returns 1 when n == 0 and otherwise returns n * factorial(n - 1).

    +

    No. While this logic is close, it doesn't handle the case when n = 1, and using long as return type when int parameter is used creates inconsistency.

    @@ -408,20 +408,20 @@ public class ArrayProcessor {

    Which statement about recursion limits and errors is accurate?

    - + -

    Java can handle very deep or even infinite recursion if the method body is short and does not perform significant operations.

    +

    When the call stack is exhausted, Python raises a RecursionError whereas Java throws a StackOverflowError, and neither language applies automatic tail call optimization.

    -

    No. Regardless of the method’s complexity, each recursive call consumes stack space, and infinite recursion will always cause a stack overflow.

    +

    Correct. This difference in exception types and the lack of built-in tail call optimization is a key distinction between the two languages.

    - + -

    When the call stack is exhausted, Python raises a RecursionError whereas Java throws a StackOverflowError, and neither language applies automatic tail call optimization.

    +

    Java automatically applies tail call optimization to recursive methods marked as final, preventing most stack overflows.

    -

    Correct. This difference in exception types and the lack of built-in tail call optimization is a key distinction between the two languages.

    +

    No. Java does not perform automatic tail call optimization, regardless of whether methods are marked as final.

    @@ -434,10 +434,10 @@ public class ArrayProcessor { -

    Increasing a method’s parameter type from int to long in Java can prevent stack overflows for large input values by storing bigger numbers more efficiently.

    +

    The JVM can detect simple recursive patterns and automatically convert them to iterative loops to prevent stack overflow.

    -

    No. The size of the number type does not influence the maximum recursion depth; stack space usage depends on the number of active calls, not numeric range.

    +

    No. The JVM does not automatically convert recursive methods to iterative ones. This optimization must be done manually by the programmer.

    From 0fc9cc49283898ffdb9f22a09386e9cb780949bf Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Mon, 11 Aug 2025 20:42:31 -0400 Subject: [PATCH 122/357] Changed class name in first code block in 8.4 from Main to WriteFile --- source/ch8_filehandling.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 82608c1..19ab18f 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -254,7 +254,7 @@ import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; - public class Main { + public class WriteFile { public static void main(String[] args) { String filename = "test_file.txt"; try (FileWriter writer = new FileWriter(filename)) { From 4c9d26c7f39238982aac32c7474d719f2bd8e772 Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Tue, 12 Aug 2025 09:37:39 -0400 Subject: [PATCH 123/357] Changed the code block about writing to files in section 8.1 to pre tags, and removed all code except for the File class import. This pretag code block and the paragaph preceding it focus exclusively on importing the File class now. --- source/ch8_filehandling.ptx | 24 +++++++----------------- 1 file changed, 7 insertions(+), 17 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 19ab18f..7aaadd6 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -37,24 +37,14 @@

    Much like the Math class, in order for your program to work with files you need use import. Java includes a class called File in the io library. This class allows you to create File objects, and use its public methods. the following code imports the File class and creates a File object called myFile. for now focus on how the class is imported and used in the program; We will cover the IOException class and createNewFile method later.

    - - - import java.io.File; - import java.io.IOException; - public class Main { - public static void main(String[] args) { - try { - File myFile = new File("newfile.txt"); - myFile.createNewFile(); - System.out.println("File Made."); - } catch (IOException e) { - System.out.println("An error occurred."); - } - } - } - - +

    + Much like the Math class, in order for your program to work with files you need use import. Java includes a class called File in the io library. This class allows you to create File objects, and use its public methods. +

    + +
    +        import java.io.File;
    +        

    The Scanner class from the util library will need to be imported if there is any need for a program to read a file. It should be noted that this library is unnecessary if the program will not be reading any data from a file.

    From 2059e315fea1c446ecb6bc80a7d38f5f27c4cb14 Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Tue, 12 Aug 2025 09:44:42 -0400 Subject: [PATCH 124/357] Removed the data file form 8.2. Running the Python code in this section appears to work fine without it. I am unable to test the Java code. --- source/ch8_filehandling.ptx | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 7aaadd6..3678712 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -79,11 +79,7 @@

    We will now create a File object. It is important to create a meaningful name for the File object. We will call ours myFile.

    - -
    -                    empty file
    -                
    -
    + import java.io.File; From 0e6bf21789338bdf26ecd587d756e47e8c2a29f8 Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Tue, 12 Aug 2025 10:17:36 -0400 Subject: [PATCH 125/357] Gave meaningful class names to all classes in chapter. --- source/ch8_filehandling.ptx | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 3678712..b59f5aa 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -23,7 +23,7 @@ import java.lang.Math; - public class Main { + public class SquareRoot { public static void main(String[] args) { System.out.println(Math.sqrt(25)); } @@ -77,13 +77,13 @@

    - We will now create a File object. It is important to create a meaningful name for the File object. We will call ours myFile. + We will now create a File object. It is important to create a meaningful name for the File object. We will call ours myFile. We will also call our class CreateFile

    import java.io.File; - public class Main { + public class CreateFile { public static void main(String[] args) { File myFile = new File("myfile.txt"); System.out.println(myFile); @@ -202,8 +202,9 @@ import java.io.File; import java.io.FileNotFoundException; - import java.util.Scanner;public class Main { - public static void main(String[] args) { + import java.util.Scanner; + public class ReadFile { + public static void main (String[] args) { String filename = "myfile.txt"; try (Scanner fileReader = new Scanner(new File(filename))) { while (fileReader.hasNextLine()) { @@ -319,7 +320,7 @@ import java.io.File; import java.io.IOException; - import java.util.Scanner;public class Main { + import java.util.Scanner;public class WriteFile { public static void main(String[] args) { String filename = "myfile8-4-3.txt"; try (Scanner reader = new Scanner(new File(filename))) { From 5d462402ac1ac6fbbb3fecf0435a84672f44a671 Mon Sep 17 00:00:00 2001 From: Eun Sung Wang <156254694+esw0624@users.noreply.github.com> Date: Tue, 12 Aug 2025 11:11:06 -0400 Subject: [PATCH 126/357] Adding index term and new paragraph in Chapter 7 --- source/ch7_recursion.ptx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/source/ch7_recursion.ptx b/source/ch7_recursion.ptx index f09149f..ec8659d 100644 --- a/source/ch7_recursion.ptx +++ b/source/ch7_recursion.ptx @@ -284,8 +284,10 @@ public class ArrayProcessor {
  • In Java, this throws a StackOverflowError.
  • - Neither language supports tail call optimization tail call optimization, so the practical limits on recursion depth are a factor in both. If an algorithm requires thousands of recursive calls, an iterative, loop-based, approach is likely going to be the preferred solution in both Python and Java. + Neither language supports tail call optimization, so the practical limits on recursion depth are a factor in both. If an algorithm requires thousands of recursive calls, an iterative, loop-based, approach is likely going to be the preferred solution in both Python and Java.

    +

    Tail Call Optimization Tail Call Optimization (TCO) is a technique used in programming to improve the efficiency of recursive function calls by reusing the current function's stack frame instead of creating a new one. This helps prevent stack overflow errors and reduces memory usage, especially in languages that support it.

    +

    The following Python code demonstrates a situation where a function calls itself indefinitely without a base case, leading to a RecursionError.

    From c55c7bedea3b9b4394e011baafd4cddd6ca8ea7e Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Tue, 12 Aug 2025 11:31:53 -0400 Subject: [PATCH 127/357] Removed the paragraph on saving to a specific file path. Made some changes to the code in 8.4 so that the code is more in-line with what the text is describing for each one. --- source/ch8_filehandling.ptx | 75 +++++++++++++------------------------ 1 file changed, 26 insertions(+), 49 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index b59f5aa..48720d3 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -195,7 +195,7 @@

    - The following Java code functions very similarly to the previous Python. The main difference here is that unlike Python, In Java we use the Scanner object to iterate through and read lines in the file. You will notice that the structure of the Java code is still similar to the Python; Both use a try and catch statement to read the file and catch any errors. + The following Java code functions very similarly to the previous Python. The main difference here is that unlike Python, in Java we use the Scanner object to iterate through and read lines in the file. You will notice that the structure of the Java code is still similar to the Python; Both use a try and catch statement to read the file and catch any errors.

    @@ -235,34 +235,17 @@ Let us create the framework for a class that will write to a file. Let's call this class WriteFile:

    - - +
                 import java.io.File;
                 import java.io.FileWriter;
                 import java.io.IOException;
                 import java.util.Scanner;
                 public class WriteFile {
                     public static void main(String[] args) {
    -                    String filename = "test_file.txt";        
    -                    try (FileWriter writer = new FileWriter(filename)) {
    -                        writer.write("This line was written by the program.");
    -                        System.out.println("Successfully wrote to the file.");
    -                    } 
    -                    catch (IOException e) {
    -                        System.out.println("An error occurred during writing.");
    -                    }        System.out.println("--- Reading file back ---");        
    -                    try (Scanner reader = new Scanner(new File(filename))) {
    -                        while (reader.hasNextLine()) {
    -                            System.out.println(reader.nextLine());
    -                        }
    -                    } 
    -                    catch (IOException e) {
    -                        System.out.println("An error occurred during reading.");
    -                    }
    +                 
                     }
                 }
    -             
    -        
    +        

    Next, we will create a FileWriter object. Let's call it myWriter: @@ -299,12 +282,14 @@ - with open("myfile8-4-2.txt", "r") as file_reader: - while True: - line = file_reader.readline() - if not line: # End of file - break - print(line.strip()) + try: + with open("myfile.txt", "w") as my_writer: + my_writer.write("File successfully updated!") + print("File successfully written to.") + except OSError as e: + print("An error occurred.") + import traceback + traceback.print_exc() @@ -312,29 +297,21 @@ And the equivalent Java code:

    -
    -                    
    -                
    -
    - - - import java.io.File; - import java.io.IOException; - import java.util.Scanner;public class WriteFile { - public static void main(String[] args) { - String filename = "myfile8-4-3.txt"; - try (Scanner reader = new Scanner(new File(filename))) { - while (reader.hasNextLine()) { - String line = reader.nextLine(); - System.out.println(line.trim()); - } - } catch (IOException e) { - System.out.println("An error occurred."); - } - } +
    +                
    +            
    + +
    +            try {
    +                FileWriter myWriter = new FileWriter("myfile.txt");
    +                myWriter.write("File successfully updated!");
    +                myWriter.close();
    +                System.out.println("File successfully written to.");
    +            } catch (IOException e) {
    +                System.out.println("An error occurred.");
    +                e.printStackTrace();
                 }
    -             
    -        
    +        

    And that's it! We will add our code to the foundational code for a complete program. First, an example of equivalent Python code: From ec296668e28d73e500de7f8f30a5a84206227350 Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Tue, 12 Aug 2025 11:36:19 -0400 Subject: [PATCH 128/357] Removed paragraph and code on using lineseparator method for new lines. --- source/ch8_filehandling.ptx | 19 +++---------------- 1 file changed, 3 insertions(+), 16 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 48720d3..c592f9e 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -363,10 +363,6 @@ -

    - Files in a specific directory can be written to using the same technique as the last section in which file paths are specified, with two back slashes used in Windows environments. -

    -

    If a file does not already exist (for example, myfile.txt does not exist), the write() method will create the file. Despite this, it is still a good idea to create separate methods or classes for creating and writing to files. Not only is it good practice to ensure methods only accomplish one thing, but the createNewFile() method avoids overwriting files that already exist. Imagine a file with the name myfile.txt already exists and contains important information. Attempting to create a file using the write() method will delete that data forever. @@ -382,7 +378,7 @@

    - Now, when we use write() method like before, the text will be appended if there is already text in the document. If we were to update our code to include the boolean argument: + Now, when we use write() method like before, the text will be appended if there is already tSext in the document. If we were to update our code to include the boolean argument:

    @@ -419,7 +415,7 @@
             

    - This doesn't look very good! If we want each additional write to appear on a new line? The first solution may be to use the \n newline character: + This doesn't look very good! If we want each additional write to appear on a new line? A simple solution is to use the \n newline character:

    @@ -428,16 +424,7 @@
             

    - The System.lineseseparator() method is a better solution. This method returns the system's default line separator, which is platform-dependent. For example, on Windows, it returns \n, while on Linux and macOS, it returns \n. Using this method ensures that your code works correctly across different operating systems: -

    - -
    -            myWriter.write("File successfully updated!" + System.lineseparator()); // Added newline character 
    -            myWriter.close();
    -        
    - -

    - Running it twice will result in the following contents in myfile.txt: + Running the code with the newline character twice will result in the following contents in myfile.txt:

    
    From 434cd1b78e31f0819cc0d82e8d92f0b2e6a7d821 Mon Sep 17 00:00:00 2001
    From: Jan Pearce 
    Date: Tue, 12 Aug 2025 12:06:52 -0400
    Subject: [PATCH 129/357] put tail-call optimization into an aside
    
    ---
     source/ch7_recursion.ptx | 25 ++++++++++++++++---------
     1 file changed, 16 insertions(+), 9 deletions(-)
    
    diff --git a/source/ch7_recursion.ptx b/source/ch7_recursion.ptx
    index ec8659d..7dc933a 100644
    --- a/source/ch7_recursion.ptx
    +++ b/source/ch7_recursion.ptx
    @@ -273,23 +273,30 @@ public class ArrayProcessor {
     
         
    Recursion Limits: Python vs. Java -

    - The consequence of deep recursion, running out of stack space, is a concept you may have already encountered in Python. Java handles this in a very similar way to Python, throwing an error when the call stack depth is exceeded. +

    recursion limitscall stack + When using recursion, both Python and Java have practical limits on how deep the recursion can go before running into errors. This is due to the way both languages manage something called the call stack, which is a limited amount of memory used to keep track of function or method calls.

    - The key difference is the name of the error: -

    + The consequence of running out of call stack space, is a concept you may have already encountered in Python. Java handles this in a very similar way to Python, both throwing an error when the call stack depth is exceeded. +RecursionErrorStackOverflowError + The only difference is the name of the error: +
      -
    • In Python, this raises a RecursionError.
    • -
    • In Java, this throws a StackOverflowError.
    • +
    • In Python, overflowing the call stack raises a RecursionError error.
    • +
    • In Java, it throws a StackOverflowError.
    +

    +

    - Neither language supports tail call optimization, so the practical limits on recursion depth are a factor in both. If an algorithm requires thousands of recursive calls, an iterative, loop-based, approach is likely going to be the preferred solution in both Python and Java. + In both languages, if you write a recursive function that doesn't have a base case or that just recurses too deeply, you'll eventually hit this limit. When this happens, Python will raise a RecursionError, while Java will throw a StackOverflowError. This is because both languages use a call stack to keep track of function calls, and when the stack runs out of space, it results in an error. + Hence, when an algorithm might require thousands of recursive calls, an iterative, loop-based, approach is likely going to be the preferred solution in both Python and Java.

    -

    Tail Call Optimization Tail Call Optimization (TCO) is a technique used in programming to improve the efficiency of recursive function calls by reusing the current function's stack frame instead of creating a new one. This helps prevent stack overflow errors and reduces memory usage, especially in languages that support it.

    - The following Python code demonstrates a situation where a function calls itself indefinitely without a base case, leading to a RecursionError. + The following Python code demonstrates a situation where a function calls itself indefinitely without a base case, leading to a RecursionError due to overflowing the call stack.

    From 680f110d466042f825e23311428e03e347384ef6 Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Tue, 12 Aug 2025 13:56:00 -0400 Subject: [PATCH 130/357] Exchanged pre tags with code tags for all code snippets. --- source/ch8_filehandling.ptx | 78 +++++++++++++++++++++++++------------ 1 file changed, 54 insertions(+), 24 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index c592f9e..c45882b 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -42,33 +42,33 @@ Much like the Math class, in order for your program to work with files you need use import. Java includes a class called File in the io library. This class allows you to create File objects, and use its public methods.

    -
    +        
             import java.io.File;
    -        
    +

    The Scanner class from the util library will need to be imported if there is any need for a program to read a file. It should be noted that this library is unnecessary if the program will not be reading any data from a file.

    -
    +        
                 import java.util.Scanner; 
    -        
    +

    The FileWriter class can be used to write to files. In the same way that the Scanner class isn't needed unless the program will read from a file, the FileWriter class isn't needed unless the program will write to a file.

    -
    +        
                 import java.io.FileWriter;
    -        
    +

    Finally, these last two classes provide error handling and must be used in tandem with the File class when reading from or writing to files. IOException handles file creation and writing errors, while FileNotFoundException handles errors when trying to read files.

    -
    +        
                 import java.io.IOException;
                 import java.io.FileNotFoundException;
    -        
    +
    @@ -235,7 +235,7 @@ Let us create the framework for a class that will write to a file. Let's call this class WriteFile:

    -
    +        
                 import java.io.File;
                 import java.io.FileWriter;
                 import java.io.IOException;
    @@ -245,24 +245,24 @@
                      
                     }
                 }
    -        
    +

    Next, we will create a FileWriter object. Let's call it myWriter:

    -
    +        
                 FileWriter myWriter = new FileWriter("myfile.txt");
    -        
    +

    In this next step, we will use the write() method from the FileWriter class. This Method will take any data within the parenthesis and write that data to the file selected. The write() method takes most standard data types:

    -
    +        
                 myWriter.write("File successfully updated!");
                 myWriter.close();
    -        
    +

    @@ -301,7 +301,7 @@

    -
    +        
                 try {
                     FileWriter myWriter = new FileWriter("myfile.txt");
                     myWriter.write("File successfully updated!");
    @@ -311,7 +311,7 @@
                     System.out.println("An error occurred.");
                     e.printStackTrace();
                 }
    -        
    +

    And that's it! We will add our code to the foundational code for a complete program. First, an example of equivalent Python code: @@ -373,17 +373,17 @@ Speaking of overwriting data, what if we want to append text to the end of any text already in myfile.txt? To accomplish this, we can pass a boolean argument along with the file name when creating a new data argument:

    -
    +        
                 FileWriter myWriter = new FileWriter("myfile.txt", true); // true enables append mode
    -        
    +

    Now, when we use write() method like before, the text will be appended if there is already tSext in the document. If we were to update our code to include the boolean argument:

    -
    +                
                         
    -                
    +
    @@ -410,18 +410,18 @@ Then if we run the program twice, the contents of myfile.txt would be:

    -
    +        
                 File successfully updated!File successfully updated!
    -        
    +

    This doesn't look very good! If we want each additional write to appear on a new line? A simple solution is to use the \n newline character:

    -
    +        
                 myWriter.write("File successfully updated!\n"); // Added newline character 
                 myWriter.close(); 
    -        
    +

    Running the code with the newline character twice will result in the following contents in myfile.txt: @@ -439,6 +439,36 @@

    Finally, we will take a look at using Java to delete files. This one is pretty straight-forward and follows the structure used to create files. This time, however, try/catch blocks are not needed for the program to compile. We will call this class DeleteFile. The completed code should look something like this.

    + + +
    +                1
    +                2
    +                3
    +                4
    +                5
    +                6
    +                7
    +                8
    +            
    +
    + + + + # Name of the file to delete + file_name = "myfile.txt" + + # Check if the file exists before deleting + if os.path.exists(file_name): + try: + os.remove(file_name) + print("Deleted", file_name) + except Exception as e: + print("File could not be deleted.") + else: + print("File could not be deleted.") + + From a226ed067d274a9f2a87344e28af99baec5d34fc Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Tue, 12 Aug 2025 14:22:26 -0400 Subject: [PATCH 131/357] changed all code tags to input tags in code blocks. Added or changed xml ids for all code. --- source/ch8_filehandling.ptx | 94 ++++++++++++++++++------------------- 1 file changed, 47 insertions(+), 47 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index c45882b..1be9ecd 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -10,17 +10,17 @@ File handling is an integral part of programming. Most programming languages have the ability to create, read from, write to, and delete, files. In Python, most built-in libraries are available without needing to explicitly import additional packages, but some libraries like math do need to be imported. Consider the following.

    - + import math print(math.sqrt(25)) - +

    Delete the first line that says import math and see what happens. The import math is needed. The same program in Java would look like this:

    - + import java.lang.Math; public class SquareRoot { @@ -28,7 +28,7 @@ System.out.println(Math.sqrt(25)); } } - +

    Note the use of import java.lang.Math; in the above to import the Math class. Unlike Python, Java requires explicit import for most libraries, including the Math class and many classes related to file handling. @@ -42,14 +42,14 @@ Much like the Math class, in order for your program to work with files you need use import. Java includes a class called File in the io library. This class allows you to create File objects, and use its public methods.

    - + import java.io.File;

    The Scanner class from the util library will need to be imported if there is any need for a program to read a file. It should be noted that this library is unnecessary if the program will not be reading any data from a file.

    - + import java.util.Scanner; @@ -57,7 +57,7 @@ The FileWriter class can be used to write to files. In the same way that the Scanner class isn't needed unless the program will read from a file, the FileWriter class isn't needed unless the program will write to a file.

    - + import java.io.FileWriter; @@ -65,7 +65,7 @@ Finally, these last two classes provide error handling and must be used in tandem with the File class when reading from or writing to files. IOException handles file creation and writing errors, while FileNotFoundException handles errors when trying to read files.

    - + import java.io.IOException; import java.io.FileNotFoundException; @@ -80,8 +80,8 @@ We will now create a File object. It is important to create a meaningful name for the File object. We will call ours myFile. We will also call our class CreateFile

    - - + + import java.io.File; public class CreateFile { public static void main(String[] args) { @@ -89,7 +89,7 @@ System.out.println(myFile); } } - + @@ -108,7 +108,7 @@

    - + filename = "newfile.txt" print("Attempting to write to '" + filename + "' using 'w' mode...") try: @@ -119,15 +119,15 @@ # This would only catch other unexpected errors print("An unexpected error occurred during write: " + str(e)) - +

    Now, let's look at Java code that accomplishes the same task:

    - - + + import java.io.File; import java.io.IOException; @@ -147,7 +147,7 @@ } } } - + @@ -179,8 +179,8 @@ - - + + filename = "myfile.txt" try: # Attempt to open the file in read mode ('r') @@ -191,7 +191,7 @@ except: #catches if the file doesn't exist or can't be written to print("file could not be opened") - +

    @@ -199,7 +199,7 @@

    - + import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; @@ -217,7 +217,7 @@ } } } - +

    You may have noticed that there are some new methods you haven't seen yet. The hasNextLine() method checks if there is a next line in the file, and returns false if there isn't. This method allows us to iterate over every line till there is no next line. The nextLine() method of the Scanner object returns the next line in the file as a string. @@ -235,7 +235,7 @@ Let us create the framework for a class that will write to a file. Let's call this class WriteFile:

    - + import java.io.File; import java.io.FileWriter; import java.io.IOException; @@ -251,7 +251,7 @@ Next, we will create a FileWriter object. Let's call it myWriter:

    - + FileWriter myWriter = new FileWriter("myfile.txt"); @@ -259,7 +259,7 @@ In this next step, we will use the write() method from the FileWriter class. This Method will take any data within the parenthesis and write that data to the file selected. The write() method takes most standard data types:

    - + myWriter.write("File successfully updated!"); myWriter.close(); @@ -280,8 +280,8 @@ 3 - - + + try: with open("myfile.txt", "w") as my_writer: my_writer.write("File successfully updated!") @@ -290,7 +290,7 @@ print("An error occurred.") import traceback traceback.print_exc() - +

    @@ -301,7 +301,7 @@ - + try { FileWriter myWriter = new FileWriter("myfile.txt"); myWriter.write("File successfully updated!"); @@ -321,8 +321,8 @@ - - + + try: with open("myfile.txt", "w") as my_writer: my_writer.write("File successfully updated!") @@ -331,7 +331,7 @@ print("An error occurred.") import traceback traceback.print_exc() - +

    @@ -342,8 +342,8 @@ - - + + import java.io.FileWriter; import java.io.IOException; @@ -360,7 +360,7 @@ } } } - + @@ -373,7 +373,7 @@ Speaking of overwriting data, what if we want to append text to the end of any text already in myfile.txt? To accomplish this, we can pass a boolean argument along with the file name when creating a new data argument:

    - + FileWriter myWriter = new FileWriter("myfile.txt", true); // true enables append mode @@ -381,12 +381,12 @@ Now, when we use write() method like before, the text will be appended if there is already tSext in the document. If we were to update our code to include the boolean argument:

    - +
                         
    -                
    +                
    - - + + import java.io.FileWriter; import java.io.IOException; @@ -403,22 +403,22 @@ } } } - +

    Then if we run the program twice, the contents of myfile.txt would be:

    - +
                 File successfully updated!File successfully updated!
    -        
    +        

    This doesn't look very good! If we want each additional write to appear on a new line? A simple solution is to use the \n newline character:

    - + myWriter.write("File successfully updated!\n"); // Added newline character myWriter.close(); @@ -453,7 +453,7 @@ - + # Name of the file to delete file_name = "myfile.txt" @@ -470,8 +470,8 @@ - - + + import java.io.File; public class DeleteFile { @@ -484,7 +484,7 @@ } } } - +

    From 72593244e7cb58a78284972fee6fe5006aea5dfe Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Tue, 12 Aug 2025 14:53:36 -0400 Subject: [PATCH 132/357] Updated some code blocks so they are consistent. Added Python code examples to match some of the Java code examples. --- source/ch8_filehandling.ptx | 41 ++++++++++++++++++++++--------------- 1 file changed, 25 insertions(+), 16 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 1be9ecd..5f87ba2 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -85,8 +85,7 @@ import java.io.File; public class CreateFile { public static void main(String[] args) { - File myFile = new File("myfile.txt"); - System.out.println(myFile); + } } @@ -248,7 +247,15 @@

    - Next, we will create a FileWriter object. Let's call it myWriter: + Next, we will create a FileWriter object. Let's call it myWriter. The equivalent Python code to this operation is: +

    + + + with open("myfile.txt", "w") as myWriter: + + +

    + The Java code to create a FileWriter object is:

    @@ -256,10 +263,18 @@

    - In this next step, we will use the write() method from the FileWriter class. This Method will take any data within the parenthesis and write that data to the file selected. The write() method takes most standard data types: + In this next step, we will use the write() method from the FileWriter class. This Method will take any data within the parenthesis and write that data to the file selected. The write() method takes most standard data types. First, how this step is completed with Python:

    + + + my_writer.write("File successfully updated!") + - +

    + And the Java equivalent. This is almost completely identical except for the second line, which is very important! +

    + + myWriter.write("File successfully updated!"); myWriter.close(); @@ -280,8 +295,7 @@ 3 - - + try: with open("myfile.txt", "w") as my_writer: my_writer.write("File successfully updated!") @@ -290,17 +304,12 @@ print("An error occurred.") import traceback traceback.print_exc() -

    And the equivalent Java code:

    - -
    -                
    -            
    -
    + try { FileWriter myWriter = new FileWriter("myfile.txt"); @@ -316,11 +325,11 @@

    And that's it! We will add our code to the foundational code for a complete program. First, an example of equivalent Python code:

    - +
                         
                     
    -
    +
    try: @@ -380,7 +389,7 @@

    Now, when we use write() method like before, the text will be appended if there is already tSext in the document. If we were to update our code to include the boolean argument:

    - +
                         
                     
    From f214376bc68dcc1661d5589622939d775d4f58dd Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Tue, 12 Aug 2025 14:55:07 -0400 Subject: [PATCH 133/357] Addendum to last commit. Removed duplicate xml id --- source/ch8_filehandling.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 5f87ba2..44a8de8 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -250,7 +250,7 @@ Next, we will create a FileWriter object. Let's call it myWriter. The equivalent Python code to this operation is:

    - + with open("myfile.txt", "w") as myWriter: From cac4a9e1ca2f17235917634fcfd50b008c0059c1 Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Tue, 12 Aug 2025 15:48:48 -0400 Subject: [PATCH 134/357] Updated section on deleting files. This section now includes Java code that will create a file so the last block of Java code has something to delete. The Python example provided will not run because the os library cannot be imported. I was unable to test the Java code within the book. --- source/ch8_filehandling.ptx | 76 ++++++++++++++++++++++--------------- 1 file changed, 46 insertions(+), 30 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 44a8de8..0aaf05f 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -446,39 +446,55 @@ Deleting Files

    - Finally, we will take a look at using Java to delete files. This one is pretty straight-forward and follows the structure used to create files. This time, however, try/catch blocks are not needed for the program to compile. We will call this class DeleteFile. The completed code should look something like this. -

    - - -
    -                1
    -                2
    -                3
    -                4
    -                5
    -                6
    -                7
    -                8
    -            
    -
    - - + Finally, we will take a look at using Java to delete files. This one is pretty straight-forward and follows the structure used to create files. This time, however, try/catch blocks are not needed for the program to compile. First, the CreateFile class from before will be used to create a file: +

    + + - # Name of the file to delete - file_name = "myfile.txt" - - # Check if the file exists before deleting - if os.path.exists(file_name): - try: - os.remove(file_name) - print("Deleted", file_name) - except Exception as e: - print("File could not be deleted.") - else: - print("File could not be deleted.") - + import java.io.File; + import java.io.IOException; + + public class CreateFile { + public static void main(String[] args) { + File myFile = new File("myfile.txt"); + try { + if (myFile.createNewFile()) { + System.out.println("The file " + myFile.getName() + " was created successfully."); + } else { + System.out.println("The file " + myFile.getName() + " already exists."); + } + } catch (IOException e) { + // This code runs if an IOException occurs + System.out.println("An error occurred while creating the file."); + e.printStackTrace(); // This prints the stack trace for more detailed error info + } + } + } + +

    + The next example is Python code that can be used to delete files. This code cannot be run because importing os is not possible with the technologies used to write this book: +

    + + + import os + file_name = "myfile.txt" + if os.path.exists(file_name): + try: + os.remove(file_name) + print("Deleted", file_name) + except Exception as e: + print("File could not be deleted.") + else: + print("File could not be deleted.") + + +

    + And finally, we have Java code that deletes files. We will call this class DeleteFile: +

    + + import java.io.File; From d02e194d8046000de92816655edf9d0d44e9afc3 Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Tue, 12 Aug 2025 15:50:16 -0400 Subject: [PATCH 135/357] Addendum to last commit. Duplicate xml id error was corrected. --- source/ch8_filehandling.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 0aaf05f..9d17070 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -477,7 +477,7 @@ The next example is Python code that can be used to delete files. This code cannot be run because importing os is not possible with the technologies used to write this book:

    - + import os file_name = "myfile.txt" if os.path.exists(file_name): From 2769ba1e5523cbfac638721f92ae5dbf7195a6e7 Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Wed, 13 Aug 2025 10:54:50 -0400 Subject: [PATCH 136/357] Final commit for now that fixes several issues in the issues queue (listed in PR). The chapter is in a state that could be usable in a class now, though, I believe there is still work to do. 8.2 and 8.4 take different approaches to presenting the content. I'm not sure which one would work better, but I think it would be a good idea to settle on one or the other at some point and rewrite one of these sections to match the presentation of the other. Additionally, I couldn't get the data files to work in the section on writing to files. Not sure what the problem was here. Finally, I was unable to test Java code in the book. I worry that the two Java code blocks in the section on deleting files will need to be combined into one code block for the deletion to work correctly. --- source/ch8_filehandling.ptx | 30 +++++++++++------------------- 1 file changed, 11 insertions(+), 19 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 9d17070..8544dc3 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -34,10 +34,6 @@ Note the use of import java.lang.Math; in the above to import the Math class. Unlike Python, Java requires explicit import for most libraries, including the Math class and many classes related to file handling.

    -

    - Much like the Math class, in order for your program to work with files you need use import. Java includes a class called File in the io library. This class allows you to create File objects, and use its public methods. the following code imports the File class and creates a File object called myFile. for now focus on how the class is imported and used in the program; We will cover the IOException class and createNewFile method later. -

    -

    Much like the Math class, in order for your program to work with files you need use import. Java includes a class called File in the io library. This class allows you to create File objects, and use its public methods.

    @@ -85,7 +81,9 @@ import java.io.File; public class CreateFile { public static void main(String[] args) { - + import java.io.File; + File myFile = new File("myfile.txt"); + System.out.println(myFile); } } @@ -99,7 +97,7 @@

    - Now let's learn how to make a file in Java. In Python. files can be made using the open() function on a file path that doesn't exist yet. Similarly, in Java you create a file by using the createNewFile() method on a File object. This method actually does the work of creating a file and saving it in the current working directory, and returns a boolean value of either true or false if the file is successfully created. We can use this method's possible return values in tandem with an try/catch structure to determine if the file was created, or catch the error if a file with that file name already exists in the directory. + Now let's learn how to make a file in Java. In Python. files can be made using the open() function on a file path that doesn't exist yet. Similarly, in Java you create a file by using the createNewFile() method on a File object. This method actually does the work of creating a file and saving it in the current working directory, and returns a boolean value of either true or false if the file is successfully created. We can use this method's possible return values in tandem with an if/else selection to determine if the file was created. Finally, we encase this code within try/catch blocks. This step is required in the Java code to be compiled. If try/catch blocks using IOException are not included, there will be compilation errors.

    @@ -263,7 +261,7 @@

    - In this next step, we will use the write() method from the FileWriter class. This Method will take any data within the parenthesis and write that data to the file selected. The write() method takes most standard data types. First, how this step is completed with Python: + In this next step, we will use the write() method from the FileWriter class. This method will take any data within the parenthesis and write that data to the file selected. The write() method takes most standard data types. First, how this step is completed with Python:

    @@ -281,20 +279,14 @@

    - You may have noticed the close() function being used after writing to the file. This is a very important step and must be included when working with files! Without using this method, the file may remain active in system resources even after the program is closed. This can lead file corruption or other terrible problems that are best avoided! + The close() method is being used after writing to the file. This is a very important step and must be included when working with files! Without using this method, the file may remain active in system resources even after the program is closed. This can lead file corruption or other terrible problems that are best avoided!

    Next, we will again add the required try/catch blocks utilizing the IOException class. Just like with creating files, the program will not compile without these crucial additions! We will also add some print statements to inform us of the success of the file write operation. First, a Python example:

    - -
    -                    1
    -                    2
    -                    3
    -                
    -
    + try: with open("myfile.txt", "w") as my_writer: @@ -325,7 +317,7 @@

    And that's it! We will add our code to the foundational code for a complete program. First, an example of equivalent Python code:

    - +
                         
                     
    @@ -359,7 +351,7 @@ public class WriteFile { public static void main(String[] args) { try { - FileWriter myWriter = new FileWriter("newfile.txt"); + FileWriter myWriter = new FileWriter("myfile.txt"); myWriter.write("File successfully updated!"); myWriter.close(); System.out.println("File successfully written to."); @@ -389,7 +381,7 @@

    Now, when we use write() method like before, the text will be appended if there is already tSext in the document. If we were to update our code to include the boolean argument:

    - +
                         
                     
    @@ -402,7 +394,7 @@ public class WriteFile { public static void main(String[] args) { try { - FileWriter myWriter = new FileWriter("newfile.txt", true); // true enables append mode + FileWriter myWriter = new FileWriter("myfile.txt", true); // true enables append mode myWriter.write("File successfully updated!"); myWriter.close(); System.out.println("File successfully written to."); From c2b00f50f2dc84dc0207c1a127ff1afbbde75462 Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Wed, 13 Aug 2025 11:30:21 -0400 Subject: [PATCH 137/357] Added a one-sentance definition for yield and added it to the index. --- source/ch4_conditionals.ptx | 57 ++++++++++++++++++------------------- 1 file changed, 28 insertions(+), 29 deletions(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 6b7a86b..5720ee1 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -194,39 +194,38 @@ Java also supports a switch statement that acts something like the eli

    switch The switch statement in Java provides a clean and efficient alternative to chaining multiple if-else conditions, especially when comparing a single variable against several constant values. It supports a variety of data types, including primitive types (byte, short, char, int), their wrapper classes, enumerations, and String (introduced in Java 7). Each case within a switch must be defined using a constant expression, and duplicate case values are not permitted. By default, control flow "falls through" from one case to the next unless a break, return, or throw statement is used to terminate execution.

    -

    switch expressions - Java 14 introduced switch expressions, enhancing functionality by allowing the switch to return values and eliminating fall-through via the -> arrow syntax. These expressions can even use yield within code blocks for more complex evaluations. It’s important to note that traditional switch statements do not support null values and will throw a NullPointerException if evaluated with null. As the language evolves, newer versions of Java continue to extend switch capabilities with features like pattern matching and enhanced type handling, making it a more powerful and expressive tool for decision-making in Java programs. -

    - - - +

    + switch expressions + yield + Java 14 introduced switch expressions, enhancing functionality by allowing the switch to return values and eliminating fall-through via the -> arrow syntax. These expressions can even use yield within code blocks for more complex evaluations. yield is used inside a switch expression’s block to produce the value of that expression, unlike break which simply exits a switch statement or loop. It’s important to note that traditional switch statements do not support null values and will throw a NullPointerException if evaluated with null. As the language evolves, newer versions of Java continue to extend switch capabilities with features like pattern matching and enhanced type handling, making it a more powerful and expressive tool for decision-making in Java programs. +

    -public class SwitchUp { - public static void main(String args[]) { - int grade = 85; - int tempgrade = grade / 10; - switch(tempgrade) { - case 10: - case 9: - System.out.println('A'); - break; - case 8: - System.out.println('B'); - break; - case 7: - System.out.println('C'); - break; - case 6: - System.out.println('A'); - break; - default: - System.out.println('F'); - } - } - } + public class SwitchUp { + public static void main(String args[]) { + int grade = 85; + int tempgrade = grade / 10; + switch(tempgrade) { + case 10: + case 9: + System.out.println('A'); + break; + case 8: + System.out.println('B'); + break; + case 7: + System.out.println('C'); + break; + case 6: + System.out.println('A'); + break; + default: + System.out.println('F'); + } + } + } From 21f03b9095b9322920b3dafc02856e647a6110d8 Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Wed, 13 Aug 2025 12:24:41 -0400 Subject: [PATCH 138/357] Moved the Naming conventions subsection from 6.3 to chapter 3 and made it a section instead of a subsection. --- source/ch3_javadatatypes.ptx | 38 ++++++++++++++++++++++++++++++++++ source/ch6_definingclasses.ptx | 37 --------------------------------- 2 files changed, 38 insertions(+), 37 deletions(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index ad28a23..070177b 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -798,6 +798,44 @@ public class HistoMap { Improve the program above to remove the punctuation.

    + +
    + Naming Conventions +

    + It is worth pointing out that Java has some very handy naming conventions. It is advisable to both use meaningful names and to follow these naming conventions while developing software in Java for good maintenance and readability of code. +

    + +

    +

      +
    • +

      + Class names should be nouns that are written in UpperCamelCase, namely with the first letter of each word capitalized including the first. + For example, ArrayList, Scanner, StringBuilder, System, etc. +

      +
    • + +
    • +

      + Method names use lowerCamelCase which start with a verb that describes the action they perform. This means that method names start with a lower case letter, and use upper case for each internal-word method names. For example, isInt(), nextLine(), getDenominator(), setNumerator(), etc. +

      +
    • + +
    • +

      + Instance variables of a class start with a lower case letter and use lowerCamelCase like method names. For example, count, totalAmount, etc. +

      +
    • + +
    • +

      + Constants are in all upper case letters or in upper snake case, which also known as screaming snake case, and which is a naming convention in which each word is written in uppercase letters, separated by underscores. + For example, Math.MAXINT or MAX_INT. +

      +
    • +
    +

    +
    +
    Summary & Reading Questions

      diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index 77f82be..ee13890 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -430,43 +430,6 @@ public class Fraction { - - - Naming Conventions -

      - It is worth pointing out that Java has some very handy naming conventions. It is advisable to both use meaningful names and to follow these naming conventions while developing software in Java for good maintenance and readability of code. -

      - -

      -

        -
      • -

        - Class names should be nouns that are written in UpperCamelCase, namely with the first letter of each word capitalized including the first. - For example, ArrayList, Scanner, StringBuilder, System, etc. -

        -
      • - -
      • -

        - Method names use lowerCamelCase which start with a verb that describes the action they perform. This means that method names start with a lower case letter, and use upper case for each internal-word method names. For example, isInt(), nextLine(), getDenominator(), setNumerator(), etc. -

        -
      • - -
      • -

        - Instance variables of a class start with a lower case letter and use lowerCamelCase like method names. For example, count, totalAmount, etc. -

        -
      • - -
      • -

        - Constants are in all upper case letters or in upper snake case, which also known as screaming snake case, and which is a naming convention in which each word is written in uppercase letters, separated by underscores. - For example, Math.MAXINT or MAX_INT. -

        -
      • -
      -

      -
    From 9839c070a6e976038a89db8037328cba0ff6dcd6 Mon Sep 17 00:00:00 2001 From: logananglin98 Date: Wed, 13 Aug 2025 12:41:02 -0400 Subject: [PATCH 139/357] Added stdin and tests tags to the code block. --- source/ch4_conditionals.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 6b7a86b..67839a0 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -316,7 +316,7 @@ The switch statement is not used very often, and we recommend you do not } } } - +

    From 67450321e7d662f954331f8d064e0ea7ef63307b Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Mon, 25 Aug 2025 13:16:05 -0400 Subject: [PATCH 140/357] fix 8.2 --- source/ch8_filehandling.ptx | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 8544dc3..9705cfd 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -73,20 +73,22 @@

    - We will now create a File object. It is important to create a meaningful name for the File object. We will call ours myFile. We will also call our class CreateFile + We will now create a File object. It is important to create a meaningful name for the File object. We will call ours myFile, and we will call our class CreateFileObject.

    - - - import java.io.File; - public class CreateFile { - public static void main(String[] args) { - import java.io.File; - File myFile = new File("myfile.txt"); - System.out.println(myFile); - } - } - + + +import java.io.File; + +public class CreateFile { + public static void main(String[] args) { + // First, create a File object that represents "myfile.txt" + File myFile = new File("myfile.txt"); + // Mext, print the file path (just the filename.) + System.out.println(myFile); + } +} + From 9f82b78047c9e065b1c182c94feb99451976ab00 Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Mon, 25 Aug 2025 17:50:25 -0400 Subject: [PATCH 141/357] add xml:ids to ch2 --- source/ch2_firstjavaprogram.ptx | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/source/ch2_firstjavaprogram.ptx b/source/ch2_firstjavaprogram.ptx index d911d4b..f129618 100644 --- a/source/ch2_firstjavaprogram.ptx +++ b/source/ch2_firstjavaprogram.ptx @@ -30,7 +30,7 @@ The best way to understand classes and objects is to see them in action. Let's define a Dog class in Python:

    - + class Dog: def __init__(self, name, breed, fur_color): @@ -71,7 +71,7 @@ Next, we will use this class to create a new Dog object. We will call this new Dog object my_dog:

    - + class Dog: def __init__(self, name, breed, fur_color): @@ -106,7 +106,7 @@ Now that we have created a Dog object using the class we defined, we can utilize the class's methods:

    - + class Dog: def __init__(self, name, breed, fur_color): @@ -167,7 +167,7 @@

    - + public class Hello { public static void main(String[] args) { @@ -188,7 +188,7 @@ public class Hello {

    - + $ javac Hello.java $ ls -l Hello.* @@ -208,7 +208,7 @@ $ ls -l Hello.*

    - + $ java Hello Hello World! @@ -285,7 +285,7 @@ $

    - + public class Hello { @@ -307,7 +307,7 @@ public class Hello {

    - + public static void main(String[] args) @@ -397,7 +397,7 @@ public static void main(String[] args)

    - + System.out.println("Hello World!"); @@ -426,7 +426,7 @@ System.out.println("Hello World!");

    - + System.out.println("Hello World"); System.out.println("Hello World") @@ -453,7 +453,7 @@ System.

    - + class Hello(object): @staticmethod @@ -468,7 +468,7 @@ class Hello(object):

    - + >>> Hello.main("") Hello World! From ba6a8354ad1c66cb1457ffa003f03a3b4d353a12 Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Mon, 25 Aug 2025 17:53:16 -0400 Subject: [PATCH 142/357] Revert "add xml:ids to ch2" This reverts commit 9f82b78047c9e065b1c182c94feb99451976ab00. --- source/ch2_firstjavaprogram.ptx | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/source/ch2_firstjavaprogram.ptx b/source/ch2_firstjavaprogram.ptx index f129618..d911d4b 100644 --- a/source/ch2_firstjavaprogram.ptx +++ b/source/ch2_firstjavaprogram.ptx @@ -30,7 +30,7 @@ The best way to understand classes and objects is to see them in action. Let's define a Dog class in Python:

    - + class Dog: def __init__(self, name, breed, fur_color): @@ -71,7 +71,7 @@ Next, we will use this class to create a new Dog object. We will call this new Dog object my_dog:

    - + class Dog: def __init__(self, name, breed, fur_color): @@ -106,7 +106,7 @@ Now that we have created a Dog object using the class we defined, we can utilize the class's methods:

    - + class Dog: def __init__(self, name, breed, fur_color): @@ -167,7 +167,7 @@

    - + public class Hello { public static void main(String[] args) { @@ -188,7 +188,7 @@ public class Hello {

    - + $ javac Hello.java $ ls -l Hello.* @@ -208,7 +208,7 @@ $ ls -l Hello.*

    - + $ java Hello Hello World! @@ -285,7 +285,7 @@ $

    - + public class Hello { @@ -307,7 +307,7 @@ public class Hello {

    - + public static void main(String[] args) @@ -397,7 +397,7 @@ public static void main(String[] args)

    - + System.out.println("Hello World!"); @@ -426,7 +426,7 @@ System.out.println("Hello World!");

    - + System.out.println("Hello World"); System.out.println("Hello World") @@ -453,7 +453,7 @@ System.

    - + class Hello(object): @staticmethod @@ -468,7 +468,7 @@ class Hello(object):

    - + >>> Hello.main("") Hello World! From 291413d5744906a3989ed7891d3ecdf84d77b0dc Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Mon, 25 Aug 2025 18:05:28 -0400 Subject: [PATCH 143/357] add xml:ids to programs in ch3 --- source/ch2_firstjavaprogram.ptx | 2 +- source/ch3_javadatatypes.ptx | 16 ++++++++-------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/source/ch2_firstjavaprogram.ptx b/source/ch2_firstjavaprogram.ptx index d911d4b..16be255 100644 --- a/source/ch2_firstjavaprogram.ptx +++ b/source/ch2_firstjavaprogram.ptx @@ -30,7 +30,7 @@ The best way to understand classes and objects is to see them in action. Let's define a Dog class in Python:

    - + class Dog: def __init__(self, name, breed, fur_color): diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index 070177b..830e0c2 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -95,7 +95,7 @@

    - + def main(): fahr = int(input("Enter the temperature in F: ")) @@ -110,7 +110,7 @@ main()

    - + import java.util.Scanner; public class TempConv { @@ -431,7 +431,7 @@ if (myAnimal instanceof Dog) {

    - + def main(): count = [0]*10 @@ -528,7 +528,7 @@ Here is the Java code needed to write the exact same program:

    - + import java.util.Scanner; import java.util.ArrayList; @@ -655,11 +655,11 @@ public class Histo { Arrays

    - As I said at the outset of this section, we are going to use Java ArrayLists because they are easier to use and more closely match the way that Python lists behave. However, if you look at Java code on the internet or even in your Core Java books you are going to see examples of something called arrays. In fact you have already seen one example of an array declared in the ‘Hello World’ program. Lets rewrite this program to use primitive arrays rather than array lists. + As was said at the outset of this section, we are going to use Java ArrayLists because they are easier to use and more closely match the way that Python lists behave. However, if you look at Java code on the internet or even in your core Java books you are going to see examples of something called an array. In fact, you have already seen one example of an array declared in the ‘Hello World’ program. Let's rewrite this program to use primitive arrays rather than array lists.

    - + import java.util.Scanner; import java.io.File; @@ -708,7 +708,7 @@ public class HistoArray {

    - + def main(): data = open('alice30.txt') @@ -755,7 +755,7 @@ main()

    - + import java.util.Scanner; import java.util.ArrayList; From 1938c229260c843c0e3293544349560d9dce55f8 Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Mon, 25 Aug 2025 18:19:01 -0400 Subject: [PATCH 144/357] add xml:ids to all programs in ch4 --- source/ch4_conditionals.ptx | 38 ++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 508e926..04b1e6b 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -16,7 +16,7 @@ In Python the simple if statement is written as:

    - + score = 95 if score >= 90: @@ -26,7 +26,7 @@ if score >= 90:

    In Java, this same pattern requires two changes: the condition must be in parentheses (), and the code block must be enclosed in curly braces {}.

    - + public class SimpleIfExample { public static void main(String[] args) { @@ -40,15 +40,15 @@ if score >= 90:

    Once again you can see that in Java the curly braces define a block rather than indentation. - In Java the parenthesis around the condition are required because it is technically a function that evaluates to True or False. + In Java, the parentheses around the condition are required because it is technically a function that evaluates to True or False.

    -
    +
    Using the <c>if</c> - <c>else</c> Statement

    The Java equivalent follows the same syntactical rules as before.

    - + age = 16 if age >= 18: @@ -58,7 +58,7 @@ if score >= 90: - + public class IfElseExample { public static void main(String[] args) { @@ -84,7 +84,7 @@ if score >= 90:

    - + grade = int(input('enter a grade')) if grade < 60: @@ -101,11 +101,11 @@ else:

    -In Java we have a couple of ways to write this. +In Java, we have a couple of ways to write this.

    - + public class ElseIf { public static void main(String args[]) { @@ -133,12 +133,12 @@ public class ElseIf {

    -We can get even closer to the elif statement by taking advantage of the Java rule that a single statement does not need to be enclosed in curly braces. Since the if is the only statement used in each else we can get away with the following. +We can get even closer to the elif statement by taking advantage of the Java rule that a single statement does not need to be enclosed in curly braces. Since the if is the only statement used in each else block, we can get away with the following.

    - + public class ElseIf { public static void main(String args[]) { @@ -167,9 +167,9 @@ Java also supports a switch statement that acts something like the eli

    - Depending on your knowledge and experience with Python you may already be familiar and questioning why we are not using the match statement in our Python examples. The answer is that this book currently runs its active code examples using Python 3.7, which does not support the match statement which was introduced in Python 3.10. Below is an example of the match statement similar to our grade method. + Depending on your knowledge and experience with Python you may be questioning why we are not using the match statement in our Python examples. The answer is that this book currently runs its active code examples using Python 3.7, which does not support the match statement which was introduced in Python 3.10. Below is an example of the match statement similar to our grade method.

    - + Match Case Example grade = 85 @@ -201,7 +201,7 @@ Java also supports a switch statement that acts something like the eli Java 14 introduced switch expressions, enhancing functionality by allowing the switch to return values and eliminating fall-through via the -> arrow syntax. These expressions can even use yield within code blocks for more complex evaluations. yield is used inside a switch expression’s block to produce the value of that expression, unlike break which simply exits a switch statement or loop. It’s important to note that traditional switch statements do not support null values and will throw a NullPointerException if evaluated with null. As the language evolves, newer versions of Java continue to extend switch capabilities with features like pattern matching and enhanced type handling, making it a more powerful and expressive tool for decision-making in Java programs.

    - + public class SwitchUp { public static void main(String args[]) { @@ -241,7 +241,7 @@ The switch statement is not used very often, and we recommend you do not In Python, if you want a program to continue running when an error has occurred, you can use try-except blocks to handle exceptions. If you wanted to write a program that asks the user to enter a whole number and then squares that number, you could use the following code to do so:

    - + number = int(input("Please enter a whole number: ")) squared = number ** 2 @@ -253,7 +253,7 @@ The switch statement is not used very often, and we recommend you do not The Java code that would perform the same task is a little more complex and utilizes the Scanner class for input.

    - + import java.util.Scanner; @@ -275,7 +275,7 @@ The switch statement is not used very often, and we recommend you do not This code works well, but will end with an exception if the user types anything other than a whole number (such as 12.5 or two). If we wanted to ensure the code will continue to run until the user enters the correct format, we could add try-except (Python) or try-catch (Java) blocks within a while loop that iterates until the user enter the correct code. Adding try-except blocks and a while loop to the Python code will look something like this:

    - + while True: try: @@ -292,7 +292,7 @@ The switch statement is not used very often, and we recommend you do not Now that we have Python code that will continuously prompt the user until they enter a whole number, let's look at Java code that accomplishes the same task. Like most other equivalent Java code blocks, this code has a lot of extra bits that are necessary to get working code.

    - + import java.util.Scanner; import java.util.InputMismatchException; @@ -439,7 +439,7 @@ of an assignment statement. The following table summarizes how this works:

    Using this operator can make code shorter and more readable in cases where a simple conditional assignment is needed.

    - + class Main { public static void main(String[] args) { From 7287ff6150fef786efad4bf6653ae16c9d34fe77 Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Mon, 25 Aug 2025 18:22:42 -0400 Subject: [PATCH 145/357] replace depreciated input with code --- source/ch8_filehandling.ptx | 44 ++++++++++++++++++------------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 9705cfd..63621ae 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -10,17 +10,17 @@ File handling is an integral part of programming. Most programming languages have the ability to create, read from, write to, and delete, files. In Python, most built-in libraries are available without needing to explicitly import additional packages, but some libraries like math do need to be imported. Consider the following.

    - + import math print(math.sqrt(25)) - +

    Delete the first line that says import math and see what happens. The import math is needed. The same program in Java would look like this:

    - + import java.lang.Math; public class SquareRoot { @@ -28,7 +28,7 @@ System.out.println(Math.sqrt(25)); } } - +

    Note the use of import java.lang.Math; in the above to import the Math class. Unlike Python, Java requires explicit import for most libraries, including the Math class and many classes related to file handling. @@ -107,7 +107,7 @@ public class CreateFile {

    - + filename = "newfile.txt" print("Attempting to write to '" + filename + "' using 'w' mode...") try: @@ -118,7 +118,7 @@ public class CreateFile { # This would only catch other unexpected errors print("An unexpected error occurred during write: " + str(e)) - +

    @@ -126,7 +126,7 @@ public class CreateFile {

    - + import java.io.File; import java.io.IOException; @@ -146,7 +146,7 @@ public class CreateFile { } } } - + @@ -179,7 +179,7 @@ public class CreateFile { - + filename = "myfile.txt" try: # Attempt to open the file in read mode ('r') @@ -190,7 +190,7 @@ public class CreateFile { except: #catches if the file doesn't exist or can't be written to print("file could not be opened") - +

    @@ -198,7 +198,7 @@ public class CreateFile {

    - + import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; @@ -216,7 +216,7 @@ public class CreateFile { } } } - +

    You may have noticed that there are some new methods you haven't seen yet. The hasNextLine() method checks if there is a next line in the file, and returns false if there isn't. This method allows us to iterate over every line till there is no next line. The nextLine() method of the Scanner object returns the next line in the file as a string. @@ -325,7 +325,7 @@ public class CreateFile { - + try: with open("myfile.txt", "w") as my_writer: my_writer.write("File successfully updated!") @@ -334,7 +334,7 @@ public class CreateFile { print("An error occurred.") import traceback traceback.print_exc() - +

    @@ -346,7 +346,7 @@ public class CreateFile { - + import java.io.FileWriter; import java.io.IOException; @@ -363,7 +363,7 @@ public class CreateFile { } } } - + @@ -389,7 +389,7 @@ public class CreateFile { - + import java.io.FileWriter; import java.io.IOException; @@ -406,7 +406,7 @@ public class CreateFile { } } } - +

    @@ -444,7 +444,7 @@ public class CreateFile {

    - + import java.io.File; import java.io.IOException; @@ -464,7 +464,7 @@ public class CreateFile { } } } - +

    @@ -490,7 +490,7 @@ public class CreateFile { - + import java.io.File; public class DeleteFile { @@ -503,7 +503,7 @@ public class CreateFile { } } } - +

    From eda9708761aa7634d85d644856dc30e5ed8e9bbb Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Mon, 25 Aug 2025 18:31:34 -0400 Subject: [PATCH 146/357] add xml:ids to all programs in ch5 --- source/ch5_loopsanditeration.ptx | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/source/ch5_loopsanditeration.ptx b/source/ch5_loopsanditeration.ptx index 07f33c9..ff221d2 100644 --- a/source/ch5_loopsanditeration.ptx +++ b/source/ch5_loopsanditeration.ptx @@ -15,7 +15,7 @@ For example:

    - + for i in range(10): print(i) @@ -26,7 +26,7 @@ for i in range(10): In Java, we would write this as:

    - + public class DefiniteLoopExample { public static void main(String[] args) { @@ -65,7 +65,7 @@ public class DefiniteLoopExample { If you want to start at 100, stop at 0 and count backward by 5, the Python loop would be written as:

    - + for i in range(100, -1, -5): print(i) @@ -76,7 +76,7 @@ for i in range(100, -1, -5): In Java, we would write this as:

    - + public class DefiniteLoopBackward { public static void main(String[] args) { @@ -97,7 +97,7 @@ public class DefiniteLoopBackward { In Python, we can iterate over a list as follows:

    - + l = [1, 1, 2, 3, 5, 8, 13, 21] for fib in l: @@ -109,7 +109,7 @@ for fib in l: In Java we can iterate over an ArrayList of integers too. Note that this requires importing the ArrayList class.

    - + import java.util.ArrayList; @@ -134,10 +134,10 @@ public class ForEachArrayListExample {

    This example stretches the imagination a bit, and in fact points out one area where Java's primitive arrays are easier to use than an array list. - In fact all primitive arrays can be used in a for each loop. + In fact, all primitive arrays can be used in a for each loop.

    - + public class ForEachArrayExample { public static void main(String[] args) { @@ -154,7 +154,7 @@ public class ForEachArrayExample { To iterate over the characters in a string in Java do the following:

    - + public class StringIterationExample { public static void main(String[] args) { @@ -176,7 +176,7 @@ public class StringIterationExample { Both Python and Java support the while loop, which continues to execute as long as a condition is true. Here is a simple example in Python that counts down from 5:

    - + i = 5 while i > 0: @@ -186,9 +186,9 @@ while i > 0:

    - In Java we add parenthesis and curly braces. Here is the same countdown loop in Java: + In Java, we add parentheses and curly braces. Here is the same countdown loop in Java:

    - + public class WhileLoopExample { public static void main(String[] args) { @@ -210,7 +210,7 @@ public class WhileLoopExample { For example, the following loop will execute once even though the condition is initially false.

    - + public class DoWhileExample { public static void main(String[] args) { From b93f714322012c76c778735f379ed8dcd5db09f9 Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Mon, 25 Aug 2025 18:52:02 -0400 Subject: [PATCH 147/357] add xml:ids to all programs in ch6 --- source/ch6_definingclasses.ptx | 60 +++++++++++++++++----------------- 1 file changed, 30 insertions(+), 30 deletions(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index ee13890..f2e6d55 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -66,7 +66,7 @@

    - + class Fraction: def __init__(self, num, den): @@ -137,7 +137,7 @@

    - + public class Fraction { private Integer numerator; @@ -152,7 +152,7 @@

    - + Fraction f = new Fraction(1,2); Integer y = f.numerator * 10; @@ -168,7 +168,7 @@

    - + public Integer getNumerator() { return numerator; @@ -199,7 +199,7 @@ public void setDenominator(Integer denominator) {

    - + public Fraction(Integer top, Integer bottom) { num = top; @@ -220,7 +220,7 @@ public Fraction(Integer top, Integer bottom) {

    - + public Fraction(Integer num, Integer den) { this.num = num; @@ -276,7 +276,7 @@ public Fraction(Integer num, Integer den) {

    - + public Fraction add(Fraction otherFrac) { Integer newNum = otherFrac.getDenominator() * this.numerator + @@ -296,11 +296,11 @@ public Fraction add(Fraction otherFrac) {

    Second, you will notice that the method makes use of the this variable. In this method, this is not necessary, because there is no ambiguity about the numerator and denominator variables. - So this version of the code is equivalent: + So the following version of the code is equivalent:

    - + public Fraction add(Fraction otherFrac) { Integer newNum = otherFrac.getDenominator() * numerator + @@ -361,7 +361,7 @@ public Fraction add(Fraction otherFrac) {

    - + public Fraction(Integer num) { this.numerator = num; @@ -385,7 +385,7 @@ public Fraction add(Integer other) {

    - + public class Fraction { private Integer numerator; @@ -441,7 +441,7 @@ public class Fraction {

    - + Fraction@6ff3c5b5 @@ -531,7 +531,7 @@ Fraction@6ff3c5b5

    - + public String toString() { return numerator.toString() + "/" + denominator.toString(); @@ -549,18 +549,18 @@ public String toString() {

    - + object1 == object2

    - is NOT the same as + is NOT the same as:

    - + object1.equals(object2) @@ -571,7 +571,7 @@ object1.equals(object2)

    - + public boolean equals(Fraction other) { Integer num1 = this.numerator * other.getDenominator(); @@ -610,7 +610,7 @@ public boolean equals(Fraction other) {

    - + public class Fraction extends Number { ... @@ -661,7 +661,7 @@ public class Fraction extends Number {

    - + public double doubleValue() { return numerator.doubleValue() / denominator.doubleValue(); @@ -696,7 +696,7 @@ public long longValue() {

    - + public void test(Number a, Number b) { a.add(b); @@ -745,7 +745,7 @@ public void test(Number a, Number b) {

    - + int compareTo(T o) Compares this object with the specified object for order. Returns a @@ -763,7 +763,7 @@ iff y.compareTo(x) throws an exception.)

    - + public class Fraction extends Number implements Comparable<Fraction> { ... @@ -777,7 +777,7 @@ public class Fraction extends Number implements Comparable<Fraction> {

    - + public int compareTo(Fraction other) { Integer num1 = this.numerator * other.getDenominator(); @@ -794,12 +794,12 @@ public int compareTo(Fraction other) {

    Suppose that you wanted to write a Student class so that the class could keep track of the number of students it had created. Although you could do this with a global counter variable that is an ugly solution. - The right way to do it is to use a static variable. - In Python we could do this as follows: + The right way to do it is to use a static variable. + In Python, we could do this as follows:

    - + class Student: numStudents = 0 @@ -816,11 +816,11 @@ main()

    - In Java we would write this same example using a static declaration. + In Java, we would write this same example using a static declaration.

    - + public class Student { public static Integer numStudents = 0; @@ -855,7 +855,7 @@ public class Student {

    - + private static Integer gcd(Integer m, Integer n) { while (m % n != 0) { @@ -878,7 +878,7 @@ private static Integer gcd(Integer m, Integer n) {

    - + import java.util.ArrayList; import java.util.Collections; From faa8a521bfe4d7227796abb3a8ccc4780a2a9570 Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Mon, 25 Aug 2025 20:49:54 -0400 Subject: [PATCH 148/357] add xml:id to ch2 --- source/ch2_firstjavaprogram.ptx | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/source/ch2_firstjavaprogram.ptx b/source/ch2_firstjavaprogram.ptx index 16be255..5f4d958 100644 --- a/source/ch2_firstjavaprogram.ptx +++ b/source/ch2_firstjavaprogram.ptx @@ -71,7 +71,7 @@ Next, we will use this class to create a new Dog object. We will call this new Dog object my_dog:

    - + class Dog: def __init__(self, name, breed, fur_color): @@ -106,7 +106,7 @@ Now that we have created a Dog object using the class we defined, we can utilize the class's methods:

    - + class Dog: def __init__(self, name, breed, fur_color): @@ -163,11 +163,11 @@
    >>> main() "Hello World!" >>>

    - Now lets look at the same program written in Java: + Now let's look at the same program written in Java:

    - + public class Hello { public static void main(String[] args) { @@ -188,7 +188,7 @@ public class Hello {

    - + $ javac Hello.java $ ls -l Hello.* @@ -208,7 +208,7 @@ $ ls -l Hello.*

    - + $ java Hello Hello World! @@ -285,7 +285,7 @@ $

    - + public class Hello { @@ -307,7 +307,7 @@ public class Hello {

    - + public static void main(String[] args) @@ -397,7 +397,7 @@ public static void main(String[] args)

    - + System.out.println("Hello World!"); @@ -426,7 +426,7 @@ System.out.println("Hello World!");

    - + System.out.println("Hello World"); System.out.println("Hello World") @@ -453,7 +453,7 @@ System.

    - + class Hello(object): @staticmethod @@ -468,7 +468,7 @@ class Hello(object):

    - + >>> Hello.main("") Hello World! From 2ff5c3eead310eb7d5df65a617d177f71bf794e4 Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Mon, 25 Aug 2025 20:55:21 -0400 Subject: [PATCH 149/357] fix duplicate xml:id --- source/ch2_firstjavaprogram.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch2_firstjavaprogram.ptx b/source/ch2_firstjavaprogram.ptx index 5f4d958..1413416 100644 --- a/source/ch2_firstjavaprogram.ptx +++ b/source/ch2_firstjavaprogram.ptx @@ -453,7 +453,7 @@ System.

    - + class Hello(object): @staticmethod From 4c9a785e3b7b49c2cf4677509a7a4ca65e4aaae2 Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Tue, 26 Aug 2025 08:22:01 -0400 Subject: [PATCH 150/357] add import java.util.Arrays; --- source/ch7_recursion.ptx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/source/ch7_recursion.ptx b/source/ch7_recursion.ptx index 7dc933a..d2cd7bc 100644 --- a/source/ch7_recursion.ptx +++ b/source/ch7_recursion.ptx @@ -233,6 +233,8 @@ main()

    +import java.util.Arrays; + public class ArrayProcessor { public static int sumArray(int[] arr) { // Handle empty array From 33f0f1bf9e74bda503a89bf8d0c059c1ea1944b9 Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Tue, 26 Aug 2025 08:25:26 -0400 Subject: [PATCH 151/357] improve explanation of helper method --- source/ch7_recursion.ptx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/ch7_recursion.ptx b/source/ch7_recursion.ptx index d2cd7bc..1ed5804 100644 --- a/source/ch7_recursion.ptx +++ b/source/ch7_recursion.ptx @@ -265,11 +265,11 @@ public class ArrayProcessor {

    - Compare these improved versions with the earlier problematic ones. Notice how much cleaner the method calls become: processor.sum_array(numbers) in Python and sumArray(numbers) in Java. Users no longer need to worry about providing the correct starting index or understanding the internal mechanics of the recursion. The helper method pattern creates a clear separation between what users need to know (just pass an array) and the implementation details (tracking the index through recursion). + Compare these improved versions with the earlier problematic ones. Notice how much cleaner the method calls become: processor.sum_array(numbers) in Python and sumArray(numbers) in Java. Users no longer need to worry about providing a starting index or understanding the internal mechanics of the recursion. The helper method pattern creates a clear separation between what users need to know (just pass an array) and the implementation details (tracking the index through recursion).

    - This helper method pattern is essential when your recursive algorithm needs to track additional state (like array positions, accumulated values, or depth counters) that the original caller shouldn't need to provide or care about. It's a fundamental pattern and technique you'll likely use frequently in recursive problem solving. + This helper method pattern is invaluable when your recursive algorithm needs to track additional state detailes (like array positions, accumulated values, or depth counters) that the original caller shouldn't need to know about or care about. It's a fundamental pattern and technique you'll likely use frequently in recursive problem solving.

    From cbaee736052581ec9d095bf7e7803a8a18d8309b Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Tue, 26 Aug 2025 08:28:47 -0400 Subject: [PATCH 152/357] fix typo --- source/ch7_recursion.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch7_recursion.ptx b/source/ch7_recursion.ptx index 1ed5804..a0d2c01 100644 --- a/source/ch7_recursion.ptx +++ b/source/ch7_recursion.ptx @@ -269,7 +269,7 @@ public class ArrayProcessor {

    - This helper method pattern is invaluable when your recursive algorithm needs to track additional state detailes (like array positions, accumulated values, or depth counters) that the original caller shouldn't need to know about or care about. It's a fundamental pattern and technique you'll likely use frequently in recursive problem solving. + This helper method pattern is invaluable when your recursive algorithm needs to track additional state details (like array positions, accumulated values, or depth counters) that the original caller shouldn't need to know about or care about. It's a fundamental pattern and technique you'll likely use frequently in recursive problem solving.

    From dc2ce86a9823cd54fa67a1cd53ca88b25022ac1b Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Tue, 26 Aug 2025 08:59:09 -0400 Subject: [PATCH 153/357] improve code and clarity of Deleting Files section --- source/ch8_filehandling.ptx | 54 +++++++++++++++++-------------------- 1 file changed, 24 insertions(+), 30 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 63621ae..47e6171 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -440,7 +440,7 @@ public class CreateFile { Deleting Files

    - Finally, we will take a look at using Java to delete files. This one is pretty straight-forward and follows the structure used to create files. This time, however, try/catch blocks are not needed for the program to compile. First, the CreateFile class from before will be used to create a file: + Lastly, we will take a look at using Java to delete a file. This is pretty straight-forward and follows the structure used to create files. Here is the CreateFile class from before that will be used to create a file that we will soon delete:

    @@ -467,47 +467,41 @@ public class CreateFile {
    -

    - The next example is Python code that can be used to delete files. This code cannot be run because importing os is not possible with the technologies used to write this book: -

    - - - import os - file_name = "myfile.txt" - if os.path.exists(file_name): - try: - os.remove(file_name) - print("Deleted", file_name) - except Exception as e: - print("File could not be deleted.") - else: - print("File could not be deleted.") -

    - And finally, we have Java code that deletes files. We will call this class DeleteFile: + And finally, we have Java code that deletes a file. We will call this class DeleteFile:

    - import java.io.File; - - public class DeleteFile { - public static void main(String[] args) { - File myFile = new File("myfile.txt"); - if (myFile.delete()) { - System.out.println("Deleted " + myFile.getName()); - } else { - System.out.println("File could not be deleted."); - } - } +import java.io.File; +import java.io.IOException; + +public class DeleteFile { + public static void main(String[] args) { + try { + File myFile = new File("myfile.txt"); + + // Create the file (does nothing if it already exists) + myFile.createNewFile(); + System.out.println("File created: " + myFile.getName()); + + // Delete the file + if (myFile.delete()) { + System.out.println("Deleted " + myFile.getName()); } + } catch (IOException e) { + e.printStackTrace(); + } + } +} +

    - This is almost identical to the code within the try block of the CreateFile class we made earlier. The main difference is the use of the delete() method. This method will delete any file with the name provided when creating the myFile object. Similar to the createNewFile() method, it will return true if the file existed and could be deleted, and false if the file could not be deleted. + Note that this is almost identical to the code within the try block of the CreateFile class we made earlier. The key difference is the use of the delete() method. This method will delete any file with the name that was linked to the myFile object. Similar to the createNewFile() method, it will return true if the file exists and can be deleted, and false if the file cannot be deleted.

    From ba444bc3786926253c4b6c20645caf64cf471ebb Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Tue, 26 Aug 2025 09:01:58 -0400 Subject: [PATCH 154/357] improve language --- source/ch8_filehandling.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 47e6171..89909cb 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -501,7 +501,7 @@ public class DeleteFile {

    - Note that this is almost identical to the code within the try block of the CreateFile class we made earlier. The key difference is the use of the delete() method. This method will delete any file with the name that was linked to the myFile object. Similar to the createNewFile() method, it will return true if the file exists and can be deleted, and false if the file cannot be deleted. + Note that this is almost identical to the code within the try block of the CreateFile class that we made earlier. The key difference is the use of the delete() method which will delete the file with the name that was linked to the myFile object. Similar to the createNewFile() method, it will return true if the file exists and can be deleted, and false if the file cannot be deleted.

    From 2758e878703584fd361351e7727c1d1d1cdf84bf Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Tue, 26 Aug 2025 09:46:46 -0400 Subject: [PATCH 155/357] improve ternary code section --- source/ch4_conditionals.ptx | 44 +++++++++++++++++++++---------------- 1 file changed, 25 insertions(+), 19 deletions(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 04b1e6b..0290b45 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -385,17 +385,15 @@ The switch statement is not used very often, and we recommend you do not -
    - Boolean Operators +
    + The Ternary Operator

    Boolean operators simple comparisons compound Boolean expressions The conditionals used in the if statement can be Boolean variables, simple comparisons, and compound Boolean expressions.

    ternary operator -Java also supports the boolean expression using the ternary operator -condition ? trueValue : falseValue. This operator tests a condition as part -of an assignment statement. The following table summarizes how this works: +Java also provides the ternary operator condition ? valueIfTrue : valueIfFalse, which lets you use a boolean test directly inside an assignment. If the condition is true, the first value is chosen; otherwise, the second value is used. The table below summarizes how it works:

    @@ -437,27 +435,35 @@ of an assignment statement. The following table summarizes how this works:

    -Using this operator can make code shorter and more readable in cases where a simple conditional assignment is needed. +Using this operator can make code shorter and more readable in cases where a simple conditional assignment is needed. See the following as an example where we see the same logic implemented in two different ways.

    - + - class Main { - public static void main(String[] args) { - int a = 4; - int x = 2; - - // Using the ternary operator - a = (a % 2 == 0) ? a * a : 3 * x - 1; +public class Ternary { + public static void main(String[] args) { + int a = 4; + int x = 2; + int outp; + + // ternary: + outp = (a % 2 == 0) ? (a * a) : (3 * x - 1); + System.out.println("Result: " + outp); + + // Equivalent using if/else + if (a % 2 == 0) { + outp = a * a; + } else { + outp = 3 * x - 1; + } - System.out.println("Result: " + a); - } - } - + System.out.println("Result: " + outp); + } +}

    - In this example we are using this ternary operator to assign a value to a based on whether a is even or odd. If a is even, it will be squared; if odd, it will be instead be calculated as 3 * x - 1. This is a concise way to write conditional assignments in Java. However, it should be used reasonably, as it can make code less readable if overused or used in complex expressions. + In this example we are using this ternary operator to assign a value to a based on whether a is even or odd. If a is even, it will be squared; if odd, it will be instead be calculated as 3 * x - 1. This is a concise way to write conditional assignments in Java. However, you might want to use it sparingly, as it can make code less readable if overused or used with complex expressions.

    From 3fcd04d4d22e541780235e35cfb71c724f3f98a4 Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Tue, 26 Aug 2025 09:50:43 -0400 Subject: [PATCH 156/357] improve output --- source/ch4_conditionals.ptx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 0290b45..770f388 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -447,7 +447,7 @@ public class Ternary { // ternary: outp = (a % 2 == 0) ? (a * a) : (3 * x - 1); - System.out.println("Result: " + outp); + System.out.println("ternary result: " + outp); // Equivalent using if/else if (a % 2 == 0) { @@ -456,7 +456,7 @@ public class Ternary { outp = 3 * x - 1; } - System.out.println("Result: " + outp); + System.out.println("if/else result: " + outp); } }
    From e35c6b378d117f04105b6919eac78ceeebf43a8a Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Tue, 26 Aug 2025 10:04:26 -0400 Subject: [PATCH 157/357] improve switch section --- source/ch4_conditionals.ptx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 770f388..4b972df 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -232,6 +232,8 @@ Java also supports a switch statement that acts something like the eli

    The switch statement is not used very often, and we recommend you do not use it. First, it is not as powerful as the else if model because the switch variable can only be compared for equality with an integer or enumerated constant. Second, it is very easy to forget to put in the break statement, so it is more error-prone. If the break statement is left out then then the next alternative will be automatically executed. For example, if the grade was 95 and the break was omitted from the case 9: alternative then the program would print(out both A and B.)

    +

    + Finally, the switch statement does not support relational expressions such as greater than or less than. So you cannot use it to completely replace the elif. Even with the new features of Java 14+ the switch statement is still limited to constant comparisons using equality.

    @@ -479,7 +481,7 @@ public class Ternary {
  • - Java's switch statement is similar to Python's match statement, but it only supports equality checks against constant values and does not evaluate relational expressions like greater than or less than. + Java's switch statement is similar to Python's match statement, but it only supports equality checks against constant values and does not evaluate relational expressions like greater than or less than.

  • From 72896c90e0ef02adf6fa4067d31ce05a23f08129 Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Tue, 26 Aug 2025 10:10:09 -0400 Subject: [PATCH 158/357] clarifications of match-case --- source/ch4_conditionals.ptx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 4b972df..186c522 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -162,12 +162,12 @@ public class ElseIf { Using the <c>switch</c> Statement

    -Java also supports a switch statement that acts something like the elif statement of Python under certain conditions. To write the grade program using a switch statement we would use the following: +Java also supports a switch statement that acts something like the elif or Python match statement of Python under certain conditions. To write the grade program using a switch statement we would use the following:

    - Depending on your knowledge and experience with Python you may be questioning why we are not using the match statement in our Python examples. The answer is that this book currently runs its active code examples using Python 3.7, which does not support the match statement which was introduced in Python 3.10. Below is an example of the match statement similar to our grade method. + The match - case statement was introduced in Python 3.10, so doesn't run in earlier version of Python. Here is an example using Python's match - case structure.

    Match Case Example @@ -192,7 +192,7 @@ Java also supports a switch statement that acts something like the eli

    switch - The switch statement in Java provides a clean and efficient alternative to chaining multiple if-else conditions, especially when comparing a single variable against several constant values. It supports a variety of data types, including primitive types (byte, short, char, int), their wrapper classes, enumerations, and String (introduced in Java 7). Each case within a switch must be defined using a constant expression, and duplicate case values are not permitted. By default, control flow "falls through" from one case to the next unless a break, return, or throw statement is used to terminate execution. + The switch statement in Java provides an alternative to chaining multiple if-else conditions, when comparing a single variable against several constant values. It supports a variety of data types, including primitive types (byte, short, char, int), their wrapper classes, enumerations, and String (introduced in Java 7). Each case within a switch must be defined using a constant expression, and duplicate case values are not permitted. By default, control flow "falls through" from one case to the next unless a break, return, or throw statement is used to terminate execution.

    From e6af616fd5c284c436ab4eb0874b46a3957acd15 Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Tue, 26 Aug 2025 10:20:01 -0400 Subject: [PATCH 159/357] add comments about integer division --- source/ch4_conditionals.ptx | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 186c522..8238a56 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -173,6 +173,7 @@ Java also supports a switch statement that acts something like the eli Match Case Example grade = 85 + # Convert grade to a scale of 0-10 using integer division tempgrade = grade // 10 def grading(tempgrade): match grade: @@ -204,8 +205,9 @@ Java also supports a switch statement that acts something like the eli public class SwitchUp { - public static void main(String args[]) { + public static void main(String args[]) { int grade = 85; + // Convert grade to a scale of 0-10 using integer division int tempgrade = grade / 10; switch(tempgrade) { case 10: @@ -224,7 +226,7 @@ Java also supports a switch statement that acts something like the eli default: System.out.println('F'); } - } + } } From 982643d39ac626aaac00a19ef9bd1036cf43525a Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Tue, 26 Aug 2025 10:29:03 -0400 Subject: [PATCH 160/357] remove redundency --- source/ch4_conditionals.ptx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 8238a56..382e671 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -162,8 +162,8 @@ public class ElseIf { Using the <c>switch</c> Statement

    -Java also supports a switch statement that acts something like the elif or Python match statement of Python under certain conditions. To write the grade program using a switch statement we would use the following: -

    +Java also supports a switch statement that acts something like the elif or Python match statement under certain conditions. To write the grade program using a switch statement we would use the following: +

    From e675e9733c66d894a7c2557db5240af15f56fcd3 Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Tue, 26 Aug 2025 10:36:22 -0400 Subject: [PATCH 161/357] hot-fix --- source/ch4_conditionals.ptx | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 382e671..0b32d00 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -163,12 +163,12 @@ public class ElseIf {

    Java also supports a switch statement that acts something like the elif or Python match statement under certain conditions. To write the grade program using a switch statement we would use the following: -

    The match - case statement was introduced in Python 3.10, so doesn't run in earlier version of Python. Here is an example using Python's match - case structure. -

    +

    Match Case Example @@ -190,7 +190,6 @@ Java also supports a switch statement that acts something like the eli print(grading(tempgrade)) -

    switch The switch statement in Java provides an alternative to chaining multiple if-else conditions, when comparing a single variable against several constant values. It supports a variety of data types, including primitive types (byte, short, char, int), their wrapper classes, enumerations, and String (introduced in Java 7). Each case within a switch must be defined using a constant expression, and duplicate case values are not permitted. By default, control flow "falls through" from one case to the next unless a break, return, or throw statement is used to terminate execution. From ff1b772ee5806d29ddc3c72b7b27f5ccee2552cf Mon Sep 17 00:00:00 2001 From: Puskar Chapagain Date: Fri, 26 Jun 2026 16:52:02 -0400 Subject: [PATCH 162/357] Added description for JVM --- source/ch2_firstjavaprogram.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch2_firstjavaprogram.ptx b/source/ch2_firstjavaprogram.ptx index 1413416..b64d843 100644 --- a/source/ch2_firstjavaprogram.ptx +++ b/source/ch2_firstjavaprogram.ptx @@ -240,7 +240,7 @@ $ JVM byte code The job of the compiler is to turn your java code into language that the Java Virtual Machine (JVM) can understand. - We call the code that the JVM understands byte code. + JVM is a bytecode interpreter that allows Java programs to run on any platform without having to modify them. The JVM interprets the byte code much like the Python interpreter interprets your Python. However since byte code is much closer to the native language of the computer it can run faster.

    From 65c62eb36152a9f1aacecb53d986dd064834ad72 Mon Sep 17 00:00:00 2001 From: Puskar Chapagain Date: Mon, 29 Jun 2026 09:02:23 -0400 Subject: [PATCH 163/357] Added the JVM definition and cleaned up the paragraph --- source/ch2_firstjavaprogram.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch2_firstjavaprogram.ptx b/source/ch2_firstjavaprogram.ptx index b64d843..9b62f7d 100644 --- a/source/ch2_firstjavaprogram.ptx +++ b/source/ch2_firstjavaprogram.ptx @@ -241,7 +241,7 @@ $ byte code The job of the compiler is to turn your java code into language that the Java Virtual Machine (JVM) can understand. JVM is a bytecode interpreter that allows Java programs to run on any platform without having to modify them. - The JVM interprets the byte code much like the Python interpreter interprets your Python. + The JVM interprets the byte code much like the Python interpreter does with Python. However since byte code is much closer to the native language of the computer it can run faster.

    From d9ceaa8f713f99b4dd05db836d782f6b9ada6bf9 Mon Sep 17 00:00:00 2001 From: Galina Pokitko Date: Mon, 29 Jun 2026 15:39:00 -0400 Subject: [PATCH 164/357] Changed line 8 to 7 --- source/ch3_javadatatypes.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index 830e0c2..4b75654 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -692,7 +692,7 @@ public class HistoArray {

    - The main difference between this example and the previous example is that we declare count to be an Array of integers. We also can initialize short arrays directly using the syntax shown on line 8. Then notice that on line 22 we can use the square bracket notation to index into an array. + The main difference between this example and the previous example is that we declare count to be an Array of integers. We also can initialize short arrays directly using the syntax shown on line 7. Then notice that on line 22 we can use the square bracket notation to index into an array.

    From 0c00f45be645e25324fafc2a3b1af2c4c8456da2 Mon Sep 17 00:00:00 2001 From: Galina Pokitko Date: Mon, 29 Jun 2026 16:10:35 -0400 Subject: [PATCH 165/357] removed unclear line references and instead replaced with the code in c tags --- source/ch3_javadatatypes.ptx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index 4b75654..ef3342d 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -692,8 +692,8 @@ public class HistoArray {

    - The main difference between this example and the previous example is that we declare count to be an Array of integers. We also can initialize short arrays directly using the syntax shown on line 7. Then notice that on line 22 we can use the square bracket notation to index into an array. -

    + The main difference between this example and the previous example is that we declare count to be an Array of integers. We also can initialize short arrays directly using the syntax shown here: Integer[] count = {0,0,0,0,0,0,0,0,0,0}Then notice that we can use the square bracket notation count[idx] to index into an array. +

    From 4f44f970beab4801c4f48385a2b4e67b86671975 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Wed, 22 Jul 2026 18:30:52 +0300 Subject: [PATCH 166/357] added listing and comments to the blocks of code in 2.1 --- source/ch2_firstjavaprogram.ptx | 51 ++++++++++++++++++++++----------- 1 file changed, 35 insertions(+), 16 deletions(-) diff --git a/source/ch2_firstjavaprogram.ptx b/source/ch2_firstjavaprogram.ptx index 9b62f7d..be1728b 100644 --- a/source/ch2_firstjavaprogram.ptx +++ b/source/ch2_firstjavaprogram.ptx @@ -30,32 +30,39 @@ The best way to understand classes and objects is to see them in action. Let's define a Dog class in Python:

    - - + + + class Dog: + """ A simple Dog class definition. """ def __init__(self, name, breed, fur_color): + # constructor method to create a Dog object self.name = name self.breed = breed self.fur_color = fur_color - self.trained = False + self.trained = False # dogs are not trained by default print("Dog named " + self.name + " created!") def bark(self): + # method to make the dog bark print(self.name + " says woof!") def sit(self): - if self.trained: + # method to make the dog sit + if self.trained: # check if the dog has been trained otherwise it will not sit print(self.name + " sits.") else: print(self.name + " has not been trained.") def train(self): + # method to train the dog, which will set the trained attribute to True self.trained = True - - + + +

    - Let's unpack what is going on in this code. The first line is where we declare the class definition and name it Dog. Next, we have a special method called __init__. This __init__ method is the constructor and is required for every Python class definition. Within the __init__ method, attributes are defined. As you can see, the attributes name, breed, and fur_color must be defined when creating a Dog object using this class definition, but the trained attribute is defined within the constructor and is initialized as False. We can also have the __init__ method run any code, such as the print statement informing us that a Dog object was created. + Let's unpack what is going on in . The first line is where we declare the class definition and name it Dog. Next, we have a special method called __init__. This __init__ method is the constructor and is required for every Python class definition. Within the __init__ method, attributes are defined. As you can see, the attributes name, breed, and fur_color must be defined when creating a Dog object using this class definition, but the trained attribute is defined within the constructor and is initialized as False. We can also have the __init__ method run any code, such as the print statement informing us that a Dog object was created.

    @@ -70,11 +77,13 @@

    Next, we will use this class to create a new Dog object. We will call this new Dog object my_dog:

    - - + + class Dog: + """ A simple Dog class definition. """ def __init__(self, name, breed, fur_color): + # constructor method to create a Dog object self.name = name self.breed = breed self.fur_color = fur_color @@ -82,22 +91,25 @@ print("Dog named " + self.name + " created!") def bark(self): + # method to make the dog bark print(self.name + " says woof!") def sit(self): - if self.trained: + # method to make the dog sit + if self.trained: # check if the dog has been trained otherwise it will not sit print(self.name + " sits.") else: print(self.name + " has not been trained.") def train(self): + # method to train the dog, which will set the trained attribute to True self.trained = True - + # Create a Dog object called my_dog my_dog = Dog("Rex", "pug", "brown") - +

    In the final line of code, we have created an object called my_dog. We have initialized its attributes, setting name to Rex, breed to pug, and fur_color to brown.

    @@ -106,10 +118,13 @@ Now that we have created a Dog object using the class we defined, we can utilize the class's methods:

    - + + class Dog: + """ A simple Dog class definition. """ def __init__(self, name, breed, fur_color): + # constructor method to create a Dog object self.name = name self.breed = breed self.fur_color = fur_color @@ -117,27 +132,31 @@ print("Dog named " + self.name + " created!") def bark(self): + # method to make the dog bark print(self.name + " says woof!") def sit(self): + # method to make the dog sit if self.trained: print(self.name + " sits.") else: print(self.name + " has not been trained.") def train(self): + # method to train the dog, which will set the trained attribute to True self.trained = True my_dog = Dog("Rex", "pug", "brown") - my_dog.bark() - my_dog.sit() + my_dog.bark() # call the bark method + my_dog.sit() # call the sit method +

    - When running the code above, the line Rex has not ben trained. will appear in the output when calling the sit() method. Try adding a one or more lines of code so that Rex sits. appears in the output! + When running , the line Rex has not ben trained. will appear in the output when calling the sit() method. Try adding a one or more lines of code so that Rex sits. appears in the output!

    From 06860e07605292868f7ca79a49ae701d8075d561 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Wed, 22 Jul 2026 18:37:04 +0300 Subject: [PATCH 167/357] added a reference to 2.1.2 in paragraph text --- source/ch2_firstjavaprogram.ptx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/source/ch2_firstjavaprogram.ptx b/source/ch2_firstjavaprogram.ptx index be1728b..34e6ea9 100644 --- a/source/ch2_firstjavaprogram.ptx +++ b/source/ch2_firstjavaprogram.ptx @@ -87,7 +87,7 @@ self.name = name self.breed = breed self.fur_color = fur_color - self.trained = False + self.trained = False # dogs are not trained by default print("Dog named " + self.name + " created!") def bark(self): @@ -111,7 +111,7 @@

    - In the final line of code, we have created an object called my_dog. We have initialized its attributes, setting name to Rex, breed to pug, and fur_color to brown. + In the final line of code in , we have created an object called my_dog. We have initialized its attributes, setting name to Rex, breed to pug, and fur_color to brown.

    @@ -128,7 +128,7 @@ self.name = name self.breed = breed self.fur_color = fur_color - self.trained = False + self.trained = False # dogs are not trained by default print("Dog named " + self.name + " created!") def bark(self): From 195e43e6a9cbfe6a816488ab85cf33819aadc87e Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Wed, 22 Jul 2026 20:20:49 +0300 Subject: [PATCH 168/357] fixed a typo in 8.2 --- source/ch8_filehandling.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 89909cb..ba5d0cf 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -84,7 +84,7 @@ public class CreateFile { public static void main(String[] args) { // First, create a File object that represents "myfile.txt" File myFile = new File("myfile.txt"); - // Mext, print the file path (just the filename.) + // Next, print the file path (just the filename.) System.out.println(myFile); } } From 2c36fb61539d717119df76881cd226a48b58eace Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Wed, 22 Jul 2026 22:55:50 +0300 Subject: [PATCH 169/357] added a title for table 3.1.1 --- source/ch3_javadatatypes.ptx | 1 + 1 file changed, 1 insertion(+) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index ef3342d..68fd5bf 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -18,6 +18,7 @@

    + Comparison between Java's primitive and object data types. Primitive From ace692ab66bd59040094e0afb40a2e2d62d88103 Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Thu, 23 Jul 2026 09:49:23 -0400 Subject: [PATCH 170/357] fix typo in pull request --- source/ch2_firstjavaprogram.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch2_firstjavaprogram.ptx b/source/ch2_firstjavaprogram.ptx index 34e6ea9..9f0e546 100644 --- a/source/ch2_firstjavaprogram.ptx +++ b/source/ch2_firstjavaprogram.ptx @@ -156,7 +156,7 @@

    - When running , the line Rex has not ben trained. will appear in the output when calling the sit() method. Try adding a one or more lines of code so that Rex sits. appears in the output! + When running , the line Rex has not been trained. will appear in the output when calling the sit() method. Try adding a one or more lines of code so that Rex sits. appears in the output!

    From 5f94fdd3558ff8440829376f29b2dafc16a46617 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Thu, 23 Jul 2026 17:23:18 +0300 Subject: [PATCH 171/357] fixed the format of python in 2.2 --- source/ch2_firstjavaprogram.ptx | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/source/ch2_firstjavaprogram.ptx b/source/ch2_firstjavaprogram.ptx index 9b62f7d..04994ae 100644 --- a/source/ch2_firstjavaprogram.ptx +++ b/source/ch2_firstjavaprogram.ptx @@ -156,12 +156,19 @@ To be clear, lets look at a “complicated” version of hello world for Python:

    -
    def main(): print("Hello World!")
    + + + def main(): + print("Hello World!") + + +

    Remember that we can define this program right at the Python command line and then run it:

    -
    >>> main() "Hello World!" >>>
    +
    >>> main() 
    +Hello World! 

    Now let's look at the same program written in Java:

    From 8e988a7dd2d0fc49f48387fd22f9bf061ac376da Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Thu, 23 Jul 2026 17:24:13 +0300 Subject: [PATCH 172/357] made the Hello World in the paragraph capatalized --- source/ch2_firstjavaprogram.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch2_firstjavaprogram.ptx b/source/ch2_firstjavaprogram.ptx index 04994ae..ac5da42 100644 --- a/source/ch2_firstjavaprogram.ptx +++ b/source/ch2_firstjavaprogram.ptx @@ -151,7 +151,7 @@
    Lets look at a Java Program

    - A time-honored tradition in Computer Science is to write a program called “hello world.” The “hello world” program is simple and easy. + A time-honored tradition in Computer Science is to write a program called “Hello World.” The “Hello World” program is simple and easy. There are no logic errors to make, so getting it to run relies only on understanding the syntax. To be clear, lets look at a “complicated” version of hello world for Python:

    From f337694b2bdd67f989127bfc838e8b061d376c07 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Thu, 23 Jul 2026 20:41:26 +0300 Subject: [PATCH 173/357] add listing to blocks of code 2.2 --- source/ch2_firstjavaprogram.ptx | 44 ++++++++++++++++++++++++--------- 1 file changed, 32 insertions(+), 12 deletions(-) diff --git a/source/ch2_firstjavaprogram.ptx b/source/ch2_firstjavaprogram.ptx index 8e7cdb8..6bab910 100644 --- a/source/ch2_firstjavaprogram.ptx +++ b/source/ch2_firstjavaprogram.ptx @@ -175,25 +175,34 @@ To be clear, lets look at a “complicated” version of hello world for Python:

    - + + def main(): print("Hello World!") +

    Remember that we can define this program right at the Python command line and then run it:

    -
    >>> main() 
    -Hello World! 
    + + + +>>> main() +Hello World! + + +

    Now let's look at the same program written in Java:

    - + + public class Hello { public static void main(String[] args) { @@ -202,6 +211,7 @@ public class Hello { } +

    What we see is that at the core there are a few similarities, such as a main and the string “Hello World”. However, there is a lot more stuff around the edges that make it harder to see the core of the program. Do not worry! An important skill for a computer scientist is to learn what to ignore and what to look at carefully. You will soon find that there are some elements of Java that will fade into the background as you become used to seeing them. @@ -214,7 +224,8 @@ public class Hello {

    - + + $ javac Hello.java $ ls -l Hello.* @@ -222,6 +233,7 @@ $ ls -l Hello.* -rw-r--r-- 1 bmiller bmiller 117 Jul 19 17:46 Hello.java +

    The command javac compiles our java source code into compiled byte code and saves it in a file called Hello.class. @@ -234,13 +246,16 @@ $ ls -l Hello.*

    - + + $ java Hello Hello World! $ + +

    Now you may be wondering what good is that extra step? What does compiling do for us? There are a couple of important benefits we get from compiling: @@ -310,7 +325,7 @@ $ On line 1 we see that we are declaring a class called Hello:

    - + public class Hello { @@ -451,8 +466,8 @@ System.out.println("Hello World!"); I would not encourage you to write your code like this, but you should know that it is legal.

    - - + + System.out.println("Hello World"); System.out.println("Hello World") @@ -467,6 +482,7 @@ System. ; +

    The last two lines of the hello world program simply close the two blocks using }. @@ -478,8 +494,8 @@ System. If we wanted to translate the Java back to Python we would have something like the following class definition.

    - - + + class Hello(object): @staticmethod @@ -487,6 +503,7 @@ class Hello(object): print("Hello World!") +

    Notice that we used the decorator @staticmethod to tell the Python interpreter that main is going to be a static method. @@ -494,13 +511,16 @@ class Hello(object):

    - + + >>> Hello.main("") Hello World! >>> + +
    Summary & Reading Questions From 3b67541fa6d7c6104916b5799c38dc7ce9e20986 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Thu, 23 Jul 2026 20:55:16 +0300 Subject: [PATCH 174/357] added references inside the paraggraog --- source/ch2_firstjavaprogram.ptx | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/source/ch2_firstjavaprogram.ptx b/source/ch2_firstjavaprogram.ptx index 6bab910..1a89717 100644 --- a/source/ch2_firstjavaprogram.ptx +++ b/source/ch2_firstjavaprogram.ptx @@ -163,16 +163,15 @@

    Now, we have a full class definition and have utilized its methods. Class definitions in Java will be covered thoroughly in chapter 6. For now, it is important to know that Python programs can be written without using classes at all. Java, on the other hand, requires all code to reside in a class. This will be discussed in the next section.

    - - - +
    +
    Lets look at a Java Program

    A time-honored tradition in Computer Science is to write a program called “Hello World.” The “Hello World” program is simple and easy. There are no logic errors to make, so getting it to run relies only on understanding the syntax. - To be clear, lets look at a “complicated” version of hello world for Python: + To be clear, lets look at a “complicated” version of hello world for Python in .

    @@ -185,7 +184,7 @@

    - Remember that we can define this program right at the Python command line and then run it: + Remember that we can define this program right at the Python command line and then run it as per .

    @@ -214,13 +213,13 @@ public class Hello {

    - What we see is that at the core there are a few similarities, such as a main and the string “Hello World”. However, there is a lot more stuff around the edges that make it harder to see the core of the program. Do not worry! An important skill for a computer scientist is to learn what to ignore and what to look at carefully. You will soon find that there are some elements of Java that will fade into the background as you become used to seeing them. + Based on , what we see in the code is that at the core there are a few similarities, such as a main and the string “Hello World”. However, there is a lot more stuff around the edges that make it harder to see the core of the program. Do not worry! An important skill for a computer scientist is to learn what to ignore and what to look at carefully. You will soon find that there are some elements of Java that will fade into the background as you become used to seeing them.

    interpreter compile - The first question you probably have about this little program is “How do I run it?” Running a Java program is not as simple as running a Python program. The first thing you need to do with a Java program is compile it. The first big difference between Java and Python is that Python is an interpreted language. We could run our Python programs in the Python interpreter and we were quite happy to do that. Java makes running programs a two step process. First we must type the hello world program into a file and save that file using the name Hello.java The file name must be the same as the public class you define in the file. Once we have saved the file we compile it from the command line as follows: + The first question you probably have about this little program is “How do I run it?” Running a Java program is not as simple as running a Python program. The first thing you need to do with a Java program is compile it. The first big difference between Java and Python is that Python is an interpreted language. We could run our Python programs in the Python interpreter and we were quite happy to do that. Java makes running programs a two step process. First we must type the hello world program into a file and save that file using the name Hello.java The file name must be the same as the public class you define in the file. Once we have saved the file we compile it from the command line as .

    @@ -242,7 +241,7 @@ $ ls -l Hello.*

    - Now that we have compiled our java source code we can run the compiled code using the java command. + Now that we have compiled our java source code we can run the compiled code using the java command as per .

    @@ -462,7 +461,7 @@ System.out.println("Hello World!"); Java statements can spread across many lines, but the compiler knows it has reached the end of a statement when it encounters a ;. In Python, it is not required (or recommend) to use semicolons in this way, but whitespace is meaningful. In contrast, in Java semicolons are required to end statements, but whitespace is not considered meaningful. - This is a very important difference to remember! In Java, the following statements are all legal and equivalent. + This is a very important difference to remember! In Java, the statements in are all legal and equivalent. I would not encourage you to write your code like this, but you should know that it is legal.

    @@ -491,7 +490,7 @@ System.

    - If we wanted to translate the Java back to Python we would have something like the following class definition. + If we wanted to translate the Java back to Python we would have something like class definition.

    From 4a32f234a27c67995ce572fbfe21074d082c7f9d Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Thu, 23 Jul 2026 20:59:49 +0300 Subject: [PATCH 175/357] fixed python that was attributed to java --- source/ch2_firstjavaprogram.ptx | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/source/ch2_firstjavaprogram.ptx b/source/ch2_firstjavaprogram.ptx index 1a89717..b00d4cf 100644 --- a/source/ch2_firstjavaprogram.ptx +++ b/source/ch2_firstjavaprogram.ptx @@ -490,11 +490,11 @@ System.

    - If we wanted to translate the Java back to Python we would have something like class definition. + If we wanted to translate the Java back to Python we would have something like class definition.

    - - + + class Hello(object): @staticmethod @@ -506,12 +506,12 @@ class Hello(object):

    Notice that we used the decorator @staticmethod to tell the Python interpreter that main is going to be a static method. - The impact of this is that we don’t have to, indeed we should not, use self as the first parameter of the main method! Using this definition we can call the main method in a Python session like this: + The impact of this is that we don’t have to, indeed we should not, use self as the first parameter of the main method! Using this definition we can call the main method in a Python session like .

    - - + + >>> Hello.main("") Hello World! From f3c7d95d45e56e6bea0a302bb288c6c5f3599830 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Thu, 23 Jul 2026 22:17:37 +0300 Subject: [PATCH 176/357] added listing tags to 3.1 --- source/ch3_javadatatypes.ptx | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index 68fd5bf..6220e0b 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -95,8 +95,8 @@ If this program were run on the command-line, you would enter the temperature when prompted – the Javascript pop-up for input is only an artifact of the digital textbook.

    - - + + def main(): fahr = int(input("Enter the temperature in F: ")) @@ -105,13 +105,15 @@ def main(): main() +

    Next, lets look at the Java equivalent. If this program were run on the command-line, you would enter the temperature when prompted – the “Input for Program” text box is only an artifact of the digital textbook.

    - + + import java.util.Scanner; public class TempConv { @@ -128,7 +130,8 @@ public class TempConv { } - + +

    There are several new concepts introduced in this example. We will look at them in the following order:

    From 25ef435e60823ef521911ac1ee3dd129636fecb9 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Thu, 23 Jul 2026 22:27:38 +0300 Subject: [PATCH 177/357] added linking to the parts --- source/ch3_javadatatypes.ptx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index 6220e0b..bd331cb 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -91,7 +91,7 @@

    - Let’s look at a simple Python function which converts a Fahrenheit temperature to Celsius. + is a simple Python function which converts a Fahrenheit temperature to Celsius. If this program were run on the command-line, you would enter the temperature when prompted – the Javascript pop-up for input is only an artifact of the digital textbook.

    @@ -108,7 +108,7 @@ main()

    - Next, lets look at the Java equivalent. If this program were run on the command-line, you would enter the temperature when prompted – the “Input for Program” text box is only an artifact of the digital textbook. + Next, is the Java equivalent. If this program were run on the command-line, you would enter the temperature when prompted – the “Input for Program” text box is only an artifact of the digital textbook.

    @@ -131,7 +131,7 @@ public class TempConv {
    - +

    There are several new concepts introduced in this example. We will look at them in the following order:

    From aa7b28735788047d6f2c432cd069b7364a267ec1 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Thu, 23 Jul 2026 22:38:20 +0300 Subject: [PATCH 178/357] fixed a block in the later sections --- source/ch3_javadatatypes.ptx | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index bd331cb..e33d9b1 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -250,7 +250,9 @@ public class TempConv { For Python programmers, the following error is likely to be even more common. Suppose we forgot the declaration for cel and instead left line 6 blank. What would happen when we type javac TempConv.java on the command line?

    -
    +            +            
    +            
                 TempConv.java:13: cannot find symbol 
                 symbol  : variable cel 
                 location: class TempConv 
    @@ -262,10 +264,12 @@ public class TempConv {
                 System.out.println("The temperature in C is: " + cel); 
                 ^ 
                 2 errors
    -            
    + +
    +

    - When you see the first kind of error, where the symbol is on the left side of the equals sign, it usually means that you have not declared the variable. If you have ever tried to use a Python variable that you have not initialized the second error message will be familiar to you. The difference here is that we see the message before we ever try to test our program. More common error messages are discussed in the section . + When you see the first kind of error in , where the symbol is on the left side of the equals sign, it usually means that you have not declared the variable. If you have ever tried to use a Python variable that you have not initialized the second error message will be familiar to you. The difference here is that we see the message before we ever try to test our program. More common error messages are discussed in the section .

    From babba04ae075be8285943f23d65e359cc8c7bb86 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Thu, 23 Jul 2026 23:15:15 +0300 Subject: [PATCH 179/357] made blocks active, changed some wording to work with these changes --- source/ch2_firstjavaprogram.ptx | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/source/ch2_firstjavaprogram.ptx b/source/ch2_firstjavaprogram.ptx index b00d4cf..e6f65c4 100644 --- a/source/ch2_firstjavaprogram.ptx +++ b/source/ch2_firstjavaprogram.ptx @@ -31,10 +31,10 @@

    - + class Dog: - """ A simple Dog class definition. """ + """ A simple Dog class definition. """ def __init__(self, name, breed, fur_color): # constructor method to create a Dog object self.name = name @@ -175,7 +175,7 @@

    - + def main(): print("Hello World!") @@ -184,7 +184,11 @@

    - Remember that we can define this program right at the Python command line and then run it as per . + Remember that we can define this program right at the Python command line and then run it with main() Try it in . +

    + +

    + The command line interface of the program is shown in .

    @@ -494,7 +498,7 @@ System.

    - + class Hello(object): @staticmethod @@ -506,21 +510,25 @@ class Hello(object):

    Notice that we used the decorator @staticmethod to tell the Python interpreter that main is going to be a static method. - The impact of this is that we don’t have to, indeed we should not, use self as the first parameter of the main method! Using this definition we can call the main method in a Python session like . + The impact of this is that we don’t have to, indeed we should not, use self as the first parameter of the main method! Using this definition we can call the main method in a Python session with Hello.main(""). Try it in .

    +

    + The command line interface of the program is shown in . +

    >>> Hello.main("") Hello World! ->>>
    + +
    Summary & Reading Questions

      From 553c5acab6751339b3e4635b4fef0512f7659306 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 24 Jul 2026 16:55:45 +0300 Subject: [PATCH 180/357] fixed typos in chapter 3 --- source/ch3_javadatatypes.ptx | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index e33d9b1..ffca06d 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -87,7 +87,7 @@ - A data type fundamentally defines a set of values and the operations you can perform on them. For instance, you can do math with int and double values, but not with boolean values. This is simlar to Python, where you can perform arithmetic on integers and floats, but not on booleans or strings. + A data type fundamentally defines a set of values and the operations you can perform on them. For instance, you can do math with int and double values, but not with boolean values. This is similar to Python, where you can perform arithmetic on integers and floats, but not on booleans or strings.

      @@ -448,7 +448,7 @@ def main(): count[int(line)] = count[int(line)] + 1 idx = 0 for num in count: - print(idx, " occured ", num, " times.") + print(idx, " occurred ", num, " times.") idx += 1 main() @@ -565,7 +565,7 @@ public class Histo { } idx = 0; for(Integer i : count) { - System.out.println(idx + " occured " + i + " times."); + System.out.println(idx + " occurred " + i + " times."); idx++; } } @@ -691,7 +691,7 @@ public class HistoArray { } idx = 0; for(Integer i : count) { - System.out.println(idx + " occured " + i + " times."); + System.out.println(idx + " occurred " + i + " times."); idx++; } } @@ -795,7 +795,7 @@ public class HistoMap { count.put(word,++wordCount); } for(String i : count.keySet()) { - System.out.printf("%-20s occured %5d times\n", i, count.get(i) ); + System.out.printf("%-20s occurred %5d times\n", i, count.get(i) ); } } } From c4e7aa47d0fed0de291877fba6c938905c3ddf0f Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 24 Jul 2026 17:18:33 +0300 Subject: [PATCH 181/357] added comments to code blocks in 3.1 --- source/ch3_javadatatypes.ptx | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index e33d9b1..39defc9 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -99,8 +99,9 @@ def main(): - fahr = int(input("Enter the temperature in F: ")) - cel = (fahr - 32) * 5.0/9.0 + """ Program to convert a temperature from Fahrenheit to Celsius. """ + fahr = int(input("Enter the temperature in F: ")) # get the temperature in Fahrenheit + cel = (fahr - 32) * 5.0/9.0 # convert to Celsius print("the temperature in C is: ", cel) main() @@ -115,16 +116,19 @@ main()

      -import java.util.Scanner; +import java.util.Scanner; // import the Scanner class to read input from the user + /** + * Program to convert a temperature from Fahrenheit to Celsius in Java. + */ public class TempConv { public static void main(String[] args) { - Double fahr; + Double fahr; Double cel; - Scanner in; - in = new Scanner(System.in); + Scanner in; // declare a Scanner variable called in + in = new Scanner(System.in); // create a Scanner object to read input from the user System.out.println("Enter the temperature in F: "); - fahr = in.nextDouble(); - cel = (fahr - 32) * 5.0/9.0; + fahr = in.nextDouble(); // read the temperature in Fahrenheit from the user + cel = (fahr - 32) * 5.0/9.0; // convert to Celsius System.out.println("The temperature in C is: " + cel); } } From 1089a3a054b28f3d61e667cf0f298f99a20c73f5 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 24 Jul 2026 21:39:55 +0300 Subject: [PATCH 182/357] made blocks of code interactive --- source/ch3_javadatatypes.ptx | 109 +++++++++++++++++++++++++++-------- 1 file changed, 85 insertions(+), 24 deletions(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index e3ffe69..624b05c 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -296,18 +296,35 @@ public class TempConv {

      Implicit typecasting happens automatically when converting a value from a smaller data type to a larger one, as there is no risk of losing information. For example, you can assign an int to a double without any special syntax.

      -
       
      -        int myInt = 10;
      -        double myDouble = myInt; // Automatic casting from int to double
      -        
      - + + + + + void main() { + int myInt = 10; + double myDouble = myInt; // Automatic casting from int to double + + System.out.println(myDouble); +} + + + +

      Explicit typecasting is required when converting from a larger data type to a smaller one, as you might lose data. You must do this manually by placing the target type in parentheses () before the value.

      -
      -        double originalDouble = 9.78;
      -        int castedInt = (int) originalDouble; // Explicitly casts double to int. The value of castedInt is now 9.
      -        
      + + + +void main() { + double originalDouble = 9.78; + int castedInt = (int) originalDouble; // Explicitly casts double to int. The value of castedInt is now 9. + + System.out.println(castedInt); +} + + +

      Besides primitive types, type casting is also a fundamental concept when working with objects, especially within an inheritance hierarchy. This involves converting an object reference from one class type to another, typically between a superclass and a subclass. This is often referred to as upcasting and downcasting. @@ -315,8 +332,12 @@ public class TempConv {

      Let's imagine we have a simple class hierarchy: an Animal superclass and a Dog subclass.

      -
      +
      +    +    
      +        
       class Animal {
      +
           public void makeSound() {
               System.out.println("The animal makes a sound.");
           }
      @@ -327,37 +348,77 @@ class Dog extends Animal {
               System.out.println("The dog barks!");
           }
       }
      -    
      + +
      +

      Upcasting (Implicit): Upcasting is casting a subclass instance to a superclass reference type. This is always safe because a subclass object is guaranteed to have all the methods and properties of its superclass. Therefore, upcasting is done implicitly by the compiler.

      -
      +    +    
      +        
      +class Animal {
      +    public void makeSound() {
      +        System.out.println("The animal makes a sound.");
      +    }
      +}
      +
      +class Dog extends Animal {
      +    public void bark() {
      +        System.out.println("The dog barks!");
      +    }
      +}
      +
      +void main() {
       // A Dog object is created, but the reference is of type Animal.
       // This is implicit upcasting.
      -Animal myAnimal = new Dog(); 
      +    Animal myAnimal = new Dog(); 
       
      -myAnimal.makeSound(); // This is valid, as makeSound() is defined in Animal.
      +    myAnimal.makeSound(); // This is valid, as makeSound() is defined in Animal.
       
       // myAnimal.bark(); // This would cause a compile-time error!
       // The compiler only knows about the methods in the Animal reference type.
      -    
      +} + + + +

      Downcasting (Explicit): Downcasting is casting a superclass reference back to its original subclass type. This is potentially unsafe because the superclass reference might not actually point to an object of the target subclass. You must perform an explicit cast. If you cast to the wrong type, Java will throw a ClassCastException at runtime.

      To safely downcast, you should first check the object's type using the instanceof operator.

      -
      -// 'myAnimal' is an Animal reference, but it points to a Dog object.
      -if (myAnimal instanceof Dog) {
      -    // The check passed, so this downcast is safe.
      -    Dog myDog = (Dog) myAnimal;
      -
      -    // Now we can access methods specific to the Dog class.
      -    myDog.bark(); // This is now valid.
      +    +    
      +        
      +class Animal {
      +    public void makeSound() {
      +        System.out.println("The animal makes a sound.");
      +    }
       }
      -    
      + +class Dog extends Animal { + public void bark() { + System.out.println("The dog barks!"); + } +} + +void main() { + + Animal myAnimal = new Dog(); + + // 'myAnimal' is an Animal reference, but it points to a Dog object. + if (myAnimal instanceof Dog myDog) { + // Now we can access methods specific to the Dog class. + myDog.bark(); + } +} + + + +

      In this example, we first create a Dog object and assign it to an Animal reference (upcasting). Then, we check if the Animal reference is actually pointing to a Dog object before downcasting it back to a Dog reference. From 7e349a086625946ca8f56836174d808c2d5eda26 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 24 Jul 2026 21:48:53 +0300 Subject: [PATCH 183/357] added listing in paragraphs --- source/ch3_javadatatypes.ptx | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index 624b05c..15bb291 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -294,13 +294,13 @@ public class TempConv {

      - Implicit typecasting happens automatically when converting a value from a smaller data type to a larger one, as there is no risk of losing information. For example, you can assign an int to a double without any special syntax. + Implicit typecasting happens automatically when converting a value from a smaller data type to a larger one, as there is no risk of losing information. For example, you can assign an int to a double without any special syntax as shown in .

      - void main() { +void main() { int myInt = 10; double myDouble = myInt; // Automatic casting from int to double @@ -311,7 +311,7 @@ public class TempConv {

      - Explicit typecasting is required when converting from a larger data type to a smaller one, as you might lose data. You must do this manually by placing the target type in parentheses () before the value. + Explicit typecasting is required when converting from a larger data type to a smaller one, as you might lose data. You must do this manually by placing the target type in parentheses () before the value as shown in .

      @@ -330,7 +330,7 @@ void main() { Besides primitive types, type casting is also a fundamental concept when working with objects, especially within an inheritance hierarchy. This involves converting an object reference from one class type to another, typically between a superclass and a subclass. This is often referred to as upcasting and downcasting.

      - Let's imagine we have a simple class hierarchy: an Animal superclass and a Dog subclass. + In , we have a simple class hierarchy: an Animal superclass and a Dog subclass.

      @@ -353,7 +353,7 @@ class Dog extends Animal {

      - Upcasting (Implicit): Upcasting is casting a subclass instance to a superclass reference type. This is always safe because a subclass object is guaranteed to have all the methods and properties of its superclass. Therefore, upcasting is done implicitly by the compiler. + Upcasting (Implicit): Upcasting is casting a subclass instance to a superclass reference type. This is always safe because a subclass object is guaranteed to have all the methods and properties of its superclass. Therefore, upcasting is done implicitly by the compiler as .

      @@ -388,7 +388,7 @@ void main() { Downcasting (Explicit): Downcasting is casting a superclass reference back to its original subclass type. This is potentially unsafe because the superclass reference might not actually point to an object of the target subclass. You must perform an explicit cast. If you cast to the wrong type, Java will throw a ClassCastException at runtime.

      - To safely downcast, you should first check the object's type using the instanceof operator. + To safely downcast, you should first check the object's type using the instanceof operator as shown in .

      @@ -421,7 +421,7 @@ void main() {

      - In this example, we first create a Dog object and assign it to an Animal reference (upcasting). Then, we check if the Animal reference is actually pointing to a Dog object before downcasting it back to a Dog reference. + In , we first create a Dog object and assign it to an Animal reference (upcasting). Then, we check if the Animal reference is actually pointing to a Dog object before downcasting it back to a Dog reference.

    From a5cfcd022571beab991bb999622b1bb0643d118b Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 24 Jul 2026 22:04:32 +0300 Subject: [PATCH 184/357] added comments to the code sections --- source/ch3_javadatatypes.ptx | 31 +++++++++++++++++++++++++++---- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index 15bb291..f38811b 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -336,13 +336,18 @@ void main() { +/** + * Animal class is the superclass, with a method makeSound(). + */ class Animal { - public void makeSound() { System.out.println("The animal makes a sound."); } } +/** + * Dog class is a subclass of Animal, with an additional method bark(). + */ class Dog extends Animal { public void bark() { System.out.println("The dog barks!"); @@ -358,18 +363,28 @@ class Dog extends Animal { + +/** + * Animal class is the superclass, with a method makeSound(). + */ class Animal { public void makeSound() { System.out.println("The animal makes a sound."); } } +/** + * Dog class is a subclass of Animal, with an additional method bark(). + */ class Dog extends Animal { public void bark() { System.out.println("The dog barks!"); } } +/** + * Upcasting example: A Dog object is created, but the reference is of type Animal. + */ void main() { // A Dog object is created, but the reference is of type Animal. // This is implicit upcasting. @@ -377,8 +392,8 @@ void main() { myAnimal.makeSound(); // This is valid, as makeSound() is defined in Animal. -// myAnimal.bark(); // This would cause a compile-time error! -// The compiler only knows about the methods in the Animal reference type. + // myAnimal.bark(); // This would cause a compile-time error! + // The compiler only knows about the methods in the Animal reference type. } @@ -393,20 +408,28 @@ void main() { +/** + * Animal class is the superclass, with a method makeSound(). + */ class Animal { public void makeSound() { System.out.println("The animal makes a sound."); } } +/** + * Dog class is a subclass of Animal, with an additional method bark(). + */ class Dog extends Animal { public void bark() { System.out.println("The dog barks!"); } } +/** + * Downcasting example: An Animal reference is downcast to a Dog reference after checking its type. + */ void main() { - Animal myAnimal = new Dog(); // 'myAnimal' is an Animal reference, but it points to a Dog object. From e7bdb447cfbfa5b16415dde8a810798322660d9b Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 24 Jul 2026 23:39:22 +0300 Subject: [PATCH 185/357] added a title for 3.3.1 --- source/ch3_javadatatypes.ptx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index f38811b..823ac73 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -460,7 +460,8 @@ void main() { In fact, this is the first example of another big difference between Java and Python. Java does not support any operator overloading. Table 3 maps common Python string operations to their Java counterparts. For the examples shown in the table we will use a string variable called “str”

    -
    +
    + Comparison of common string operations in Python and Java. Python From 2e371f5b0746c5b18d5734b1fa2d4dc06ec89892 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 24 Jul 2026 23:41:16 +0300 Subject: [PATCH 186/357] added an xml:id to the table and correctly referenced it --- source/ch3_javadatatypes.ptx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index 823ac73..9033d61 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -457,11 +457,11 @@ void main() {

    - In fact, this is the first example of another big difference between Java and Python. Java does not support any operator overloading. Table 3 maps common Python string operations to their Java counterparts. For the examples shown in the table we will use a string variable called “str” + In fact, this is the first example of another big difference between Java and Python. Java does not support any operator overloading. maps common Python string operations to their Java counterparts. For the examples shown in the table we will use a string variable called “str”

    -
    - Comparison of common string operations in Python and Java. +
    + Comparison of common string operations in Python and Java. Python From 49613647116ffee2f9108173e2ec46d75d8ccabc Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 24 Jul 2026 23:50:00 +0300 Subject: [PATCH 187/357] fixed reference to table 3.1.1 --- source/ch3_javadatatypes.ptx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index f38811b..76258b8 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -14,10 +14,10 @@ In Java, some of the most basic data types like integers and floating point numbers are not objects. The benefit of having these primitive data types be non-objects is that operations on the primitives are fast. The problem is that it became difficult for programmers to combine objects and non-objects in the way that we do in Python. - So, eventually all the non-object primitives ended up with Objectified versions. + So, eventually all the non-object primitives ended up with Objectified versions. shows the comparison between Java's primitive and object data types.

    -
    +
    Comparison between Java's primitive and object data types. From d6cc70c49911e9953e5a995b6761c3861539e883 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Mon, 27 Jul 2026 16:11:00 +0300 Subject: [PATCH 188/357] fixed math formatting in 3.1 --- source/ch3_javadatatypes.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index 1cdf4b6..d86d5ca 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -277,7 +277,7 @@ public class TempConv {

    - The general rule in Java is that you must decide what kind of an object your variable is going to reference and then you must declare that variable before you use it. In our temperature converter, the calculation (fahr - 32) * 5.0/9.0 works correctly because 5.0 and 9.0 are treated as double values, preventing the integer division that would occur if we had written 5/9, which would result in 0. + The general rule in Java is that you must decide what kind of an object your variable is going to reference and then you must declare that variable before you use it. In our temperature converter, the calculation (fahr - 32) * 5.0/9.0 works correctly because 5.0 and 9.0 are treated as double values, preventing the integer division that would occur if we had written 5/9, which would result in 0.

    From 0dcbed70d80ab45320bde8f3a3c7800381a65add Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Mon, 27 Jul 2026 17:08:12 +0300 Subject: [PATCH 189/357] added listing blocks --- source/ch3_javadatatypes.ptx | 30 +++++++++++++++++++++--------- 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index 1cdf4b6..7bdce4c 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -527,8 +527,8 @@ void main() { Next, let’s look at a program which reads numbers from a file and produces a histogram showing the frequency of the numbers. The data file we will use has one number between 0 and 9 on each line of the file. Here is a simple Python program that creates and prints a histogram.

    - - + + def main(): count = [0]*10 @@ -542,11 +542,13 @@ def main(): main() +

    Test running the program. It will read this data:

    - + +
        1
        2
    @@ -625,7 +627,8 @@ Here is the Java code needed to write the exact same program:
                 

    - + + import java.util.Scanner; import java.util.ArrayList; @@ -661,6 +664,7 @@ public class Histo { } +

    Before going any further, I suggest you try to compile the above program and run it on some test data that you create. @@ -674,10 +678,14 @@ public class Histo { Technically, you don’t have to declare what is going to be in an array list. The compiler will allow you to leave the <``*Type*>`` off the declaration. If you don’t tell Java what kind of object is going to be on the list Java will give you a warning message like this:

    -
    +        +        
    +        
             Note: Histo.java uses unchecked or unsafe operations. 
             Note: Recompile with -Xlint:unchecked for details.
    -        
    + +
    +

    Without the <Integer> part of the declaration Java simply assumes that any object can be on the list. However, without resorting to an ugly notation called casting, you cannot do anything with the objects on a list like this! So, if you forget you will surely see more errors later in your code. (Try it and see what you get) @@ -686,14 +694,18 @@ public class Histo {

    Lines 13—20 are required to open the file. Why so many lines to open a file in Java? The additional code mainly comes from the fact that Java forces you to reckon with the possibility that the file you want to open is not going to be there. If you attempt to open a file that is not there you will get an error. A try/catch construct allows us to try things that are risky, and gracefully recover from an error if one occurs. The following example shows the general structure of a try/catch block.

    - -
    +        
    +        +        
    +        
             try { 
                 Put some risky code in here, like opening a file 
             } catch (Exception e) { 
                 If an error happens in the try block an exception is thrown. We will catch that exception here! 
             }
    -        
    + + +

    Notice that in line 16 we are catching an IOException. In fact, we will see later that we can have multiple catch blocks to catch different types of exceptions. If we want to be lazy and catch any old exception we can catch an Exception which is the parent of all exceptions. However, catching Exception is a terrible practice, since you may inadvertently catch exceptions you do not intend to, making it harder to identify bugs in your program. From 8c2e1f50769d50fda9b0ec6296eff1df4cefa764 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Mon, 27 Jul 2026 18:03:47 +0300 Subject: [PATCH 190/357] added linking to text --- source/ch3_javadatatypes.ptx | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index 7bdce4c..36c8a98 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -524,10 +524,10 @@ void main() { List

    - Next, let’s look at a program which reads numbers from a file and produces a histogram showing the frequency of the numbers. The data file we will use has one number between 0 and 9 on each line of the file. Here is a simple Python program that creates and prints a histogram. + Next, let’s look at a program which reads numbers from a file and produces a histogram showing the frequency of the numbers. The data file we will use has one number between 0 and 9 on each line of the file. is a simple Python program that creates and prints a histogram.

    - + def main(): @@ -545,17 +545,18 @@ main()

    - Test running the program. It will read this data: + Test running the program. It will read this data:

    - +
        1
        2
        3
        9
        1
    -        
    +
    +

    Lets review what is happening in this little program. First, we create a list and initialize the first 10 positions in the list to be 0. Next we open the data file called ‘test.dat’. Third, we have a loop that reads each line of the file. As we read each line we convert it to an integer and increment the counter at the position in the list indicated by the number on the line we just read. Finally we iterate over each element in the list, printing out both the position in the list and the total value stored in that position. @@ -618,7 +619,7 @@ The code will be executed once for each element in the collection.

    -Here is the Java code needed to write the exact same program: + is the Java code needed to write the exact same program.

    @@ -627,7 +628,7 @@ Here is the Java code needed to write the exact same program:

    - + import java.util.Scanner; @@ -667,7 +668,7 @@ public class Histo {

    - Before going any further, I suggest you try to compile the above program and run it on some test data that you create. + Before going any further, I suggest you try to compile and run it on some test data that you create.

    @@ -675,7 +676,7 @@ public class Histo {

    - Technically, you don’t have to declare what is going to be in an array list. The compiler will allow you to leave the <``*Type*>`` off the declaration. If you don’t tell Java what kind of object is going to be on the list Java will give you a warning message like this: + Technically, you don’t have to declare what is going to be in an array list. The compiler will allow you to leave the <``*Type*>`` off the declaration. If you don’t tell Java what kind of object is going to be on the list Java will give you a warning message like when you compile the program.

    @@ -692,7 +693,7 @@ public class Histo {

    - Lines 13—20 are required to open the file. Why so many lines to open a file in Java? The additional code mainly comes from the fact that Java forces you to reckon with the possibility that the file you want to open is not going to be there. If you attempt to open a file that is not there you will get an error. A try/catch construct allows us to try things that are risky, and gracefully recover from an error if one occurs. The following example shows the general structure of a try/catch block. + Lines 13—20 are required to open the file. Why so many lines to open a file in Java? The additional code mainly comes from the fact that Java forces you to reckon with the possibility that the file you want to open is not going to be there. If you attempt to open a file that is not there you will get an error. A try/catch construct allows us to try things that are risky, and gracefully recover from an error if one occurs. shows the general structure of a try/catch block.

    From 297ccda5d3c75758d8955035d4c32b0f530fa4c6 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Mon, 27 Jul 2026 18:06:10 +0300 Subject: [PATCH 191/357] removed . from code mention --- source/ch3_javadatatypes.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index 36c8a98..6d1d6b1 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -563,7 +563,7 @@ Lets review what is happening in this little program. First, we create a list an

    -To write the Java version of this program we will have to introduce several new Java concepts. First, you will see the Java equivalent of a list, called an ArrayList. Next, you will see three different kinds of loops used in Java. Two of the loops we will use are going to be very familiar, the third one is different from what you are used to in Python but is easy when you understand the syntax: +To write the Java version of this program we will have to introduce several new Java concepts. First, you will see the Java equivalent of a list, an ArrayList. Next, you will see three different kinds of loops used in Java. Two of the loops we will use are going to be very familiar, the third one is different from what you are used to in Python but is easy when you understand the syntax:

    From bf922d3e1899f606286b784ad8f35344535b2a9b Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Mon, 27 Jul 2026 18:27:50 +0300 Subject: [PATCH 192/357] added data block for datafile --- source/ch3_javadatatypes.ptx | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index 6d1d6b1..926c82f 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -528,7 +528,7 @@ void main() {

    - + def main(): count = [0]*10 @@ -545,9 +545,11 @@ main()

    - Test running the program. It will read this data: + Test running the program. It will read .

    - + + + Data file for testing the histogram program
        1
    @@ -557,6 +559,7 @@ main()
        1
             
    +

    Lets review what is happening in this little program. First, we create a list and initialize the first 10 positions in the list to be 0. Next we open the data file called ‘test.dat’. Third, we have a loop that reads each line of the file. As we read each line we convert it to an integer and increment the counter at the position in the list indicated by the number on the line we just read. Finally we iterate over each element in the list, printing out both the position in the list and the total value stored in that position. From 64a6356ebfbe5f93062496bf1790e23138f8e00f Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Mon, 27 Jul 2026 20:27:44 +0300 Subject: [PATCH 193/357] comments in codeblocks in 3.4 --- source/ch3_javadatatypes.ptx | 35 ++++++++++++++++++++++------------- 1 file changed, 22 insertions(+), 13 deletions(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index 1cdf4b6..f4eb0eb 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -531,12 +531,14 @@ void main() { def main(): - count = [0]*10 - data = open('test.dat') + """ Program to read numbers from a file and produce a histogram. """ + count = [0]*10 # create a list of 10 zeros + data = open('test.dat') # open the data file + # read each line and update the count for line in data: count[int(line)] = count[int(line)] + 1 idx = 0 - for num in count: + for num in count: # iterate over the list and print the histogram print(idx, " occurred ", num, " times.") idx += 1 main() @@ -627,33 +629,40 @@ Here is the Java code needed to write the exact same program: -import java.util.Scanner; -import java.util.ArrayList; -import java.io.File; -import java.io.IOException; +import java.util.Scanner; // import the Scanner class to read input from the user +import java.util.ArrayList; // import the ArrayList class to use dynamic arrays +import java.io.File; // import the File class to read from files +import java.io.IOException; // import the IOException class to handle file input/output exceptions +/** + * Program to read numbers from a file and produce a histogram in Java. + */ public class Histo { public static void main(String[] args) { - Scanner data = null; - ArrayList<Integer> count; + Scanner data = null; + ArrayList<Integer> count; // create an ArrayList to hold counts of numbers, of type Integer Integer idx; + + // Try to open the data file and handle any potential IOExceptions try { data = new Scanner(new File("test.dat")); } catch ( IOException e) { System.out.println("Unable to open data file"); - e.printStackTrace(); + e.printStackTrace(); // print the stack trace for debugging System.exit(0); } - count = new ArrayList<Integer>(10); + count = new ArrayList<Integer>(10); // create an ArrayList with an initial capacity of 10 for (Integer i = 0; i < 10; i++) { - count.add(i,0); + count.add(i,0); // initialize the first 10 positions in the ArrayList to hold the value 0 } while(data.hasNextInt()) { - idx = data.nextInt(); + // read each integer from the file and update the count + idx = data.nextInt(); count.set(idx,count.get(idx)+1); } idx = 0; for(Integer i : count) { + // iterate over each element in the ArrayList and print the histogram System.out.println(idx + " occurred " + i + " times."); idx++; } From 99b99c09769ab0b4388735d70fcd836d813c8e9d Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Mon, 27 Jul 2026 20:46:54 +0300 Subject: [PATCH 194/357] add listing --- source/ch3_javadatatypes.ptx | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index 199b13b..e87cf82 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -780,8 +780,8 @@ public class Histo { As was said at the outset of this section, we are going to use Java ArrayLists because they are easier to use and more closely match the way that Python lists behave. However, if you look at Java code on the internet or even in your core Java books you are going to see examples of something called an array. In fact, you have already seen one example of an array declared in the ‘Hello World’ program. Let's rewrite this program to use primitive arrays rather than array lists.

    - - + + import java.util.Scanner; import java.io.File; @@ -812,6 +812,7 @@ public class HistoArray { } +

    The main difference between this example and the previous example is that we declare count to be an Array of integers. We also can initialize short arrays directly using the syntax shown here: Integer[] count = {0,0,0,0,0,0,0,0,0,0}Then notice that we can use the square bracket notation count[idx] to index into an array. From 7e5e090f63827566ce826f1e6015d5f88d5aa5a4 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Mon, 27 Jul 2026 20:53:13 +0300 Subject: [PATCH 195/357] added listing in text --- source/ch3_javadatatypes.ptx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index e87cf82..932aef3 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -777,7 +777,7 @@ public class Histo { Arrays

    - As was said at the outset of this section, we are going to use Java ArrayLists because they are easier to use and more closely match the way that Python lists behave. However, if you look at Java code on the internet or even in your core Java books you are going to see examples of something called an array. In fact, you have already seen one example of an array declared in the ‘Hello World’ program. Let's rewrite this program to use primitive arrays rather than array lists. + As was said at the outset of this section, we are going to use Java ArrayLists because they are easier to use and more closely match the way that Python lists behave. However, if you look at Java code on the internet or even in your core Java books you are going to see examples of something called an array. In fact, you have already seen one example of an array declared in the ‘Hello World’ program. is a rewritten version of that uses primitive arrays rather than array lists.

    @@ -815,7 +815,7 @@ public class HistoArray {

    - The main difference between this example and the previous example is that we declare count to be an Array of integers. We also can initialize short arrays directly using the syntax shown here: Integer[] count = {0,0,0,0,0,0,0,0,0,0}Then notice that we can use the square bracket notation count[idx] to index into an array. + The main difference between and is that we declare count to be an Array of integers. We also can initialize short arrays directly using the syntax shown here: Integer[] count = {0,0,0,0,0,0,0,0,0,0}Then notice that we can use the square bracket notation count[idx] to index into an array.

    From 543f57cb8593c8b0f62898dfc9a2ffb2622814cd Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Mon, 27 Jul 2026 21:29:29 +0300 Subject: [PATCH 196/357] add comments to the code block --- source/ch3_javadatatypes.ptx | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index 199b13b..9764bd7 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -783,13 +783,16 @@ public class Histo { -import java.util.Scanner; -import java.io.File; -import java.io.IOException; +import java.util.Scanner; // import the Scanner class to read input from the user +import java.io.File; // import the File class to read from files +import java.io.IOException; // import the IOException class to handle file input/output exceptions +/** + * Program to read numbers from a file and produce a histogram using arrays in Java. + */ public class HistoArray { public static void main(String[] args) { Scanner data = null; - Integer[] count = {0,0,0,0,0,0,0,0,0,0}; + Integer[] count = {0,0,0,0,0,0,0,0,0,0}; // create an array of 10 integers initialized to 0 Integer idx; try { data = new Scanner(new File("test.dat")); @@ -801,7 +804,7 @@ public class HistoArray { } while(data.hasNextInt()) { idx = data.nextInt(); - count[idx] = count[idx] + 1; + count[idx] = count[idx] + 1; // increment the count for the number read from the file, using array indexing } idx = 0; for(Integer i : count) { From c4fd0a750586fc59f2f7e0ea17237b9fdf8246e8 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Mon, 27 Jul 2026 22:01:20 +0300 Subject: [PATCH 197/357] added listing blocks --- source/ch3_javadatatypes.ptx | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index 199b13b..9944bde 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -829,8 +829,8 @@ public class HistoArray { Lets stay with a simple frequency counting example, only this time we will count the frequency of words in a document. A simple Python program for this job could look like this:

    - - + + def main(): data = open('alice30.txt') @@ -845,11 +845,14 @@ def main(): main() +

    This program reads the file alice30.txt (which follows), and it then splits it into a list of words. Next it creates a dictionary called count which maps each word to the number of times that word occurs in the text. Finally, it prints out the words in alphabetical order along with their frequency.

    + + Data file for testing the word frequency program
     
                 Down, down, down. Would the fall NEVER
    @@ -872,12 +875,13 @@ main()
                 nice grand words to say.)
                 
    +

    Notice that the structure of the program is very similar to the numeric histogram program.

    - - + + import java.util.Scanner; import java.util.ArrayList; @@ -915,6 +919,7 @@ public class HistoMap { } +

    Improve the program above to remove the punctuation. From 1ff02cbe589cfcf9c1139c47f453ea98fd87e106 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Mon, 27 Jul 2026 22:48:33 +0300 Subject: [PATCH 198/357] added listing to text --- source/ch3_javadatatypes.ptx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index 9944bde..d7187f6 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -826,7 +826,7 @@ public class HistoArray {

    - Lets stay with a simple frequency counting example, only this time we will count the frequency of words in a document. A simple Python program for this job could look like this: + Lets stay with a simple frequency counting example, only this time we will count the frequency of words in a document. shows a simple Python program for what this could look.

    @@ -848,7 +848,7 @@ main()

    - This program reads the file alice30.txt (which follows), and it then splits it into a list of words. Next it creates a dictionary called count which maps each word to the number of times that word occurs in the text. Finally, it prints out the words in alphabetical order along with their frequency. + This program reads the file alice30.txt in , and it then splits it into a list of words. Next it creates a dictionary called count which maps each word to the number of times that word occurs in the text. Finally, it prints out the words in alphabetical order along with their frequency.

    @@ -877,7 +877,7 @@ main()

    - Notice that the structure of the program is very similar to the numeric histogram program. + Notice that the structure of is very similar to the numeric histogram program.

    @@ -922,7 +922,7 @@ public class HistoMap {

    - Improve the program above to remove the punctuation. + Improve to remove the punctuation.

    From 27496f7ae8bf5349e96c3e5016a2ff35daa1ac2a Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Mon, 27 Jul 2026 23:54:55 +0300 Subject: [PATCH 199/357] added comments to 3.6 code blocks --- source/ch3_javadatatypes.ptx | 38 ++++++++++++++++++++---------------- 1 file changed, 21 insertions(+), 17 deletions(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index 932aef3..bddf8f5 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -833,15 +833,16 @@ public class HistoArray { -def main(): +def main(): + """ Program to read a file and count the frequency of words in the file. """ data = open('alice30.txt') - wordList = data.read().split() + wordList = data.read().split() # split the file into a list of words count = {} - for w in wordList: + for w in wordList: # iterate over the list of words w = w.lower() count[w] = count.get(w,0) + 1 - keyList = sorted(count.keys()) - for k in keyList: + keyList = sorted(count.keys()) # sort the keys in alphabetical order + for k in keyList: # iterate over the sorted list of keys print("%-20s occurred %4d times" % (k, count[k])) main() @@ -880,19 +881,22 @@ main() -import java.util.Scanner; -import java.util.ArrayList; -import java.io.File; -import java.io.IOException; -import java.util.TreeMap; +import java.util.Scanner; +import java.util.ArrayList; // import the ArrayList class to use dynamic arrays +import java.io.File; +import java.io.IOException; +import java.util.TreeMap; // import the TreeMap class to use a map for counting word frequencies +/** + * Program to read a file and count the frequency of words in the file. + */ public class HistoMap { public static void main(String[] args) { Scanner data = null; - TreeMap<String,Integer> count; + TreeMap<String,Integer> count; // create a TreeMap to hold word counts, mapping each word (String) to its frequency (Integer) Integer idx; String word; Integer wordCount; - try { + try { // Try to open the data file and handle any potential IOExceptions data = new Scanner(new File("alice30.txt")); } catch ( IOException e) { @@ -900,16 +904,16 @@ public class HistoMap { e.printStackTrace(); System.exit(0); } - count = new TreeMap<String,Integer>(); + count = new TreeMap<String,Integer>(); // create a TreeMap to hold word counts while(data.hasNext()) { - word = data.next().toLowerCase(); - wordCount = count.get(word); + word = data.next().toLowerCase(); // read each word from the file, convert it to lowercase + wordCount = count.get(word); // get the current count for the word from the TreeMap if (wordCount == null) { wordCount = 0; } - count.put(word,++wordCount); + count.put(word,++wordCount); // increment the count for the word and put it back into the TreeMap } - for(String i : count.keySet()) { + for(String i : count.keySet()) { // iterate over the keys (words) in the TreeMap System.out.printf("%-20s occurred %5d times\n", i, count.get(i) ); } } From cc41a704b662d7e2d4bc02768ad36aa6618e6a71 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Tue, 28 Jul 2026 16:47:54 +0300 Subject: [PATCH 200/357] fixed c tag format --- source/ch3_javadatatypes.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index 932aef3..7f37af6 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -688,7 +688,7 @@ public class Histo {

    - Technically, you don’t have to declare what is going to be in an array list. The compiler will allow you to leave the <``*Type*>`` off the declaration. If you don’t tell Java what kind of object is going to be on the list Java will give you a warning message like when you compile the program. + Technically, you don’t have to declare what is going to be in an array list. The compiler will allow you to leave the <*Type*> off the declaration. If you don’t tell Java what kind of object is going to be on the list Java will give you a warning message like when you compile the program.

    From 6e452dcb42e129b9d82c3b3fbbcdd5266babb6f9 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Tue, 28 Jul 2026 20:41:04 +0300 Subject: [PATCH 201/357] add listing --- source/ch4_conditionals.ptx | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 0b32d00..aedec88 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -16,17 +16,21 @@ In Python the simple if statement is written as:

    - + + score = 95 if score >= 90: print("Excellent work!") + +

    In Java, this same pattern requires two changes: the condition must be in parentheses (), and the code block must be enclosed in curly braces {}.

    - + + public class SimpleIfExample { public static void main(String[] args) { @@ -38,6 +42,8 @@ if score >= 90: } + +

    Once again you can see that in Java the curly braces define a block rather than indentation. In Java, the parentheses around the condition are required because it is technically a function that evaluates to True or False. From 3134fb387f92389e91d8e58234964f95b1dc2104 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Tue, 28 Jul 2026 20:46:41 +0300 Subject: [PATCH 202/357] add the listing on text --- source/ch4_conditionals.ptx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index aedec88..bbb175c 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -13,7 +13,7 @@

    - In Python the simple if statement is written as: + shows how the simple if statement is written in Python.

    @@ -25,9 +25,9 @@ if score >= 90: - +

    - In Java, this same pattern requires two changes: the condition must be in parentheses (), and the code block must be enclosed in curly braces {}. + shows how the simple if statement is written in Java.

    From d4bf0cdd8a38b8ca5695cee6dce842b62eef8a6f Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Tue, 28 Jul 2026 21:15:42 +0300 Subject: [PATCH 203/357] addd comments to blocks --- source/ch4_conditionals.ptx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 0b32d00..9cc307e 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -19,7 +19,7 @@ score = 95 -if score >= 90: +if score >= 90: # Note the colon at the end of the line print("Excellent work!") @@ -31,7 +31,7 @@ if score >= 90: public class SimpleIfExample { public static void main(String[] args) { int score = 70; - if (score <= 70) { + if (score <= 70) { // Note the parentheses and curly braces System.out.println("Needs work!"); } } From 8f4791ef78285ccde3cf0814bb0c8c2dc89e08e1 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Tue, 28 Jul 2026 21:17:04 +0300 Subject: [PATCH 204/357] made the two conditions the same --- source/ch4_conditionals.ptx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 9cc307e..052be65 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -30,9 +30,9 @@ if score >= 90: # Note the colon at the end of the line public class SimpleIfExample { public static void main(String[] args) { - int score = 70; - if (score <= 70) { // Note the parentheses and curly braces - System.out.println("Needs work!"); + int score = 95; + if (score >= 90) { // Note the parentheses and curly braces + System.out.println("Excellent work!"); } } } From a572688c0fbda902d9d13869b083d7bd0693ce34 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Tue, 28 Jul 2026 21:44:14 +0300 Subject: [PATCH 205/357] made the java block interactive --- source/ch4_conditionals.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 0b32d00..eac50fc 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -58,7 +58,7 @@ if score >= 90: - + public class IfElseExample { public static void main(String[] args) { From 28bb0c2a4fb79b6c89edcf86f085fabfdc9ed5b0 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Tue, 28 Jul 2026 21:49:36 +0300 Subject: [PATCH 206/357] added listing to blocks --- source/ch4_conditionals.ptx | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index eac50fc..a97b00b 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -48,7 +48,8 @@ if score >= 90: Using the <c>if</c> - <c>else</c> Statement

    The Java equivalent follows the same syntactical rules as before.

    - + + age = 16 if age >= 18: @@ -57,8 +58,10 @@ if score >= 90: print("You are not yet eligible to vote.") + - + + public class IfElseExample { public static void main(String[] args) { @@ -72,6 +75,7 @@ if score >= 90: } +
    From a623e6cad194f03f2407870e4cb50cfaee8f9c1f Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Tue, 28 Jul 2026 22:16:49 +0300 Subject: [PATCH 207/357] added listing to the text --- source/ch4_conditionals.ptx | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index a97b00b..925a19a 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -47,7 +47,7 @@ if score >= 90:
    Using the <c>if</c> - <c>else</c> Statement -

    The Java equivalent follows the same syntactical rules as before.

    + shows how Python the if - elsestatement is written in Python. @@ -59,7 +59,8 @@ if score >= 90: - + +

    is Java equivalent that follows the same syntactical rules as before.

    From fe0ef24dd30f60b140d80f5317d30bacc4959071 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Tue, 28 Jul 2026 22:19:38 +0300 Subject: [PATCH 208/357] fixed display --- source/ch4_conditionals.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 925a19a..9aa166a 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -47,7 +47,7 @@ if score >= 90:
    Using the <c>if</c> - <c>else</c> Statement - shows how Python the if - elsestatement is written in Python. +

    shows how the if - elsestatement is written in Python.

    From 40f1886393ca0ea2cb4a8db452a15b589e633fb0 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Tue, 28 Jul 2026 22:52:25 +0300 Subject: [PATCH 209/357] added comments to 4.2 blocks --- source/ch4_conditionals.ptx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 0b32d00..9ff1edc 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -51,9 +51,9 @@ if score >= 90: age = 16 - if age >= 18: + if age >= 18: print("You can vote.") - else: + else: # notice the semicolon print("You are not yet eligible to vote.") @@ -65,7 +65,7 @@ if score >= 90: int age = 16; if (age >= 18) { System.out.println("You can vote."); - } else { + } else { // else has its own block. System.out.println("You are not yet eligible to vote."); } } From 2b3c9ef0f04b34b9f32e3890f07c91d1607716b3 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Tue, 28 Jul 2026 23:35:29 +0300 Subject: [PATCH 210/357] fixed a deleted paragraph --- source/ch4_conditionals.ptx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index bbb175c..91dd65a 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -26,7 +26,9 @@ if score >= 90: +

    + In Java, this same pattern requires two changes: the condition must be in parentheses (), and the code block must be enclosed in curly braces {}. shows how the simple if statement is written in Java.

    From 0c2f70c2de9aec5bb4cef38eb3177a309742b9be Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Wed, 29 Jul 2026 16:25:28 +0300 Subject: [PATCH 211/357] added listing tags --- source/ch4_conditionals.ptx | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 0b32d00..83a90fe 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -83,8 +83,8 @@ if score >= 90: Here is a simple example in both Python and Java.

    - - + + grade = int(input('enter a grade')) if grade < 60: @@ -99,13 +99,14 @@ else: print('A') +

    In Java, we have a couple of ways to write this.

    - - + + public class ElseIf { public static void main(String args[]) { @@ -131,14 +132,15 @@ public class ElseIf { } +

    We can get even closer to the elif statement by taking advantage of the Java rule that a single statement does not need to be enclosed in curly braces. Since the if is the only statement used in each else block, we can get away with the following.

    - - + + public class ElseIf { public static void main(String args[]) { @@ -156,6 +158,7 @@ public class ElseIf { } +
    From 4630f29190f92112a3829b25485c13c9434885a9 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Wed, 29 Jul 2026 16:37:36 +0300 Subject: [PATCH 212/357] added listing to text --- source/ch4_conditionals.ptx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 83a90fe..ef86858 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -80,14 +80,14 @@ if score >= 90:

    elif statement Java does not have an elif pattern like Python. In Java you can get the functionality of an elif statement by nesting if and else. - Here is a simple example in both Python and Java. + Here is a simple example in both Python and Java. shows how it is written in Python.

    grade = int(input('enter a grade')) -if grade < 60: +if grade < 60: print('F') elif grade < 70: print('D') @@ -102,7 +102,7 @@ else:

    -In Java, we have a couple of ways to write this. +In Java, we have a couple of ways to write this. shows one way.

    @@ -135,7 +135,7 @@ public class ElseIf {

    -We can get even closer to the elif statement by taking advantage of the Java rule that a single statement does not need to be enclosed in curly braces. Since the if is the only statement used in each else block, we can get away with the following. +We can get even closer to the elif statement by taking advantage of the Java rule that a single statement does not need to be enclosed in curly braces. Since the if is the only statement used in each else block, we can get away with .

    From 28a5002bd87527f0514fb9df241b955118fac322 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Wed, 29 Jul 2026 17:15:34 +0300 Subject: [PATCH 213/357] fix sentence fragment --- source/ch3_javadatatypes.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index d7187f6..621b514 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -826,7 +826,7 @@ public class HistoArray {

    - Lets stay with a simple frequency counting example, only this time we will count the frequency of words in a document. shows a simple Python program for what this could look. + Lets stay with a simple frequency counting example, only this time we will count the frequency of words in a document. shows a simple Python program for how this could look.

    From 937725ea25fb0f20a493ed9015bf882a866cbf0d Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Wed, 29 Jul 2026 20:04:11 +0300 Subject: [PATCH 214/357] added listings --- source/ch4_conditionals.ptx | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 3023211..ce6218b 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -155,9 +155,9 @@ We can get even closer to the elif statement by taking advantage of the J -public class ElseIf { +public class ElseIf { public static void main(String args[]) { - int grade = 85; + int grade = 85; if (grade < 60) { System.out.println('F'); } else if (grade < 70) { @@ -185,7 +185,8 @@ Java also supports a switch statement that acts something like the eli

    The match - case statement was introduced in Python 3.10, so doesn't run in earlier version of Python. Here is an example using Python's match - case structure.

    - + + Match Case Example grade = 85 @@ -206,6 +207,7 @@ Java also supports a switch statement that acts something like the eli print(grading(tempgrade)) +

    switch The switch statement in Java provides an alternative to chaining multiple if-else conditions, when comparing a single variable against several constant values. It supports a variety of data types, including primitive types (byte, short, char, int), their wrapper classes, enumerations, and String (introduced in Java 7). Each case within a switch must be defined using a constant expression, and duplicate case values are not permitted. By default, control flow "falls through" from one case to the next unless a break, return, or throw statement is used to terminate execution. @@ -216,8 +218,9 @@ Java also supports a switch statement that acts something like the eli yield Java 14 introduced switch expressions, enhancing functionality by allowing the switch to return values and eliminating fall-through via the -> arrow syntax. These expressions can even use yield within code blocks for more complex evaluations. yield is used inside a switch expression’s block to produce the value of that expression, unlike break which simply exits a switch statement or loop. It’s important to note that traditional switch statements do not support null values and will throw a NullPointerException if evaluated with null. As the language evolves, newer versions of Java continue to extend switch capabilities with features like pattern matching and enhanced type handling, making it a more powerful and expressive tool for decision-making in Java programs.

    - - + + + public class SwitchUp { public static void main(String args[]) { @@ -245,6 +248,7 @@ Java also supports a switch statement that acts something like the eli } +

    The switch statement is not used very often, and we recommend you do not use it. First, it is not as powerful as the else if model because the switch variable can only be compared for equality with an integer or enumerated constant. Second, it is very easy to forget to put in the break statement, so it is more error-prone. If the break statement is left out then then the next alternative will be automatically executed. For example, if the grade was 95 and the break was omitted from the case 9: alternative then the program would print(out both A and B.) From 94f305a28ca7c9cf5d05b6018a4015097ab9c4b7 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Wed, 29 Jul 2026 20:09:51 +0300 Subject: [PATCH 215/357] Added listing to text --- source/ch4_conditionals.ptx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index ce6218b..47965b8 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -178,7 +178,7 @@ public class ElseIf { Using the <c>switch</c> Statement

    -Java also supports a switch statement that acts something like the elif or Python match statement under certain conditions. To write the grade program using a switch statement we would use the following: +Java also supports a switch statement that acts something like the elif or Python match statement under certain conditions. shows how the the grade program using a switch statement could be in Python.

    @@ -216,7 +216,7 @@ Java also supports a switch statement that acts something like the eli

    switch expressions yield - Java 14 introduced switch expressions, enhancing functionality by allowing the switch to return values and eliminating fall-through via the -> arrow syntax. These expressions can even use yield within code blocks for more complex evaluations. yield is used inside a switch expression’s block to produce the value of that expression, unlike break which simply exits a switch statement or loop. It’s important to note that traditional switch statements do not support null values and will throw a NullPointerException if evaluated with null. As the language evolves, newer versions of Java continue to extend switch capabilities with features like pattern matching and enhanced type handling, making it a more powerful and expressive tool for decision-making in Java programs. + Java 14 introduced switch expressions, enhancing functionality by allowing the switch to return values and eliminating fall-through via the -> arrow syntax. These expressions can even use yield within code blocks for more complex evaluations. yield is used inside a switch expression’s block to produce the value of that expression, unlike break which simply exits a switch statement or loop. It’s important to note that traditional switch statements do not support null values and will throw a NullPointerException if evaluated with null. As the language evolves, newer versions of Java continue to extend switch capabilities with features like pattern matching and enhanced type handling, making it a more powerful and expressive tool for decision-making in Java programs. shows how the switch expression is written in Java.

    From 7b653dc31a5ce0aa42cbf3d23c7567f4dee6c5a2 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Wed, 29 Jul 2026 20:18:57 +0300 Subject: [PATCH 216/357] added active code --- source/ch4_conditionals.ptx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 47965b8..14225dc 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -178,7 +178,7 @@ public class ElseIf { Using the <c>switch</c> Statement

    -Java also supports a switch statement that acts something like the elif or Python match statement under certain conditions. shows how the the grade program using a switch statement could be in Python. +Java also supports a switch statement that acts something like the elif or Python match statement under certain conditions. shows how a grade program using a switch statement would look in Python.

    @@ -186,7 +186,7 @@ Java also supports a switch statement that acts something like the eli The match - case statement was introduced in Python 3.10, so doesn't run in earlier version of Python. Here is an example using Python's match - case structure.

    - + Match Case Example grade = 85 From 28681c17539fd82555fba65fa1e1eea3ed3c69ec Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Wed, 29 Jul 2026 20:58:47 +0300 Subject: [PATCH 217/357] add comments to code 4.3 --- source/ch4_conditionals.ptx | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 3023211..023fb5e 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -60,7 +60,7 @@ if score >= 90: # Note the colon at the end of the line age = 16 - if age >= 18: + if age >= 18: # notice the semicolon print("You can vote.") else: # notice the semicolon print("You are not yet eligible to vote.") @@ -75,7 +75,7 @@ if score >= 90: # Note the colon at the end of the line public class IfElseExample { public static void main(String[] args) { int age = 16; - if (age >= 18) { + if (age >= 18) { System.out.println("You can vote."); } else { // else has its own block. System.out.println("You are not yet eligible to vote."); @@ -102,7 +102,7 @@ if score >= 90: # Note the colon at the end of the line grade = int(input('enter a grade')) if grade < 60: print('F') -elif grade < 70: +elif grade < 70: # notice the semicolon print('D') elif grade < 80: print('C') @@ -126,7 +126,7 @@ public class ElseIf { int grade = 85; if (grade < 60) { System.out.println('F'); - } else { + } else { // else has its own block. if (grade < 70) { System.out.println('D'); } else { @@ -160,7 +160,7 @@ public class ElseIf { int grade = 85; if (grade < 60) { System.out.println('F'); - } else if (grade < 70) { + } else if (grade < 70) { // notice how we got rid of the curly braces. System.out.println('D'); } else if (grade < 80) { System.out.println('C'); From 4c2a1b4eb0e7a2d7dc7d2bf1fb96e50674000595 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Wed, 29 Jul 2026 21:41:51 +0300 Subject: [PATCH 218/357] added listing tag to blocks --- source/ch4_conditionals.ptx | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 14225dc..194d34b 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -264,19 +264,21 @@ The switch statement is not used very often, and we recommend you do not In Python, if you want a program to continue running when an error has occurred, you can use try-except blocks to handle exceptions. If you wanted to write a program that asks the user to enter a whole number and then squares that number, you could use the following code to do so:

    - + + number = int(input("Please enter a whole number: ")) squared = number ** 2 print("Your number squared is " + str(squared)) +

    The Java code that would perform the same task is a little more complex and utilizes the Scanner class for input.

    - - + + import java.util.Scanner; @@ -293,12 +295,13 @@ The switch statement is not used very often, and we recommend you do not } +

    This code works well, but will end with an exception if the user types anything other than a whole number (such as 12.5 or two). If we wanted to ensure the code will continue to run until the user enters the correct format, we could add try-except (Python) or try-catch (Java) blocks within a while loop that iterates until the user enter the correct code. Adding try-except blocks and a while loop to the Python code will look something like this:

    - - + + while True: try: @@ -310,12 +313,13 @@ The switch statement is not used very often, and we recommend you do not print("That was not a valid number. Please try again: ") +

    Now that we have Python code that will continuously prompt the user until they enter a whole number, let's look at Java code that accomplishes the same task. Like most other equivalent Java code blocks, this code has a lot of extra bits that are necessary to get working code.

    - - + + import java.util.Scanner; import java.util.InputMismatchException; @@ -340,6 +344,7 @@ The switch statement is not used very often, and we recommend you do not } +

    Firstly, let's talk about the extra import alongside the Scanner import. In Java, we need to import InputMismatchException because it's not automatically available like basic exceptions. This is different from Python where most exceptions are readily accessible. If you ran the previous Java codeblock without try-catch blocks and entered an erroneous input, you would have got an InputMismatchException exception despite not having imported this class. That being said, removing the explicit import of this library for the try-catch code block above will lead to compilation errors. From 2b1f682415178957d93d1936cc996dfe14472a3a Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Wed, 29 Jul 2026 22:07:44 +0300 Subject: [PATCH 219/357] added the listing to text --- source/ch4_conditionals.ptx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 194d34b..0212eac 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -261,7 +261,7 @@ The switch statement is not used very often, and we recommend you do not Exception Handling

    - In Python, if you want a program to continue running when an error has occurred, you can use try-except blocks to handle exceptions. If you wanted to write a program that asks the user to enter a whole number and then squares that number, you could use the following code to do so: + In Python, if you want a program to continue running when an error has occurred, you can use try-except blocks to handle exceptions. If you wanted to write a program that asks the user to enter a whole number and then squares that number, you could use the following code to do so. shows the Python code to achieve this.

    @@ -275,7 +275,7 @@ The switch statement is not used very often, and we recommend you do not

    - The Java code that would perform the same task is a little more complex and utilizes the Scanner class for input. + shows the Java code that would perform the same task. It is a little more complex and utilizes the Scanner class for input.

    @@ -298,7 +298,7 @@ The switch statement is not used very often, and we recommend you do not

    - This code works well, but will end with an exception if the user types anything other than a whole number (such as 12.5 or two). If we wanted to ensure the code will continue to run until the user enters the correct format, we could add try-except (Python) or try-catch (Java) blocks within a while loop that iterates until the user enter the correct code. Adding try-except blocks and a while loop to the Python code will look something like this: + This code works well, but will end with an exception if the user types anything other than a whole number (such as 12.5 or two). If we wanted to ensure the code will continue to run until the user enters the correct format, we could add try-except (Python) or try-catch (Java) blocks within a while loop that iterates until the user enter the correct code. shows how adding try-except blocks and a while loop to the Python code will look.

    @@ -316,7 +316,7 @@ The switch statement is not used very often, and we recommend you do not

    - Now that we have Python code that will continuously prompt the user until they enter a whole number, let's look at Java code that accomplishes the same task. Like most other equivalent Java code blocks, this code has a lot of extra bits that are necessary to get working code. + Now that we have Python code that will continuously prompt the user until they enter a whole number, shows the Java code that accomplishes the same task. Like most other equivalent Java code blocks, this code has a lot of extra bits that are necessary to get working code.

    From ebaaf169e3b32b0d782e207a5c3ac4e742765ad6 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Wed, 29 Jul 2026 22:31:48 +0300 Subject: [PATCH 220/357] changed wording --- source/ch4_conditionals.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 0212eac..b44474a 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -298,7 +298,7 @@ The switch statement is not used very often, and we recommend you do not

    - This code works well, but will end with an exception if the user types anything other than a whole number (such as 12.5 or two). If we wanted to ensure the code will continue to run until the user enters the correct format, we could add try-except (Python) or try-catch (Java) blocks within a while loop that iterates until the user enter the correct code. shows how adding try-except blocks and a while loop to the Python code will look. + This code works well, but will end with an exception if the user types anything other than a whole number (such as 12.5 or two). If we wanted to ensure the code will continue to run until the user enters the correct format, we could add try-except (Python) or try-catch (Java) blocks within a while loop that iterates until the user enter the correct code. While try-except blocks aren't strictly required in Python, shows how using them alongside a while loop makes the code more robust.

    From 5bb3ac8a93e21302c146a6c3f0eca7c93d0219a9 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Wed, 29 Jul 2026 22:39:06 +0300 Subject: [PATCH 221/357] add table linkin text --- source/ch4_conditionals.ptx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 293af19..992ed7a 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -348,10 +348,10 @@ The switch statement is not used very often, and we recommend you do not

    checked exception unchecked exception - Exceptions in Java fall under two categories: checked and unchecked. Checked exceptions must be explicitly imported and declared along with try-catch blocks for a program to compile. Unchecked exceptions do not need to be imported unless try-catch blocks are implemented for them (except for java.lang exceptions). InputMismatchException is an unchecked exception that is not part of the java.lang library, so it is only included if try-catch blocks declare it. Here are some common exceptions used with try-catch blocks: + Exceptions in Java fall under two categories: checked and unchecked. Checked exceptions must be explicitly imported and declared along with try-catch blocks for a program to compile. Unchecked exceptions do not need to be imported unless try-catch blocks are implemented for them (except for java.lang exceptions). InputMismatchException is an unchecked exception that is not part of the java.lang library, so it is only included if try-catch blocks declare it. shows the exceptions used with try-catch blocks.

    -
    +
    Exceptions From 7b1fff9760bb99c1d1d88f563df09b50d52a33e8 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Wed, 29 Jul 2026 22:52:06 +0300 Subject: [PATCH 222/357] added a more descriptive title --- source/ch4_conditionals.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 992ed7a..78b2d64 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -352,7 +352,7 @@ The switch statement is not used very often, and we recommend you do not

    - Exceptions + Java Exceptions Used with <c>try-catch</c> Blocks Exception From 04c9849e1b1167d2ec071562927feb0e9e32217d Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Wed, 29 Jul 2026 23:30:49 +0300 Subject: [PATCH 223/357] add comments to 4.5 code blocks --- source/ch4_conditionals.ptx | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 293af19..7d9b651 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -266,9 +266,9 @@ The switch statement is not used very often, and we recommend you do not - number = int(input("Please enter a whole number: ")) - squared = number ** 2 - print("Your number squared is " + str(squared)) + number = int(input("Please enter a whole number: ")) # ask user for a number + squared = number ** 2 # square the number + print("Your number squared is " + str(squared)) @@ -282,11 +282,11 @@ The switch statement is not used very often, and we recommend you do not public class SquareNumber { public static void main(String[] args) { - Scanner user_input = new Scanner(System.in); + Scanner user_input = new Scanner(System.in); // create a scanner object - System.out.print("Please enter a whole number: "); - int number = user_input.nextInt(); - int squared = number * number; + System.out.print("Please enter a whole number: "); + int number = user_input.nextInt(); // ask user for a number + int squared = number * number; // square the number System.out.println("Your number squared is " + squared); } @@ -301,12 +301,12 @@ The switch statement is not used very often, and we recommend you do not while True: - try: + try: # try to convert the user input to an integer number = int(input("Please enter a whole number: ")) squared = number ** 2 print("Your number squared is " + str(squared)) break - except ValueError: + except ValueError: # if the user enters a non-integer, print an error message print("That was not a valid number. Please try again: ") @@ -324,14 +324,14 @@ The switch statement is not used very often, and we recommend you do not public static void main(String[] args) { Scanner scanner = new Scanner(System.in); - while (true) { - try { + while (true) { // keep asking the user for a number until they enter a valid integer + try { // try to convert the user input to an integer System.out.print("Please enter a whole number: "); int number = scanner.nextInt(); int squared = number * number; System.out.println("Your number squared is " + squared); break; - } catch (InputMismatchException e) { + } catch (InputMismatchException e) { // if the user enters a non-integer, print an error message System.out.println("That was not a valid number. Please try again: "); scanner.nextLine(); // Clear the invalid input from the scanner } From 6909dcf8cf38a4269ed71e7bd8f51f8eda341059 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Wed, 29 Jul 2026 23:39:09 +0300 Subject: [PATCH 224/357] addlisting to code block --- source/ch4_conditionals.ptx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 293af19..1fa0385 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -460,7 +460,8 @@ Java also provides the ternary operator condition ? valueIfTrue : valueIfFals

    Using this operator can make code shorter and more readable in cases where a simple conditional assignment is needed. See the following as an example where we see the same logic implemented in two different ways.

    - + + public class Ternary { public static void main(String[] args) { @@ -484,6 +485,7 @@ public class Ternary { } +

    In this example we are using this ternary operator to assign a value to a based on whether a is even or odd. If a is even, it will be squared; if odd, it will be instead be calculated as 3 * x - 1. This is a concise way to write conditional assignments in Java. However, you might want to use it sparingly, as it can make code less readable if overused or used with complex expressions. From b469353ca63d357b12a73c9ce8049649e770ad90 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Wed, 29 Jul 2026 23:39:42 +0300 Subject: [PATCH 225/357] add listing to text --- source/ch4_conditionals.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 1fa0385..6eb57c7 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -458,7 +458,7 @@ Java also provides the ternary operator condition ? valueIfTrue : valueIfFals

    -Using this operator can make code shorter and more readable in cases where a simple conditional assignment is needed. See the following as an example where we see the same logic implemented in two different ways. +Using this operator can make code shorter and more readable in cases where a simple conditional assignment is needed. shows an example where we see the same logic implemented in two different ways.

    From 09e5d99661297da9a1f77b34466bfe4e1e87d4e5 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Wed, 29 Jul 2026 23:41:16 +0300 Subject: [PATCH 226/357] add listing to text 2.0 --- source/ch4_conditionals.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 6eb57c7..34676b5 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -488,7 +488,7 @@ public class Ternary {

    - In this example we are using this ternary operator to assign a value to a based on whether a is even or odd. If a is even, it will be squared; if odd, it will be instead be calculated as 3 * x - 1. This is a concise way to write conditional assignments in Java. However, you might want to use it sparingly, as it can make code less readable if overused or used with complex expressions. + In , we are using this ternary operator to assign a value to a based on whether a is even or odd. If a is even, it will be squared; if odd, it will be instead be calculated as 3 * x - 1. This is a concise way to write conditional assignments in Java. However, you might want to use it sparingly, as it can make code less readable if overused or used with complex expressions.

    From 450392209d8a4c6cdba3f7f1490983fa1ffa4b94 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Thu, 30 Jul 2026 00:18:49 +0300 Subject: [PATCH 227/357] added xml:id to table --- source/ch4_conditionals.ptx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 293af19..db756c6 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -416,10 +416,10 @@ The conditionals used in the if statement can be Boolean variables,

    ternary operator -Java also provides the ternary operator condition ? valueIfTrue : valueIfFalse, which lets you use a boolean test directly inside an assignment. If the condition is true, the first value is chosen; otherwise, the second value is used. The table below summarizes how it works: +Java also provides the ternary operator condition ? valueIfTrue : valueIfFalse, which lets you use a boolean test directly inside an assignment. If the condition is true, the first value is chosen; otherwise, the second value is used. summarizes how it works.

    - +
    Ternary Operator in Java From 964581e04e6be9122ca229aef386af66222f43e6 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Thu, 30 Jul 2026 17:05:11 +0300 Subject: [PATCH 228/357] added a match interactive question --- source/ch3_javadatatypes.ptx | 55 +++++++++++++++++------------------- 1 file changed, 26 insertions(+), 29 deletions(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index 151e699..e73daaa 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -729,36 +729,33 @@ public class Histo {

    - The syntax of this for loop probably looks very strange to you, but in fact it is not too different from what happens in Python using range. In fact for (Integer i = 0; i < 10; i++) is exactly equivalent to the Python for i in range(10) The first statement inside the parenthesis declares and initializes a loop variable i. The second statement is a Boolean expression that is our exit condition. In other words we will keep looping as long as this expression evaluates to true. The third clause is used to increment the value of the loop variable at the end of iteration through the loop. In fact i++ is Java shorthand for i = i + 1 Java also supports the shorthand i-- to decrement the value of i. Like Python, you can also write i += 2 as shorthand for i = i + 2 Try to rewrite the following Python for loops as Java for loops: -

    - -

    -

      -
    • -

      - for i in range(2,101,2) -

      -
    • - -
    • -

      - for i in range(1,100) -

      -
    • + The syntax of this for loop probably looks very strange to you, but in fact it is not too different from what happens in Python using range. In fact for (Integer i = 0; i < 10; i++) is exactly equivalent to the Python for i in range(10) The first statement inside the parenthesis declares and initializes a loop variable i. The second statement is a Boolean expression that is our exit condition. In other words we will keep looping as long as this expression evaluates to true. The third clause is used to increment the value of the loop variable at the end of iteration through the loop. In fact i++ is Java shorthand for i = i + 1 Java also supports the shorthand i-- to decrement the value of i. Like Python, you can also write i += 2 as shorthand for i = i + 2.

      -
    • -

      - for i in range(100,0,-1) -

      -
    • - -
    • -

      - for x,y in zip(range(10),range(0,20,2)) [hint, you can separate statements in the same clause with a ,] -

      -
    • -
    -

    + + +

    + Match each Python for loop with its equivalent Java for loop. +

    +
    + + + for i in range(2, 101, 2) + for (int i = 2; i < 101; i += 2) + + + for i in range(1, 100) + for (int i = 1; i < 100; i++) + + + for i in range(100, 0, -1) + for (int i = 100; i > 0; i--) + + + for x, y in zip(range(10), range(0, 20, 2)) + for (int x = 0, y = 0; x < 10; x++, y += 2) + + +

    The next loop (lines 27–30) shows a typical Java pattern for reading data from a file. Java while loops and Python while loops are identical in their logic. In this case, we will continue to process the body of the loop as long as data.hasNextInt() returns true. From 15a02a09606a88a6097636581ef1073325bc8005 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Thu, 30 Jul 2026 18:13:05 +0300 Subject: [PATCH 229/357] add listing tags --- source/ch5_loopsanditeration.ptx | 40 ++++++++++++++++++++------------ 1 file changed, 25 insertions(+), 15 deletions(-) diff --git a/source/ch5_loopsanditeration.ptx b/source/ch5_loopsanditeration.ptx index ff221d2..5e1d7c1 100644 --- a/source/ch5_loopsanditeration.ptx +++ b/source/ch5_loopsanditeration.ptx @@ -14,19 +14,21 @@ A definite loop is a loop that is executed a specific or definite number of times. In Python, the easiest way to write a definite loop is using the for loop in conjunction with the range function. For example:

    - - + + for i in range(10): print(i) +

    In Java, we would write this as:

    - + + public class DefiniteLoopExample { public static void main(String[] args) { @@ -37,6 +39,7 @@ public class DefiniteLoopExample { } +

    Recall that the range function provides you with a wide variety of options for controlling the value of the loop variable. @@ -65,18 +68,20 @@ public class DefiniteLoopExample { If you want to start at 100, stop at 0 and count backward by 5, the Python loop would be written as:

    - + + for i in range(100, -1, -5): print(i) +

    In Java, we would write this as:

    - - + + public class DefiniteLoopBackward { public static void main(String[] args) { @@ -87,7 +92,7 @@ public class DefiniteLoopBackward { } - +

    In Python, the for loop can also iterate over any sequence such as a list, a string, or a tuple. Java also provides a variation of its for loop that provides the same functionality in its so-called for each loop. @@ -96,20 +101,21 @@ public class DefiniteLoopBackward {

    In Python, we can iterate over a list as follows:

    - - + + l = [1, 1, 2, 3, 5, 8, 13, 21] for fib in l: print(fib) +

    In Java we can iterate over an ArrayList of integers too. Note that this requires importing the ArrayList class.

    - - + + import java.util.ArrayList; @@ -131,13 +137,15 @@ public class ForEachArrayListExample { } +

    This example stretches the imagination a bit, and in fact points out one area where Java's primitive arrays are easier to use than an array list. In fact, all primitive arrays can be used in a for each loop.

    - + + public class ForEachArrayExample { public static void main(String[] args) { @@ -149,12 +157,13 @@ public class ForEachArrayExample { } +

    To iterate over the characters in a string in Java do the following: -

    - - +

    + + public class StringIterationExample { public static void main(String[] args) { @@ -166,6 +175,7 @@ public class StringIterationExample { } + From 49cdd3ff47ab10ff534c5ec6b0e672d467b907d3 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Thu, 30 Jul 2026 18:18:11 +0300 Subject: [PATCH 230/357] made pre tags to program and code for better readabiliy --- source/ch5_loopsanditeration.ptx | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/source/ch5_loopsanditeration.ptx b/source/ch5_loopsanditeration.ptx index 5e1d7c1..41b6ff2 100644 --- a/source/ch5_loopsanditeration.ptx +++ b/source/ch5_loopsanditeration.ptx @@ -45,24 +45,28 @@ public class DefiniteLoopExample { Recall that the range function provides you with a wide variety of options for controlling the value of the loop variable.

    -
    +        
    +        
             range(stop)
             range(start,stop)
             range(start,stop,step)
    -        
    + +

    The Java for loop is really analogous to the last option giving you explicit control over the starting, stopping, and stepping in the three clauses inside the parenthesis. You can think of it this way:

    -
    +        
    +        
             for (start clause; stop clause; step clause) {
                 statement1
                 statement2
             ...
             }
    -        
    + +

    If you want to start at 100, stop at 0 and count backward by 5, the Python loop would be written as: From 47f40842e81464ac17d9c7d7d7e2230b7c63d402 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Thu, 30 Jul 2026 18:45:27 +0300 Subject: [PATCH 231/357] add listing to text --- source/ch5_loopsanditeration.ptx | 39 ++++++++++++++++---------------- 1 file changed, 20 insertions(+), 19 deletions(-) diff --git a/source/ch5_loopsanditeration.ptx b/source/ch5_loopsanditeration.ptx index 41b6ff2..9e230ab 100644 --- a/source/ch5_loopsanditeration.ptx +++ b/source/ch5_loopsanditeration.ptx @@ -11,8 +11,7 @@

    for loop - A definite loop is a loop that is executed a specific or definite number of times. In Python, the easiest way to write a definite loop is using the for loop in conjunction with the range function. - For example: + A definite loop is a loop that is executed a specific or definite number of times. In Python, the easiest way to write a definite loop is using the for loop in conjunction with the range function. shows the syntax for the range function.

    @@ -24,7 +23,7 @@ for i in range(10):

    - In Java, we would write this as: + shows how the for loop is written in Java.

    @@ -42,23 +41,24 @@ public class DefiniteLoopExample {

    - Recall that the range function provides you with a wide variety of options for controlling the value of the loop variable. + Recall that the range function provides you with a wide variety of options for controlling the value of the loop variable as shown in .

    - - + + range(stop) range(start,stop) range(start,stop,step) +

    - The Java for loop is really analogous to the last option giving you explicit control over the starting, stopping, and stepping in the three clauses inside the parenthesis. - You can think of it this way: + The Java for loop is really analogous to the last option giving you explicit control over the starting, stopping, and stepping in the three clauses inside the parenthesis. + shows how the Java for loop is written.

    - - + + for (start clause; stop clause; step clause) { statement1 @@ -67,12 +67,13 @@ public class DefiniteLoopExample { } - + +

    - If you want to start at 100, stop at 0 and count backward by 5, the Python loop would be written as: + If you want to start at 100, stop at 0 and count backward by 5, shows how the Python for loop is written.

    - + for i in range(100, -1, -5): @@ -82,7 +83,7 @@ for i in range(100, -1, -5):

    - In Java, we would write this as: + shows how the for loop is written in Java.

    @@ -103,7 +104,7 @@ public class DefiniteLoopBackward {

    - In Python, we can iterate over a list as follows: + shows how the for loop can be used to iterate over a list in Python.

    @@ -116,7 +117,7 @@ for fib in l:

    - In Java we can iterate over an ArrayList of integers too. Note that this requires importing the ArrayList class. + shows how the for loop can be used to iterate over an ArrayList of integers in Java.

    @@ -144,8 +145,8 @@ public class ForEachArrayListExample {

    - This example stretches the imagination a bit, and in fact points out one area where Java's primitive arrays are easier to use than an array list. - In fact, all primitive arrays can be used in a for each loop. + stretches the imagination a bit, and in fact points out one area where Java's primitive arrays are easier to use than an array list. + shows how the for loop can be used to iterate over all elements in a primitive array in Java.

    @@ -164,7 +165,7 @@ public class ForEachArrayExample {

    - To iterate over the characters in a string in Java do the following: + shows how the for loop can be used to iterate over all elements in a string in Java.

    From ba43d1450a21659e6b793b4ee92bc991a67c8d3f Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Thu, 30 Jul 2026 20:15:42 +0300 Subject: [PATCH 232/357] added more options to make it harder --- source/ch3_javadatatypes.ptx | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index e73daaa..81e3d7a 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -734,25 +734,47 @@ public class Histo {

    - Match each Python for loop with its equivalent Java for loop. + Match each Python for loop with its equivalent Java for loop. + Note: There are extra options that represent common syntax mistakes or off-by-one errors.

    + + for i in range(2, 101, 2) for (int i = 2; i < 101; i += 2) + for i in range(1, 100) for (int i = 1; i < 100; i++) + + + for (int i = 1; i <= 100; i++) + + for i in range(100, 0, -1) for (int i = 100; i > 0; i--) + + for (int i = 2; i <= 101; i += 2) + + + for x, y in zip(range(10), range(0, 20, 2)) for (int x = 0, y = 0; x < 10; x++, y += 2) + + + + for (int i = 100; i < 0; i--) + + + + for (int x = 0, int y = 0; x < 10; x++, y += 2)
    From 3d367c6931714e8d632354d662542cead00cbf5b Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Thu, 30 Jul 2026 20:40:27 +0300 Subject: [PATCH 233/357] added comments to 5.1 --- source/ch5_loopsanditeration.ptx | 34 ++++++++++++++++---------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/source/ch5_loopsanditeration.ptx b/source/ch5_loopsanditeration.ptx index ff221d2..fb3df2d 100644 --- a/source/ch5_loopsanditeration.ptx +++ b/source/ch5_loopsanditeration.ptx @@ -17,7 +17,7 @@ -for i in range(10): +for i in range(10): # range(10) is a list of integers from 0 to 9 print(i) @@ -30,7 +30,7 @@ for i in range(10): public class DefiniteLoopExample { public static void main(String[] args) { - for (Integer i = 0; i < 10; i++ ) { + for (Integer i = 0; i < 10; i++ ) { // notice how the initialization, condition, and update are all on the same line. System.out.println(i); } } @@ -67,7 +67,7 @@ public class DefiniteLoopExample { -for i in range(100, -1, -5): +for i in range(100, -1, -5): # start at 100, stop at 0, decrement by 5 print(i) @@ -80,7 +80,7 @@ for i in range(100, -1, -5): public class DefiniteLoopBackward { public static void main(String[] args) { - for (Integer i = 100; i >= 0; i -= 5) { + for (Integer i = 100; i >= 0; i -= 5) { // start at 100, stop at 0, decrement by 5 System.out.println(i); } } @@ -99,8 +99,8 @@ public class DefiniteLoopBackward { -l = [1, 1, 2, 3, 5, 8, 13, 21] -for fib in l: +l = [1, 1, 2, 3, 5, 8, 13, 21] # create a list of integers +for fib in l: # iterate over the list print(fib) @@ -115,16 +115,16 @@ import java.util.ArrayList; public class ForEachArrayListExample { public static void main(String[] args) { - ArrayList<Integer> l = new ArrayList<Integer>(); - l.add(1); - l.add(1); - l.add(2); + ArrayList<Integer> l = new ArrayList< // create an ArrayList of integers + l.add(1); // add the first integer to the list + l.add(1); // add the second integer to the list + l.add(2); // keep going l.add(3); l.add(5); l.add(8); l.add(13); - l.add(21); - for (Integer i : l) { + l.add(21); // add the last integer to the list + for (Integer i : l) { // iterate over the list System.out.println(i); } } @@ -141,8 +141,8 @@ public class ForEachArrayListExample { public class ForEachArrayExample { public static void main(String[] args) { - int l[] = {1,1,2,3,5,8,13,21}; - for(int i : l) { + int l[] = {1,1,2,3,5,8,13,21}; // create an array of integers using primitive syntax + for(int i : l) { // iterate over the array System.out.println(i); } } @@ -158,8 +158,8 @@ public class ForEachArrayExample { public class StringIterationExample { public static void main(String[] args) { - String t = "Hello World"; - for (char c : t.toCharArray()) { + String t = "Hello World"; // create a string + for (char c : t.toCharArray()) { // iterate over the characters in the string System.out.println(c); } } @@ -179,7 +179,7 @@ public class StringIterationExample { i = 5 -while i > 0: +while i > 0: print(i) i = i - 1 From 6c7aa640f1b53c3b5b82023d3c12fc1cfabca752 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Thu, 30 Jul 2026 20:56:06 +0300 Subject: [PATCH 234/357] add listing tags --- source/ch5_loopsanditeration.ptx | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/source/ch5_loopsanditeration.ptx b/source/ch5_loopsanditeration.ptx index ff221d2..7939524 100644 --- a/source/ch5_loopsanditeration.ptx +++ b/source/ch5_loopsanditeration.ptx @@ -176,7 +176,8 @@ public class StringIterationExample { Both Python and Java support the while loop, which continues to execute as long as a condition is true. Here is a simple example in Python that counts down from 5:

    - + + i = 5 while i > 0: @@ -184,11 +185,13 @@ while i > 0: i = i - 1 +

    In Java, we add parentheses and curly braces. Here is the same countdown loop in Java:

    - + + public class WhileLoopExample { public static void main(String[] args) { @@ -201,6 +204,7 @@ public class WhileLoopExample { } +

    do-while loop Java adds an additional, if seldom used variation of the while loop called the do-while loop. @@ -209,8 +213,8 @@ public class WhileLoopExample { Some programmers prefer this loop in some situations because it avoids an additional assignment prior to the loop. For example, the following loop will execute once even though the condition is initially false.

    - - + + public class DoWhileExample { public static void main(String[] args) { @@ -222,6 +226,8 @@ public class DoWhileExample { } + +
    Summary & Reading Questions From 69e453b494d07eb0b2bdd3a76a47d20a58530247 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Thu, 30 Jul 2026 21:27:33 +0300 Subject: [PATCH 235/357] add listing to text --- source/ch5_loopsanditeration.ptx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/source/ch5_loopsanditeration.ptx b/source/ch5_loopsanditeration.ptx index 7939524..d278d87 100644 --- a/source/ch5_loopsanditeration.ptx +++ b/source/ch5_loopsanditeration.ptx @@ -174,7 +174,7 @@ public class StringIterationExample {

    while loop Both Python and Java support the while loop, which continues to execute as long as a condition is true. - Here is a simple example in Python that counts down from 5: + shows a simple example in Python that counts down from 5.

    @@ -188,7 +188,7 @@ while i > 0:

    - In Java, we add parentheses and curly braces. Here is the same countdown loop in Java: + In Java, we add parentheses and curly braces. shows the same countdown loop in Java.

    @@ -211,7 +211,7 @@ public class WhileLoopExample { The do-while loop is very similar to while except that the condition is evaluated at the end of the loop rather than the beginning. This ensures that a loop will be executed at least one time. Some programmers prefer this loop in some situations because it avoids an additional assignment prior to the loop. - For example, the following loop will execute once even though the condition is initially false. + For example, shows how loop will execute once even though the condition is initially false.

    @@ -227,7 +227,7 @@ public class DoWhileExample { - +
    Summary & Reading Questions From 4076192c16ff47177f5b3d66f24f8f61099316ef Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Thu, 30 Jul 2026 21:39:49 +0300 Subject: [PATCH 236/357] changes to match --- source/ch3_javadatatypes.ptx | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index 81e3d7a..cd27074 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -735,15 +735,14 @@ public class Histo {

    Match each Python for loop with its equivalent Java for loop. - Note: There are extra options that represent common syntax mistakes or off-by-one errors.

    - for i in range(2, 101, 2) - for (int i = 2; i < 101; i += 2) + for i in range(2, 102, 2) + for (int i = 2; i < 102; i += 2) @@ -761,7 +760,7 @@ public class Histo { - for (int i = 2; i <= 101; i += 2) + for (int i = 2; i <= 102; i += 2) From bc89252974f2628e518a85f0077531e6932b0091 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Thu, 30 Jul 2026 22:04:14 +0300 Subject: [PATCH 237/357] add comments to 5.2 --- source/ch5_loopsanditeration.ptx | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/source/ch5_loopsanditeration.ptx b/source/ch5_loopsanditeration.ptx index ff221d2..2b03d82 100644 --- a/source/ch5_loopsanditeration.ptx +++ b/source/ch5_loopsanditeration.ptx @@ -179,9 +179,9 @@ public class StringIterationExample { i = 5 -while i > 0: +while i > 0: # while i is greater than 0 print(i) - i = i - 1 + i = i - 1 # decrement i by 1 @@ -192,10 +192,10 @@ while i > 0: public class WhileLoopExample { public static void main(String[] args) { - int i = 5; - while (i > 0) { + int i = 5; // initialize i to 5 + while (i > 0) { // while i is greater than 0 System.out.println(i); - i = i - 1; + i = i - 1; // decrement i by 1 } } } @@ -214,10 +214,10 @@ public class WhileLoopExample { public class DoWhileExample { public static void main(String[] args) { - int i = 10; - do { + int i = 10; // initialize i to 10 + do { // do-while loop, will run at least once no matter the condition System.out.println("This runs once, i = " + i); - } while (i < 5); + } while (i < 5); // while i is less than 5 } } From 3c923ced6753e33a92c4ee9430012bb3de33348a Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Thu, 30 Jul 2026 23:04:41 +0300 Subject: [PATCH 238/357] merged sections 4.1-4.4 into one section --- source/ch4_conditionals.ptx | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 8a9682d..777057e 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -4,8 +4,7 @@ Conditionals -
    - Using the Simple <c>if</c> Statement +
    Using Conditional Statements in Java

    conditional statements Conditional statements in Python and Java are very similar. In Python we have three patterns: @@ -50,9 +49,9 @@ if score >= 90: # Note the colon at the end of the line Once again you can see that in Java the curly braces define a block rather than indentation. In Java, the parentheses around the condition are required because it is technically a function that evaluates to True or False.

    -
    + -
    + Using the <c>if</c> - <c>else</c> Statement

    shows how the if - elsestatement is written in Python.

    @@ -85,9 +84,9 @@ if score >= 90: # Note the colon at the end of the line
    - + -
    + Can we use <c>elif</c>?

    elif statement @@ -172,9 +171,9 @@ public class ElseIf {

    - + -
    + Using the <c>switch</c> Statement

    @@ -255,6 +254,7 @@ The switch statement is not used very often, and we recommend you do not

    Finally, the switch statement does not support relational expressions such as greater than or less than. So you cannot use it to completely replace the elif. Even with the new features of Java 14+ the switch statement is still limited to constant comparisons using equality.

    +
    From 443e2aec5e46fa5c21e90c09d3a937a684866199 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 31 Jul 2026 00:02:51 +0300 Subject: [PATCH 239/357] moved ternary operator before file handling --- source/ch4_conditionals.ptx | 172 ++++++++++++++++++------------------ 1 file changed, 85 insertions(+), 87 deletions(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 777057e..7410fc6 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -257,7 +257,91 @@ The switch statement is not used very often, and we recommend you do not
    -
    +
    + The Ternary Operator + +

    Boolean operators simple comparisons compound Boolean expressions +The conditionals used in the if statement can be Boolean variables, simple comparisons, and compound Boolean expressions. +

    + +

    ternary operator +Java also provides the ternary operator condition ? valueIfTrue : valueIfFalse, which lets you use a boolean test directly inside an assignment. If the condition is true, the first value is chosen; otherwise, the second value is used. summarizes how it works. +

    + +
    + Ternary Operator in Java + + + Component + Description + + + condition + The boolean expression that is evaluated (e.g., a % 2 == 0). + + + ? + This is the ternary operator that separates the condition from the trueValue. + + + trueValue + The value assigned if the condition is true (e.g., a * a). + + + : + This is the ternary operator that separates the trueValue from the falseValue. + + + falseValue + The value assigned if the condition is false (e.g., 3 * x - 1). + + + Example Usage + a = a % 2 == 0 ? a * a : 3 * x - 1 + + + Equivalent if-else Code + Can also be written with a regular if-else statement, but the ternary form is more concise. + + +
    + +

    +Using this operator can make code shorter and more readable in cases where a simple conditional assignment is needed. shows an example where we see the same logic implemented in two different ways. +

    + + + +public class Ternary { + public static void main(String[] args) { + int a = 4; + int x = 2; + int outp; + + // ternary: + outp = (a % 2 == 0) ? (a * a) : (3 * x - 1); + System.out.println("ternary result: " + outp); + + // Equivalent using if/else + if (a % 2 == 0) { + outp = a * a; + } else { + outp = 3 * x - 1; + } + + System.out.println("if/else result: " + outp); + } +} + + + + +

    + In , we are using this ternary operator to assign a value to a based on whether a is even or odd. If a is even, it will be squared; if odd, it will be instead be calculated as 3 * x - 1. This is a concise way to write conditional assignments in Java. However, you might want to use it sparingly, as it can make code less readable if overused or used with complex expressions. +

    +
    + +
    Exception Handling

    @@ -411,92 +495,6 @@ The switch statement is not used very often, and we recommend you do not Note that as with other structures in Java, try-catch blocks blocks must be encased with braces {}. The most important part of this code is, after catch, there is a set of parenthesis with an exception type and a variable name catch (InputMismatchException e). This is where we declare a InputMismatchException exception and name it with the variable name e. It is common practice, though not a requirement, to name exception variables e in this manner.

    -
    - -
    - The Ternary Operator - -

    Boolean operators simple comparisons compound Boolean expressions -The conditionals used in the if statement can be Boolean variables, simple comparisons, and compound Boolean expressions. -

    - -

    ternary operator -Java also provides the ternary operator condition ? valueIfTrue : valueIfFalse, which lets you use a boolean test directly inside an assignment. If the condition is true, the first value is chosen; otherwise, the second value is used. summarizes how it works. -

    - - - Ternary Operator in Java - - - Component - Description - - - condition - The boolean expression that is evaluated (e.g., a % 2 == 0). - - - ? - This is the ternary operator that separates the condition from the trueValue. - - - trueValue - The value assigned if the condition is true (e.g., a * a). - - - : - This is the ternary operator that separates the trueValue from the falseValue. - - - falseValue - The value assigned if the condition is false (e.g., 3 * x - 1). - - - Example Usage - a = a % 2 == 0 ? a * a : 3 * x - 1 - - - Equivalent if-else Code - Can also be written with a regular if-else statement, but the ternary form is more concise. - - -
    - -

    -Using this operator can make code shorter and more readable in cases where a simple conditional assignment is needed. shows an example where we see the same logic implemented in two different ways. -

    - - - -public class Ternary { - public static void main(String[] args) { - int a = 4; - int x = 2; - int outp; - - // ternary: - outp = (a % 2 == 0) ? (a * a) : (3 * x - 1); - System.out.println("ternary result: " + outp); - - // Equivalent using if/else - if (a % 2 == 0) { - outp = a * a; - } else { - outp = 3 * x - 1; - } - - System.out.println("if/else result: " + outp); - } -} - - - - -

    - In , we are using this ternary operator to assign a value to a based on whether a is even or odd. If a is even, it will be squared; if odd, it will be instead be calculated as 3 * x - 1. This is a concise way to write conditional assignments in Java. However, you might want to use it sparingly, as it can make code less readable if overused or used with complex expressions. -

    - -
    Summary & Reading Questions From e3710661fc092d37a9e7c74f1a4c70b6c9ced34e Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 31 Jul 2026 16:18:20 +0300 Subject: [PATCH 240/357] added listing to programs --- source/ch6_definingclasses.ptx | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index f2e6d55..0990195 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -65,8 +65,8 @@ Here is a mostly complete implementation of a Fraction class in Python that we will refer to throughout this section:

    - - + + class Fraction: def __init__(self, num, den): @@ -126,6 +126,7 @@ print(sorted([Fraction(5, 16), Fraction(3, 16), Fraction(1, 16) + 1])) +

    data members @@ -136,8 +137,8 @@ The declarations of instance variables can come at the beginning of the class definition or the end. Cay Horstman, author of the “Core Java” books puts the declarations at the end of the class. I like them at the very beginning so you see the variables that are declared before you begin looking at the code that uses them. With that in mind the first part of the Fraction class definition is as follows:

    - - + + public class Fraction { private Integer numerator; @@ -145,19 +146,21 @@ } +

    Notice that we have declared the numerator and denominator to be private. This means that the compiler will generate an error if another method tries to write code like the following:

    - - + + Fraction f = new Fraction(1,2); Integer y = f.numerator * 10; +

    getter method @@ -167,8 +170,8 @@ Hence, it is a very common programming practice to both provide getter methods and setter methods when needed for instance variables in Java.

    - - + + public Integer getNumerator() { return numerator; @@ -184,6 +187,7 @@ public void setDenominator(Integer denominator) { } +
    From 00a013cbd7f090511e0d4d1a4ff2dab8da8b31bd Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 31 Jul 2026 16:26:47 +0300 Subject: [PATCH 241/357] add listing to text --- source/ch6_definingclasses.ptx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index 0990195..453bf0c 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -62,7 +62,7 @@

    - Here is a mostly complete implementation of a Fraction class in Python that we will refer to throughout this section: + is a mostly complete implementation of a Fraction class in Python that we will refer to throughout this section.

    @@ -134,7 +134,7 @@

    - The declarations of instance variables can come at the beginning of the class definition or the end. Cay Horstman, author of the “Core Java” books puts the declarations at the end of the class. I like them at the very beginning so you see the variables that are declared before you begin looking at the code that uses them. With that in mind the first part of the Fraction class definition is as follows: + The declarations of instance variables can come at the beginning of the class definition or the end. Cay Horstman, author of the “Core Java” books puts the declarations at the end of the class. I like them at the very beginning so you see the variables that are declared before you begin looking at the code that uses them. With that in mind shows the first part of the Fraction class definition.

    @@ -150,7 +150,7 @@

    Notice that we have declared the numerator and denominator to be private. - This means that the compiler will generate an error if another method tries to write code like the following: + This means that the compiler will generate an error if another method tries to write code like .

    @@ -167,7 +167,7 @@ setter method Direct access to instance variables is not allowed in Java. Therefore if we legitimately want to be able to access information such as the numerator or the denominator for a particular fraction we must have a getter method that returns the needed value. - Hence, it is a very common programming practice to both provide getter methods and setter methods when needed for instance variables in Java. + Hence, it is a very common programming practice to both provide getter methods and setter methods when needed for instance variables in Java. shows how the getter and setter methods are written.

    From 81b7943ffa84b907761c70f041a865aa039f2ff4 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 31 Jul 2026 16:36:33 +0300 Subject: [PATCH 242/357] added idx tag --- source/ch5_loopsanditeration.ptx | 1 + 1 file changed, 1 insertion(+) diff --git a/source/ch5_loopsanditeration.ptx b/source/ch5_loopsanditeration.ptx index 9e230ab..caad45f 100644 --- a/source/ch5_loopsanditeration.ptx +++ b/source/ch5_loopsanditeration.ptx @@ -11,6 +11,7 @@

    for loop + definite loop A definite loop is a loop that is executed a specific or definite number of times. In Python, the easiest way to write a definite loop is using the for loop in conjunction with the range function. shows the syntax for the range function.

    From ab399a1f07cef9e3741b70c0edbecda78cd66aba Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 31 Jul 2026 16:56:09 +0300 Subject: [PATCH 243/357] removed some of the comments --- source/ch5_loopsanditeration.ptx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/ch5_loopsanditeration.ptx b/source/ch5_loopsanditeration.ptx index 2b03d82..f677133 100644 --- a/source/ch5_loopsanditeration.ptx +++ b/source/ch5_loopsanditeration.ptx @@ -192,10 +192,10 @@ while i > 0: # while i is greater than 0 public class WhileLoopExample { public static void main(String[] args) { - int i = 5; // initialize i to 5 + int i = 5; while (i > 0) { // while i is greater than 0 System.out.println(i); - i = i - 1; // decrement i by 1 + i = i - 1; } } } From 269c931f2a0537765805a92d5850736309a89a08 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 31 Jul 2026 17:10:17 +0300 Subject: [PATCH 244/357] added idx tags --- source/ch6_definingclasses.ptx | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index 453bf0c..252ec9b 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -62,10 +62,10 @@

    - is a mostly complete implementation of a Fraction class in Python that we will refer to throughout this section. + is a mostly complete implementation of a Fraction class in Python that we will refer to throughout this section.

    - + class Fraction: @@ -134,10 +134,10 @@

    - The declarations of instance variables can come at the beginning of the class definition or the end. Cay Horstman, author of the “Core Java” books puts the declarations at the end of the class. I like them at the very beginning so you see the variables that are declared before you begin looking at the code that uses them. With that in mind shows the first part of the Fraction class definition. + The declarations of instance variables can come at the beginning of the class definition or the end. Cay Horstman, author of the “Core Java” books puts the declarations at the end of the class. I like them at the very beginning so you see the variables that are declared before you begin looking at the code that uses them. With that in mind shows the first part of the Fraction class definition.

    - + public class Fraction { @@ -149,6 +149,7 @@

    + private Notice that we have declared the numerator and denominator to be private. This means that the compiler will generate an error if another method tries to write code like .

    From fab036027dc2a718f56511a4b44504199871413d Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Fri, 31 Jul 2026 10:29:03 -0400 Subject: [PATCH 245/357] add "for loop" idx Clarified definition of a definite loop and its relation to for loops in Python. --- source/ch5_loopsanditeration.ptx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/ch5_loopsanditeration.ptx b/source/ch5_loopsanditeration.ptx index caad45f..833f363 100644 --- a/source/ch5_loopsanditeration.ptx +++ b/source/ch5_loopsanditeration.ptx @@ -12,7 +12,7 @@

    for loop definite loop - A definite loop is a loop that is executed a specific or definite number of times. In Python, the easiest way to write a definite loop is using the for loop in conjunction with the range function. shows the syntax for the range function. + A definite loop, also known as a for loop, is a loop that is executed for a specific or definite number of times. In Python, the easiest way to write a definite loop is using the for loop structure in conjunction with the range function. shows the syntax for the range function.

    @@ -339,4 +339,4 @@ public class DoWhileExample { - \ No newline at end of file + From 1997b67c58d9bb21d2052b6f213eabe53927a697 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 31 Jul 2026 18:20:45 +0300 Subject: [PATCH 246/357] addd comments to code --- source/ch6_definingclasses.ptx | 64 ++++++++++++++++++++++------------ 1 file changed, 42 insertions(+), 22 deletions(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index 252ec9b..ba083b2 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -76,37 +76,54 @@ """ self.num = num self.den = den - def __repr__(self): - if self.num > self.den: - retWhole = int(self.num / self.den) - retNum = self.num - (retWhole * self.den) + def __repr__(self): + """ + :return: a string representation of the fraction + """ + if self.num > self.den: + retWhole = int(self.num / self.den) # find the whole number part + retNum = self.num - (retWhole * self.den) # find the numerator part return str(retWhole) + " " + str(retNum) + "/" + str(self.den) else: return str(self.num) + "/" + str(self.den) def show(self): + """ + :return: print the fraction + """ print(self.num, "/", self.den) def __add__(self, other): + """ + :param other: the fraction to add + :return: the sum of the two fractions + """ # convert to a fraction other = self.toFract(other) - newnum = self.num * other.den + self.den * other.num - newden = self.den * other.den + newnum = self.num * other.den + self.den * other.num # find the new numerator + newden = self.den * other.den # find the new denominator common = gcd(newnum, newden) return Fraction(int(newnum / common), int(newden / common)) - __radd__ = __add__ + __radd__ = __add__ # allow the fraction to be added to a number def __lt__(self, other): + """ + :param other: the fraction to compare + :return: whether the fraction is less than the other + """ num1 = self.num * other.den num2 = self.den * other.num return num1 < num2 def toFract(self, n): + """ + :param n: the number to convert to a fraction + :return: the fraction representation of the number + """ if isinstance(n, int): other = Fraction(n, 1) elif isinstance(n, float): wholePart = int(n) - fracPart = n - wholePart - # convert to 100ths??? - fracNum = int(fracPart * 100) - newNum = wholePart * 100 + fracNum - other = Fraction(newNum, 100) + fracPart = n - wholePart + fracNum = int(fracPart * 100) # convert to 100ths + newNum = wholePart * 100 + fracNum # combine the whole and fractional parts + other = Fraction(newNum, 100) elif isinstance(n, Fraction): other = n else: @@ -115,9 +132,12 @@ return other def gcd(m, n): """ - A helper function for Fraction + A helper function for Fraction. + :param m: the first number + :param n: the second number + :return: the greatest common divisor """ - while m % n != 0: + while m % n != 0: # keep going until the gcd is found oldm = m oldn = n m = oldn @@ -140,8 +160,8 @@ - public class Fraction { - private Integer numerator; + public class Fraction { + private Integer numerator; // notice the private modifier private Integer denominator; } @@ -157,8 +177,8 @@ - Fraction f = new Fraction(1,2); - Integer y = f.numerator * 10; + Fraction f = new Fraction(1,2); + Integer y = f.numerator * 10; // trying to access the numerator @@ -174,16 +194,16 @@ -public Integer getNumerator() { +public Integer getNumerator() { // getter method return numerator; } -public void setNumerator(Integer numerator) { +public void setNumerator(Integer numerator) { // setter method this.numerator = numerator; } -public Integer getDenominator() { +public Integer getDenominator() { // getter method return denominator; } -public void setDenominator(Integer denominator) { +public void setDenominator(Integer denominator) { // setter method this.denominator = denominator; } From 1eb27de8c3fde657aea5376c57d5b84bccab6947 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 31 Jul 2026 18:47:46 +0300 Subject: [PATCH 247/357] added listing tags --- source/ch6_definingclasses.ptx | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index 252ec9b..e5012be 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -203,8 +203,8 @@ public void setDenominator(Integer denominator) { Our constructor will take two parameters: the numerator and the denominator.

    - - + + public Fraction(Integer top, Integer bottom) { num = top; @@ -212,6 +212,7 @@ public Fraction(Integer top, Integer bottom) { } +

    this @@ -224,8 +225,8 @@ public Fraction(Integer top, Integer bottom) { For example this alternate definition of the the Fraction constructor uses this to differentiate between parameters and instance variables.

    - - + + public Fraction(Integer num, Integer den) { this.num = num; @@ -233,6 +234,7 @@ public Fraction(Integer num, Integer den) { } +
    From 7c86b21541b43c63e5da2825329df06d14b88241 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 31 Jul 2026 18:52:05 +0300 Subject: [PATCH 248/357] added listing to txt --- source/ch6_definingclasses.ptx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index e5012be..185851a 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -200,7 +200,7 @@ public void setDenominator(Integer denominator) { In Java, constructors have the same name as the class and are declared public. They are declared without a return type. So any method that is named the same as the class and has no return type is a constructor. - Our constructor will take two parameters: the numerator and the denominator. + Our constructor will take two parameters: the numerator and the denominator. shows the constructor for the Fraction class.

    @@ -222,7 +222,7 @@ public Fraction(Integer top, Integer bottom) { This allows the Java compiler to do the work of dereferencing the current Java object. Java does provide a special variable called this that works like the self variable. In Java, this is typically only used when it is needed to differentiate between a parameter or local variable and an instance variable. - For example this alternate definition of the the Fraction constructor uses this to differentiate between parameters and instance variables. + For example, shows an alternate definition of the the Fraction constructor that uses this to differentiate between parameters and instance variables.

    From d15068ba949ff3a1069495acdbea70b2ef8f60d4 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 31 Jul 2026 19:00:32 +0300 Subject: [PATCH 249/357] added comments to code --- source/ch6_definingclasses.ptx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index 252ec9b..2d4a321 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -207,7 +207,7 @@ public void setDenominator(Integer denominator) { public Fraction(Integer top, Integer bottom) { - num = top; + num = top; // notice the use of num instead of top den = bottom; } @@ -228,7 +228,7 @@ public Fraction(Integer top, Integer bottom) { public Fraction(Integer num, Integer den) { - this.num = num; + this.num = num; // notice how we use this.num instead of num this.den = den; } From a34caa9d73799300fa3912ca38291c6db423208d Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 31 Jul 2026 19:01:30 +0300 Subject: [PATCH 250/357] added an idx tag --- source/ch6_definingclasses.ptx | 1 + 1 file changed, 1 insertion(+) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index 2d4a321..07b6931 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -196,6 +196,7 @@ public void setDenominator(Integer denominator) { Writing a constructor

    + constructor Once you have identified the instance variables for your class the next thing to consider is the constructor. In Java, constructors have the same name as the class and are declared public. They are declared without a return type. From b859e71dee5a68248a0093482a70d7d06a8a081c Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 31 Jul 2026 20:33:47 +0300 Subject: [PATCH 251/357] added listing tags --- source/ch6_definingclasses.ptx | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index 252ec9b..8bf6bdb 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -280,8 +280,8 @@ public Fraction(Integer num, Integer den) { Let’s begin by implementing addition in Java:

    - - + + public Fraction add(Fraction otherFrac) { Integer newNum = otherFrac.getDenominator() * this.numerator + @@ -292,6 +292,7 @@ public Fraction add(Fraction otherFrac) { } +

    First you will notice that the add method is declared as public Fraction The public part means that any other method may call the add method. @@ -304,8 +305,8 @@ public Fraction add(Fraction otherFrac) { So the following version of the code is equivalent:

    - - + + public Fraction add(Fraction otherFrac) { Integer newNum = otherFrac.getDenominator() * numerator + @@ -316,6 +317,7 @@ public Fraction add(Fraction otherFrac) { } +

    The addition takes place by multiplying each numerator by the opposite denominator before adding. @@ -365,8 +367,8 @@ public Fraction add(Fraction otherFrac) { The new methods that accomplish this task are as follows:

    - - + + public Fraction(Integer num) { this.numerator = num; @@ -377,6 +379,7 @@ public Fraction add(Integer other) { } +

    Notice that the overloading approach can provide us with a certain elegance to our code. @@ -389,8 +392,8 @@ public Fraction add(Integer other) { You should compile and run the program to see what happens.

    - - + + public class Fraction { private Integer numerator; @@ -434,6 +437,8 @@ public class Fraction { } + +
    From 4359d36941ae3bc440995d26966f7181f251e00b Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 31 Jul 2026 20:37:53 +0300 Subject: [PATCH 252/357] made the xml:id more defined --- source/ch6_definingclasses.ptx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index 8bf6bdb..0b1b293 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -280,7 +280,7 @@ public Fraction(Integer num, Integer den) { Let’s begin by implementing addition in Java:

    - + public Fraction add(Fraction otherFrac) { @@ -305,7 +305,7 @@ public Fraction add(Fraction otherFrac) { So the following version of the code is equivalent:

    - + public Fraction add(Fraction otherFrac) { @@ -438,7 +438,7 @@ public class Fraction { - + From e0796f87757c40d043417dc72a01a6f5f663beed Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 31 Jul 2026 20:51:02 +0300 Subject: [PATCH 253/357] made half programs that won't run on its own in a different format --- source/ch6_definingclasses.ptx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index 0b1b293..2c00298 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -281,7 +281,7 @@ public Fraction(Integer num, Integer den) {

    - + public Fraction add(Fraction otherFrac) { Integer newNum = otherFrac.getDenominator() * this.numerator + @@ -306,7 +306,7 @@ public Fraction add(Fraction otherFrac) {

    - + public Fraction add(Fraction otherFrac) { Integer newNum = otherFrac.getDenominator() * numerator + @@ -368,7 +368,7 @@ public Fraction add(Fraction otherFrac) {

    - + public Fraction(Integer num) { this.numerator = num; From d83e30dfdd29ab550732be4acc10ed1917b0c9c4 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 31 Jul 2026 20:54:52 +0300 Subject: [PATCH 254/357] add listing to txt --- source/ch6_definingclasses.ptx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index 2c00298..abd13ea 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -277,7 +277,7 @@ public Fraction(Integer num, Integer den) { However, if you reassign the parameter to a completely new object inside the method (e.g., otherFrac = new Fraction(0,1);), it would not affect the original variable outside the method, because you are only changing the local copy of the reference.

    - Let’s begin by implementing addition in Java: + shows the first part of the Fraction class definition.

    @@ -302,7 +302,7 @@ public Fraction add(Fraction otherFrac) {

    Second, you will notice that the method makes use of the this variable. In this method, this is not necessary, because there is no ambiguity about the numerator and denominator variables. - So the following version of the code is equivalent: + is an equivalent version of .

    @@ -364,7 +364,7 @@ public Fraction add(Fraction otherFrac) { To solve the problem of adding an Integer and a Fraction in Java we will overload both the constructor and the add method. We will overload the constructor so that if it only receives a single Integer it will convert the Integer into a Fraction. We will also overload the add method so that if it receives an Integer as a parameter it will first construct a Fraction from that integer and then add the two Fractions together. - The new methods that accomplish this task are as follows: + shows the new methods that accomplish this task.

    From ae6b7aeef75b34b1356252c4a760b0579f5a6d2b Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 31 Jul 2026 20:55:25 +0300 Subject: [PATCH 255/357] add listing to txt --- source/ch6_definingclasses.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index abd13ea..a5a1573 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -388,7 +388,7 @@ public Fraction add(Integer other) {

    - Our full Fraction class to this point would look like the following. + Our full Fraction class to this point would look . You should compile and run the program to see what happens.

    From 3b6a1e381a007dfdf6a5e38c51fd148ca8bbd89c Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 31 Jul 2026 21:48:23 +0300 Subject: [PATCH 256/357] addd comments to code blocks --- source/ch6_definingclasses.ptx | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index ba083b2..0c71d11 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -303,11 +303,12 @@ public Fraction(Integer num, Integer den) { -public Fraction add(Fraction otherFrac) { +public Fraction add(Fraction otherFrac) { Integer newNum = otherFrac.getDenominator() * this.numerator + - this.denominator * otherFrac.getNumerator(); + this.denominator * otherFrac.getNumerator(); // notice the use of this. + Integer newDen = this.denominator * otherFrac.getDenominator(); // find the new denominator Integer newDen = this.denominator * otherFrac.getDenominator(); - Integer common = gcd(newNum, newDen); + Integer common = gcd(newNum, newDen); // find the greatest common divisor return new Fraction(newNum/common, newDen/common); } @@ -329,7 +330,7 @@ public Fraction add(Fraction otherFrac) { public Fraction add(Fraction otherFrac) { Integer newNum = otherFrac.getDenominator() * numerator + - denominator * otherFrac.getNumerator(); + denominator * otherFrac.getNumerator(); // notice the absence of this. Integer newDen = denominator * otherFrac.getDenominator(); Integer common = gcd(newNum, newDen); return new Fraction(newNum/common, newDen/common); @@ -388,12 +389,12 @@ public Fraction add(Fraction otherFrac) { -public Fraction(Integer num) { - this.numerator = num; +public Fraction(Integer num) { + this.numerator = num; // set the numerator to the Integer this.denominator = 1; } -public Fraction add(Integer other) { - return add(new Fraction(other)); +public Fraction add(Integer other) { // overload the add method when the parameter is an Integer + return add(new Fraction(other)); } @@ -415,11 +416,11 @@ public Fraction add(Integer other) { public class Fraction { private Integer numerator; private Integer denominator; - public Fraction(Integer num, Integer den) { + public Fraction(Integer num, Integer den) { // constructor that takes two Integers this.numerator = num; this.denominator = den; } - public Fraction(Integer num) { + public Fraction(Integer num) { // constructor that takes a single Integer, sets the denominator to 1 this.numerator = num; this.denominator = 1; } @@ -435,10 +436,10 @@ public class Fraction { Integer common = gcd(newNum,newDen); return new Fraction(newNum/common, newDen/common ); } - public Fraction add(Integer other) { + public Fraction add(Integer other) { // overload the add method when the parameter is an Integer return add(new Fraction(other)); } - private static Integer gcd(Integer m, Integer n) { + private static Integer gcd(Integer m, Integer n) { // a helper method for the add method while (m % n != 0) { Integer oldm = m; Integer oldn = n; @@ -447,7 +448,7 @@ public class Fraction { } return n; } - public static void main(String[] args) { + public static void main(String[] args) { // a main method Fraction f1 = new Fraction(1,2); System.out.println(f1.add(1)); } From 1a65123021360234424eb164edb090bc5a70e196 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 31 Jul 2026 21:53:57 +0300 Subject: [PATCH 257/357] accidnetal duplicate --- source/ch6_definingclasses.ptx | 1 - 1 file changed, 1 deletion(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index 0c71d11..c1b2d6f 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -307,7 +307,6 @@ public Fraction add(Fraction otherFrac) { Integer newNum = otherFrac.getDenominator() * this.numerator + this.denominator * otherFrac.getNumerator(); // notice the use of this. Integer newDen = this.denominator * otherFrac.getDenominator(); // find the new denominator - Integer newDen = this.denominator * otherFrac.getDenominator(); Integer common = gcd(newNum, newDen); // find the greatest common divisor return new Fraction(newNum/common, newDen/common); } From eac2a83815a2d440ff936af20ecadd6a81f11bd1 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 31 Jul 2026 22:34:51 +0300 Subject: [PATCH 258/357] added listing tags --- source/ch6_definingclasses.ptx | 40 ++++++++++++++++++++-------------- 1 file changed, 24 insertions(+), 16 deletions(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index c1b2d6f..a5915c9 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -465,12 +465,13 @@ public class Fraction { If you ran the program above you probably noticed that the output is not very satisfying. Chances are your output looked something like this:

    - - + + Fraction@6ff3c5b5 +

    The reason is that we have not yet provided a friendly string representation for our Fraction objects. @@ -555,14 +556,15 @@ Fraction@6ff3c5b5 A simple version of the method is provided below.

    - - + + public String toString() { return numerator.toString() + "/" + denominator.toString(); } +

    The other important class for us to implement from the list of methods inherited from Object is the equals method. @@ -573,30 +575,32 @@ public String toString() { Therefore once you write your own equals method:

    - - + + object1 == object2 +

    is NOT the same as:

    - - + + object1.equals(object2) +

    Here is an equals method for the Fraction class:

    - - + + public boolean equals(Fraction other) { Integer num1 = this.numerator * other.getDenominator(); @@ -608,6 +612,7 @@ public boolean equals(Fraction other) { } +

    One important thing to remember about equals is that it only checks to see if two objects are equal – it does not have any notion of less than or greater than. @@ -634,14 +639,15 @@ public boolean equals(Fraction other) { Here is code that makes the Fraction class a child of Number:

    - - + + public class Fraction extends Number { ... } +

    extends @@ -685,8 +691,8 @@ public class Fraction extends Number { This really isn’t much work for us to implement these methods, as all we have to do is some type conversion and some division:

    - - + + public double doubleValue() { return numerator.doubleValue() / denominator.doubleValue(); @@ -702,6 +708,7 @@ public long longValue() { } +

    is-a @@ -720,14 +727,15 @@ public long longValue() { Suppose you try to define a method as follows:

    - - + + public void test(Number a, Number b) { a.add(b); } +

    The Java compiler would give an error because add is not a defined method of the Number class. From e23d4f923b67e272c8d0e5c0e13c1e877c73f498 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 31 Jul 2026 22:36:52 +0300 Subject: [PATCH 259/357] fixed xml:id --- source/ch6_definingclasses.ptx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index a5915c9..b7c78b4 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -575,7 +575,7 @@ public String toString() { Therefore once you write your own equals method:

    - + object1 == object2 @@ -639,7 +639,7 @@ public boolean equals(Fraction other) { Here is code that makes the Fraction class a child of Number:

    - + public class Fraction extends Number { From 8c744053068f81620be04ec13c7e29e81be379ff Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 31 Jul 2026 22:40:29 +0300 Subject: [PATCH 260/357] added idx and term tags --- source/ch6_definingclasses.ptx | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index b7c78b4..b14761a 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -488,7 +488,7 @@ Fraction@6ff3c5b5

    toString In Java, the equivalent of __str__ is the toString method. - Every object in Java already has a toString method defined for it because every class in Java automatically inherits from the Object class. + Every object in Java already has a toString method defined for it because every class in Java automatically inherits from the Object class. The Object class provides default implementations for the following methods.

    @@ -567,6 +567,7 @@ public String toString() {

    + equals The other important class for us to implement from the list of methods inherited from Object is the equals method. In Java, when two objects are compared using the == operator they are tested to see if they are exactly the same object (that is, do the two objects occupy the same exact space in the computer’s memory?). This is also the default behavior of the equals method provided by Object. @@ -651,7 +652,7 @@ public class Fraction extends Number {

    extends - The keyword extends tells the compiler that the class Fraction extends, or adds new functionality to the Number class. + The keyword extends tells the compiler that the class Fraction extends, or adds new functionality to the Number class. A child class always extends its parent.

    From e15fa0cf20aa73e7f17afe4be05c543b40a553f8 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 31 Jul 2026 22:52:03 +0300 Subject: [PATCH 261/357] added listing to text and program tags --- source/ch6_definingclasses.ptx | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index b14761a..b2a66fa 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -462,7 +462,7 @@ public class Fraction {

    - If you ran the program above you probably noticed that the output is not very satisfying. Chances are your output looked something like this: + If you ran the program above you probably noticed that the output is not very satisfying. Chances are your output looked something like .

    @@ -552,8 +552,7 @@ Fraction@6ff3c5b5

    We are not interested in most of the methods on that list, and many Java programmers live happy and productive lives without knowing much about most of the methods on that list. - However, to make our output nicer we will implement the toString method for the Fraction class. - A simple version of the method is provided below. + However, to make our output nicer we will implement the toString method for the Fraction class. shows a simple version of the method.

    @@ -576,8 +575,8 @@ public String toString() { Therefore once you write your own equals method:

    - - + + object1 == object2 @@ -585,11 +584,11 @@ object1 == object2

    - is NOT the same as: + is NOT the same as .

    - + object1.equals(object2) @@ -597,7 +596,7 @@ object1.equals(object2)

    - Here is an equals method for the Fraction class: + is an equals method for the Fraction class.

    @@ -637,11 +636,11 @@ public boolean equals(Fraction other) {

    - Here is code that makes the Fraction class a child of Number: + makes the Fraction class a child of Number.

    - + public class Fraction extends Number { ... @@ -689,7 +688,7 @@ public class Fraction extends Number {

    - This really isn’t much work for us to implement these methods, as all we have to do is some type conversion and some division: + This really isn’t much work for us to implement these methods, as all we have to do is some type conversion and some division as shown in .

    @@ -725,7 +724,7 @@ public long longValue() {

    - Suppose you try to define a method as follows: + Suppose you try to define a method as .

    From e7368957fb0dbf8be5633d126aaae50a152b50c3 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 31 Jul 2026 23:55:17 +0300 Subject: [PATCH 262/357] added comments to code --- source/ch6_definingclasses.ptx | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index c1b2d6f..aa0a311 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -559,7 +559,7 @@ Fraction@6ff3c5b5 public String toString() { - return numerator.toString() + "/" + denominator.toString(); + return numerator.toString() + "/" + denominator.toString(); // convert to a string } @@ -598,10 +598,10 @@ object1.equals(object2) -public boolean equals(Fraction other) { - Integer num1 = this.numerator * other.getDenominator(); - Integer num2 = this.denominator * other.getNumerator(); - if (num1 == num2) + +public boolean equals(Fraction other) { // a method to compare two fractions + Integer num1 = this.numerator * other.getDenominator(); Integer num2 = this.denominator * other.getNumerator(); + if (num1 == num2) // if the numerators are equal in value, the fractions are equal return true; else return false; @@ -688,16 +688,16 @@ public class Fraction extends Number { -public double doubleValue() { +public double doubleValue() { // convert to a double return numerator.doubleValue() / denominator.doubleValue(); } -public float floatValue() { +public float floatValue() { // convert to a float return numerator.floatValue() / denominator.floatValue(); } -public int intValue() { +public int intValue() { // convert to an int return numerator.intValue() / denominator.intValue(); } -public long longValue() { +public long longValue() { // convert to a long return numerator.longValue() / denominator.longValue(); } @@ -724,7 +724,7 @@ public long longValue() { public void test(Number a, Number b) { - a.add(b); + a.add(b); // this is a bad idea } From 965723778987bd20999c9cd1ef3d5fb9d81629e9 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Sat, 1 Aug 2026 00:43:49 +0300 Subject: [PATCH 263/357] added listing tags --- source/ch6_definingclasses.ptx | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index c1b2d6f..582ecd6 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -769,8 +769,8 @@ public void test(Number a, Number b) { Here is an excerpt from the official documentation for the compareTo method as specified by the Comparable interface.

    - - + + int compareTo(T o) Compares this object with the specified object for order. Returns a @@ -782,27 +782,29 @@ iff y.compareTo(x) throws an exception.) ... +

    To make our Fraction class Comparable we must modify the class declaration line as follows:

    - - + + public class Fraction extends Number implements Comparable<Fraction> { ... } +

    The specification Comparable<Fraction> makes it clear that Fraction is only comparable with another Fraction. The compareTo method could be implemented as follows:

    - - + + public int compareTo(Fraction other) { Integer num1 = this.numerator * other.getDenominator(); @@ -811,8 +813,11 @@ public int compareTo(Fraction other) { } + + +
    Static member variables From 591a5fca21d0d0f7c02572fe9cfcf22f12874b3b Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Sat, 1 Aug 2026 00:46:09 +0300 Subject: [PATCH 264/357] fixed xml:id --- source/ch6_definingclasses.ptx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index 582ecd6..ac53379 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -803,7 +803,7 @@ public class Fraction extends Number implements Comparable<Fraction> { The compareTo method could be implemented as follows:

    - + public int compareTo(Fraction other) { @@ -814,7 +814,7 @@ public int compareTo(Fraction other) { - +
    From cfcccbda92d9a0ae38ab15b78e563b4463a43743 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Sat, 1 Aug 2026 00:47:26 +0300 Subject: [PATCH 265/357] added listing to tags --- source/ch6_definingclasses.ptx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index ac53379..3450de8 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -766,7 +766,7 @@ public void test(Number a, Number b) {

    The Comparable interface says that any object that claims to be Comparable must implement the compareTo method. - Here is an excerpt from the official documentation for the compareTo method as specified by the Comparable interface. + Here is an excerpt from the official documentation for the compareTo method as specified by the Comparable interface. shows the excerpt.

    @@ -785,7 +785,7 @@ iff y.compareTo(x) throws an exception.)

    - To make our Fraction class Comparable we must modify the class declaration line as follows: + To make our Fraction class Comparable we must modify the class declaration line as shown in .

    @@ -800,7 +800,7 @@ public class Fraction extends Number implements Comparable<Fraction> {

    The specification Comparable<Fraction> makes it clear that Fraction is only comparable with another Fraction. - The compareTo method could be implemented as follows: + The compareTo method could be implemented as shown in .

    From 704454092a7603efef8fec2136897a67d91921d0 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Mon, 3 Aug 2026 17:05:04 +0300 Subject: [PATCH 266/357] added comments --- source/ch6_definingclasses.ptx | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index c1b2d6f..1c96ab1 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -576,7 +576,7 @@ public String toString() { -object1 == object2 +object1 == object2 // this checks to see if the two objects are the same object in memory @@ -587,7 +587,7 @@ object1 == object2 -object1.equals(object2) +object1.equals(object2) // this checks to see if the two objects are equal by looking at their instance variables @@ -598,7 +598,7 @@ object1.equals(object2) -public boolean equals(Fraction other) { +public boolean equals(Fraction other) { // check if this fraction is equal to another fraction Integer num1 = this.numerator * other.getDenominator(); Integer num2 = this.denominator * other.getNumerator(); if (num1 == num2) @@ -637,7 +637,7 @@ public boolean equals(Fraction other) { -public class Fraction extends Number { +public class Fraction extends Number { // fraction class is a child of Number ... } @@ -790,7 +790,7 @@ iff y.compareTo(x) throws an exception.) -public class Fraction extends Number implements Comparable<Fraction> { +public class Fraction extends Number implements Comparable<Fraction> { // fraction class is a child of Number and implements the Comparable interface ... } @@ -804,7 +804,7 @@ public class Fraction extends Number implements Comparable<Fraction> { -public int compareTo(Fraction other) { +public int compareTo(Fraction other) { // compare this fraction with another fraction Integer num1 = this.numerator * other.getDenominator(); Integer num2 = this.denominator * other.getNumerator(); return num1 - num2; From 5e7bd1c715762b08a179cefd475bc3f3178db379 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Mon, 3 Aug 2026 17:17:53 +0300 Subject: [PATCH 267/357] added listing tags --- source/ch6_definingclasses.ptx | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index c1b2d6f..6a0f461 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -823,8 +823,8 @@ public int compareTo(Fraction other) { In Python, we could do this as follows:

    - - + + class Student: numStudents = 0 @@ -839,13 +839,14 @@ def main(): main() +

    In Java, we would write this same example using a static declaration.

    - - + + public class Student { public static Integer numStudents = 0; @@ -865,6 +866,7 @@ public class Student { } +

    static member variable From abb645512e3b0befe3c017429f69ceb94fa18255 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Mon, 3 Aug 2026 17:19:16 +0300 Subject: [PATCH 268/357] added listing in tags --- source/ch6_definingclasses.ptx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index 6a0f461..0e0a0e9 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -820,7 +820,7 @@ public int compareTo(Fraction other) { Suppose that you wanted to write a Student class so that the class could keep track of the number of students it had created. Although you could do this with a global counter variable that is an ugly solution. The right way to do it is to use a static variable. - In Python, we could do this as follows: + shows how to do this in Python.

    @@ -842,7 +842,7 @@ main()

    - In Java, we would write this same example using a static declaration. + shows how to do this in Java.

    From aca87817d4b736bb837967455d763af15917f452 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Mon, 3 Aug 2026 17:24:03 +0300 Subject: [PATCH 269/357] fixed some mistakes --- source/ch6_definingclasses.ptx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index 0e0a0e9..a99c5d9 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -820,7 +820,7 @@ public int compareTo(Fraction other) { Suppose that you wanted to write a Student class so that the class could keep track of the number of students it had created. Although you could do this with a global counter variable that is an ugly solution. The right way to do it is to use a static variable. - shows how to do this in Python. + shows how to do this in Python.

    @@ -842,7 +842,7 @@ main()

    - shows how to do this in Java. + shows how to do this in Java.

    @@ -870,7 +870,7 @@ public class Student {

    static member variable - In this example notice that we create a static member variable by using the static modifier on the variable declaration. Once a variable has been declared static in Java it can be accessed from inside the class without prefixing the name of the class as we had to do in Python. + In , notice that we create a static member variable by using the static modifier on the variable declaration. Once a variable has been declared static in Java it can be accessed from inside the class without prefixing the name of the class as we had to do in Python.

    From cac7e73cd8945ff795ad5cfec558236641c4d75f Mon Sep 17 00:00:00 2001 From: Jan Pearce Date: Mon, 3 Aug 2026 11:05:47 -0400 Subject: [PATCH 270/357] correcting use of term tag --- source/ch6_definingclasses.ptx | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index b2a66fa..6f39d5f 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -215,7 +215,7 @@ public void setDenominator(Integer denominator) { // setter method
    Writing a constructor -

    +

    constructor Once you have identified the instance variables for your class the next thing to consider is the constructor. In Java, constructors have the same name as the class and are declared public. They are declared without a return type. @@ -278,8 +278,8 @@ public Fraction(Integer num, Integer den) {

  • pass-by-value - value of the reference - Java is strictly pass-by-value. For primitive types (like int), a copy of the value is passed. For object types (like our Fraction), a copy of the value of the reference (the memory address) is passed. + + Java is strictly pass-by-value. For primitive types (like int), a copy of the value is passed. For object types (like our Fraction), a copy of the reference(Namely, the memory address) is passed.

  • @@ -571,7 +571,7 @@ public String toString() { In Java, when two objects are compared using the == operator they are tested to see if they are exactly the same object (that is, do the two objects occupy the same exact space in the computer’s memory?). This is also the default behavior of the equals method provided by Object. The equals method allows us to decide if two objects are equal by looking at their instance variables. - However it is important to remember that since Java does not have operator overloading if you want to use your equals method you must call it directly. + However it is important to remember that since Java does not have operator overloading if you want to use your equals method you must call it directly. Therefore once you write your own equals method:

    @@ -631,7 +631,7 @@ public boolean equals(Fraction other) { If you look at the documentation for Integer you will see that Integer’s parent class is Number. Number is an abstract class that specifies several methods that all of its children must implement. In Java an abstract class is more than just a placeholder for common methods. - In Java an abstract class has the power to specify certain methods that all of its children must implement. + In Java an abstract class has the power to specify certain methods that all of its children must implement. You can trace this power back to the strong typing nature of Java.

    @@ -650,7 +650,7 @@ public class Fraction extends Number {
  • - extends + extending a class The keyword extends tells the compiler that the class Fraction extends, or adds new functionality to the Number class. A child class always extends its parent.

    @@ -720,7 +720,7 @@ public long longValue() {

    - However, and this is a big however, it is important to remember that if you specify Number as the type of a particular parameter then the Java compiler will only let you use the methods of a Number: longValue, intValue, floatValue, and doubleValue. + However, and this is a big however, it is important to remember that if you specify Number as the type of a particular parameter then the Java compiler will only let you use the methods of a Number: longValue, intValue, floatValue, and doubleValue.

    @@ -739,7 +739,7 @@ public void test(Number a, Number b) {

    The Java compiler would give an error because add is not a defined method of the Number class. - You will still get this error even if all your code that calls this test method passes two Fractions as parameters (remember that Fraction does implement add). + You will still get this error even if all your code that calls this test method passes two Fractions as parameters (remember that Fraction does implement add).

    @@ -748,7 +748,6 @@ public void test(Number a, Number b) { Interfaces

    - Comparable single inheritance Lets turn our attention to making a list of fractions sortable by the standard Java sorting method Collections.sort. In Python, we would just need to implement the __cmp__ method. From f48fa0e6de1db9d41e126342f352d45400e5f182 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Mon, 3 Aug 2026 18:29:27 +0300 Subject: [PATCH 271/357] added comments to code --- source/ch6_definingclasses.ptx | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index 9ad5051..d3632f8 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -836,13 +836,13 @@ public int compareTo(Fraction other) { class Student: numStudents = 0 - def __init__(self, id, name): + def __init__(self, id, name): self.id = id self.name = name - Student.numStudents = Student.numStudents + 1 + Student.numStudents = Student.numStudents + 1 # increment the static variable def main(): for i in range(10): - s = Student(i,"Student-"+str(i)) + s = Student(i,"Student-"+str(i)) // create a new student print('Number of students:', Student.numStudents) main() @@ -856,13 +856,13 @@ main() public class Student { - public static Integer numStudents = 0; + public static Integer numStudents = 0; // static member variable, shared by all instances of the class private int id; private String name; public Student(Integer id, String name) { this.id = id; this.name = name; - numStudents = numStudents + 1; + numStudents = numStudents + 1; // a static variable, that can be accessed without the Student prefix } public static void main(String[] args) { for(Integer i = 0; i < 10; i++) { From ef74077384e65e04efaf3b2b0419a070c074ee88 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Mon, 3 Aug 2026 18:32:35 +0300 Subject: [PATCH 272/357] fixed a comment --- source/ch6_definingclasses.ptx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index d3632f8..0c04a74 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -839,10 +839,10 @@ class Student: def __init__(self, id, name): self.id = id self.name = name - Student.numStudents = Student.numStudents + 1 # increment the static variable + Student.numStudents = Student.numStudents + 1 # this is a static variable, that can be accessed without the self prefix def main(): for i in range(10): - s = Student(i,"Student-"+str(i)) // create a new student + s = Student(i,"Student-"+str(i)) # create a new Student object print('Number of students:', Student.numStudents) main() From 7002f82269f189aa11d1bad03060ae46ed010c2a Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Mon, 3 Aug 2026 18:33:25 +0300 Subject: [PATCH 273/357] fixed a comment --- source/ch6_definingclasses.ptx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index 0c04a74..1573906 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -839,7 +839,8 @@ class Student: def __init__(self, id, name): self.id = id self.name = name - Student.numStudents = Student.numStudents + 1 # this is a static variable, that can be accessed without the self prefix + # this is a static variable, that can be accessed without the self prefix + Student.numStudents = Student.numStudents + 1 def main(): for i in range(10): s = Student(i,"Student-"+str(i)) # create a new Student object From e1d138d588a5c2da5dbb4e11ce44707d87cbd1c6 Mon Sep 17 00:00:00 2001 From: "nshizirungudieumerci@gmail.com" Date: Mon, 3 Aug 2026 13:22:31 -0400 Subject: [PATCH 274/357] Added the listing tag to the chapter 6.7.1, I also renamed the XMLID to a more meaningful name, and added a paragrph describing the listing --- source/ch6_definingclasses.ptx | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index c1b2d6f..004cb68 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -879,8 +879,12 @@ public class Student { We have already discussed the most common static method of all, main. However in our Fraction class we also implemented a method to calculate the greatest common divisor for two fractions (gdc). There is no reason for this method to be a member method since it takes two Integer values as its parameters. Therefore we declare the method to be a static method of the class. Furthermore, since we are only going to use this gcd method for our own purposes we can make it private.

    +

    + shows the implementation of the static gcd helper method in Java. +

    - + + private static Integer gcd(Integer m, Integer n) { while (m % n != 0) { @@ -893,6 +897,7 @@ private static Integer gcd(Integer m, Integer n) { } +
    From e2d3dbe30e35e51203b0aeb37621cb2fadcabecd Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Mon, 3 Aug 2026 20:30:26 +0300 Subject: [PATCH 275/357] add comments --- source/ch6_definingclasses.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index d773a10..8ca9e36 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -905,7 +905,7 @@ public class Student { -private static Integer gcd(Integer m, Integer n) { +private static Integer gcd(Integer m, Integer n) { // static method to compute the greatest common divisor of two integers while (m % n != 0) { Integer oldm = m; Integer oldn = n; From 0045755090e8647d8ed83c96bbb9cabc0d13beb4 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Mon, 3 Aug 2026 22:06:36 +0300 Subject: [PATCH 276/357] fix math formatting --- source/ch7_recursion.ptx | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/source/ch7_recursion.ptx b/source/ch7_recursion.ptx index a0d2c01..4daa403 100644 --- a/source/ch7_recursion.ptx +++ b/source/ch7_recursion.ptx @@ -14,24 +14,24 @@

    - Let's take the familiar factorial function, which calculates n! (read as "n factorial"), so for example 5! = 5 × 4 × 3 × 2 × 1 = 120. Factorial is a classic example of recursion, where the function calls itself with a smaller value until it reaches a base case. - In general, n! = n \times (n-1) \times (n-2) \times \cdots \times 2 \times 1, - or recursively defined as n! = n \times (n-1)! with base cases 0! = 1 and 1! = 1. + Let's take the familiar factorial function, which calculates n! (read as "n factorial"), so for example 5! = 5 × 4 × 3 × 2 × 1 = 120. Factorial is a classic example of recursion, where the function calls itself with a smaller value until it reaches a base case. + In general, n! = n \times (n-1) \times (n-2) \times \cdots \times 2 \times 1, + or recursively defined as n! = n \times (n-1)! with base cases 0! = 1 and 1! = 1.

    You may recall mathematical notation using the symbol \sum (Greek letter sigma) to represent "sum." For example, when we sum all elements in an array, we write - \sum_{i=0}^{n-1} a_i, where i=0 below the symbol indicates we start at index 0, + \sum_{i=0}^{n-1} a_i, where i=0 below the symbol indicates we start at index 0, n-1 above it means we end at index n-1, and a_i represents the array - element at each index i. Similarly, \sum_{i=1}^{n} i means "sum all integers + element at each index i. Similarly, \sum_{i=1}^{n} i means "sum all integers i from 1 to n."

    Factorial involves multiplication rather than addition, so we use the product symbol - \prod (Greek letter pi): n! = \prod_{i=1}^{n} i, which means "multiply + \prod (Greek letter pi): n! = \prod_{i=1}^{n} i, which means "multiply all integers i from 1 to n." Both summation and factorial can be expressed recursively—summation as the first element plus the sum of remaining elements, and factorial - as n \times (n-1)!. + as n \times (n-1)!.

    Here is a Python implementation of factorial using just one function: From 2f10a33ee3c408700ac47d2025f1eb6148a35872 Mon Sep 17 00:00:00 2001 From: "nshizirungudieumerci@gmail.com" Date: Mon, 3 Aug 2026 15:08:46 -0400 Subject: [PATCH 277/357] I added the listing tags and placed the ref tag in the beginning paragraph --- source/ch6_definingclasses.ptx | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index 1e16fed..19da9a6 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -922,11 +922,11 @@ private static Integer gcd(Integer m, Integer n) { Full Implementation of the Fraction Class

    - Here is a final version of the Fraction class in Java, which includes all the features we discussed: + shows a final version of the Fraction class in Java, which includes all the features we discussed:

    - + import java.util.ArrayList; import java.util.Collections; @@ -1020,6 +1020,7 @@ public class Fraction extends Number implements Comparable<Fraction> { } +
    From ff92dab14484bef4e7e6b006f7f2deedc01e241e Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Mon, 3 Aug 2026 22:21:22 +0300 Subject: [PATCH 278/357] add listing tags --- source/ch7_recursion.ptx | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/source/ch7_recursion.ptx b/source/ch7_recursion.ptx index a0d2c01..15bb4f9 100644 --- a/source/ch7_recursion.ptx +++ b/source/ch7_recursion.ptx @@ -36,7 +36,8 @@

    Here is a Python implementation of factorial using just one function:

    - + + def factorial(n): # Check for negative numbers @@ -54,11 +55,13 @@ print(str(number) + "! is " + str(factorial(number))) +

    Many Python programs organize related functions into classes. The same factorial function can be placed inside a class as a method instead of as a function. When this is done, you need to create an instance of the class in order to call the method. Below, we create the class MathTools with a method factorial, and we call it from the main function.

    - + + class MTools: def factorial(self, n): @@ -81,6 +84,7 @@ def main(): main() +

    See if you can spot the differences in the Java version below. @@ -88,7 +92,8 @@ main()

    Here is the equivalent Java code:

    - + + public class MTools { public static int factorial(int n) { @@ -112,6 +117,7 @@ public class MTools { } +

    Notice the key differences from Python: instead of def factorial(n):, Java uses public static int factorial(int n) which declares the method's visibility as public, that it belongs to the class rather than an instance (hence, static), the return type as integer, and the parameter type also as integer. The recursive logic—base case and recursive step—remains identical to Python, and, of course, all code blocks use curly braces {} instead of indentation.

    From 5d01328d61a73d3996c8c4ac57aa0716a3605431 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Mon, 3 Aug 2026 22:30:08 +0300 Subject: [PATCH 279/357] added listing to text --- source/ch7_recursion.ptx | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/source/ch7_recursion.ptx b/source/ch7_recursion.ptx index 15bb4f9..007f313 100644 --- a/source/ch7_recursion.ptx +++ b/source/ch7_recursion.ptx @@ -34,7 +34,7 @@ as n \times (n-1)!.

    - Here is a Python implementation of factorial using just one function: + is the Python implementation of the factorial function. It checks for negative numbers, defines the base case for 0! and 1!, and implements the recursive step.

    @@ -60,6 +60,10 @@ print(str(number) + "! is " + str(factorial(number)))

    Many Python programs organize related functions into classes. The same factorial function can be placed inside a class as a method instead of as a function. When this is done, you need to create an instance of the class in order to call the method. Below, we create the class MathTools with a method factorial, and we call it from the main function.

    +

    + is the Python implementation of the factorial function as a method within a class. It maintains the same logic as the previous function but is now encapsulated within a class structure. +

    + @@ -90,7 +94,7 @@ main() See if you can spot the differences in the Java version below.

    - Here is the equivalent Java code: + is the Java implementation of the factorial function. It follows the same logic as the Python version but adapts to Java's syntax and type system.

    From 1862bd7595afb4cce591a73a249d05a576f21c12 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Mon, 3 Aug 2026 22:41:09 +0300 Subject: [PATCH 280/357] added listing tags --- source/ch7_recursion.ptx | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/source/ch7_recursion.ptx b/source/ch7_recursion.ptx index 4daa403..b8ac849 100644 --- a/source/ch7_recursion.ptx +++ b/source/ch7_recursion.ptx @@ -131,7 +131,8 @@ public class MTools {

    First, let's see what happens if we try to write a recursive array sum function without using a helper method. In this approach, the user must provide the starting index, which is awkward and exposes implementation details:

    - + + class ArrayProcessor: def sum_array(self, arr, index): @@ -156,11 +157,13 @@ def main(): main() +

    This approach has a significant problem, namely that users must remember to start with index 0. Hence, the method signature is cluttered with an implementation detail, and it's easy to make a mistake by passing the wrong starting index. The same awkward pattern appears in Java:

    - + + public class ArrayProcessor { public static int sumArray(int[] arr, int index) { @@ -182,6 +185,7 @@ public class ArrayProcessor { } +

    Both versions force users to understand and provide implementation details they shouldn't need to know about. Now let's see how helper methods solve this problem by providing a clean, user-friendly interface. Notice how the public method only requires the array itself, and the hidden recursive logic tracks the current index position. @@ -189,7 +193,8 @@ public class ArrayProcessor {

    Here's the improved Python version using a helper method:

    - + + class ArrayProcessor: def sum_array(self, arr): @@ -231,7 +236,8 @@ main()

    Now let's see the improved Java version using a helper method:

    - + + import java.util.Arrays; @@ -263,6 +269,7 @@ public class ArrayProcessor { } +

    Compare these improved versions with the earlier problematic ones. Notice how much cleaner the method calls become: processor.sum_array(numbers) in Python and sumArray(numbers) in Java. Users no longer need to worry about providing a starting index or understanding the internal mechanics of the recursion. The helper method pattern creates a clear separation between what users need to know (just pass an array) and the implementation details (tracking the index through recursion). From ea99928c5704dbf361dc864f7c4525e3742f3315 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Mon, 3 Aug 2026 22:46:38 +0300 Subject: [PATCH 281/357] added listing to text --- source/ch7_recursion.ptx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/source/ch7_recursion.ptx b/source/ch7_recursion.ptx index b8ac849..79b09b9 100644 --- a/source/ch7_recursion.ptx +++ b/source/ch7_recursion.ptx @@ -129,7 +129,7 @@ public class MTools {

    - First, let's see what happens if we try to write a recursive array sum function without using a helper method. In this approach, the user must provide the starting index, which is awkward and exposes implementation details: + First, let's see what happens if we try to write a recursive array sum function without using a helper method. In this approach, the user must provide the starting index, which is awkward and exposes implementation details. shows a Python version.

    @@ -160,7 +160,7 @@ main()

    - This approach has a significant problem, namely that users must remember to start with index 0. Hence, the method signature is cluttered with an implementation detail, and it's easy to make a mistake by passing the wrong starting index. The same awkward pattern appears in Java: + 's approach has a significant problem, namely that users must remember to start with index 0. Hence, the method signature is cluttered with an implementation detail, and it's easy to make a mistake by passing the wrong starting index. The same awkward pattern appears in Java as shown in .

    @@ -191,7 +191,7 @@ public class ArrayProcessor { Both versions force users to understand and provide implementation details they shouldn't need to know about. Now let's see how helper methods solve this problem by providing a clean, user-friendly interface. Notice how the public method only requires the array itself, and the hidden recursive logic tracks the current index position.

    - Here's the improved Python version using a helper method: + shows the improved Python version using a helper method.

    @@ -234,7 +234,7 @@ main()

    - Now let's see the improved Java version using a helper method: + The same helper method pattern can be applied in Java, as shown in . The public method sumArray provides a clean interface, while the private helper method sumHelper manages the recursion and index tracking.

    From c9ddb0279969820b80e909ad282bef432aec2f9a Mon Sep 17 00:00:00 2001 From: "nshizirungudieumerci@gmail.com" Date: Mon, 3 Aug 2026 15:47:31 -0400 Subject: [PATCH 282/357] added the listing tag and refrenced it in the paragraph above it --- source/ch7_recursion.ptx | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/source/ch7_recursion.ptx b/source/ch7_recursion.ptx index a0d2c01..7d333a2 100644 --- a/source/ch7_recursion.ptx +++ b/source/ch7_recursion.ptx @@ -298,10 +298,11 @@ public class ArrayProcessor {

    - The following Python code demonstrates a situation where a function calls itself indefinitely without a base case, leading to a RecursionError due to overflowing the call stack. + The following Python code in demonstrates a situation where a function calls itself indefinitely without a base case, leading to a RecursionError due to overflowing the call stack.

    - - + + + def cause_recursion_error(): """ This function calls itself without a base case, guaranteeing an error. @@ -317,6 +318,7 @@ public class ArrayProcessor { cause_recursion_error() +

    The following Java code demonstrates a similar situation, where a method calls itself indefinitely without a base case, leading to a StackOverflowError. From 29ac12b4d0a2b0750f61a295989598615ee80349 Mon Sep 17 00:00:00 2001 From: "nshizirungudieumerci@gmail.com" Date: Mon, 3 Aug 2026 15:50:51 -0400 Subject: [PATCH 283/357] Added the listing tag for 7.3.2 and refrenced it int he paragraph above --- source/ch7_recursion.ptx | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/source/ch7_recursion.ptx b/source/ch7_recursion.ptx index 7d333a2..aae48c8 100644 --- a/source/ch7_recursion.ptx +++ b/source/ch7_recursion.ptx @@ -321,10 +321,11 @@ public class ArrayProcessor {

    - The following Java code demonstrates a similar situation, where a method calls itself indefinitely without a base case, leading to a StackOverflowError. + The following Java code in demonstrates a similar situation, where a method calls itself indefinitely without a base case, leading to a StackOverflowError.

    - - + + + public class Crash { public static void causeStackOverflow() { // The line below will start the infinite recursion. @@ -342,6 +343,7 @@ public class ArrayProcessor { } +
    From 3e64cedc0d08358d2273085676e8037d4290e861 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Mon, 3 Aug 2026 23:46:36 +0300 Subject: [PATCH 284/357] added listing tags --- source/ch8_filehandling.ptx | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index ba5d0cf..329a7f3 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -165,6 +165,8 @@ public class CreateFile {

    Consider the following Python code example that reads each line of the file and prints it to the console.

    + + Data file for reading example
                         1
    @@ -177,8 +179,9 @@ public class CreateFile {
                         8
                     
    - - +
    + + filename = "myfile.txt" try: @@ -192,12 +195,14 @@ public class CreateFile { print("file could not be opened") +

    The following Java code functions very similarly to the previous Python. The main difference here is that unlike Python, in Java we use the Scanner object to iterate through and read lines in the file. You will notice that the structure of the Java code is still similar to the Python; Both use a try and catch statement to read the file and catch any errors.

    - + + import java.io.File; import java.io.FileNotFoundException; @@ -218,6 +223,7 @@ public class CreateFile { } +

    You may have noticed that there are some new methods you haven't seen yet. The hasNextLine() method checks if there is a next line in the file, and returns false if there isn't. This method allows us to iterate over every line till there is no next line. The nextLine() method of the Scanner object returns the next line in the file as a string.

    From 9564a2f690d1c8f1d4471607e160cc60b677a972 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Mon, 3 Aug 2026 23:55:06 +0300 Subject: [PATCH 285/357] add listing to text --- source/ch8_filehandling.ptx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 329a7f3..c6597dd 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -163,7 +163,7 @@ public class CreateFile { Let’s take a look at how we can use Python to understand how read file contents in Java. In order to read files generally you iterate through each line in the file and read the line's content. In Java, you read files in a very similar way, however in Java we will use the Scanner class in order to iterate through the lines.

    - Consider the following Python code example that reads each line of the file and prints it to the console. + Consider that reads each line of and prints it to the console.

    Data file for reading example @@ -198,7 +198,7 @@ public class CreateFile {

    - The following Java code functions very similarly to the previous Python. The main difference here is that unlike Python, in Java we use the Scanner object to iterate through and read lines in the file. You will notice that the structure of the Java code is still similar to the Python; Both use a try and catch statement to read the file and catch any errors. + functions very similarly to . The main difference here is that unlike Python, in Java we use the Scanner object to iterate through and read lines in the file. You will notice that the structure of the Java code is still similar to the Python; Both use a try and catch statement to read the file and catch any errors.

    From 09c9d407bcb22bbb5572f03340f2347f5da1e5cb Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Tue, 4 Aug 2026 00:01:43 +0300 Subject: [PATCH 286/357] add listing to text --- source/ch8_filehandling.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index c6597dd..b0e0a49 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -167,7 +167,7 @@ public class CreateFile {

    Data file for reading example - +
                         1
                         2
    
    From f46f5efd829f874966e868a4f20f2d665d401d64 Mon Sep 17 00:00:00 2001
    From: Habiba Sorour 
    Date: Tue, 4 Aug 2026 00:27:41 +0300
    Subject: [PATCH 287/357] add listing tags
    
    ---
     source/ch8_filehandling.ptx | 15 +++++++++------
     1 file changed, 9 insertions(+), 6 deletions(-)
    
    diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx
    index ba5d0cf..5399ecd 100644
    --- a/source/ch8_filehandling.ptx
    +++ b/source/ch8_filehandling.ptx
    @@ -75,8 +75,8 @@
             

    We will now create a File object. It is important to create a meaningful name for the File object. We will call ours myFile, and we will call our class CreateFileObject.

    - - + + import java.io.File; @@ -90,6 +90,7 @@ public class CreateFile { } +

    @@ -105,8 +106,8 @@ public class CreateFile {

    First, lets look at the equivalent Python code:

    - - + + filename = "newfile.txt" print("Attempting to write to '" + filename + "' using 'w' mode...") @@ -120,12 +121,13 @@ public class CreateFile { +

    Now, let's look at Java code that accomplishes the same task:

    - - + + import java.io.File; import java.io.IOException; @@ -148,6 +150,7 @@ public class CreateFile { } +

    From 82168dbff673f1c606a078604862ba0abafc760d Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Tue, 4 Aug 2026 00:32:07 +0300 Subject: [PATCH 288/357] fixed a broken code --- source/ch7_recursion.ptx | 1 + 1 file changed, 1 insertion(+) diff --git a/source/ch7_recursion.ptx b/source/ch7_recursion.ptx index 5f1da65..f04f71c 100644 --- a/source/ch7_recursion.ptx +++ b/source/ch7_recursion.ptx @@ -238,6 +238,7 @@ def main(): main() +

    separation of concerns The key insight here is called the separation of concerns. The public sum_array method provides a user-friendly interface—callers just pass an array and get the sum. Users don't need to know about indexes or how the recursion works internally. The private _sum_helper method handles the recursive logic with the extra parameter needed to track progress through the array. From 92c752881cd7ffda8fb79fd5f76759c8e12fc07b Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Tue, 4 Aug 2026 00:32:23 +0300 Subject: [PATCH 289/357] add listing in text --- source/ch8_filehandling.ptx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 5399ecd..e1b654d 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -73,7 +73,7 @@

    - We will now create a File object. It is important to create a meaningful name for the File object. We will call ours myFile, and we will call our class CreateFileObject. + We will now create a File object. It is important to create a meaningful name for the File object. We will call ours myFile, and we will call our class CreateFileObject. shows the code to create a File object in Java.

    @@ -104,7 +104,7 @@ public class CreateFile {

    - First, lets look at the equivalent Python code: + shows the equivalent code to create a file in Python.

    @@ -124,7 +124,7 @@ public class CreateFile {

    - Now, let's look at Java code that accomplishes the same task: + shows the equivalent code to create a file in Java.

    From b2ca8bc3d153299592bf50600c754dab0a627913 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Tue, 4 Aug 2026 00:35:11 +0300 Subject: [PATCH 290/357] fixed a code --- source/ch8_filehandling.ptx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index e1b654d..542ebfb 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -73,7 +73,7 @@

    - We will now create a File object. It is important to create a meaningful name for the File object. We will call ours myFile, and we will call our class CreateFileObject. shows the code to create a File object in Java. + We will now create a File object. It is important to create a meaningful name for the File object. We will call ours myFile, and we will call our class CreateFileObject. shows the code to create a File object in Java.

    @@ -104,7 +104,7 @@ public class CreateFile {

    - shows the equivalent code to create a file in Python. + shows the equivalent code to create a file in Python.

    @@ -124,7 +124,7 @@ public class CreateFile {

    - shows the equivalent code to create a file in Java. + shows the equivalent code to create a file in Java.

    From bf5eed8ed164d1f0b0cc3d882d4944f30ceab0ae Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Tue, 4 Aug 2026 16:14:43 +0300 Subject: [PATCH 291/357] add listing tags --- source/ch8_filehandling.ptx | 31 +++++++++++++++++++++++-------- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index ba5d0cf..6a7002c 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -9,17 +9,22 @@

    File handling is an integral part of programming. Most programming languages have the ability to create, read from, write to, and delete, files. In Python, most built-in libraries are available without needing to explicitly import additional packages, but some libraries like math do need to be imported. Consider the following.

    - + + + import math print(math.sqrt(25)) +

    Delete the first line that says import math and see what happens. The import math is needed. The same program in Java would look like this:

    - + + + import java.lang.Math; @@ -30,6 +35,8 @@ } + +

    Note the use of import java.lang.Math; in the above to import the Math class. Unlike Python, Java requires explicit import for most libraries, including the Math class and many classes related to file handling.

    @@ -38,34 +45,42 @@ Much like the Math class, in order for your program to work with files you need use import. Java includes a class called File in the io library. This class allows you to create File objects, and use its public methods.

    - + + import java.io.File; + +

    The Scanner class from the util library will need to be imported if there is any need for a program to read a file. It should be noted that this library is unnecessary if the program will not be reading any data from a file.

    - - + + import java.util.Scanner; +

    The FileWriter class can be used to write to files. In the same way that the Scanner class isn't needed unless the program will read from a file, the FileWriter class isn't needed unless the program will write to a file.

    - + + import java.io.FileWriter; +

    Finally, these last two classes provide error handling and must be used in tandem with the File class when reading from or writing to files. IOException handles file creation and writing errors, while FileNotFoundException handles errors when trying to read files.

    - + + import java.io.IOException; import java.io.FileNotFoundException; - + +
    From 6d385b46cd3d9c79d5673827f87a549722a6fcb5 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Tue, 4 Aug 2026 16:16:24 +0300 Subject: [PATCH 292/357] fixed program tags --- source/ch8_filehandling.ptx | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 6a7002c..4d98c52 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -36,7 +36,7 @@
    - +

    Note the use of import java.lang.Math; in the above to import the Math class. Unlike Python, Java requires explicit import for most libraries, including the Math class and many classes related to file handling.

    @@ -46,7 +46,7 @@

    - + import java.io.File; @@ -55,7 +55,7 @@ The Scanner class from the util library will need to be imported if there is any need for a program to read a file. It should be noted that this library is unnecessary if the program will not be reading any data from a file.

    - + import java.util.Scanner; @@ -65,7 +65,7 @@

    - + import java.io.FileWriter; @@ -75,7 +75,7 @@

    - + import java.io.IOException; import java.io.FileNotFoundException; From b51dc8d2cc1ba16a12fa74ad86d61455fb5fd0b5 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Tue, 4 Aug 2026 16:24:47 +0300 Subject: [PATCH 293/357] added listing to txt --- source/ch8_filehandling.ptx | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 4d98c52..3d6cb05 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -7,7 +7,7 @@
    Class Imports

    - File handling is an integral part of programming. Most programming languages have the ability to create, read from, write to, and delete, files. In Python, most built-in libraries are available without needing to explicitly import additional packages, but some libraries like math do need to be imported. Consider the following. + File handling is an integral part of programming. Most programming languages have the ability to create, read from, write to, and delete, files. In Python, most built-in libraries are available without needing to explicitly import additional packages, but some libraries like math do need to be imported. shows an example of importing the math library in Python.

    @@ -20,10 +20,10 @@

    - Delete the first line that says import math and see what happens. The import math is needed. The same program in Java would look like this: + Delete the first line that says import math and see what happens. The import math is needed. The same program in Java would look like .

    - + import java.lang.Math; @@ -42,7 +42,7 @@

    - Much like the Math class, in order for your program to work with files you need use import. Java includes a class called File in the io library. This class allows you to create File objects, and use its public methods. + Much like the Math class, in order for your program to work with files you need use import. Java includes a class called File in the io library shown in . This class allows you to create File objects, and use its public methods.

    @@ -52,7 +52,7 @@

    - The Scanner class from the util library will need to be imported if there is any need for a program to read a file. It should be noted that this library is unnecessary if the program will not be reading any data from a file. + The Scanner class from the util library will need to be imported if there is any need for a program to read a file as shown in . It should be noted that this library is unnecessary if the program will not be reading any data from a file.

    @@ -61,7 +61,7 @@

    - The FileWriter class can be used to write to files. In the same way that the Scanner class isn't needed unless the program will read from a file, the FileWriter class isn't needed unless the program will write to a file. + The FileWriter class can be used to write to files as shown in . In the same way that the Scanner class isn't needed unless the program will read from a file, the FileWriter class isn't needed unless the program will write to a file.

    @@ -71,7 +71,7 @@

    - Finally, these last two classes provide error handling and must be used in tandem with the File class when reading from or writing to files. IOException handles file creation and writing errors, while FileNotFoundException handles errors when trying to read files. + Finally, these last two classes provide error handling and must be used in tandem with the File class when reading from or writing to files as shown in . IOException handles file creation and writing errors, while FileNotFoundException handles errors when trying to read files.

    From ef07c21cde741d0387734ff20dfd30c75383329b Mon Sep 17 00:00:00 2001 From: "nshizirungudieumerci@gmail.com" Date: Tue, 4 Aug 2026 10:24:56 -0400 Subject: [PATCH 294/357] removed section 2.1 so it could be placed in the most apropriate part in the book --- source/ch2_firstjavaprogram.ptx | 160 -------------------------------- 1 file changed, 160 deletions(-) diff --git a/source/ch2_firstjavaprogram.ptx b/source/ch2_firstjavaprogram.ptx index e6f65c4..8fa1e56 100644 --- a/source/ch2_firstjavaprogram.ptx +++ b/source/ch2_firstjavaprogram.ptx @@ -4,167 +4,7 @@ Java Programs -
    - Classes and Objects -

    - object-oriented programming OOP - Depending on how deep your knowledge of Python and programming in general is, you may or may not be familiar with classes and objects. These two important Object-Oriented Programming (OOP) concepts will briefly be discussed. If you already have a good understanding of classes and objects in Python, this section may be skipped. -

    - -

    - object - attribute - instance variable - method - Objects in the context of programming are instances of classes. Objects contain attributes (also referred to as instance variables), which are data that describe the object or are associated with the object, and methods, which are special functions used by the object. Methods are typically actions the object can perform, or can be used to make changes to the object's attributes. -

    - -

    - class - constructor - Classes can be thought of as being similar to blueprints or a recipe; they hold details of how to create an instance of an object. Classes contain a special method called a constructor that is used to create an instance of an object. Once the object is created, it will use the class definition to define its attributes and call methods. -

    - -

    - The best way to understand classes and objects is to see them in action. Let's define a Dog class in Python: -

    - - - - - class Dog: - """ A simple Dog class definition. """ - def __init__(self, name, breed, fur_color): - # constructor method to create a Dog object - self.name = name - self.breed = breed - self.fur_color = fur_color - self.trained = False # dogs are not trained by default - print("Dog named " + self.name + " created!") - - def bark(self): - # method to make the dog bark - print(self.name + " says woof!") - - def sit(self): - # method to make the dog sit - if self.trained: # check if the dog has been trained otherwise it will not sit - print(self.name + " sits.") - else: - print(self.name + " has not been trained.") - - def train(self): - # method to train the dog, which will set the trained attribute to True - self.trained = True - - - - -

    - Let's unpack what is going on in . The first line is where we declare the class definition and name it Dog. Next, we have a special method called __init__. This __init__ method is the constructor and is required for every Python class definition. Within the __init__ method, attributes are defined. As you can see, the attributes name, breed, and fur_color must be defined when creating a Dog object using this class definition, but the trained attribute is defined within the constructor and is initialized as False. We can also have the __init__ method run any code, such as the print statement informing us that a Dog object was created. -

    - -

    - The next three blocks of code are the class's methods. These include bark(self), sit(self), and train(self). As you can see, the class defines attributes (the variables in the __init__ method) and methods for instances of the Dog class. -

    - -

    - self - Within each method, and for each attribute, you will notice the use of self. This is required in Python. self simply indicates that an attribute or method is being used for a specific instance of an object created with a class. -

    - -

    - Next, we will use this class to create a new Dog object. We will call this new Dog object my_dog: -

    - - - - class Dog: - """ A simple Dog class definition. """ - def __init__(self, name, breed, fur_color): - # constructor method to create a Dog object - self.name = name - self.breed = breed - self.fur_color = fur_color - self.trained = False # dogs are not trained by default - print("Dog named " + self.name + " created!") - - def bark(self): - # method to make the dog bark - print(self.name + " says woof!") - - def sit(self): - # method to make the dog sit - if self.trained: # check if the dog has been trained otherwise it will not sit - print(self.name + " sits.") - else: - print(self.name + " has not been trained.") - - def train(self): - # method to train the dog, which will set the trained attribute to True - self.trained = True - - # Create a Dog object called my_dog - my_dog = Dog("Rex", "pug", "brown") - - - -

    - In the final line of code in , we have created an object called my_dog. We have initialized its attributes, setting name to Rex, breed to pug, and fur_color to brown. -

    - -

    - Now that we have created a Dog object using the class we defined, we can utilize the class's methods: -

    - - - - - class Dog: - """ A simple Dog class definition. """ - def __init__(self, name, breed, fur_color): - # constructor method to create a Dog object - self.name = name - self.breed = breed - self.fur_color = fur_color - self.trained = False # dogs are not trained by default - print("Dog named " + self.name + " created!") - - def bark(self): - # method to make the dog bark - print(self.name + " says woof!") - - def sit(self): - # method to make the dog sit - if self.trained: - print(self.name + " sits.") - else: - print(self.name + " has not been trained.") - - def train(self): - # method to train the dog, which will set the trained attribute to True - self.trained = True - - - my_dog = Dog("Rex", "pug", "brown") - my_dog.bark() # call the bark method - my_dog.sit() # call the sit method - - - - - -

    - When running , the line Rex has not been trained. will appear in the output when calling the sit() method. Try adding a one or more lines of code so that Rex sits. appears in the output! -

    -
    - -

    - Now, we have a full class definition and have utilized its methods. Class definitions in Java will be covered thoroughly in chapter 6. For now, it is important to know that Python programs can be written without using classes at all. Java, on the other hand, requires all code to reside in a class. This will be discussed in the next section. -

    - -
    Lets look at a Java Program From e7d92cd256a7283a3b9b66ec32428f34d9ee18ab Mon Sep 17 00:00:00 2001 From: "nshizirungudieumerci@gmail.com" Date: Tue, 4 Aug 2026 10:26:12 -0400 Subject: [PATCH 295/357] Took section 2.1 and made it the new section 6.1 --- source/ch6_definingclasses.ptx | 166 +++++++++++++++++++++++++++++++++ 1 file changed, 166 insertions(+) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index 0bb5249..f2c8bf7 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -4,6 +4,172 @@ Classes in Java + + +
    + Classes and Objects + +

    + object-oriented programming OOP + Depending on how deep your knowledge of Python and programming in general is, you may or may not be familiar with classes and objects. These two important Object-Oriented Programming (OOP) concepts will briefly be discussed. If you already have a good understanding of classes and objects in Python, this section may be skipped. +

    + +

    + object + attribute + instance variable + method + Objects in the context of programming are instances of classes. Objects contain attributes (also referred to as instance variables), which are data that describe the object or are associated with the object, and methods, which are special functions used by the object. Methods are typically actions the object can perform, or can be used to make changes to the object's attributes. +

    + +

    + class + constructor + Classes can be thought of as being similar to blueprints or a recipe; they hold details of how to create an instance of an object. Classes contain a special method called a constructor that is used to create an instance of an object. Once the object is created, it will use the class definition to define its attributes and call methods. +

    + +

    + The best way to understand classes and objects is to see them in action. Let's define a Dog class in Python: +

    + + + + + class Dog: + """ A simple Dog class definition. """ + def __init__(self, name, breed, fur_color): + # constructor method to create a Dog object + self.name = name + self.breed = breed + self.fur_color = fur_color + self.trained = False # dogs are not trained by default + print("Dog named " + self.name + " created!") + + def bark(self): + # method to make the dog bark + print(self.name + " says woof!") + + def sit(self): + # method to make the dog sit + if self.trained: # check if the dog has been trained otherwise it will not sit + print(self.name + " sits.") + else: + print(self.name + " has not been trained.") + + def train(self): + # method to train the dog, which will set the trained attribute to True + self.trained = True + + + + +

    + Let's unpack what is going on in . The first line is where we declare the class definition and name it Dog. Next, we have a special method called __init__. This __init__ method is the constructor and is required for every Python class definition. Within the __init__ method, attributes are defined. As you can see, the attributes name, breed, and fur_color must be defined when creating a Dog object using this class definition, but the trained attribute is defined within the constructor and is initialized as False. We can also have the __init__ method run any code, such as the print statement informing us that a Dog object was created. +

    + +

    + The next three blocks of code are the class's methods. These include bark(self), sit(self), and train(self). As you can see, the class defines attributes (the variables in the __init__ method) and methods for instances of the Dog class. +

    + +

    + self + Within each method, and for each attribute, you will notice the use of self. This is required in Python. self simply indicates that an attribute or method is being used for a specific instance of an object created with a class. +

    + +

    + Next, we will use this class to create a new Dog object. We will call this new Dog object my_dog: +

    + + + + class Dog: + """ A simple Dog class definition. """ + def __init__(self, name, breed, fur_color): + # constructor method to create a Dog object + self.name = name + self.breed = breed + self.fur_color = fur_color + self.trained = False # dogs are not trained by default + print("Dog named " + self.name + " created!") + + def bark(self): + # method to make the dog bark + print(self.name + " says woof!") + + def sit(self): + # method to make the dog sit + if self.trained: # check if the dog has been trained otherwise it will not sit + print(self.name + " sits.") + else: + print(self.name + " has not been trained.") + + def train(self): + # method to train the dog, which will set the trained attribute to True + self.trained = True + + # Create a Dog object called my_dog + my_dog = Dog("Rex", "pug", "brown") + + + +

    + In the final line of code in , we have created an object called my_dog. We have initialized its attributes, setting name to Rex, breed to pug, and fur_color to brown. +

    + +

    + Now that we have created a Dog object using the class we defined, we can utilize the class's methods: +

    + + + + + class Dog: + """ A simple Dog class definition. """ + def __init__(self, name, breed, fur_color): + # constructor method to create a Dog object + self.name = name + self.breed = breed + self.fur_color = fur_color + self.trained = False # dogs are not trained by default + print("Dog named " + self.name + " created!") + + def bark(self): + # method to make the dog bark + print(self.name + " says woof!") + + def sit(self): + # method to make the dog sit + if self.trained: + print(self.name + " sits.") + else: + print(self.name + " has not been trained.") + + def train(self): + # method to train the dog, which will set the trained attribute to True + self.trained = True + + + my_dog = Dog("Rex", "pug", "brown") + my_dog.bark() # call the bark method + my_dog.sit() # call the sit method + + + + + +

    + When running , the line Rex has not been trained. will appear in the output when calling the sit() method. Try adding a one or more lines of code so that Rex sits. appears in the output! +

    +
    + +

    + Now, we have a full class definition and have utilized its methods. Class definitions in Java will be covered thoroughly in chapter 6. For now, it is important to know that Python programs can be written without using classes at all. Java, on the other hand, requires all code to reside in a class. This will be discussed later in chapter 6. +

    + +
    + + +
    Defining Classes in Java From 98ebc1d3d11ab14efe594ed9582e4aed4bafd7cd Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Tue, 4 Aug 2026 17:34:51 +0300 Subject: [PATCH 296/357] added comments to code blocks --- source/ch8_filehandling.ptx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index aa86bf3..be024d0 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -12,7 +12,7 @@ import math - print(math.sqrt(25)) + print(math.sqrt(25)) # notice the lower case 'm' in math @@ -25,7 +25,7 @@ public class SquareRoot { public static void main(String[] args) { - System.out.println(Math.sqrt(25)); + System.out.println(Math.sqrt(25)); // notice the upper case 'M' in Math } } From f33f44b70e2c184252c53dbc62c3799cba015f54 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Tue, 4 Aug 2026 17:58:11 +0300 Subject: [PATCH 297/357] add comments to code --- source/ch8_filehandling.ptx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index aa86bf3..db1cc2c 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -208,18 +208,18 @@ public class CreateFile { import java.io.File; - import java.io.FileNotFoundException; + import java.io.FileNotFoundException; // This import is necessary to handle the exception if the file is not found import java.util.Scanner; public class ReadFile { public static void main (String[] args) { String filename = "myfile.txt"; - try (Scanner fileReader = new Scanner(new File(filename))) { - while (fileReader.hasNextLine()) { + try (Scanner fileReader = new Scanner(new File(filename))) { // try to open the file and create a Scanner object + while (fileReader.hasNextLine()) { // while there is a next line in the file String data = fileReader.nextLine(); System.out.println(data); } } - catch (FileNotFoundException e) { + catch (FileNotFoundException e) { // and catch the exception if the file is not found System.out.println("Error: The file '" + filename + "' was not found."); } } From ffaf7dda5f5408bcc44f6b2211e65cfdc77b0ec1 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Tue, 4 Aug 2026 20:23:36 +0300 Subject: [PATCH 298/357] added listing tags --- source/ch8_filehandling.ptx | 63 +++++++++++++++++++++++++++---------- 1 file changed, 47 insertions(+), 16 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index aa86bf3..1117858 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -242,8 +242,9 @@ public class CreateFile {

    Let us create the framework for a class that will write to a file. Let's call this class WriteFile:

    - - + + + import java.io.File; import java.io.FileWriter; import java.io.IOException; @@ -254,39 +255,46 @@ public class CreateFile { } } +

    Next, we will create a FileWriter object. Let's call it myWriter. The equivalent Python code to this operation is:

    - - + + with open("myfile.txt", "w") as myWriter: +

    The Java code to create a FileWriter object is:

    - + + FileWriter myWriter = new FileWriter("myfile.txt"); +

    In this next step, we will use the write() method from the FileWriter class. This method will take any data within the parenthesis and write that data to the file selected. The write() method takes most standard data types. First, how this step is completed with Python:

    - - + + my_writer.write("File successfully updated!") +

    And the Java equivalent. This is almost completely identical except for the second line, which is very important!

    - + + myWriter.write("File successfully updated!"); myWriter.close(); +

    @@ -298,7 +306,8 @@ public class CreateFile { Next, we will again add the required try/catch blocks utilizing the IOException class. Just like with creating files, the program will not compile without these crucial additions! We will also add some print statements to inform us of the success of the file write operation. First, a Python example:

    - + + try: with open("myfile.txt", "w") as my_writer: my_writer.write("File successfully updated!") @@ -308,12 +317,14 @@ public class CreateFile { import traceback traceback.print_exc() +

    And the equivalent Java code:

    - + + try { FileWriter myWriter = new FileWriter("myfile.txt"); myWriter.write("File successfully updated!"); @@ -324,16 +335,22 @@ public class CreateFile { e.printStackTrace(); } +

    And that's it! We will add our code to the foundational code for a complete program. First, an example of equivalent Python code:

    + + Data file for writing example
                         
                     
    - +
    + + + try: with open("myfile.txt", "w") as my_writer: @@ -345,10 +362,13 @@ public class CreateFile { traceback.print_exc() +

    The completed Java code:

    + + Data file for writing example
                         
    @@ -374,6 +394,7 @@ public class CreateFile {
                 }
                  
             
    +        
     
             
                 

    @@ -385,19 +406,26 @@ public class CreateFile { Speaking of overwriting data, what if we want to append text to the end of any text already in myfile.txt? To accomplish this, we can pass a boolean argument along with the file name when creating a new data argument:

    - + + FileWriter myWriter = new FileWriter("myfile.txt", true); // true enables append mode +

    Now, when we use write() method like before, the text will be appended if there is already tSext in the document. If we were to update our code to include the boolean argument:

    - + + Data file for writing example +
                         
                     
    - +
    + + + import java.io.FileWriter; import java.io.IOException; @@ -417,6 +445,7 @@ public class CreateFile { } +

    Then if we run the program twice, the contents of myfile.txt would be: @@ -430,15 +459,17 @@ public class CreateFile { This doesn't look very good! If we want each additional write to appear on a new line? A simple solution is to use the \n newline character:

    - + + myWriter.write("File successfully updated!\n"); // Added newline character myWriter.close(); +

    Running the code with the newline character twice will result in the following contents in myfile.txt:

    - +
                 File successfully updated!
                 File successfully updated!
    
    From 54e5c7153b625f04052079a4cdfac70d0135a558 Mon Sep 17 00:00:00 2001
    From: Habiba Sorour 
    Date: Tue, 4 Aug 2026 20:25:06 +0300
    Subject: [PATCH 299/357] fixed pre tags, to add linking
    
    ---
     source/ch8_filehandling.ptx | 15 ++++++++++-----
     1 file changed, 10 insertions(+), 5 deletions(-)
    
    diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx
    index 1117858..8cfca92 100644
    --- a/source/ch8_filehandling.ptx
    +++ b/source/ch8_filehandling.ptx
    @@ -451,9 +451,11 @@ public class CreateFile {
                 Then if we run the program twice, the contents of myfile.txt would be:
             

    -
    +        +        
                 File successfully updated!File successfully updated!
    -        
    + +

    This doesn't look very good! If we want each additional write to appear on a new line? A simple solution is to use the \n newline character: @@ -469,11 +471,14 @@ public class CreateFile {

    Running the code with the newline character twice will result in the following contents in myfile.txt:

    - -
    +
    +        +        
                 File successfully updated!
                 File successfully updated!
    -        
    +
    +
    +
    From 29827e379cd0132806d8cb98a1d196c586fd9245 Mon Sep 17 00:00:00 2001 From: "nshizirungudieumerci@gmail.com" Date: Tue, 4 Aug 2026 13:49:06 -0400 Subject: [PATCH 300/357] added listing tags to the appropriate places and in the appropriate paragraphs. --- source/ch8_filehandling.ptx | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index aa86bf3..05acc96 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -449,10 +449,10 @@ public class CreateFile { Deleting Files

    - Lastly, we will take a look at using Java to delete a file. This is pretty straight-forward and follows the structure used to create files. Here is the CreateFile class from before that will be used to create a file that we will soon delete: + Lastly, we will take a look at using Java to delete a file. This is pretty straight-forward and follows the structure used to create files. shows the CreateFile class from before that will be used to create a file that we will soon delete:

    - + import java.io.File; import java.io.IOException; @@ -475,15 +475,17 @@ public class CreateFile { } +

    - And finally, we have Java code that deletes a file. We will call this class DeleteFile: + And finally, shows the Java code that deletes a file. We will call this class DeleteFile:

    - - + + + import java.io.File; import java.io.IOException; @@ -508,7 +510,7 @@ public class DeleteFile { - +

    Note that this is almost identical to the code within the try block of the CreateFile class that we made earlier. The key difference is the use of the delete() method which will delete the file with the name that was linked to the myFile object. Similar to the createNewFile() method, it will return true if the file exists and can be deleted, and false if the file cannot be deleted.

    From c0fb145c036c81c6005e5761c23a5aaa87e61c86 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Tue, 4 Aug 2026 21:04:24 +0300 Subject: [PATCH 301/357] added listing to text --- source/ch8_filehandling.ptx | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 8cfca92..32d2b8b 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -240,7 +240,7 @@ public class CreateFile {

    - Let us create the framework for a class that will write to a file. Let's call this class WriteFile: + shows the framework for a class that will write to a file. Let's call this class WriteFile.

    @@ -258,7 +258,7 @@ public class CreateFile {

    - Next, we will create a FileWriter object. Let's call it myWriter. The equivalent Python code to this operation is: + Next, we will create a FileWriter object. Let's call it myWriter. shows the code to create a myWriter object in Python.

    @@ -267,7 +267,7 @@ public class CreateFile {

    - The Java code to create a FileWriter object is: + shows the Java code to create a FileWriter object. Note that the FileWriter object is created with the name of the file to write to as an argument. If the file does not exist, it will be created. If it does exist, it will be overwritten.:

    @@ -277,7 +277,7 @@ public class CreateFile {

    - In this next step, we will use the write() method from the FileWriter class. This method will take any data within the parenthesis and write that data to the file selected. The write() method takes most standard data types. First, how this step is completed with Python: + In this next step, we will use the write() method from the FileWriter class. This method will take any data within the parenthesis and write that data to the file selected. The write() method takes most standard data types. The shows the code to write to a file in Python.

    @@ -286,7 +286,7 @@ public class CreateFile {

    - And the Java equivalent. This is almost completely identical except for the second line, which is very important! + shows the Java equivalent. This is almost completely identical except for the second line, which is very important!

    @@ -303,7 +303,7 @@ public class CreateFile {

    - Next, we will again add the required try/catch blocks utilizing the IOException class. Just like with creating files, the program will not compile without these crucial additions! We will also add some print statements to inform us of the success of the file write operation. First, a Python example: + Next, we will again add the required try/catch blocks utilizing the IOException class. Just like with creating files, the program will not compile without these crucial additions! We will also add some print statements to inform us of the success of the file write operation. shows the code to write to a file in Python.

    @@ -320,7 +320,7 @@ public class CreateFile {

    - And the equivalent Java code: + shows the Java equivalent.

    @@ -338,7 +338,7 @@ public class CreateFile {

    - And that's it! We will add our code to the foundational code for a complete program. First, an example of equivalent Python code: + And that's it! We will add our code to the foundational code for a complete program. First, shows the completed Python code.

    Data file for writing example @@ -365,7 +365,7 @@ public class CreateFile {

    - The completed Java code: + shows the completed Java code.

    Data file for writing example @@ -403,7 +403,7 @@ public class CreateFile {

    - Speaking of overwriting data, what if we want to append text to the end of any text already in myfile.txt? To accomplish this, we can pass a boolean argument along with the file name when creating a new data argument: + Speaking of overwriting data, what if we want to append text to the end of any text already in myfile.txt? To accomplish this, we can pass a boolean argument along with the file name when creating a new data argument as shown in .

    @@ -413,8 +413,8 @@ public class CreateFile {

    - Now, when we use write() method like before, the text will be appended if there is already tSext in the document. If we were to update our code to include the boolean argument: -

    + Now, when we use write() method like before, the text will be appended if there is already tSext in the document. If we were to update our code to include the boolean argument as shown in . + Data file for writing example @@ -448,7 +448,7 @@ public class CreateFile {

    - Then if we run the program twice, the contents of myfile.txt would be: + Then if we run the program twice, the contents of myfile.txt would be as shows.

    @@ -458,7 +458,7 @@ public class CreateFile {

    - This doesn't look very good! If we want each additional write to appear on a new line? A simple solution is to use the \n newline character: + This doesn't look very good! If we want each additional write to appear on a new line? A simple solution is to use the \n newline character as shows.

    @@ -469,7 +469,7 @@ public class CreateFile {

    - Running the code with the newline character twice will result in the following contents in myfile.txt: + Running the code with the newline character twice will result in the following contents in myfile.txt as shows.

    From 79437de7b191274c043e954591161bbac52ef31d Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Tue, 4 Aug 2026 21:18:19 +0300 Subject: [PATCH 302/357] fixed xml:id tag --- source/ch8_filehandling.ptx | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 32d2b8b..167c6d3 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -340,9 +340,9 @@ public class CreateFile {

    And that's it! We will add our code to the foundational code for a complete program. First, shows the completed Python code.

    - + Data file for writing example - +
                         
                     
    @@ -350,7 +350,7 @@ public class CreateFile {
    - + try: with open("myfile.txt", "w") as my_writer: @@ -367,14 +367,14 @@ public class CreateFile {

    shows the completed Java code.

    - + Data file for writing example - +
                         
                     
    - + import java.io.FileWriter; import java.io.IOException; @@ -415,9 +415,9 @@ public class CreateFile {

    Now, when we use write() method like before, the text will be appended if there is already tSext in the document. If we were to update our code to include the boolean argument as shown in . - + Data file for writing example - +

                         
                     
    @@ -425,7 +425,7 @@ public class CreateFile {
    - + import java.io.FileWriter; import java.io.IOException; From 47d278a30309ab553dd9bb9a8e394e58cef11ab0 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Tue, 4 Aug 2026 21:19:08 +0300 Subject: [PATCH 303/357] added a missing listing --- source/ch8_filehandling.ptx | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 167c6d3..7df8f92 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -374,7 +374,10 @@ public class CreateFile { - + + + + import java.io.FileWriter; import java.io.IOException; @@ -394,7 +397,8 @@ public class CreateFile { } - + +

    From 13467a6ff31c9f698f29d44c240b3351cacd78d6 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Tue, 4 Aug 2026 21:20:11 +0300 Subject: [PATCH 304/357] fixed a build error --- source/ch8_filehandling.ptx | 1 + 1 file changed, 1 insertion(+) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 7df8f92..d86d6e5 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -418,6 +418,7 @@ public class CreateFile {

    Now, when we use write() method like before, the text will be appended if there is already tSext in the document. If we were to update our code to include the boolean argument as shown in . +

    Data file for writing example From b56a824b429b495b0e1a80a4ed896c6c7cf11c81 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Tue, 4 Aug 2026 22:00:33 +0300 Subject: [PATCH 305/357] fixed issue with datafile block --- source/ch8_filehandling.ptx | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index d86d6e5..eba0f10 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -340,9 +340,10 @@ public class CreateFile {

    And that's it! We will add our code to the foundational code for a complete program. First, shows the completed Python code.

    - + + Data file for writing example - +
                         
                     
    @@ -367,9 +368,9 @@ public class CreateFile {

    shows the completed Java code.

    - + Data file for writing example - +
                         
                     
    @@ -395,7 +396,7 @@ public class CreateFile { } } } -
    +
    ~
    @@ -420,9 +421,9 @@ public class CreateFile { Now, when we use write() method like before, the text will be appended if there is already tSext in the document. If we were to update our code to include the boolean argument as shown in .

    - + Data file for writing example - +
                         
                     
    @@ -467,7 +468,7 @@ public class CreateFile {

    - + myWriter.write("File successfully updated!\n"); // Added newline character myWriter.close(); From 2560b4224b7b42c937be91b98ee658a1e95e5942 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Tue, 4 Aug 2026 22:03:57 +0300 Subject: [PATCH 306/357] fixed data tag --- source/ch8_filehandling.ptx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index db1cc2c..7543a4c 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -166,11 +166,11 @@ public class CreateFile { Let’s take a look at how we can use Python to understand how read file contents in Java. In order to read files generally you iterate through each line in the file and read the line's content. In Java, you read files in a very similar way, however in Java we will use the Scanner class in order to iterate through the lines.

    - Consider that reads each line of and prints it to the console. + Consider that reads each line of and prints it to the console.

    - + Data file for reading example - +
                         1
                         2
    
    From dd0522f3e16f57f58884d0150066b8617a9dac81 Mon Sep 17 00:00:00 2001
    From: Habiba Sorour 
    Date: Tue, 4 Aug 2026 23:01:11 +0300
    Subject: [PATCH 307/357] added listing tag
    
    ---
     source/ch9_commonmistakes.ptx | 5 +++--
     1 file changed, 3 insertions(+), 2 deletions(-)
    
    diff --git a/source/ch9_commonmistakes.ptx b/source/ch9_commonmistakes.ptx
    index 1a041b9..961aeb5 100644
    --- a/source/ch9_commonmistakes.ptx
    +++ b/source/ch9_commonmistakes.ptx
    @@ -23,8 +23,9 @@
             

    - Consider the following example where we have a method that multiplies a number by two. We can add print statements to help us debug the code: + Consider the following example where we have a method that multiplies a number by two. We can add print statements to help us debug the code and verify that the method is being called correctly and returning the expected result as shown below in .

    + // DebugExample.java @@ -46,7 +47,7 @@

    - In the example above, System.out.println() is used inside both main and multiplyByTwo() to trace what values are being passed and returned. This kind of print-based debugging can quickly reveal logic errors, unexpected behavior, or whether a method is even being called. However, overuse of this technique will often take more time than using the debugging tools that are built into your IDE. + In , System.out.println() is used inside both main and multiplyByTwo() to trace what values are being passed and returned. This kind of print-based debugging can quickly reveal logic errors, unexpected behavior, or whether a method is even being called. However, overuse of this technique will often take more time than using the debugging tools that are built into your IDE.

    Useful tools in the built-in Java debugger can help you step through your code, inspect variables, and evaluate expressions at runtime. Familiarizing yourself with these tools can greatly enhance your debugging efficiency. From ca7ef224558af8a1379f713c05b9ce240a81f653 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Tue, 4 Aug 2026 23:01:57 +0300 Subject: [PATCH 308/357] added a line --- source/ch9_commonmistakes.ptx | 1 + 1 file changed, 1 insertion(+) diff --git a/source/ch9_commonmistakes.ptx b/source/ch9_commonmistakes.ptx index 961aeb5..6851db5 100644 --- a/source/ch9_commonmistakes.ptx +++ b/source/ch9_commonmistakes.ptx @@ -46,6 +46,7 @@ }//End of class +

    In , System.out.println() is used inside both main and multiplyByTwo() to trace what values are being passed and returned. This kind of print-based debugging can quickly reveal logic errors, unexpected behavior, or whether a method is even being called. However, overuse of this technique will often take more time than using the debugging tools that are built into your IDE.

    From ab083d5030c248faad3cd8c87509c0571c243ba9 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Tue, 4 Aug 2026 23:02:45 +0300 Subject: [PATCH 309/357] added a line --- source/ch9_commonmistakes.ptx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/ch9_commonmistakes.ptx b/source/ch9_commonmistakes.ptx index 6851db5..dfeeed5 100644 --- a/source/ch9_commonmistakes.ptx +++ b/source/ch9_commonmistakes.ptx @@ -23,9 +23,9 @@

    - Consider the following example where we have a method that multiplies a number by two. We can add print statements to help us debug the code and verify that the method is being called correctly and returning the expected result as shown below in . + Consider the following example where we have a method that multiplies a number by two. We can add print statements to help us debug the code and verify that the method is being called correctly and returning the expected result as shown below in .

    - + // DebugExample.java From 05dde6e11129f6406336a04f623659500b60ba3b Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Tue, 4 Aug 2026 23:03:18 +0300 Subject: [PATCH 310/357] added a line to close tag --- source/ch9_commonmistakes.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch9_commonmistakes.ptx b/source/ch9_commonmistakes.ptx index dfeeed5..9ff47d7 100644 --- a/source/ch9_commonmistakes.ptx +++ b/source/ch9_commonmistakes.ptx @@ -23,7 +23,7 @@

    - Consider the following example where we have a method that multiplies a number by two. We can add print statements to help us debug the code and verify that the method is being called correctly and returning the expected result as shown below in . + Consider the following example where we have a method that multiplies a number by two. We can add print statements to help us debug the code and verify that the method is being called correctly and returning the expected result as shown below in .

    From 437cd88bd07f044ae6f9f9feed359e4ad96e2a2e Mon Sep 17 00:00:00 2001 From: "nshizirungudieumerci@gmail.com" Date: Wed, 5 Aug 2026 10:48:36 -0400 Subject: [PATCH 311/357] Added listing tag to make the text more organized --- source/ch9_commonmistakes.ptx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/source/ch9_commonmistakes.ptx b/source/ch9_commonmistakes.ptx index 9ff47d7..6fb6156 100644 --- a/source/ch9_commonmistakes.ptx +++ b/source/ch9_commonmistakes.ptx @@ -87,8 +87,9 @@ Forgetting to declare your variables

    In Python, you can use a variable without declaring it first, but in Java, you must declare all variables before using them. - If you try to use a variable that has not been declared, the Java compiler will give you an error message like this: + shows If you try to use a variable that has not been declared, the Java compiler will give you an error message like this:

    + import java.util.ArrayList; // Import necessary class @@ -108,6 +109,7 @@ } // End of class +

    The 'cannot find symbol' error for the variable count on line 6 indicates that count was used before it was declared within the Histo class. In Java, all variables must be explicitly declared with a data type (e.g., int, String, ArrayList<Integer>) before they can be assigned a value or referenced in any way. The arrow in the error message points to where the undeclared variable count was first encountered. To resolve this, count needs to be declared with its appropriate type (e.g., ArrayList<Integer> count;) before any attempt to initialize or use it.

    From 7799fe0958405f35a0078e862419ac9e23e87f8b Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Wed, 5 Aug 2026 18:13:09 +0300 Subject: [PATCH 312/357] add listing tags --- source/ch9_commonmistakes.ptx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/source/ch9_commonmistakes.ptx b/source/ch9_commonmistakes.ptx index 9ff47d7..0a78c3c 100644 --- a/source/ch9_commonmistakes.ptx +++ b/source/ch9_commonmistakes.ptx @@ -63,6 +63,7 @@

    A common mistake in Java is to forget that every statement must end with a semicolon (;).

    + // Histo.java @@ -77,6 +78,7 @@ }//End of class +

    The error "';' expected" on line 7 of Histo.java means that a semicolon is missing at the end of the statement Scanner data = null. In Java, every statement must be terminated with a semicolon (;) to indicate its completion. The arrow points to null because that's where the compiler expected to find the semicolon.

    From 37789ec19fb75a12c78bcbbc9d1f5a19fd3bbe9a Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Wed, 5 Aug 2026 18:13:26 +0300 Subject: [PATCH 313/357] add listing to txt --- source/ch9_commonmistakes.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch9_commonmistakes.ptx b/source/ch9_commonmistakes.ptx index 0a78c3c..f7b1bbb 100644 --- a/source/ch9_commonmistakes.ptx +++ b/source/ch9_commonmistakes.ptx @@ -80,7 +80,7 @@

    - The error "';' expected" on line 7 of Histo.java means that a semicolon is missing at the end of the statement Scanner data = null. In Java, every statement must be terminated with a semicolon (;) to indicate its completion. The arrow points to null because that's where the compiler expected to find the semicolon. + The error "';' expected" on line 7 of Histo.java in means that a semicolon is missing at the end of the statement Scanner data = null. In Java, every statement must be terminated with a semicolon (;) to indicate its completion. The arrow points to null because that's where the compiler expected to find the semicolon.

    From f52b6100ac6e62fa6597f1f0763798b6ef5e0890 Mon Sep 17 00:00:00 2001 From: "nshizirungudieumerci@gmail.com" Date: Wed, 5 Aug 2026 11:59:51 -0400 Subject: [PATCH 314/357] added listing tag to make the text more organized --- source/ch9_commonmistakes.ptx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/source/ch9_commonmistakes.ptx b/source/ch9_commonmistakes.ptx index 9ff47d7..446e95a 100644 --- a/source/ch9_commonmistakes.ptx +++ b/source/ch9_commonmistakes.ptx @@ -117,8 +117,9 @@
    Not importing a class

    - In Python, many classes are available by default. However, in Java, you must explicitly import most classes from external packages that you want to use. + In Python, many classes are available by default. However, in Java, you must explicitly import most classes from external packages that you want to use . If you forget to import a class, the compiler will give you an error message like this:

    + @@ -133,6 +134,7 @@ } // End of class +

    You may notice that this error message looks similar to the previous one, however, it has an entirely different cause. In Java, classes like Scanner that are part of external packages (like java.util) must be explicitly imported into your source file. Java does not automatically recognize these classes. To resolve this error, you need to add an import statement for the Scanner class at the beginning of your Histo.java file, typically import java.util.Scanner;.

    From bafd5ef921888e38ba84b6fdf510b268c3a01a0b Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Wed, 5 Aug 2026 20:26:50 +0300 Subject: [PATCH 315/357] add listing tags --- source/ch9_commonmistakes.ptx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/source/ch9_commonmistakes.ptx b/source/ch9_commonmistakes.ptx index c14c8cb..1e92589 100644 --- a/source/ch9_commonmistakes.ptx +++ b/source/ch9_commonmistakes.ptx @@ -148,6 +148,7 @@

    Unlike Python, where you can create a new object without explicitly using a keyword, Java requires the new keyword to instantiate a new object.

    + // Histo.java // The filename for this example @@ -164,6 +165,7 @@ } // End of class +

    This error message occurs when you forget to use the new keyword to instantiate an object. Specifically, on line 8 of Histo.java, data = Scanner(new File("test.dat")); leads to a 'cannot find symbol' error. From 53bf7525a19ab0c35578886203bf1ddc592c2523 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Wed, 5 Aug 2026 20:27:16 +0300 Subject: [PATCH 316/357] add listing to txt --- source/ch9_commonmistakes.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch9_commonmistakes.ptx b/source/ch9_commonmistakes.ptx index 1e92589..61502a6 100644 --- a/source/ch9_commonmistakes.ptx +++ b/source/ch9_commonmistakes.ptx @@ -167,7 +167,7 @@

    - This error message occurs when you forget to use the new keyword to instantiate an object. + The error message in occurs when you forget to use the new keyword to instantiate an object. Specifically, on line 8 of Histo.java, data = Scanner(new File("test.dat")); leads to a 'cannot find symbol' error. While the message states 'symbol: method Scanner(File)', this can be misleading. Java incorrectly interprets Scanner() as an attempt to call a static method named Scanner within the Histo class From ff0772dd5e771693f79e0d69b4523bcb10d5858a Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Wed, 5 Aug 2026 22:19:44 +0300 Subject: [PATCH 317/357] added an exercise code block --- source/ch2_firstjavaprogram.ptx | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/source/ch2_firstjavaprogram.ptx b/source/ch2_firstjavaprogram.ptx index 8fa1e56..974964b 100644 --- a/source/ch2_firstjavaprogram.ptx +++ b/source/ch2_firstjavaprogram.ptx @@ -366,6 +366,39 @@ Hello World!

    + + + + +

    + Now that we have seen the hello world program in both Python and Java, use the ideas present in this chapter to write a Java program that prints your name and your favorite color. +

    + + +public class NameColor { + public static void main(String[] args) { + // Write your code here + + } +} + + +
    + + + +public class NameColor { + public static void main(String[] args) { + System.out.println("Name: Alex"); + System.out.println("Favorite Color: Blue"); + } +} + + + +
    + + From 1bf49ad56c5662be958be25f9fc12b48fb07dc8a Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Wed, 5 Aug 2026 22:22:05 +0300 Subject: [PATCH 318/357] unify solution --- source/ch2_firstjavaprogram.ptx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/ch2_firstjavaprogram.ptx b/source/ch2_firstjavaprogram.ptx index 974964b..cbf8ca3 100644 --- a/source/ch2_firstjavaprogram.ptx +++ b/source/ch2_firstjavaprogram.ptx @@ -389,8 +389,8 @@ public class NameColor { public class NameColor { public static void main(String[] args) { - System.out.println("Name: Alex"); - System.out.println("Favorite Color: Blue"); + System.out.println("Name: your name"); + System.out.println("Favorite Color: your favorite color"); } } From 0366862353ac80f5a61cf5de1dee172bc11bd88e Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Thu, 6 Aug 2026 00:10:04 +0300 Subject: [PATCH 319/357] added a question to 3.1 --- source/ch3_javadatatypes.ptx | 38 ++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index cd27074..a526570 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -230,6 +230,44 @@ public class TempConv {

    So, what exactly does the import statement do? What it does is tell the compiler that we are going to use a shortened version of the class’s name. In this example we are going to use the class java.util.Scanner but we can refer to it as just Scanner. We could use the java.util.Scanner class without any problem and without any import statement, provided that we always referred to it by its full name. As an experiment, you may want to try this yourself. Remove the import statement and change the string Scanner to java.util.Scanner in the rest of the code. The program should still compile and run.

    + + + +

    + Write a program that converts km to miles. Use the Scanner class to read the input. Note that 1 km is approximately equal to 0.621 miles. +

    + + +public class KmToMiles { + public static void main(String[] args) { + // write your code here + } +} + + +
    + + + +import java.util.Scanner; +public class KmToMiles { + public static void main(String[] args) { + Double kilometers; + Double miles; + Scanner input; + input = new Scanner(System.in); + System.out.print("Enter distance in kilometers: "); + kilometers = input.nextDouble(); + miles = kilometers * 0.621; + System.out.println(kilometers + " kilometers is equal to " + miles + " miles."); + } +} + + + +
    + + From c117091afd56e42f2f6d78f428a3b17367ba44f2 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Thu, 6 Aug 2026 00:21:39 +0300 Subject: [PATCH 320/357] push to end of chapter --- source/ch3_javadatatypes.ptx | 75 ++++++++++++++++++------------------ 1 file changed, 38 insertions(+), 37 deletions(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index a526570..0b300b0 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -231,43 +231,6 @@ public class TempConv { So, what exactly does the import statement do? What it does is tell the compiler that we are going to use a shortened version of the class’s name. In this example we are going to use the class java.util.Scanner but we can refer to it as just Scanner. We could use the java.util.Scanner class without any problem and without any import statement, provided that we always referred to it by its full name. As an experiment, you may want to try this yourself. Remove the import statement and change the string Scanner to java.util.Scanner in the rest of the code. The program should still compile and run.

    - - -

    - Write a program that converts km to miles. Use the Scanner class to read the input. Note that 1 km is approximately equal to 0.621 miles. -

    - - -public class KmToMiles { - public static void main(String[] args) { - // write your code here - } -} - - -
    - - - -import java.util.Scanner; -public class KmToMiles { - public static void main(String[] args) { - Double kilometers; - Double miles; - Scanner input; - input = new Scanner(System.in); - System.out.print("Enter distance in kilometers: "); - kilometers = input.nextDouble(); - miles = kilometers * 0.621; - System.out.println(kilometers + " kilometers is equal to " + miles + " miles."); - } -} - - - -
    - - @@ -317,6 +280,44 @@ public class KmToMiles {

    The general rule in Java is that you must decide what kind of an object your variable is going to reference and then you must declare that variable before you use it. In our temperature converter, the calculation (fahr - 32) * 5.0/9.0 works correctly because 5.0 and 9.0 are treated as double values, preventing the integer division that would occur if we had written 5/9, which would result in 0.

    + + + + +

    + Write a program that converts km to miles. Use the Scanner class to read the input. Note that 1 km is approximately equal to 0.621 miles. +

    + + +public class KmToMiles { + public static void main(String[] args) { + // write your code here + } +} + + +
    + + + +import java.util.Scanner; +public class KmToMiles { + public static void main(String[] args) { + Double kilometers; + Double miles; + Scanner input; + input = new Scanner(System.in); + System.out.print("Enter distance in kilometers: "); + kilometers = input.nextDouble(); + miles = kilometers * 0.621; + System.out.println(kilometers + " kilometers is equal to " + miles + " miles."); + } +} + + + +
    + From d82ee5bfd7bbf6e406973a16cb3cb99bdac5d637 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Thu, 6 Aug 2026 00:41:12 +0300 Subject: [PATCH 321/357] added a text box for input --- source/ch3_javadatatypes.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index 0b300b0..859fc5b 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -294,7 +294,7 @@ public class KmToMiles { // write your code here } } - + From 39eac5038c727de71c80dff91e1e86707483354a Mon Sep 17 00:00:00 2001 From: "nshizirungudieumerci@gmail.com" Date: Thu, 6 Aug 2026 09:11:03 -0400 Subject: [PATCH 322/357] added refrence to section 9.3 where it needed to be placed --- source/ch9_commonmistakes.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch9_commonmistakes.ptx b/source/ch9_commonmistakes.ptx index f28364f..95cc765 100644 --- a/source/ch9_commonmistakes.ptx +++ b/source/ch9_commonmistakes.ptx @@ -140,7 +140,7 @@

    - You may notice that this error message looks similar to the previous one, however, it has an entirely different cause. In Java, classes like Scanner that are part of external packages (like java.util) must be explicitly imported into your source file. Java does not automatically recognize these classes. To resolve this error, you need to add an import statement for the Scanner class at the beginning of your Histo.java file, typically import java.util.Scanner;. + You may notice that this error message looks similar to the previous one , however, it has an entirely different cause. In Java, classes like Scanner that are part of external packages (like java.util) must be explicitly imported into your source file. Java does not automatically recognize these classes. To resolve this error, you need to add an import statement for the Scanner class at the beginning of your Histo.java file, typically import java.util.Scanner;.

    From 3c7c9db06645bd0fac1a7a024931b89804256db6 Mon Sep 17 00:00:00 2001 From: "nshizirungudieumerci@gmail.com" Date: Thu, 6 Aug 2026 09:45:30 -0400 Subject: [PATCH 323/357] Added listing tag to chapter9.6 to make the text more organized --- source/ch9_commonmistakes.ptx | 3 +++ 1 file changed, 3 insertions(+) diff --git a/source/ch9_commonmistakes.ptx b/source/ch9_commonmistakes.ptx index 61502a6..04794f3 100644 --- a/source/ch9_commonmistakes.ptx +++ b/source/ch9_commonmistakes.ptx @@ -183,6 +183,8 @@

    Java is a statically typed language, meaning you must specify the type of objects that can be stored in a container like an ArrayList. If you forget to declare the type, the compiler will give you an error.

    + + // UncheckedWarningDemo.java @@ -202,6 +204,7 @@ } // End of class +

    This is a compiler warning, not an error, indicating a potential type safety issue. It occurs because you are calling the add() method on rawList, which is an ArrayList used as a raw type (i.e., without specifying a generic type like <String> or <Integer>).

    From 7550ad240d1d9e2d8d4c284cf648749f96e99226 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Thu, 6 Aug 2026 16:55:00 +0300 Subject: [PATCH 324/357] changed to parson's problem --- source/ch2_firstjavaprogram.ptx | 73 +++++++++++++++++++-------------- 1 file changed, 43 insertions(+), 30 deletions(-) diff --git a/source/ch2_firstjavaprogram.ptx b/source/ch2_firstjavaprogram.ptx index cbf8ca3..2289adb 100644 --- a/source/ch2_firstjavaprogram.ptx +++ b/source/ch2_firstjavaprogram.ptx @@ -368,36 +368,6 @@ Hello World! - - -

    - Now that we have seen the hello world program in both Python and Java, use the ideas present in this chapter to write a Java program that prints your name and your favorite color. -

    - - -public class NameColor { - public static void main(String[] args) { - // Write your code here - - } -} - - -
    - - - -public class NameColor { - public static void main(String[] args) { - System.out.println("Name: your name"); - System.out.println("Favorite Color: your favorite color"); - } -} - - - -
    - @@ -509,6 +479,49 @@ public class NameColor { + + + +

    + Construct a complete Java program that prints your name and your favorite color to the console. + Drag the blocks into the correct order on the right. +

    +
    + + + public class NameColor { + + + + public static void main(String[] args) { + + + + System.out.println("Name: Alex"); + System.out.println("Favorite Color: Blue"); + + + + } + } + + + + system.out.println(Name: Alex); + System.out.println("Favorite Color: Blue") + + + + def main(args): + + + + public static main(String[] args) { + + + +
    + \ No newline at end of file From 1389b473141cd1cf45799cb8692bc2427b6bf447 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Thu, 6 Aug 2026 18:56:09 +0300 Subject: [PATCH 325/357] added or tags --- source/ch2_firstjavaprogram.ptx | 42 +++++++++++++++++---------------- 1 file changed, 22 insertions(+), 20 deletions(-) diff --git a/source/ch2_firstjavaprogram.ptx b/source/ch2_firstjavaprogram.ptx index 2289adb..c1cb7a1 100644 --- a/source/ch2_firstjavaprogram.ptx +++ b/source/ch2_firstjavaprogram.ptx @@ -480,7 +480,7 @@ Hello World! - +

    Construct a complete Java program that prints your name and your favorite color to the console. @@ -489,36 +489,38 @@ Hello World! - public class NameColor { + + public class NameColor { + + + class NameColor { + - + - public static void main(String[] args) { + + public static void main(String[] args) { + + + public static main(String[] args) { + - System.out.println("Name: Alex"); - System.out.println("Favorite Color: Blue"); + + System.out.println("Name: Alex"); + System.out.println("Favorite Color: Blue"); + + + system.out.println(Name: Alex); + System.out.println("Favorite Color: Blue") + } } - - - system.out.println(Name: Alex); - System.out.println("Favorite Color: Blue") - - - - def main(args): - - - - public static main(String[] args) { - - From 3b4875dc53b051a1efeaecfe3c942dc86853372d Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Thu, 6 Aug 2026 20:35:03 +0300 Subject: [PATCH 326/357] added parson related to section 3.1 --- source/ch3_javadatatypes.ptx | 101 ++++++++++++++++++++++------------- 1 file changed, 65 insertions(+), 36 deletions(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index 859fc5b..51f69cd 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -280,43 +280,7 @@ public class TempConv {

    The general rule in Java is that you must decide what kind of an object your variable is going to reference and then you must declare that variable before you use it. In our temperature converter, the calculation (fahr - 32) * 5.0/9.0 works correctly because 5.0 and 9.0 are treated as double values, preventing the integer division that would occur if we had written 5/9, which would result in 0.

    - - - -

    - Write a program that converts km to miles. Use the Scanner class to read the input. Note that 1 km is approximately equal to 0.621 miles. -

    - - -public class KmToMiles { - public static void main(String[] args) { - // write your code here - } -} - - -
    - - - -import java.util.Scanner; -public class KmToMiles { - public static void main(String[] args) { - Double kilometers; - Double miles; - Scanner input; - input = new Scanner(System.in); - System.out.print("Enter distance in kilometers: "); - kilometers = input.nextDouble(); - miles = kilometers * 0.621; - System.out.println(kilometers + " kilometers is equal to " + miles + " miles."); - } -} - - - -
    @@ -1171,6 +1135,71 @@ public class HistoMap {
    + + +

    + Construct a complete Java program that reads a distance in kilometers from the user and converts it to miles. + Drag the blocks into the correct order on the right. +

    +
    + + + + + import java.util.Scanner; + + + import Scanner; + + + + + public class KmToMiles { + + + + public static void main(String[] args) { + + + + + Scanner input = new Scanner(System.in); + + + Scanner input = new Scanner(System.out); + + + + + + System.out.print("Enter distance in kilometers: "); + double kilometers = input.nextDouble(); + + + System.out.print("Enter distance in kilometers: "); + double kilometers = input.readDouble(); + + + + + + double miles = kilometers * 0.621; + + + double miles = kilometers / 0.621; + + + + + System.out.println(kilometers + " kilometers is equal to " + miles + " miles."); + + + } + } + + +
    + \ No newline at end of file From a01cde69e23d92514fb55bb9007d212e3cc2e05e Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Thu, 6 Aug 2026 21:42:46 +0300 Subject: [PATCH 327/357] added for 3.2 --- source/ch3_javadatatypes.ptx | 182 +++++++++++++++++++++++------------ 1 file changed, 118 insertions(+), 64 deletions(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index 51f69cd..1933e20 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -280,6 +280,69 @@ public class TempConv {

    The general rule in Java is that you must decide what kind of an object your variable is going to reference and then you must declare that variable before you use it. In our temperature converter, the calculation (fahr - 32) * 5.0/9.0 works correctly because 5.0 and 9.0 are treated as double values, preventing the integer division that would occur if we had written 5/9, which would result in 0.

    + + + +

    + Construct a complete Java program that reads a distance in kilometers from the user and converts it to miles. + Drag the blocks into the correct order on the right. +

    +
    + + + + + import java.util.Scanner; + + + import Scanner; + + + + + public class KmToMiles { + + + + public static void main(String[] args) { + + + + + Scanner input = new Scanner(System.in); + + + Scanner input = new Scanner(System.out); + + + + + + double kilometers = input.nextDouble(); + + + double kilometers = input.readDouble(); + + + + + + double miles = kilometers * 0.621; + + + double miles = kilometers / 0.621; + + + + + System.out.println(kilometers + " kilometers is equal to " + miles + " miles."); + + + } + } + + +
    @@ -449,6 +512,61 @@ void main() {

    In , we first create a Dog object and assign it to an Animal reference (upcasting). Then, we check if the Animal reference is actually pointing to a Dog object before downcasting it back to a Dog reference.

    + + + +

    + Construct a program that safely downcasts a Shape reference to a Circle object and calls a subclass method. + Drag the blocks into the correct order on the right. +

    +
    + + + class Shape { + ... + } + + + + class Circle extends Shape { + public void drawCircle() { System.out.println("Circle"); } + } + + + + public class Downcast { + public static void main(String[] args) { + Shape myShape = new Circle(); + + + + + if (myShape instanceof Circle) { + + + if (myShape.equals(Circle)) { + + + + + + Circle myCircle = (Circle) myShape; + myCircle.drawCircle(); + + + Circle myCircle = myShape; + myCircle.drawCircle(); + + + + + } + } + } + + +
    + @@ -1135,70 +1253,6 @@ public class HistoMap {
    - - -

    - Construct a complete Java program that reads a distance in kilometers from the user and converts it to miles. - Drag the blocks into the correct order on the right. -

    -
    - - - - - import java.util.Scanner; - - - import Scanner; - - - - - public class KmToMiles { - - - - public static void main(String[] args) { - - - - - Scanner input = new Scanner(System.in); - - - Scanner input = new Scanner(System.out); - - - - - - System.out.print("Enter distance in kilometers: "); - double kilometers = input.nextDouble(); - - - System.out.print("Enter distance in kilometers: "); - double kilometers = input.readDouble(); - - - - - - double miles = kilometers * 0.621; - - - double miles = kilometers / 0.621; - - - - - System.out.println(kilometers + " kilometers is equal to " + miles + " miles."); - - - } - } - - -
    From 0f25a902e270a504ac8d5817ab5677b2d7c6ab61 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Thu, 6 Aug 2026 22:22:50 +0300 Subject: [PATCH 328/357] fixed spacing --- source/ch3_javadatatypes.ptx | 32 ++++++++++++++++++++------------ 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index 1933e20..a9ae75a 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -308,36 +308,42 @@ public class TempConv { + Scanner input; + Double kilometers; + Double miles; + + + - Scanner input = new Scanner(System.in); + input = new Scanner(System.in); - Scanner input = new Scanner(System.out); + input = new Scanner(System.out); - + - double kilometers = input.nextDouble(); + kilometers = input.nextDouble(); - double kilometers = input.readDouble(); + kilometers = input.readDouble(); - + - double miles = kilometers * 0.621; + miles = kilometers * 0.621; - double miles = kilometers / 0.621; + miles = kilometers / 0.621; - + System.out.println(kilometers + " kilometers is equal to " + miles + " miles."); - + } } @@ -529,8 +535,10 @@ void main() { class Circle extends Shape { - public void drawCircle() { System.out.println("Circle"); } - } + public void drawCircle() { + System.out.println("Circle"); + } + } From d9855422aff42979e50d94a723c1f6f731ae1fa5 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 7 Aug 2026 00:08:44 +0300 Subject: [PATCH 329/357] issue_372_listing --- source/ch3_javadatatypes.ptx | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index a9ae75a..bd2a019 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -813,7 +813,7 @@ public class Histo {

    - Now, let’s look at what is happening in the Java source. As usual, we declare the variables we are going to use at the beginning of the method. In this example we are declaring a Scanner variable called data, an integer called idx and an ArrayList called count. However, there is a new twist to the ArrayList declaration. Unlike Python where lists can contain just about anything, in Java we let the compiler know what kind of objects our array list is going to contain. In this case the ArrayList will contain Integers. The syntax we use to declare what kind of object the list will contain is the <Type> syntax. + Now, let’s look at what is happening in the Java source. As usual, we declare the variables we are going to use at the beginning of the method. In , we are declaring a Scanner variable called data, an integer called idx and an ArrayList called count. However, there is a new twist to the ArrayList declaration. Unlike Python where lists can contain just about anything, in Java we let the compiler know what kind of objects our array list is going to contain. In this case the ArrayList will contain Integers. The syntax we use to declare what kind of object the list will contain is the <Type> syntax.

    @@ -834,7 +834,7 @@ public class Histo {

    - Lines 13—20 are required to open the file. Why so many lines to open a file in Java? The additional code mainly comes from the fact that Java forces you to reckon with the possibility that the file you want to open is not going to be there. If you attempt to open a file that is not there you will get an error. A try/catch construct allows us to try things that are risky, and gracefully recover from an error if one occurs. shows the general structure of a try/catch block. + Lines 13—20 in are required to open the file. Why so many lines to open a file in Java? The additional code mainly comes from the fact that Java forces you to reckon with the possibility that the file you want to open is not going to be there. If you attempt to open a file that is not there you will get an error. A try/catch construct allows us to try things that are risky, and gracefully recover from an error if one occurs. shows the general structure of a try/catch block.

    @@ -850,11 +850,11 @@ public class Histo {

    - Notice that in line 16 we are catching an IOException. In fact, we will see later that we can have multiple catch blocks to catch different types of exceptions. If we want to be lazy and catch any old exception we can catch an Exception which is the parent of all exceptions. However, catching Exception is a terrible practice, since you may inadvertently catch exceptions you do not intend to, making it harder to identify bugs in your program. + Notice that in line 16 in , we are catching an IOException. In fact, we will see later that we can have multiple catch blocks to catch different types of exceptions. If we want to be lazy and catch any old exception we can catch an Exception which is the parent of all exceptions. However, catching Exception is a terrible practice, since you may inadvertently catch exceptions you do not intend to, making it harder to identify bugs in your program.

    - On line 22 we create our ArrayList and give it an initial size of 10. Strictly speaking, it is not necessary to give the ArrayList any size. It will grow or shrink dynamically as needed, just like a list in Python. On line 23 we start the first of three loops. The for loop on lines 23–25 serves the same purpose as the Python statement count = [0]*10, that is it initializes the first 10 positions in the ArrayList to hold the value 0. + On line 22 in , we create our ArrayList and give it an initial size of 10. Strictly speaking, it is not necessary to give the ArrayList any size. It will grow or shrink dynamically as needed, just like a list in Python. On line 23 we start the first of three loops. The for loop on lines 23–25 serves the same purpose as the Python statement count = [0]*10, that is it initializes the first 10 positions in the ArrayList to hold the value 0.

    @@ -908,15 +908,15 @@ public class Histo {

    - The next loop (lines 27–30) shows a typical Java pattern for reading data from a file. Java while loops and Python while loops are identical in their logic. In this case, we will continue to process the body of the loop as long as data.hasNextInt() returns true. + The next loop (lines 27–30) in shows a typical Java pattern for reading data from a file. Java while loops and Python while loops are identical in their logic. In this case, we will continue to process the body of the loop as long as data.hasNextInt() returns true.

    - Line 29 illustrates another important difference between Python and Java. Notice that in Java we can not write count[idx] = count[idx] + 1. This is because in Java there is no overloading of operators. Everything except the most basic math and logical operations is done using methods. So, to set the value of an ArrayList element we use the set method. The first parameter of set indicates the index or position in the ArrayList we are going to change. The next parameter is the value we want to set. Notice that, once again, we cannot use the indexing square bracket operator to retrieve a value from the list, but we must use the get method. + Line 29 in illustrates another important difference between Python and Java. Notice that in Java we can not write count[idx] = count[idx] + 1. This is because in Java there is no overloading of operators. Everything except the most basic math and logical operations is done using methods. So, to set the value of an ArrayList element we use the set method. The first parameter of set indicates the index or position in the ArrayList we are going to change. The next parameter is the value we want to set. Notice that, once again, we cannot use the indexing square bracket operator to retrieve a value from the list, but we must use the get method.

    - The last loop in this example is similar to the Python for loop where the object of the loop is a Sequence. In Java we can use this kind of for loop over all kinds of sequences, which are called Collection classes in Java. The for loop on line 33 for(Integer i : count) is equivalent to the Python loop for i in count: This loop iterates over all of the elements in the ArrayList called count. Each time through the loop the Integer variable i is bound to the next element of the ArrayList. If you tried the experiment of removing the <Integer> part of the ArrayList declaration you probably noticed that you had an error on this line. Why? + The last loop in is similar to the Python for loop where the object of the loop is a Sequence. In Java we can use this kind of for loop over all kinds of sequences, which are called Collection classes in Java. The for loop on line 33 in for(Integer i : count) is equivalent to the Python loop for i in count: This loop iterates over all of the elements in the ArrayList called count. Each time through the loop the Integer variable i is bound to the next element of the ArrayList. If you tried the experiment of removing the <Integer> part of the ArrayList declaration you probably noticed that you had an error on this line. Why?

    From 9d30e313dd06ac055fb05e28b68fde333862d6d1 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 7 Aug 2026 16:25:48 +0300 Subject: [PATCH 330/357] added mcq --- source/ch3_javadatatypes.ptx | 46 ++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index a9ae75a..85a24bf 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -1116,6 +1116,52 @@ public class HistoMap {

    + + + +

    + Which of the following is a valid variable name according to the core syntax rules of Java, but causes a syntax error in Python? +

    +
    + + + _variableName + +

    + Incorrect. Leading underscores are valid in both Java and Python (commonly used in Python for private/protected attributes). +

    +
    +
    + + + variable_name + +

    + Incorrect. Snake_case names with underscores are valid in both languages (and are actually standard convention in Python). +

    +
    +
    + + + $variableName + +

    + Correct! Java allows the dollar sign ($) in variable names, but Python generates a SyntaxError because $ is not a permitted identifier character in Python. +

    +
    +
    + + + variableName2 + +

    + Incorrect. Numbers at the end of variable names are valid syntax in both Java and Python. +

    +
    +
    +
    +
    +
    From 0bf2120840a72b676ae16d541091382a7675d026 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 7 Aug 2026 17:26:25 +0300 Subject: [PATCH 331/357] added dictionary parson --- source/ch3_javadatatypes.ptx | 56 ++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index a9ae75a..97bf2a1 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -1079,6 +1079,62 @@ public class HistoMap {

    Improve to remove the punctuation.

    + + + +

    + Rearrange and indent the blocks to create a Java method that accepts a dictionary (Map) of item prices and updates the price of a specific item. +

    +
    + + + + +public void updatePrice(Map<String, Double> catalog, String item, double newPrice) { + + + + +public void updatePrice(Map<String, Double> catalog, item, newPrice) { + + + + + + + + if (catalog.containsKey(item)) { + + + + + if (catalog.get(item) == null) { + + + + + + + + catalog.put(item, newPrice); + + + + + catalog.add(item, newPrice); + + + + + + + } +} + + + +
    +
    From 860af326c5dfcc7635fd89b47a9f58a378fc930f Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 7 Aug 2026 17:45:25 +0300 Subject: [PATCH 332/357] added changes --- source/ch3_javadatatypes.ptx | 37 +++++++++++++----------------------- 1 file changed, 13 insertions(+), 24 deletions(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index 97bf2a1..8c7f080 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -1080,57 +1080,46 @@ public class HistoMap { Improve to remove the punctuation.

    - +

    - Rearrange and indent the blocks to create a Java method that accepts a dictionary (Map) of item prices and updates the price of a specific item. + Rearrange and indent the blocks to create a general Java method that accepts a dictionary (Map) of item prices and updates the price of a specific item. If the item does not exist, do nothing.

    - -public void updatePrice(Map<String, Double> catalog, String item, double newPrice) { - + public void updatePrice(Map<String, Double> catalog, String item, double newPrice) { - -public void updatePrice(Map<String, Double> catalog, item, newPrice) { - + public void updatePrice() { + Map<String, Double> catalog, + String item, + double newPrice - - if (catalog.containsKey(item)) { - + if (catalog.containsKey(item)) { - - if (catalog.get(item) == null) { - + if (catalog.get(item) == null) { - - catalog.put(item, newPrice); - + catalog.put(item, newPrice); - - catalog.add(item, newPrice); - + catalog.add(item, newPrice); - - } -} - + } + }
    From d40e771d99149ee5672a29d5e4a7224bfb52bafd Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 7 Aug 2026 17:51:04 +0300 Subject: [PATCH 333/357] final --- source/ch3_javadatatypes.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index 8c7f080..f2c5a48 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -1083,7 +1083,7 @@ public class HistoMap {

    - Rearrange and indent the blocks to create a general Java method that accepts a dictionary (Map) of item prices and updates the price of a specific item. If the item does not exist, do nothing. + Rearrange the blocks to create a general Java method that accepts a dictionary (Map) of item prices and updates the price of a specific item. If the item does not exist, do nothing.

    From 4584265c35ecdf3f1d3870110f5c3772af28eebe Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 7 Aug 2026 18:27:35 +0300 Subject: [PATCH 334/357] added question --- source/ch4_conditionals.ptx | 63 +++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 7410fc6..0fea59b 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -255,6 +255,69 @@ The switch statement is not used very often, and we recommend you do not

    Finally, the switch statement does not support relational expressions such as greater than or less than. So you cannot use it to completely replace the elif. Even with the new features of Java 14+ the switch statement is still limited to constant comparisons using equality.

    + + + Java Temperature Status Monitor + +

    + Rearrange the blocks to create a Java method that accepts a temperature reading and returns a status string ("CRITICAL", "WARNING", or "NORMAL"). +

    +
    + + + + public String checkTemperature(double temp) { + + + public String checkTemperature(double temp); { + + + + + + if (temp >= 100.0) { + return "CRITICAL"; + } + + + if (temp == 100.0) { + return "CRITICAL"; + } + + + + + + else if (temp >= 75.0) { + return "WARNING"; + } + + + else (temp >= 75.0) { + return "WARNING"; + } + + + + + + else { + return "NORMAL"; + } + + + else if { + return "NORMAL"; + } + + + + + } + + +
    +
    From 051e8a87a34100e47f3238df05af8adf272fe215 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 7 Aug 2026 18:28:58 +0300 Subject: [PATCH 335/357] edited --- source/ch4_conditionals.ptx | 1 - 1 file changed, 1 deletion(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 0fea59b..904fbf4 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -257,7 +257,6 @@ The switch statement is not used very often, and we recommend you do not - Java Temperature Status Monitor

    Rearrange the blocks to create a Java method that accepts a temperature reading and returns a status string ("CRITICAL", "WARNING", or "NORMAL"). From e32279092981af29ed97f7d8b7e064a5ae10208e Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 7 Aug 2026 20:58:22 +0300 Subject: [PATCH 336/357] added question --- source/ch4_conditionals.ptx | 51 +++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 904fbf4..1f99114 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -401,6 +401,57 @@ public class Ternary {

    In , we are using this ternary operator to assign a value to a based on whether a is even or odd. If a is even, it will be squared; if odd, it will be instead be calculated as 3 * x - 1. This is a concise way to write conditional assignments in Java. However, you might want to use it sparingly, as it can make code less readable if overused or used with complex expressions.

    + + + +

    + Rearrange the blocks to create a Java method that calculates shipping costs. Orders over $100 get free shipping ($0.0), while members pay $5.0 and non-members pay $10.0. +

    +
    + + + + public double calculateShipping(double orderTotal, boolean isMember) { + + + public double calculateShipping() + double orderTotal + boolean isMember + { + + + + + + if (orderTotal >= 100.0) { + return 0.0; + } + + + if (orderTotal = 100.0) { + return 0.0; + } + + + + + + else { + return isMember ? 5.0 : 10.0; + } + + + else { + return isMember : 5.0 ? 10.0; + } + + + + + } + + +
    From cd459897246fc8a6be034c554a3098fe0dceda6f Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 7 Aug 2026 22:06:19 +0300 Subject: [PATCH 337/357] added question --- source/ch5_loopsanditeration.ptx | 53 ++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/source/ch5_loopsanditeration.ptx b/source/ch5_loopsanditeration.ptx index 28cbde4..743e916 100644 --- a/source/ch5_loopsanditeration.ptx +++ b/source/ch5_loopsanditeration.ptx @@ -183,6 +183,59 @@ public class StringIterationExample {
    + + +

    + Rearrange the blocks to create a Java method that accepts an upper bound integer limit and calculates the sum of all even numbers from 2 up to and including limit. +

    +
    + + + public int sumEvens(int limit) { + + + + + int total = 0; + + + int total; + + + + + + for (int i = 2; i <= limit; i += 2) { + + + for (int i = 2; i < limit; i =+ 2) { + + + + + + total += i; + } + + + total = i; + } + + + + + + return total; + } + + + return i; + } + + + +
    +
    From c0402e8eb44c8ef47fec7fae1c9ecf06f3431d18 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Fri, 7 Aug 2026 22:16:27 +0300 Subject: [PATCH 338/357] spacing --- source/ch5_loopsanditeration.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch5_loopsanditeration.ptx b/source/ch5_loopsanditeration.ptx index 743e916..7c6819b 100644 --- a/source/ch5_loopsanditeration.ptx +++ b/source/ch5_loopsanditeration.ptx @@ -234,7 +234,7 @@ public class StringIterationExample { - +
    From 00cb2c8d35a3aa48b832db26ef844916245e3f2f Mon Sep 17 00:00:00 2001 From: "nshizirungudieumerci@gmail.com" Date: Fri, 7 Aug 2026 15:40:01 -0400 Subject: [PATCH 339/357] moving naming conventions to start of chapter 3 --- source/ch2_firstjavaprogram.ptx | 84 +++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) diff --git a/source/ch2_firstjavaprogram.ptx b/source/ch2_firstjavaprogram.ptx index c1cb7a1..7f1669d 100644 --- a/source/ch2_firstjavaprogram.ptx +++ b/source/ch2_firstjavaprogram.ptx @@ -526,4 +526,88 @@ Hello World! + +
    + Naming Conventions +

    + It is worth pointing out that Java has some very handy naming conventions. It is advisable to both use meaningful names and to follow these naming conventions while developing software in Java for good maintenance and readability of code. +

    + +

    +

      +
    • +

      + Class names should be nouns that are written in UpperCamelCase, namely with the first letter of each word capitalized including the first. + For example, ArrayList, Scanner, StringBuilder, System, etc. +

      +
    • + +
    • +

      + Method names use lowerCamelCase which start with a verb that describes the action they perform. This means that method names start with a lower case letter, and use upper case for each internal-word method names. For example, isInt(), nextLine(), getDenominator(), setNumerator(), etc. +

      +
    • + +
    • +

      + Instance variables of a class start with a lower case letter and use lowerCamelCase like method names. For example, count, totalAmount, etc. +

      +
    • + +
    • +

      + Constants are in all upper case letters or in upper snake case, which also known as screaming snake case, and which is a naming convention in which each word is written in uppercase letters, separated by underscores. + For example, Math.MAXINT or MAX_INT. +

      +
    • +
    +

    + + + +

    + Which of the following is a valid variable name according to the core syntax rules of Java, but causes a syntax error in Python? +

    +
    + + + _variableName + +

    + Incorrect. Leading underscores are valid in both Java and Python (commonly used in Python for private/protected attributes). +

    +
    +
    + + + variable_name + +

    + Incorrect. Snake_case names with underscores are valid in both languages (and are actually standard convention in Python). +

    +
    +
    + + + $variableName + +

    + Correct! Java allows the dollar sign ($) in variable names, but Python generates a SyntaxError because $ is not a permitted identifier character in Python. +

    +
    +
    + + + variableName2 + +

    + Incorrect. Numbers at the end of variable names are valid syntax in both Java and Python. +

    +
    +
    +
    +
    + +
    + \ No newline at end of file From e4e2ad396a8a342cc9efbdd1eef50cc4c3f1e4f4 Mon Sep 17 00:00:00 2001 From: "nshizirungudieumerci@gmail.com" Date: Fri, 7 Aug 2026 15:40:41 -0400 Subject: [PATCH 340/357] removed naming conventions from chapter 3 --- source/ch3_javadatatypes.ptx | 81 ------------------------------------ 1 file changed, 81 deletions(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index df08c4a..62365f8 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -1126,88 +1126,7 @@ public class HistoMap { -
    - Naming Conventions -

    - It is worth pointing out that Java has some very handy naming conventions. It is advisable to both use meaningful names and to follow these naming conventions while developing software in Java for good maintenance and readability of code. -

    - -

    -

      -
    • -

      - Class names should be nouns that are written in UpperCamelCase, namely with the first letter of each word capitalized including the first. - For example, ArrayList, Scanner, StringBuilder, System, etc. -

      -
    • - -
    • -

      - Method names use lowerCamelCase which start with a verb that describes the action they perform. This means that method names start with a lower case letter, and use upper case for each internal-word method names. For example, isInt(), nextLine(), getDenominator(), setNumerator(), etc. -

      -
    • - -
    • -

      - Instance variables of a class start with a lower case letter and use lowerCamelCase like method names. For example, count, totalAmount, etc. -

      -
    • - -
    • -

      - Constants are in all upper case letters or in upper snake case, which also known as screaming snake case, and which is a naming convention in which each word is written in uppercase letters, separated by underscores. - For example, Math.MAXINT or MAX_INT. -

      -
    • -
    -

    - - - -

    - Which of the following is a valid variable name according to the core syntax rules of Java, but causes a syntax error in Python? -

    -
    - - - _variableName - -

    - Incorrect. Leading underscores are valid in both Java and Python (commonly used in Python for private/protected attributes). -

    -
    -
    - - variable_name - -

    - Incorrect. Snake_case names with underscores are valid in both languages (and are actually standard convention in Python). -

    -
    -
    - - - $variableName - -

    - Correct! Java allows the dollar sign ($) in variable names, but Python generates a SyntaxError because $ is not a permitted identifier character in Python. -

    -
    -
    - - - variableName2 - -

    - Incorrect. Numbers at the end of variable names are valid syntax in both Java and Python. -

    -
    -
    -
    -
    - -
    Summary & Reading Questions From ccd1878e64297aea8430574e1baccca68a292cce Mon Sep 17 00:00:00 2001 From: "nshizirungudieumerci@gmail.com" Date: Fri, 7 Aug 2026 16:17:38 -0400 Subject: [PATCH 341/357] added a parsons problem for section 3.5 --- source/ch3_javadatatypes.ptx | 42 ++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index df08c4a..f348eb0 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -967,6 +967,48 @@ public class HistoArray {

    The main difference between and is that we declare count to be an Array of integers. We also can initialize short arrays directly using the syntax shown here: Integer[] count = {0,0,0,0,0,0,0,0,0,0}Then notice that we can use the square bracket notation count[idx] to index into an array.

    + + + +

    + Construct a short Java program that creates an array of three integers, + changes the first value, and prints it. Drag the blocks into the correct order on the right. +

    +
    + + + public class ArrayExample { + public static void main(String[] args) { + + + + + Integer[] nums = {1, 2, 3}; + + + Integer[] nums = (1, 2, 3); + + + + + + nums[0] = 5; + + + nums(0) = 5; + + + + + System.out.println(nums[0]); + + + + } + } + + +
    From 63d2bc1a04301d662b67a6aa2a77b4fc884d4095 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Mon, 10 Aug 2026 15:52:31 +0300 Subject: [PATCH 342/357] added the question --- source/ch5_loopsanditeration.ptx | 53 ++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/source/ch5_loopsanditeration.ptx b/source/ch5_loopsanditeration.ptx index 28cbde4..8d8c102 100644 --- a/source/ch5_loopsanditeration.ptx +++ b/source/ch5_loopsanditeration.ptx @@ -244,6 +244,59 @@ public class DoWhileExample {
    + + +

    + Rearrange the blocks to create a Java method that accepts a starting balance and a target amount, then calculates how many years it takes for the balance to reach or exceed the target by doubling each year. +

    +
    + + + + public int yearsToTarget(double balance, double target) { + int years = 0; + + + public int yearsToTarget(double balance, double target) { + int years; + + + + + + while (balance < target) { + + + while (balance >= target) { + + + + + + balance *= 2; + years++; + } + + + balance * 2; + years++; + } + + + + + + return years; + } + + + return balance; + } + + + +
    +
    Summary & Reading Questions From 64b84f02327b84dccae55c389a70383448f7a0f5 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Mon, 10 Aug 2026 20:38:58 +0300 Subject: [PATCH 343/357] added the question --- source/ch6_definingclasses.ptx | 44 ++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index f2c8bf7..4adb2ff 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -629,7 +629,51 @@ public class Fraction {
    + + +

    + Rearrange the blocks to create a Printer class with two overloaded printData methods—one that accepts an int and another that accepts a String. +

    +
    + + + public class Printer { + + + + + public void printData(int number) { + System.out.println("Number: " + number); + } + + + public void printData(int number) { + System.out.println("Number: " + number); + + + + + + public void printData(String text) { + System.out.println("Text: " + text); + } + + + public void printData(int text) { + System.out.println("Text: " + text); + } + + + + + } + + +
    + + +
    From 5f1d7e3ece629169176c9a89e0e13a6e2bdd62ea Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Mon, 10 Aug 2026 22:33:26 +0300 Subject: [PATCH 344/357] replaced th section earlier --- source/ch6_definingclasses.ptx | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index f2c8bf7..f495747 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -629,15 +629,8 @@ public class Fraction {
    - - - -
    - Inheritance - -

    - If you ran the program above you probably noticed that the output is not very satisfying. Chances are your output looked something like . + If you ran the program above you probably noticed that the output is not very satisfying. Chances are your output looked something like .

    @@ -654,8 +647,12 @@ Fraction@6ff3c5b5 In Python you can control how that looks by writing an __str__ method for your class. If you do not then you will get the default, which looks something like the above.

    - + +
    + +
    + Inheritance The <c>Object</c> Class From bee7af32288e939800248a09b750d66e946ffdb5 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Mon, 10 Aug 2026 22:37:45 +0300 Subject: [PATCH 345/357] added a listing tags --- source/ch6_definingclasses.ptx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index f495747..668aa83 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -630,7 +630,7 @@ public class Fraction {

    - If you ran the program above you probably noticed that the output is not very satisfying. Chances are your output looked something like . + If you ran , you probably noticed that the output is not very satisfying. Chances are your output looked something like .

    @@ -645,7 +645,7 @@ Fraction@6ff3c5b5 The reason is that we have not yet provided a friendly string representation for our Fraction objects. Just like in Python, whenever an object is printed by the println method it must be converted to string format. In Python you can control how that looks by writing an __str__ method for your class. - If you do not then you will get the default, which looks something like the above. + If you do not then you will get the default, which looks something like .

    From 7c7441807b9dd122a2a5d5f70882bd7d55cbb527 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Mon, 10 Aug 2026 22:39:57 +0300 Subject: [PATCH 346/357] added linking to section --- source/ch6_definingclasses.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index 668aa83..67fb411 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -645,7 +645,7 @@ Fraction@6ff3c5b5 The reason is that we have not yet provided a friendly string representation for our Fraction objects. Just like in Python, whenever an object is printed by the println method it must be converted to string format. In Python you can control how that looks by writing an __str__ method for your class. - If you do not then you will get the default, which looks something like . + If you do not then you will get the default, which looks something like . We will see how to provide a friendly string representation for our Fraction class in .

    From c25d77c9aa8c0b5e81d0303b36d1d1128d051360 Mon Sep 17 00:00:00 2001 From: "nshizirungudieumerci@gmail.com" Date: Mon, 10 Aug 2026 15:44:51 -0400 Subject: [PATCH 347/357] added a parsons problem to the inheritance section --- source/ch6_definingclasses.ptx | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index 4adb2ff..4375608 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -961,6 +961,38 @@ public void test(Number a, Number b) { You will still get this error even if all your code that calls this test method passes two Fractions as parameters (remember that Fraction does implement add).

    + + + +

    + Construct the toString method for the Fraction class so that printing a + fraction shows it in the form numerator/denominator. Drag the blocks into the correct order on the right. +

    +
    + + + + public String toString() { + + + public void toString() { + + + + + + return numerator.toString() + "/" + denominator.toString(); + + + numerator.toString() + "/" + denominator.toString(); + + + + + } + + +
    From 26ad182c200fa5c20f9024f72bf0f943749edd85 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Mon, 10 Aug 2026 23:15:49 +0300 Subject: [PATCH 348/357] fixed erros after merge --- source/ch6_definingclasses.ptx | 46 +++++++++++++--------------------- 1 file changed, 18 insertions(+), 28 deletions(-) diff --git a/source/ch6_definingclasses.ptx b/source/ch6_definingclasses.ptx index 32a277b..df7a4af 100644 --- a/source/ch6_definingclasses.ptx +++ b/source/ch6_definingclasses.ptx @@ -628,6 +628,24 @@ public class Fraction {
    +

    + If you ran , you probably noticed that the output is not very satisfying. Chances are your output looked something like . +

    + + + + +Fraction@6ff3c5b5 + + + + +

    + The reason is that we have not yet provided a friendly string representation for our Fraction objects. + Just like in Python, whenever an object is printed by the println method it must be converted to string format. + In Python you can control how that looks by writing an __str__ method for your class. + If you do not then you will get the default, which looks something like . We will see how to provide a friendly string representation for our Fraction class in . +

    @@ -672,34 +690,6 @@ public class Fraction { - - - - -
    - Inheritance - - -

    - If you ran the program above you probably noticed that the output is not very satisfying. Chances are your output looked something like . -

    - - - - -Fraction@6ff3c5b5 - - - - -

    - The reason is that we have not yet provided a friendly string representation for our Fraction objects. - Just like in Python, whenever an object is printed by the println method it must be converted to string format. - In Python you can control how that looks by writing an __str__ method for your class. - If you do not then you will get the default, which looks something like . We will see how to provide a friendly string representation for our Fraction class in . -

    - -
    From 4a710abcdca97bfec2a101a509446d1da447a803 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Tue, 11 Aug 2026 20:19:22 +0300 Subject: [PATCH 349/357] fixed the error --- source/ch4_conditionals.ptx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 1f99114..0cd7e57 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -5,6 +5,7 @@ Conditionals
    Using Conditional Statements in Java +

    conditional statements Conditional statements in Python and Java are very similar. In Python we have three patterns: @@ -50,7 +51,8 @@ if score >= 90: # Note the colon at the end of the line In Java, the parentheses around the condition are required because it is technically a function that evaluates to True or False.

    - +
    + Using the <c>if</c> - <c>else</c> Statement From a558f997573e8dfcee95578a90dfd3279fb9b3b4 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Tue, 11 Aug 2026 20:34:31 +0300 Subject: [PATCH 350/357] fixed the error --- source/ap-java-cheatsheet.ptx | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/source/ap-java-cheatsheet.ptx b/source/ap-java-cheatsheet.ptx index f272981..7e8f94a 100644 --- a/source/ap-java-cheatsheet.ptx +++ b/source/ap-java-cheatsheet.ptx @@ -10,7 +10,7 @@ The following is intended to be useful in better understanding Java functions coming from a Python background.

    - + Function/Method Equivalents: Python to Java @@ -201,5 +201,4 @@

    - \ No newline at end of file From 9013d7d95f1d07db5579c684f5f93595da24c65a Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Tue, 11 Aug 2026 21:57:48 +0300 Subject: [PATCH 351/357] fixed --- source/ch4_conditionals.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 0cd7e57..08463b3 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -51,7 +51,7 @@ if score >= 90: # Note the colon at the end of the line In Java, the parentheses around the condition are required because it is technically a function that evaluates to True or False.

    - + Using the <c>if</c> - <c>else</c> Statement From 14be3761b4a4c8e39594ac807dedf6bc814f5734 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Tue, 11 Aug 2026 22:45:53 +0300 Subject: [PATCH 352/357] added a subsection --- source/ch4_conditionals.ptx | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 08463b3..0522a87 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -8,10 +8,12 @@

    conditional statements Conditional statements in Python and Java are very similar. - In Python we have three patterns: + In Python we have three patterns/

    - +
    + + Using the <c>if</c> Statement

    shows how the simple if statement is written in Python.

    @@ -51,7 +53,7 @@ if score >= 90: # Note the colon at the end of the line In Java, the parentheses around the condition are required because it is technically a function that evaluates to True or False.

    - +
    Using the <c>if</c> - <c>else</c> Statement From 3b997c6f6c1055cfdfa29068610f3755b0d412c8 Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Tue, 11 Aug 2026 22:51:02 +0300 Subject: [PATCH 353/357] fixed a dot --- source/ch4_conditionals.ptx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/ch4_conditionals.ptx b/source/ch4_conditionals.ptx index 0522a87..623587a 100644 --- a/source/ch4_conditionals.ptx +++ b/source/ch4_conditionals.ptx @@ -8,7 +8,7 @@

    conditional statements Conditional statements in Python and Java are very similar. - In Python we have three patterns/ + In Python we have three patterns.

    From a6860ff3aaada9d514893e2675ca16340974012c Mon Sep 17 00:00:00 2001 From: Habiba Sorour Date: Tue, 11 Aug 2026 23:40:33 +0300 Subject: [PATCH 354/357] fixedthe error --- source/ch3_javadatatypes.ptx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/source/ch3_javadatatypes.ptx b/source/ch3_javadatatypes.ptx index a08b796..6c69c36 100644 --- a/source/ch3_javadatatypes.ptx +++ b/source/ch3_javadatatypes.ptx @@ -867,7 +867,7 @@ public class Histo {

    - + for i in range(2, 102, 2) @@ -904,7 +904,7 @@ public class Histo { for (int x = 0, int y = 0; x < 10; x++, y += 2) - +

    From ce044bc87a9224bc3ebdfdfdcd4eece85344373d Mon Sep 17 00:00:00 2001 From: "nshizirungudieumerci@gmail.com" Date: Wed, 12 Aug 2026 11:05:14 -0400 Subject: [PATCH 355/357] added a parsons problem in section 8.2 which introduces students to creating files --- source/ch8_filehandling.ptx | 42 +++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index a610f37..7a7cf33 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -172,6 +172,48 @@ public class CreateFile { You may have noticed the use of another method from the File class; getName(). This method returns a string containing the name of the file.

    + + + +

    + Construct a short Java program that creates a File object for "myfile.txt" + and prints it. Drag the blocks into the correct order on the right. +

    +
    + + + + import java.io.File; + + + import java.io.Scanner; + + + + + public class CreateFile { + public static void main(String[] args) { + + + + + File myFile = new File("myfile.txt"); + + + File myFile = new File(); + + + + + System.out.println(myFile); + + + + } + } + + +
    From 9d3d9c69a12987c01f67098894888a83e4f6073e Mon Sep 17 00:00:00 2001 From: "nshizirungudieumerci@gmail.com" Date: Wed, 12 Aug 2026 13:43:33 -0400 Subject: [PATCH 356/357] added a parsons problem to section 8.3 --- source/ch8_filehandling.ptx | 38 +++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx index 7a7cf33..d9656b0 100644 --- a/source/ch8_filehandling.ptx +++ b/source/ch8_filehandling.ptx @@ -287,6 +287,44 @@ public class CreateFile {

    You may have noticed that there are some new methods you haven't seen yet. The hasNextLine() method checks if there is a next line in the file, and returns false if there isn't. This method allows us to iterate over every line till there is no next line. The nextLine() method of the Scanner object returns the next line in the file as a string.

    + + + +

    + Construct the part of a Java program that opens a file with a Scanner and + prints each line until there are no more lines. Drag the blocks into the correct order on the right. +

    +
    + + + + try (Scanner fileReader = new Scanner(new File(filename))) { + + + try (Scanner fileReader = new Scanner(filename)) { + + + + + + while (fileReader.hasNextLine()) { + + + while (fileReader.nextLine()) { + + + + + String data = fileReader.nextLine(); + System.out.println(data); + + + + } + } + + +
    From c7f4c7b65d38972f4705a1d97b1e1f7c9afb6fb9 Mon Sep 17 00:00:00 2001 From: "nshizirungudieumerci@gmail.com" Date: Wed, 12 Aug 2026 15:37:09 -0400 Subject: [PATCH 357/357] added a select all that apply multiple choice based question to section9.3 --- source/ch9_commonmistakes.ptx | 50 +++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/source/ch9_commonmistakes.ptx b/source/ch9_commonmistakes.ptx index 64b59cd..4dca391 100644 --- a/source/ch9_commonmistakes.ptx +++ b/source/ch9_commonmistakes.ptx @@ -115,6 +115,56 @@

    The 'cannot find symbol' error for the variable count on line 6 indicates that count was used before it was declared within the Histo class. In Java, all variables must be explicitly declared with a data type (e.g., int, String, ArrayList<Integer>) before they can be assigned a value or referenced in any way. The arrow in the error message points to where the undeclared variable count was first encountered. To resolve this, count needs to be declared with its appropriate type (e.g., ArrayList<Integer> count;) before any attempt to initialize or use it.

    + + +

    + Based on , select all of the + statements that are true about declaring variables in Java. +

    +
    + + + +

    Every variable must be declared with a data type before it is used.

    +
    + +

    Correct! Java requires a variable to be declared with its type before it can be assigned or referenced.

    +
    +
    + + +

    The "cannot find symbol" error happens because count was used before being declared.

    +
    + +

    Correct! That error means the compiler reached a variable it has no declaration for.

    +
    +
    + + +

    Writing ArrayList<Integer> count; before using count would fix the "cannot find symbol" error.

    +
    + +

    Correct! Declaring count with its type resolves the error.

    +
    +
    + + +

    Java lets you use a variable without declaring it first, just like Python.

    +
    + +

    Incorrect. Unlike Python, Java requires all variables to be declared before use.

    +
    +
    + + +

    The error can be fixed by adding an import statement.

    +
    + +

    Incorrect. The import is already present; the problem is the missing variable declaration, not a missing import.

    +
    +
    +
    +