From 5268ac43cd523493aa9674f5c0cfc7b65981c609 Mon Sep 17 00:00:00 2001
From: Peter Story I started writing this article in 2006 using Python’s restructured text.
+ In 2007 I switched to markdown since everything else I was writing used
+ markdown. In particular I switched to the variant of markdown used by
+ the excellent If you got this far, I would also like to use this space as a shameless
+ plug for two books. At Luther college we use Python for CS1 and CS2.
+ When we decided to make the switch to introducing CS with Python we
+ wanted to provide our students with two semesters of Python. The reason
+ is that after one semester students are just getting comfortable with
+ the language and it does not make sense to push them into a brand new
+ language just as they are getting some comfort. The second reason is
+ that Python really is a great language for teaching data structures. The
+ language makes the algorithms evident by clearing away all of the
+ syntactic clutter. So we (David Ranum and I) wrote a CS2 book called
+ Here’s an example of the error message that occurs when you forget to
+ use the new keyword. Notice that the message is pretty unhelpful.
+ Java thinks you are trying to call the Method Scanner, but
+ there are two problems. First Scanner is not really a method it
+ is a constructor.: Conditional statements in Python and Java are very similar. In Python we
+ have three patterns: In Java this same pattern is simply written as: 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 if is technically a function that evaluates to True
+ or False. In Java this is written as: 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. In Java we have a couple of ways to write this 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. Java also supports a The The conditionals used in the if statement can be boolean variables,
+ simple comparisons, and compound boolean expressions. Java also supports the boolean expression.
+ You have already seen how to define classes in Java. It’s unavoidable for
+ even the simplest of programs. In this section we will look at how we
+ define classes to create our own data types. Lets start by creating a
+ fraction class to extend the set of numeric data types provided by our
+ language. The requirements for this new data type are as follows:
+ Given a numerator and a denominator create a new Fraction. When a fraction is printed it should be simplified. Two fractions can be added or subtracted Two fractions can be multiplied or divided Two fractions can be compared A fraction and an integer can be added together. Given a list of Fractions that list should be sortable by the default
+ sorting function.Histo.java:21: cannot find symbol
+symbol : variable count
+location: class Histo
+ count = new ArrayList<Integer>(10);
+ ^
+ Histo.java:9: cannot find symbol
+symbol : class Scanner
+location: class Histo
+ Scanner data = null;
+ ^
+ Histo.java:14: cannot find symbol
+symbol : method Scanner(java.io.File)
+location: class Histo
+ data = Scanner(new File("test.dat"));
+ ^
+ Histo.java:19:
+';' expected
+ System.exit(0);
+ ^
+ Note: Histo.java uses unchecked or unsafe operations. Note:
+Recompile with -Xlint:unchecked for details.
+ if condition:
+ statement1
+ statement2
+ ...
+ if (condition) {
+ statement1
+ statement2
+ ...
+}
+ if condition:
+ statement1
+ statement2
+ ...
+else:
+ statement1
+ statement2
+ ...
+ if (condition) {
+ statement1
+ statement2
+ ...
+} else {
+ statement1
+ statement2
+ ...
+}
+
+
+
Here is a mostly complete implementation of a Fraction class in Python + that we will refer to throughout this section:
+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
+
The declarations of instance variables can come at the beginning of the
+ class definition or the end. Cay Horstman, author of
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:
+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.
+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. 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.
+There are a couple of important things to notice here. First, you will
+ notice that the constructor does not have a
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,
A point of terminology: Python has both “functions” (
Let’s begin by implementing addition in Java:
+First you will notice that the
Second, you will notice that the method makes use of the
The addition takes place by multiplying each numerator by the opposite
+ denominator before adding. This procedure ensures that we are adding two
+ fractions with common denominators. Using this approach the denominator
+ is computed by multiplying the two denominators. The greatest common
+ divisor method,
Finally on line 6 a new
Our specification for this project said that we need to be able to add a
+
In Java we can do runtime type checking, but the compiler will not allow
+ us to pass an Integer to the
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 name and the types of + the parameters are enough information for the Java compiler to decide + which method to call at runtime.
+To solve the problem of adding an
Notice that the overloading approach can provide us with a certain + elegance to our code. Rather than utilizing if statements to check the + types of parameters we just overload methods ahead of time which + allows us to call the method we want and allow the compiler to make the + decisions for us. This way of thinking about programming takes some + practice.
+Our full
If you ran the program above you probably noticed that the output is not + very satisfying. Chances are your output looked something like this:
+The reason is that we have not yet provided a friendly string
+ representation for our
In Java, the equivalent of
+
+
+
+
+
+
+
+
+
+
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
The other important class for us to implement from the list of methods
+ inherited from
is NOT the same as
+Here is an
One important thing to remember about
If we want to make our
Here is code that makes the
The keyword
The methods we must implement if
+
+
+
+
+
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:
+By having the
However, and this is a big however, it is important to remember
+ that if you specify
Suppose you try to define a method as follows:
+The Java compiler would give an error because
Lets turn our attention to making a list of fractions sortable by the
+ standard Java sorting method
Java’s answer to this problem is the
The
To make our
The specification
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:
+In Java we would write this same example using a static declaration.
+In this example notice that we create a static member variable by using
+ the
We have already discussed the most common static method of all,
+
Here is a final version of the
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:
+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!" +>>>+
Now lets look at the same program written in 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. One thing that will help you is to learn a
+ little bit about Java
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
The command
Now that we have compiled our java source code we can run the compiled
+ code using the
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:
++
Early detection of errors
+Faster program execution
+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
When the compiler does the translation it can find many different kinds + of errors. For example, if you make a typo, the compiler will find the + typo and point it out to you before you ever run the program. We will + look at some examples of compiler errors shortly. Chances are you will + create some on your own very soon, too.
+Now that we have run our hello world program, lets go back and look at + it carefully to see what we can learn about the Java language. This + simple example illustrates a few very important rules:
++
Every Java program must define a class, and all code is inside a class
+Everything in Java must have a type
+Every Java program must have a function called
+
Lets take the hello world example a line at a time to see how these + rules are applied. On line 1 we see that we are declaring a class called + Hello:
+As rule 1 says all Java code resides inside a class. Unlike
+ Python where a program can simply be a bunch of statements in a file,
+ Java programs must be inside a class. So, we define a class
On the next line we start our method definition. The name of this method + is:
+Everything on this line is significant, and helps in the identification + of this method. For example the following lines look similar but are in + fact treated by Java as completely different methods:
++
+
+
+
+
Just digging in to this one line will take us deep into the world of + Java, so we are going to start digging but we are not going to dig too + deeply right away. Much of what could be revealed by this one line is + better understood through other examples, so be patient.
+The first word,
The next word,
The next word,
Next we have the proper name for the method:
Finally, we have the parameter list for the method. In this example we
+ have one parameter. The name of the parameter is
That is a lot of new material to digest in only a single line of Java! + Lets press on and look at the next line:
+This line should look a bit
+ more familiar to you. Python and Java both use the dot notation for
+ finding names. In this example we start with
Now there is one more character on this line that is significant and
+ that is the
The last two lines of the hello world program simply close the two
+ blocks using
If we wanted to translate the Java back to Python we would have + something like the following class definition.
+Notice that we used the decorator
This book assumes that you are already familiar with the
+
+++
+
+ +- +
+Data Types
+- +
+Loops
+- +
+Reading user input
+- +
+Conditionals
+
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.
++++
+
+ +- +
+Classes
+- +
+Interfaces
+- +
+Collections
+- +
+Graphical User Interface Programming
+- +
+Generic Programming
+
Please note that this book is a work in progress. I will continue to + update and post new versions.
+One of the great things about Python is that all of the basic data types + are objects. Integers are objects, floating point numbers are objects, + lists are objects, everything. In Java that is not the case. 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.
+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.
+Let’s look at 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.
+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.
+There are several new concepts introduced in this example. We will look + at them in the following order:
++
Import
+Variable Declaration
+Input/Output and the Scanner Class
+In Java, you can use any class that is available without having to import + the class, subject to two very important conditions:
++
The
You must use the full name of the class
+Your first question might be how do the
+
Java knows about all the classes that are defined in .java and .class + files in your current working directory.
+Java knows about all the classes that are shipped with Java.
+Java knows about all the classes that are included in your
+
+
A .jar file that contains Java classes
+Another directory that contains Java class files
+You can think of the import statement in Java as working a little bit
+ like the
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
+
Here is where we run into one of the most important differences between
+ Java and Python. Python is a
In the example above, lines 5—7 contain variable declarations.
+ Specifically we are saying that
For Python programmers, the following error is likely to be even more
+ common. Suppose we forgot the declaration for
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
+
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.
+In the previous section we created a
On line 11 we use the
The table below shows some commonly used methods of the
Strings in Java and Python are quite similar. Like Python, Java strings + are immutable. However, manipulating strings in Java is not quite as + obvious since Strings do not support an indexing or slicing operator. + That is not to say that you can’t index into a Java string, you can. You + can also pull out a substring just as you can with slicing. The + difference is that Java uses method calls where Python uses operators.
+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”
+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.
+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.
+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
+
+
+
The
+
+
The
+
+
The
Here is the Java code needed to write the exact same program:
+Before going any further, I suggest you try to compile the above program + and run it on some test data that you create.
+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
Technically, you don’t have to declare what is going to be in an array
+ list. The compiler will allow you to leave the
Note: Histo.java uses unchecked or unsafe operations. +Note: Recompile with -Xlint:unchecked for details.+
Without the
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
On line 22 we create our
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
+
+
+
+
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
Line 29 illustrates another important difference between Python and
+ Java. Notice that in Java we can not write
+
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
As I said at the outset of this section, we are going to use Java
+
The main difference between this example and the previous example is
+ that we declare
Just as Python provides the dictionary when we want to have easy access
+ to key-value pairs, Java also provides us a similar mechanism. Rather
+ than the dictionary terminology, Java calls these objects Maps. Java
+ provides two different implementations of a map, one is called the
+
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:
++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.
+Improve the program above to remove the punctuation.
+You have already seen a couple of examples of iteration and looping in + Java. So this section will just serve as a reference for the differences + in Syntax.
+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:
+for (Integer i = 0; i < 10; i++ ) {
+ System.out.println(i);
+}
+ Recall that the
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:
+for i in range(100,-1,-5): + print(i)+
In Java we would write this as:
+for (Integer i = 100; i >= 0; i -= 5) + System.out.println(i);+
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
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:
+ArrayList<Integer> l = new ArrayList<Integer>();
+l.add(1); l.add(1); l.add(2); l.add(3);
+for (Integer i : l) {
+ System.out.println(i)
+}
+ 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
int l[] = {1,1,2,3,5,8,13,21};
+for(int i : l) {
+ System.out.println(i);
+}
+ To iterate over the characters in a string in Java do the following:
+String t = "Hello World";
+for (char c : t.toCharArray()) {
+ System.out.println(c);
+}
+ Both Python and Java support the while loop. Recall that in Python the + while loop is written as:
+while condition: + statement1 + statement2 + ...+
In Java we add parenthesis and curly braces to get:
+while (condition) {
+ statement1
+ statement2
+ ...
+}
+ Java adds an additional, if seldom used variation of the while loop + called the do loop. The do 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:
+do {
+ statement1
+ statement2
+ ...
+} while (condition);
+ All Java class libraries are documented and available online. Here are + two good resources for you to use:
++
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.
+Java has some very handy naming conventions.
++
Class names always start with an upper case letter. For example,
+
Method names always start with a lower case letter, and use camelCase
+ to represent multiword method names. for example
Instance variables of a class start with a lower case letter and use + camelCase
+Constants are in all upper case letters. for example
Welcome to Java for Python Programmers. This short ebook is an ongoing + project to help Computer Science students who have had one or two + semesters of Python learn the Java programming language. If you are not + a part of that audience you may still find this a useful way to learn + about Java. This book is written using the build on what you know + philosophy. In order to help you learn Java I will start with a Python + example and then implement the example in Java. Along the way we will + examine the strengths, weaknesses and differences between those two + languages.
+This book does not attempt to replace the many good Java reference books
+ that are available, in fact I use this in my course along with
+
I have published this article using a Creative Commons license to + encourage you to use it, change it, and modify it for your own purposes. + I would appreciate knowing what you think if you do use this book, and I + would love to see any modifications or additions you make.
+Brad Miller
+++
+ This work is licensed under a Creative Commons Attribution 3.0 + United States License. See http://creativecommons.org
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
+
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.
+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
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!
+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:
Contents:
++
+
+
+
Here is the Java code needed to write the exact same program:
-Notice that the structure of the program is very similar to the numeric histogram program.
-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
@@ -61,7 +61,7 @@ $ ls -l Hello.*
code and saves it in a file called
Now that we have compiled our java source code we can run the compiled
code using the
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 @@ -269,7 +269,7 @@ location: class TempConv flagged as an error.
The table below shows some commonly used methods of the
Strings in Java and Python are quite similar. Like Python, Java strings
are immutable. However, manipulating strings in Java is not quite as
@@ -489,8 +489,8 @@ location: class TempConv
-
-
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.
@@ -739,8 +739,8 @@ catch (Exception e) {
the
As I said at the outset of this section, we are going to use Java
Just as Python provides the dictionary when we want to have easy access to key-value pairs, Java also provides us a similar mechanism. Rather @@ -892,5 +892,5 @@ public class HistoMap {
Improve the program above to remove the punctuation.
- - + + diff --git a/source/ch_5_conditionals.ptx b/source/ch_5_conditionals.ptx index 40aac8b..1a7fb8b 100644 --- a/source/ch_5_conditionals.ptx +++ b/source/ch_5_conditionals.ptx @@ -1,12 +1,12 @@ -Conditional statements in Python and Java are very similar. In Python we have three patterns:
if condition:
statement1
@@ -22,8 +22,8 @@
rather than indentation. In Java the parenthesis around the condition
are required because if is technically a function that evaluates to True
or False.
- if condition:
statement1
@@ -43,8 +43,8 @@ else:
statement2
...
}
-
- 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 @@ -126,8 +126,8 @@ public class ElseIf {
Java also supports a
The conditionals used in the if statement can be boolean variables, simple comparisons, and compound boolean expressions.
@@ -186,5 +186,5 @@ public class SwitchUp { ofYou have already seen a couple of examples of iteration and looping in Java. So this section will just serve as a reference for the differences in Syntax.
In Python the easiest way to write a definite loop is using the for loop in conjunction with the range function. For example:
@@ -63,8 +63,8 @@ for(int i : l) { for (char c : t.toCharArray()) { System.out.println(c); } -Both Python and Java support the while loop. Recall that in Python the while loop is written as:
@@ -89,5 +89,5 @@ for (char c : t.toCharArray()) { statement2 ... } while (condition); - -You have already seen how to define classes in Java. It’s unavoidable for @@ -162,7 +162,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 @@ -197,8 +197,8 @@ 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 @@ -244,7 +244,7 @@ public Fraction add(Fraction otherFrac) { match the value that is specified as part of the declaration. So, in this case the return value on line 8 must match the declared value on line 1.
-Our specification for this project said that we need to be able to add a
If you ran the program above you probably noticed that the output is not very satisfying. Chances are your output looked something like this:
@@ -368,7 +368,7 @@ Fraction@6ff3c5b5 be converted to string format. In Python you can control how that looks by writing anIn Java, the equivalent of
One important thing to remember about
If we want to make our
The Java compiler would give an error because
Lets turn our attention to making a list of fractions sortable by the
standard Java sorting method
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
@@ -695,8 +695,8 @@ public class Student {
the
We have already discussed the most common static method of all,
Here is a final version of the
Java has some very handy naming conventions.
@@ -22,4 +22,4 @@
-Histo.java:21: cannot find symbol
symbol : variable count
location: class Histo
count = new ArrayList<Integer>(10);
^
- Histo.java:9: cannot find symbol
symbol : class Scanner
location: class Histo
Scanner data = null;
^
-
- Here’s an example of the error message that occurs when you forget to
use the new keyword. Notice that the message is pretty unhelpful.
@@ -33,17 +33,17 @@ symbol : method Scanner(java.io.File)
location: class Histo
data = Scanner(new File("test.dat"));
^
-
-
Histo.java:19:
';' expected
System.exit(0);
^
-
- Note: Histo.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details.- -
All Java class libraries are documented and available online. Here are - two good resources for you to use:
--
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.
-+ All Java class libraries are documented and available online. + Here are two good resources for you to use: +
+ ++
+
+
+ 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/ch_1_introduction.ptx b/source/ch_1_introduction.ptx index d469619..0396762 100644 --- a/source/ch_1_introduction.ptx +++ b/source/ch_1_introduction.ptx @@ -1,55 +1,88 @@ +This book assumes that you are already familiar with the
-
+-Introduction +-
-
+ This book assumes that you are already familiar with the- -
-Data Types
-- -
-Loops
-- -
-Reading user input
-- -
-Conditionals
-Python programming language. + We will use Python as a starting point for our journey intoJava . + 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: -
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.
-+ +-+++
+
+ +- +
+ ++ Data Types +
+- +
+ ++ Loops +
+- +
+ ++ Reading user input +
+- +
++ Conditionals +
+-
-
+ 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. -- -
-Classes
-- -
-Interfaces
-- -
-Collections
-- -
-Graphical User Interface Programming
-- -
-Generic Programming
-
Please note that this book is a work in progress. I will continue to - update and post new versions.
-++ ++
+
+ +- +
+ ++ Classes +
+- +
+ ++ Interfaces +
+- +
+ ++ Collections +
+- +
+ ++ Graphical User Interface Programming +
+- +
++ Generic Programming +
+
+ Please note that this book is a work in progress. + I will continue to update and post new versions. +
+ \ No newline at end of file diff --git a/source/ch_2_whylearnjava.ptx b/source/ch_2_whylearnjava.ptx index 4afa583..491d41e 100644 --- a/source/ch_2_whylearnjava.ptx +++ b/source/ch_2_whylearnjava.ptx @@ -1,59 +1,91 @@ +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
-
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.
-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
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!
-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:
+ 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
+ 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. +
++ 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
+ 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! +
+
+ 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:
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:
-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!" ->>>-
Now lets look at the same program written in Java:
-
-public class Hello {
+ 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:
+
+
+ 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!" >>>
+
+ Now lets look at the same program written in Java:
+
+
+
+
+public class Hello {
public static void main(String[] args) {
System.out.println("Hello World!");
}
-
}
-
-
-
-
-
-
- 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 .
- 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:
-
-
+
+
+
+
+ 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 .
+
+
+
+ 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:
+
+
+
+
+
$ javac Hello.java
$ ls -l Hello.*
-rw-r--r-- 1 bmiller bmiller 391 Jul 19 17:47 Hello.class
-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 . Hello.class is a
- binary file so you won’t learn much if you try to examine the class file
- with an editor. Hopefully you didn’t make any mistakes, but if you did
- you may want to consult the
- section for helpful hints on compiler errors.
- Now that we have compiled our java source code we can run the compiled
- code using the java command.
-
-
+
+
+
+
+ The command javac compiles our java source code into compiled byte code and saves it in a file called Hello.class .
+ Hello.class is a binary file so you won’t learn much if you try to examine the class file with an editor.
+ Hopefully you didn’t make any mistakes, but if you did you may want to consult the section for helpful hints on compiler errors.
+
+
+
+ Now that we have compiled our java source code we can run the compiled code using the java command.
+
+
+
+
+
$ 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:
-
-
- -
-
Early detection of errors
-
- -
-
Faster program execution
-
-
-
- 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 . 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.
- When the compiler does the translation it can find many different kinds
- of errors. For example, if you make a typo, the compiler will find the
- typo and point it out to you before you ever run the program. We will
- look at some examples of compiler errors shortly. Chances are you will
- create some on your own very soon, too.
- Now that we have run our hello world program, lets go back and look at
- it carefully to see what we can learn about the Java language. This
- simple example illustrates a few very important rules:
-
-
- -
-
Every Java program must define a class, and all code is inside a class
-
- -
-
Everything in Java must have a type
-
- -
-
Every Java program must have a function called
- public static void main(String[] args)
-
-
-
- Lets take the hello world example a line at a time to see how these
- rules are applied. On line 1 we see that we are declaring a class called
- Hello:
-
-
+
+
+
+
+ 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:
+
+
+
+
+ -
+
+ Early detection of errors
+
+
+
+ -
+
+ Faster program execution
+
+
+
+
+
+
+ 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 .
+ 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.
+
+
+
+ When the compiler does the translation it can find many different kinds of errors.
+ For example, if you make a typo, the compiler will find the typo and point it out to you before you ever run the program.
+ We will look at some examples of compiler errors shortly.
+ Chances are you will create some on your own very soon, too.
+
+
+
+ Now that we have run our hello world program, lets go back and look at it carefully to see what we can learn about the Java language.
+ This simple example illustrates a few very important rules:
+
+
+
+
+ -
+
+ Every Java program must define a class, and all code is inside a class
+
+
+
+ -
+
+ Everything in Java must have a type
+
+
+
+ -
+
+ Every Java program must have a function called public static void main(String[] args)
+
+
+
+
+
+
+ Lets take the hello world example a line at a time to see how these rules are applied.
+ On line 1 we see that we are declaring a class called Hello:
+
+
+
+
+
public class Hello {
-
-
- As rule 1 says all Java code resides inside a class. Unlike
- Python where a program can simply be a bunch of statements in a file,
- Java programs must be inside a class. So, we define a class Hello ,
- which is not a very useful class because it has no instance variables, and only one
- method. You will also notice the curly brace { . In Java, blocks of
- code are identified by pairs of curly braces. The block starts with a
- { and ends with a } . You will notice that I indented my code
- that followed the left brace, but in Java this is only done by
- convention, it is not enforced.
- On the next line we start our method definition. The name of this method
- is:
-
-
+
+
+
+
+ As rule 1 says all Java code resides inside a class.
+ Unlike Python where a program can simply be a bunch of statements in a file, Java programs must be inside a class.
+ So, we define a class Hello , which is not a very useful class because it has no instance variables, and only one method.
+ You will also notice the curly brace { .
+ In Java, blocks of code are identified by pairs of curly braces.
+ The block starts with a { and ends with a } .
+ You will notice that I indented my code that followed the left brace, but in Java this is only done by convention, it is not enforced.
+
+
+
+ On the next line we start our method definition.
+ The name of this method is:
+
+
+
+
+
public static void main(String[] args)
-
-
- Everything on this line is significant, and helps in the identification
- of this method. For example the following lines look similar but are in
- fact treated by Java as completely different methods:
-
-
- -
-
- public void main(String[] args)
-
-
- -
-
- public static void main(String args)
-
-
- -
-
- public static void main()
-
-
- -
-
- void main(String args)
-
-
-
-
- Just digging in to this one line will take us deep into the world of
- Java, so we are going to start digging but we are not going to dig too
- deeply right away. Much of what could be revealed by this one line is
- better understood through other examples, so be patient.
- The first word, public indicates to the Java compiler that this is a
- method that anyone can call. We will see that Java enforces several
- levels of security on the methods we write, including public ,
- protected , and private methods.
- The next word, static tells Java that this is a method that is part
- of the class, but is not a method for any one instance of the class. The
- kind of methods we typically wrote in Python required an instance in
- order for the method to be called. With a static method, the object to
- the left of the . is a class, not an instance of the class. For example,
- the way that we would call the main method directly is:
- Hello.main(parameter1) . For now, you can think of static methods the
- same way you think of methods in Python modules that don’t require an
- instance, for example the math module contains many methods: sin, cos,
- etc. You probably evaluated these methods using the names
- math.cos(90) or math.sin(60) .
- The next word, void tells the Java compiler that the method main
- will not return a value. This is roughly analogous to omitting the
- return statement in a Python method. In other words, the method will run
- to completion and exit but will not return a value that you can use in
- an assignment statement. As we look at other examples we will see that
- every Java function must tell the compiler what kind of an object it
- will return. This is in keeping with the rule that says everything in
- Java must have a type. In this case we use the special type called
- void which means no type.
- Next we have the proper name for the method: main . The rules for
- names in Java are similar to the rules in Python. Names can include
- letters, numbers, and the _ . Names in Java must start with a letter.
- Finally, we have the parameter list for the method. In this example we
- have one parameter. The name of the parameter is args , however,
- because everything in Java must have a type, we also have to tell the
- compiler that the value of args is an array of strings. For the
- moment you can just think of an array as being the same thing as a list
- in Python. The practical benefit of declaring that the method main must
- accept one parameter and the parameter must be an array of strings is
- that if you call main somewhere else in your code and and pass it an
- array of integers or even a single string, the compiler will flag it as
- an error.
- That is a lot of new material to digest in only a single line of Java!
- Lets press on and look at the next line:
-
-
+
+
+
+
+ Everything on this line is significant, and helps in the identification of this method.
+ For example the following lines look similar but are in fact treated by Java as completely different methods:
+
+
+
+
+ -
+
+ public void main(String[] args)
+
+
+
+ -
+
+ public static void main(String args)
+
+
+
+ -
+
+ public static void main()
+
+
+
+ -
+
+ void main(String args)
+
+
+
+
+
+
+ Just digging in to this one line will take us deep into the world of Java, so we are going to start digging but we are not going to dig too deeply right away.
+ Much of what could be revealed by this one line is better understood through other examples, so be patient.
+
+
+
+ The first word, public indicates to the Java compiler that this is a method that anyone can call.
+ We will see that Java enforces several levels of security on the methods we write, including public , protected , and private methods.
+
+
+
+ The next word, static tells Java that this is a method that is part of the class, but is not a method for any one instance of the class.
+ The kind of methods we typically wrote in Python required an instance in order for the method to be called.
+ With a static method, the object to the left of the . is a class, not an instance of the class.
+ For example, the way that we would call the main method directly is: Hello.main(parameter1) .
+ For now, you can think of static methods the same way you think of methods in Python modules that don’t require an instance, for example the math module contains many methods: sin, cos, etc.
+ You probably evaluated these methods using the names math.cos(90) or math.sin(60) .
+
+
+
+ The next word, void tells the Java compiler that the method main will not return a value.
+ This is roughly analogous to omitting the return statement in a Python method.
+ In other words, the method will run to completion and exit but will not return a value that you can use in an assignment statement.
+ As we look at other examples we will see that every Java function must tell the compiler what kind of an object it will return.
+ This is in keeping with the rule that says everything in Java must have a type.
+ In this case we use the special type called void which means no type.
+
+
+
+ Next we have the proper name for the method: main .
+ The rules for names in Java are similar to the rules in Python.
+ Names can include letters, numbers, and the _ .
+ Names in Java must start with a letter.
+
+
+
+ Finally, we have the parameter list for the method.
+ In this example we have one parameter.
+ The name of the parameter is args , however, because everything in Java must have a type, we also have to tell the compiler that the value of args is an array of strings.
+ For the moment you can just think of an array as being the same thing as a list in Python.
+ The practical benefit of declaring that the method main must accept one parameter and the parameter must be an array of strings is that if you call main somewhere else in your code and and pass it an array of integers or even a single string, the compiler will flag it as an error.
+
+
+
+ That is a lot of new material to digest in only a single line of Java! Lets press on and look at the next line:
+
+
+
+
+
System.out.println("Hello World!");
-
-
- This line should look a bit
- more familiar to you. Python and Java both use the dot notation for
- finding names. In this example we start with System . System is a
- class. Within the system class we find the object named out . The
- out object is the standard output stream for this program. Having
- located the out object Java will now call the method named
- println(String s) on that object. The println method prints a
- string and adds a newline character at the end. Anywhere in Python that
- you used the print function you will use the System.out.println
- method in Java.
- Now there is one more character on this line that is significant and
- that is the ; at the end. In Java the ; signifies the end of a
- statement. 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. I would not encourage you to
- write your code like this, but you should know that it is legal.
-
-
+
+
+
+
+ This line should look a bit more familiar to you.
+ Python and Java both use the dot notation for finding names.
+ In this example we start with System .
+ System is a class.
+ Within the system class we find the object named out .
+ The out object is the standard output stream for this program.
+ Having located the out object Java will now call the method named println(String s) on that object.
+ The println method prints a string and adds a newline character at the end.
+ Anywhere in Python that you used the print function you will use the System.out.println method in Java.
+
+
+
+ Now there is one more character on this line that is significant and that is the ; at the end.
+ In Java the ; signifies the end of a statement.
+ 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.
+ 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")
;
@@ -245,31 +286,40 @@ System.
out.
println("Hello World")
;
-
-
- The last two lines of the hello world program simply close the two
- blocks using } . The first or outer block is the class definition. The second or
- inner block is the function definition.
- If we wanted to translate the Java back to Python we would have
- something like the following class definition.
-
-
+
+
+
+
+ The last two lines of the hello world program simply close the two blocks using } .
+ The first or outer block is the class definition.
+ The second or inner block is the function definition.
+
+
+
+ If we wanted to translate the Java back to Python we would have something like the following class definition.
+
+
+
+
+
class Hello(object):
@staticmethod
def main(args):
print("Hello World!")
-
-
- 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:
-
-
+
+
+
+
+ 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:
+
+
+
+
+
>>> Hello.main("")
Hello World!
>>>
-
-
-One of the great things about Python is that all of the basic data types - are objects. Integers are objects, floating point numbers are objects, - lists are objects, everything. In Java that is not the case. 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.
-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.
-Let’s look at 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.
-
+ Java Data Types
+
+
+
+
+
+ Numeric
+
+
+ One of the great things about Python is that all of the basic data types are objects.
+ Integers are objects, floating point numbers are objects, lists are objects, everything.
+ In Java that is not the case.
+ 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.
+
+
+
+
+
+ | Primitive |
+ Object |
+
+
+
+ | int |
+ Integer |
+
+
+
+ | float |
+ Float |
+
+
+
+ | double |
+ Double |
+
+
+
+ | char |
+ Char |
+
+
+
+ | boolean |
+ Boolean |
+
+
+
+
+
+ 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.
+
+
+
+ Let’s look at 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.
+
+
+
+
+
def main():
fahr = int(input("Enter the temperature in F: "))
cel = (fahr - 32) * 5.0/9.0
print("the temperature in C is: ", cel)
-
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, 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;
+
+
+import java.util.Scanner;
public class TempConv {
public static void main(String[] args) {
Double fahr;
Double cel;
Scanner in;
-
in = new Scanner(System.in);
System.out.println("Enter the temperature in F: ");
fahr = in.nextDouble();
-
cel = (fahr - 32) * 5.0/9.0;
System.out.println("The temperature in C is: " + cel);
}
}
-
-
-
-
-
-
-
- There are several new concepts introduced in this example. We will look
- at them in the following order:
-
-
- -
-
Import
-
- -
-
Variable Declaration
-
- -
-
Input/Output and the Scanner Class
-
-
-
-
- Import
- In Java, you can use any class that is available without having to import
- the class, subject to two very important conditions:
-
-
- -
-
The javac and java commands must know that the class exists.
-
- -
-
You must use the full name of the class
-
-
-
- Your first question might be how do the java and javac commands
- know that certain classes exist. The answer is the following:
-
-
- -
-
Java knows about all the classes that are defined in .java and .class
- files in your current working directory.
-
- -
-
Java knows about all the classes that are shipped with Java.
-
- -
-
Java knows about all the classes that are included in your
- CLASSPATH environment variable. Your CLASSPATH environment
- variable can name two kinds of structures.
-
-
+
+ There are several new concepts introduced in this example. We will look at them in the following order: +
+ ++
A .jar file that contains Java classes
++ Import +
Another directory that contains Java class files
++ Variable Declaration +
+ Input/Output and the Scanner Class +
++ In Java, you can use any class that is available without having to import the class, subject to two very important conditions:
- - - -You can think of the import statement in Java as working a little bit
- like the
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
-
Here is where we run into one of the most important differences between
- Java and Python. Python is a
In the example above, lines 5—7 contain variable declarations.
- Specifically we are saying that
For Python programmers, the following error is likely to be even more
- common. Suppose we forgot the declaration for
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
-
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.
-In the previous section we created a
On line 11 we use the
The table below shows some commonly used methods of the
Strings in Java and Python are quite similar. Like Python, Java strings - are immutable. However, manipulating strings in Java is not quite as - obvious since Strings do not support an indexing or slicing operator. - That is not to say that you can’t index into a Java string, you can. You - can also pull out a substring just as you can with slicing. The - difference is that Java uses method calls where Python uses operators.
-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”
-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.
-
+
+
+
+ -
+
+ The javac and java commands must know that the class exists.
+
+
+
+ -
+
+ You must use the full name of the class
+
+
+
+
+
+
+ Your first question might be how do the java and javac commands know that certain classes exist. The answer is the following:
+
+
+
+
+ -
+
+ Java knows about all the classes that are defined in .java and .class files in your current working directory.
+
+
+
+ -
+
+ Java knows about all the classes that are shipped with Java.
+
+
+
+ -
+
+ Java knows about all the classes that are included in your CLASSPATH environment variable. Your CLASSPATH environment variable can name two kinds of structures.
+
+
+
+
+ -
+
+ A .jar file that contains Java classes
+
+
+
+ -
+
+ Another directory that contains Java class files
+
+
+
+
+
+
+
+
+
+ You can think of the import statement in Java as working a little bit like the from module import xxx statement in Python. However, behind the scenes, the two statements actually do very different things. The first important difference to understand is that the class naming system in Java is very hierarchical. The full name of the Scanner class is really java.util.Scanner . You can think of this name as having two parts: The first part java.util is called the package and the last part is the class . We’ll talk more about the class naming system a bit later. The second important difference is that it is the Java class loader’s responsibility to load classes into memory, not the import statement’s.
+
+
+
+ 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.
+
+
+
+
+
+ Declaring Variables
+
+
+ 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.
+
+
+
+ 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.
+
+
+
+ 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
+
+ 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 .
+
+
+
+ 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.
+
+
+
+
+
+ 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 |
+
+
+
+ | boolean |
+ hasNextFloat() |
+ returns true if the next thing to read is a float |
+
+
+
+ | boolean |
+ hasNextDouble() |
+ returns true if the next thing to read is a double |
+
+
+
+ | Integer |
+ nextInt() |
+ returns the next thing to read as an integer |
+
+
+
+ | Float |
+ nextFloat() |
+ returns the next thing to read as a float |
+
+
+
+ | Double |
+ nextDouble() |
+ returns the next thing to read as a Double |
+
+
+
+ | String |
+ next() |
+ returns the next thing to read as a String |
+
+
+
+
+ + Strings in Java and Python are quite similar. Like Python, Java strings are immutable. However, manipulating strings in Java is not quite as obvious since Strings do not support an indexing or slicing operator. That is not to say that you can’t index into a Java string, you can. You can also pull out a substring just as you can with slicing. The difference is that Java uses method calls where Python uses operators. +
+ ++ 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” +
+ ++ 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
data = open('test.dat')
-
for line in data:
count[int(line)] = count[int(line)] + 1
-
idx = 0
for num in count:
print(idx, " occured ", num, " times.")
idx += 1
-
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.
-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
-
-
-
The
-
-
The
-
+
+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. +
+ +
+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
The
+
+
+The
+
+
+The
+
+
+The
Here is the Java code needed to write the exact same program:
-
+
+
+
+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;
-
public class Histo {
-
public static void main(String[] args) {
Scanner data = null;
ArrayList<Integer> count;
Integer idx;
-
try {
data = new Scanner(new File("test.dat"));
}
@@ -605,17 +490,14 @@ public class Histo {
e.printStackTrace();
System.exit(0);
}
-
count = new ArrayList<Integer>(10);
for (Integer i = 0; i < 10; i++) {
count.add(i,0);
}
-
while(data.hasNextInt()) {
idx = data.nextInt();
count.set(idx,count.get(idx)+1);
}
-
idx = 0;
for(Integer i : count) {
System.out.println(idx + " occured " + i + " times.");
@@ -623,144 +505,102 @@ 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.
- 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.
- 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)
- 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.
- 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.
- 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)
-
-
- -
-
- 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 ,]
-
-
-
- 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.
- 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.
- 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?
- As I said at the outset of this section, we are going to use Java
-
+ + Before going any further, I suggest you try to compile the above program and run it on some test data that you create. +
+ +
+ 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
+ Technically, you don’t have to declare what is going to be in an array list. The compiler will allow you to leave the
Note: Histo.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details.+
+ Without the
+ 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
+ On line 22 we create our
+ 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
+
+
+
+
+
+ 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
+ Line 29 illustrates another important difference between Python and Java. Notice that in Java we can not write
+ 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
+ As I said at the outset of this section, we are going to use Java
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
-
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 idx;
-
try {
data = new Scanner(new File("test.dat"));
}
@@ -769,12 +609,10 @@ public class HistoArray {
e.printStackTrace();
System.exit(0);
}
-
while(data.hasNextInt()) {
idx = data.nextInt();
count[idx] = count[idx] + 1;
}
-
idx = 0;
for(Integer i : count) {
System.out.println(idx + " occured " + i + " times.");
@@ -782,32 +620,28 @@ public class HistoArray {
}
}
}
-
- The main difference between this example and the previous example is
- that we declare
Just as Python provides the dictionary when we want to have easy access
- to key-value pairs, Java also provides us a similar mechanism. Rather
- than the dictionary terminology, Java calls these objects Maps. Java
- provides two different implementations of a map, one is called the
-
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:
-
+
+ The main difference between this example and the previous example is that we declare
+ Just as Python provides the dictionary when we want to have easy access to key-value pairs, Java also provides us a similar mechanism. Rather than the dictionary terminology, Java calls these objects Maps. Java provides two different implementations of a map, one is called the
+ 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')
wordList = data.read().split()
@@ -815,51 +649,33 @@ def main():
for w in wordList:
w = w.lower()
count[w] = count.get(w,0) + 1
-
keyList = sorted(count.keys())
for k in keyList:
print("%-20s occurred %4d times" % (k, count[k]))
-
main()
-
- -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.
-
+ 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. +
+ + +
import java.util.Scanner;
import java.util.ArrayList;
import java.io.File;
import java.io.IOException;
import java.util.TreeMap;
-
public class HistoMap {
-
public static void main(String[] args) {
Scanner data = null;
TreeMap<String,Integer> count;
Integer idx;
String word;
Integer wordCount;
-
try {
data = new Scanner(new File("alice30.txt"));
}
@@ -868,9 +684,7 @@ public class HistoMap {
e.printStackTrace();
System.exit(0);
}
-
count = new TreeMap<String,Integer>();
-
while(data.hasNext()) {
word = data.next().toLowerCase();
wordCount = count.get(word);
@@ -879,18 +693,16 @@ public class HistoMap {
}
count.put(word,++wordCount);
}
-
for(String i : count.keySet()) {
System.out.printf("%-20s occured %5d times\n", i, count.get(i) );
}
}
}
-
- Improve the program above to remove the punctuation.
-+ Improve the program above to remove the punctuation. +
+ + \ No newline at end of file diff --git a/source/ch_5_conditionals.ptx b/source/ch_5_conditionals.ptx index 1a7fb8b..a93bb04 100644 --- a/source/ch_5_conditionals.ptx +++ b/source/ch_5_conditionals.ptx @@ -1,56 +1,54 @@ +Conditional statements in Python and Java are very similar. In Python we - have three patterns:
-if condition: - statement1 - statement2 - ...-
In Java this same pattern is simply written as:
-if (condition) {
- statement1
- statement2
- ...
-}
- 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 if is technically a function that evaluates to True - or False.
-if condition: - statement1 - statement2 - ... -else: - statement1 - statement2 - ...-
In Java this is written as:
-if (condition) {
- statement1
- statement2
- ...
-} else {
- statement1
- statement2
- ...
-}
- 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.
-
+ Conditionals
+
+
+
+ Conditional statements in Python and Java are very similar.
+ In Python we have three patterns:
+
+
+
+
+ Simple if
+
+ if condition: statement1 statement2 ...
+
+ In Java this same pattern is simply written as:
+
+
+ if (condition) { statement1 statement2 ... }
+
+ 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 if is technically a function that evaluates to True or False.
+
+
+
+
+ if else
+
+ if condition: statement1 statement2 ... else: statement1 statement2 ...
+
+ In Java this is written as:
+
+
+ if (condition) { statement1 statement2 ... } else { statement1 statement2 ... }
+
+
+
+ elif
+
+
+ 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.
+
+
+
+
+
grade = int(input('enter a grade'))
if grade < 60:
print('F')
@@ -62,19 +60,19 @@ elif grade < 90:
print('B')
else:
print('A')
-
-
+ +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[]) {
int grade = 85;
-
if (grade < 60) {
System.out.println('F');
} else {
@@ -94,18 +92,16 @@ 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.
+
+
+
+
+
public class ElseIf {
public static void main(String args[]) {
int grade = 85;
@@ -120,24 +116,23 @@ public class ElseIf {
} else System.out.println('A');
}
}
-
-
-
-
-
-
- Java also supports a
+
+Java also supports a
public class SwitchUp {
public static void main(String args[]) {
int grade = 85;
-
int tempgrade = grade / 10;
switch(tempgrade) {
case 10:
@@ -158,33 +153,23 @@ public class SwitchUp {
}
}
}
-
- The
The conditionals used in the if statement can be boolean variables, - simple comparisons, and compound boolean expressions.
-Java also supports the boolean expression.
-
+The
+The conditionals used in the if statement can be boolean variables, simple comparisons, and compound boolean expressions. +
+ +
+Java also supports the boolean expression.
You have already seen a couple of examples of iteration and looping in - Java. So this section will just serve as a reference for the differences - in Syntax.
-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:
-for (Integer i = 0; i < 10; i++ ) {
- System.out.println(i);
-}
- Recall that the
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:
-for i in range(100,-1,-5): - print(i)-
In Java we would write this as:
-for (Integer i = 100; i >= 0; i -= 5) - System.out.println(i);-
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
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:
-ArrayList<Integer> l = new ArrayList<Integer>();
-l.add(1); l.add(1); l.add(2); l.add(3);
-for (Integer i : l) {
- System.out.println(i)
-}
- 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
int l[] = {1,1,2,3,5,8,13,21};
-for(int i : l) {
- System.out.println(i);
-}
- To iterate over the characters in a string in Java do the following:
-String t = "Hello World";
-for (char c : t.toCharArray()) {
- System.out.println(c);
-}
- Both Python and Java support the while loop. Recall that in Python the - while loop is written as:
-while condition: - statement1 - statement2 - ...-
In Java we add parenthesis and curly braces to get:
-while (condition) {
- statement1
- statement2
- ...
-}
- Java adds an additional, if seldom used variation of the while loop - called the do loop. The do 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:
-do {
- statement1
- statement2
- ...
-} while (condition);
- + You have already seen a couple of examples of iteration and looping in Java. + So this section will just serve as a reference for the differences in Syntax. +
++ 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: +
+ +for (Integer i = 0; i < 10; i++ ) { System.out.println(i); }
+
+ Recall that the
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: +
+ +for i in range(100,-1,-5): print(i)+
+ In Java we would write this as: +
+ +for (Integer i = 100; i >= 0; i -= 5) System.out.println(i);+
+ 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
+ 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: +
+ +ArrayList<Integer> l = new ArrayList<Integer>(); l.add(1); l.add(1); l.add(2); l.add(3); for (Integer i : l) { System.out.println(i) }
+
+ 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
int l[] = {1,1,2,3,5,8,13,21}; for(int i : l) { System.out.println(i); }
+ + To iterate over the characters in a string in Java do the following: +
+ +String t = "Hello World"; for (char c : t.toCharArray()) { System.out.println(c); }
+ + Both Python and Java support the while loop. + Recall that in Python the while loop is written as: +
+ +while condition: statement1 statement2 ...+
+ In Java we add parenthesis and curly braces to get: +
+ +while (condition) { statement1 statement2 ... }
+ + Java adds an additional, if seldom used variation of the while loop called the do loop. + The do 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: +
+ +do { statement1 statement2 ... } while (condition);
+ You have already seen how to define classes in Java. It’s unavoidable for - even the simplest of programs. In this section we will look at how we - define classes to create our own data types. Lets start by creating a - fraction class to extend the set of numeric data types provided by our - language. The requirements for this new data type are as follows:
--
Given a numerator and a denominator create a new Fraction.
-When a fraction is printed it should be simplified.
-Two fractions can be added or subtracted
-Two fractions can be multiplied or divided
-Two fractions can be compared
-A fraction and an integer can be added together.
-Given a list of Fractions that list should be sortable by the default - sorting function.
-Here is a mostly complete implementation of a Fraction class in Python - that we will refer to throughout this section:
-
+ Defining Classes in Java
+
+
+
+ You have already seen how to define classes in Java.
+ It’s unavoidable for even the simplest of programs.
+ In this section we will look at how we define classes to create our own data types.
+ Lets start by creating a fraction class to extend the set of numeric data types provided by our language.
+ The requirements for this new data type are as follows:
+
+
+
+
+ -
+
+ Given a numerator and a denominator create a new Fraction.
+
+
+
+ -
+
+ When a fraction is printed it should be simplified.
+
+
+
+ -
+
+ Two fractions can be added or subtracted
+
+
+
+ -
+
+ Two fractions can be multiplied or divided
+
+
+
+ -
+
+ Two fractions can be compared
+
+
+
+ -
+
+ A fraction and an integer can be added together.
+
+
+
+ -
+
+ Given a list of Fractions that list should be sortable by the default sorting function.
+
+
+
+
+
+
+ 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):
"""
@@ -46,7 +74,6 @@ class Fraction:
"""
self.num = num
self.den = den
-
def __repr__(self):
if self.num > self.den:
retWhole = int(self.num / self.den)
@@ -54,10 +81,8 @@ class Fraction:
return str(retWhole) + " " + str(retNum) + "/" + str(self.den)
else:
return str(self.num) + "/" + str(self.den)
-
def show(self):
print(self.num, "/", self.den)
-
def __add__(self, other):
# convert to a fraction
other = self.toFract(other)
@@ -65,14 +90,11 @@ class Fraction:
newden = self.den * other.den
common = gcd(newnum, newden)
return Fraction(int(newnum / common), int(newden / common))
-
__radd__ = __add__
-
def __lt__(self, other):
num1 = self.num * other.den
num2 = self.den * other.num
return num1 < num2
-
def toFract(self, n):
if isinstance(n, int):
other = Fraction(n, 1)
@@ -89,8 +111,6 @@ class Fraction:
print("Error: cannot add a fraction to a ", type(n))
return None
return other
-
-
def gcd(m, n):
"""
A helper function for Fraction
@@ -101,113 +121,130 @@ def gcd(m, n):
m = oldn
n = oldm % oldn
return n
-
print(sorted([Fraction(5, 16), Fraction(3, 16), Fraction(1, 16) + 1]))
-
-
-
-
-
-
- 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 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 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 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;
private Integer denominator;
}
-
-
- 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:
-
-
+
+
+
+
+ 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;
-
-
- 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.
-
-
+
+
+
+
+ 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.
+
+
+
+
+
public Integer getNumerator() {
return numerator;
}
-
public void setNumerator(Integer numerator) {
this.numerator = numerator;
}
-
public Integer getDenominator() {
return denominator;
}
-
public void setDenominator(Integer denominator) {
this.denominator = denominator;
}
-
-
-
-
- Writing a 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. 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.
-
-
+
+
+ + 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. + 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. +
+ + +
public Fraction(Integer top, Integer bottom) {
num = top;
den = bottom;
}
-
- There are a couple of important things to notice here. First, you will
- notice that the constructor does not have a
+
+
+ There are a couple of important things to notice here.
+ First, you will notice that the constructor does not have a
public Fraction(Integer num, Integer den) {
this.num = num;
this.den = 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,
A point of terminology: Python has both “functions” (
Let’s begin by implementing addition in Java:
-
+
+
+ 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,
+ A point of terminology: Python has both “functions” (
+ Let’s begin by implementing addition in Java: +
+ + +
public Fraction add(Fraction otherFrac) {
Integer newNum = otherFrac.getDenominator() * this.numerator +
this.denominator * otherFrac.getNumerator();
@@ -215,15 +252,23 @@ public Fraction add(Fraction otherFrac) {
Integer common = gcd(newNum, newDen);
return new Fraction(newNum/common, newDen/common);
}
-
- First you will notice that the
Second, you will notice that the method makes use of the
+
+
+ First you will notice that the
+ Second, you will notice that the method makes use of the
public Fraction add(Fraction otherFrac) {
Integer newNum = otherFrac.getDenominator() * numerator +
denominator * otherFrac.getNumerator();
@@ -231,103 +276,107 @@ public Fraction add(Fraction otherFrac) {
Integer common = gcd(newNum, newDen);
return new Fraction(newNum/common, newDen/common);
}
-
- The addition takes place by multiplying each numerator by the opposite
- denominator before adding. This procedure ensures that we are adding two
- fractions with common denominators. Using this approach the denominator
- is computed by multiplying the two denominators. The greatest common
- divisor method,
Finally on line 6 a new
Our specification for this project said that we need to be able to add a
-
In Java we can do runtime type checking, but the compiler will not allow
- us to pass an Integer to the
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 name and the types of - the parameters are enough information for the Java compiler to decide - which method to call at runtime.
-To solve the problem of adding an
+
+
+ The addition takes place by multiplying each numerator by the opposite denominator before adding.
+ This procedure ensures that we are adding two fractions with common denominators.
+ Using this approach the denominator is computed by multiplying the two denominators.
+ The greatest common divisor method,
+ Finally on line 6 a new
+ Our specification for this project said that we need to be able to add a
+ In Java we can do runtime type checking, but the compiler will not allow us to pass an Integer to the
+ 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 name and the types of the parameters are enough information for the Java compiler to decide which method to call at runtime. +
+ +
+ To solve the problem of adding an
public Fraction(Integer num) {
this.numerator = num;
this.denominator = 1;
}
-
public Fraction add(Integer other) {
return add(new Fraction(other));
}
-
- Notice that the overloading approach can provide us with a certain - elegance to our code. Rather than utilizing if statements to check the - types of parameters we just overload methods ahead of time which - allows us to call the method we want and allow the compiler to make the - decisions for us. This way of thinking about programming takes some - practice.
-Our full
-public class Fraction {
+
+ + Notice that the overloading approach can provide us with a certain elegance to our code. + Rather than utilizing if statements to check the types of parameters we just overload methods ahead of time which allows us to call the method we want and allow the compiler to make the decisions for us. + This way of thinking about programming takes some practice. +
+ +
+ Our full
+public class Fraction {
private Integer numerator;
private Integer denominator;
-
public Fraction(Integer num, Integer den) {
this.numerator = num;
this.denominator = den;
}
-
public Fraction(Integer num) {
this.numerator = num;
this.denominator = 1;
}
-
public Integer getNumerator() {
return numerator;
}
-
public Integer getDenominator() {
return denominator;
}
-
public Fraction add(Fraction other) {
Integer newNum = other.getDenominator()*this.numerator + this.denominator*other.getNumerator();
Integer newDen = this.denominator * other.getDenominator();
Integer common = gcd(newNum,newDen);
return new Fraction(newNum/common, newDen/common );
}
-
public Fraction add(Integer other) {
return add(new Fraction(other));
}
-
private static Integer gcd(Integer m, Integer n) {
while (m % n != 0) {
Integer oldm = m;
@@ -337,125 +386,154 @@ public class Fraction {
}
return n;
}
-
public static void main(String[] args) {
Fraction f1 = new Fraction(1,2);
-
System.out.println(f1.add(1));
}
-
}
-
- 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 this: +
+ + +
Fraction@6ff3c5b5
-
- The reason is that we have not yet provided a friendly string
- representation for our
In Java, the equivalent of
-
-
-
-
+ The reason is that we have not yet provided a friendly string representation for our
-
-
+
+
+
+
+
+
+
+
+
-
+public String toString() {
+ return numerator.toString() + "/" + denominator.toString();
+}
+
+
-
+object1 == object2
+
+
-
+object1.equals(object2)
+
+
-
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
-public String toString() {
- return numerator.toString() + "/" + denominator.toString();
-}
-
- The other important class for us to implement from the list of methods
- inherited from
-object1 == object2
-
- is NOT the same as
-
-object1.equals(object2)
-
- Here is an
+
+
+
+
public boolean equals(Fraction other) {
Integer num1 = this.numerator * other.getDenominator();
Integer num2 = this.denominator * other.getNumerator();
@@ -464,220 +542,250 @@ public boolean equals(Fraction other) {
else
return false;
}
-
-
- 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. We’ll see more about that shortly.
- If we want to make our
Here is code that makes the
+
+
+ One important thing to remember about
+ If we want to make our
+ Here is code that makes the
public class Fraction extends Number {
...
}
-
- The keyword
The methods we must implement if
-
-
-
-
+
+
+
+
-
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();
}
-
-
public float floatValue() {
return numerator.floatValue() / denominator.floatValue();
}
-
-
public int intValue() {
return numerator.intValue() / denominator.intValue();
}
-
-
public long longValue() {
return numerator.longValue() / denominator.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. 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 .
- 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 .
- Suppose you try to define a method as follows:
-
-
+
+
+
+
+ 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.
+ 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 .
+
+
+
+ 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 .
+
+
+
+ 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. 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 ).
- Lets turn our attention to making a list of fractions sortable by the
- standard Java sorting method
Java’s answer to this problem is the
The
-int compareTo(T o)
+
+
+ The Java compiler would give an error because
+ Lets turn our attention to making a list of fractions sortable by the standard Java sorting method
+ Java’s answer to this problem is the
+ The
+int compareTo(T o)
Compares this object with the specified object for order. Returns a
negative integer, zero, or a positive integer as this object is less
than, equal to, or greater than the specified object. The
implementor must ensure sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for
all x and y. (This implies that x.compareTo(y) must throw an exception
iff y.compareTo(x) throws an exception.)
-
...
-
- To make our
+
+
+ To make our
public class Fraction extends Number implements Comparable<Fraction> {
...
}
-
- The specification
+
+
+ The specification
public int compareTo(Fraction other) {
Integer num1 = this.numerator * other.getDenominator();
Integer num2 = this.denominator * other.getNumerator();
return num1 - num2;
}
-
- 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:
-
+
+ + 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: +
+ + +
class Student:
numStudents = 0
-
def __init__(self, id, name):
self.id = id
self.name = name
-
Student.numStudents = Student.numStudents + 1
-
def main():
for i in range(10):
s = Student(i,"Student-"+str(i))
print('Number of students:', Student.numStudents)
-
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;
-
private int id;
private String name;
-
public Student(Integer id, String name) {
this.id = id;
this.name = name;
-
numStudents = numStudents + 1;
}
-
public static void main(String[] args) {
for(Integer i = 0; i < 10; i++) {
Student s = new Student(i,"Student"+i.toString());
@@ -685,28 +793,24 @@ public class Student {
System.out.println("Number of students: "+Student.numStudents.toString());
}
}
-
-
-
-
-
-
- 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.
- We have already discussed the most common static method of all,
-
+
+ In this example notice that we create a static member variable by using the
+ We have already discussed the most common static method of all,
private static Integer gcd(Integer m, Integer n) {
while (m % n != 0) {
Integer oldm = m;
@@ -716,64 +820,58 @@ private static Integer gcd(Integer m, Integer n) {
}
return n;
}
-
- Here is a final version of the
+
+
+ Here is a final version of the
import java.util.ArrayList;
import java.util.Collections;
-
public class Fraction extends Number implements Comparable<Fraction> {
-
private Integer numerator;
private Integer denominator;
-
/** Creates a new instance of Fraction */
public Fraction(Integer num, Integer den) {
this.numerator = num;
this.denominator = den;
}
-
public Fraction(Integer num) {
this.numerator = num;
this.denominator = 1;
}
-
public Fraction add(Fraction other) {
Integer newNum = other.getDenominator()*this.numerator + this.denominator*other.getNumerator();
Integer newDen = this.denominator * other.getDenominator();
Integer common = gcd(newNum,newDen);
return new Fraction(newNum/common, newDen/common);
}
-
public Fraction add(Integer other) {
return add(new Fraction(other));
}
-
public Integer getNumerator() {
return numerator;
}
-
public void setNumerator(Integer numerator) {
this.numerator = numerator;
}
-
public Integer getDenominator() {
return denominator;
}
-
public void setDenominator(Integer denominator) {
this.denominator = denominator;
}
-
public String toString() {
return numerator.toString() + "/" + denominator.toString();
}
-
public boolean equals(Fraction other) {
Integer num1 = this.numerator * other.getDenominator();
Integer num2 = this.denominator * other.getNumerator();
@@ -782,29 +880,23 @@ public class Fraction extends Number implements Comparable<Fraction> {
else
return false;
}
-
public double doubleValue() {
return numerator.doubleValue() / denominator.doubleValue();
}
-
public float floatValue() {
return numerator.floatValue() / denominator.floatValue();
}
-
public int intValue() {
return numerator.intValue() / denominator.intValue();
}
-
public long longValue() {
return numerator.longValue() / denominator.longValue();
}
-
public int compareTo(Fraction other) {
Integer num1 = this.numerator * other.getDenominator();
Integer num2 = this.denominator * other.getNumerator();
return num1 - num2;
}
-
private static Integer gcd(Integer m, Integer n) {
while (m % n != 0) {
Integer oldm = m;
@@ -814,34 +906,25 @@ public class Fraction extends Number implements Comparable<Fraction> {
}
return n;
}
-
public static void main(String[] args) {
Fraction f1 = new Fraction(1,2);
Fraction f2 = new Fraction(2,3);
Fraction f3 = new Fraction(1,4);
-
System.out.println("Adding: " + f1.add(1));
System.out.println("Calling intValue(): " + f1.intValue());
System.out.println("Calling doubleValue(): " + f1.doubleValue());
-
ArrayList<Fraction> myFracs = new ArrayList<Fraction>();
myFracs.add(f1);
myFracs.add(f2);
myFracs.add(f3);
Collections.sort(myFracs);
-
System.out.println("Sorted fractions:");
for(Fraction f : myFracs) {
System.out.println(f);
}
}
-
}
-
- Java has some very handy naming conventions.
--
Class names always start with an upper case letter. For example,
-
Method names always start with a lower case letter, and use camelCase
- to represent multiword method names. for example
Instance variables of a class start with a lower case letter and use - camelCase
-Constants are in all upper case letters. for example
+ Java has some very handy naming conventions. +
+ ++
+ Class names always start with an upper case letter.
+ For example,
+ Method names always start with a lower case letter, and use camelCase to represent multiword method names.
+ for example
+ Instance variables of a class start with a lower case letter and use camelCase +
+
+ Constants are in all upper case letters.
+ for example
Histo.java:21: cannot find symbol -symbol : variable count -location: class Histo - count = new ArrayList<Integer>(10); - ^-
Histo.java:9: cannot find symbol -symbol : class Scanner -location: class Histo - Scanner data = null; - ^-
Here’s an example of the error message that occurs when you forget to - use the new keyword. Notice that the message is pretty unhelpful. - Java thinks you are trying to call the Method Scanner, but - there are two problems. First Scanner is not really a method it - is a constructor.:
-Histo.java:14: cannot find symbol
-symbol : method Scanner(java.io.File)
-location: class Histo
- data = Scanner(new File("test.dat"));
- ^
- Histo.java:19: -';' expected - System.exit(0); - ^-
Note: Histo.java uses unchecked or unsafe operations. Note: -Recompile with -Xlint:unchecked for details.-
Histo.java:21: cannot find symbol symbol : variable count location: class Histo count = new ArrayList<Integer>(10); ^+
Histo.java:9: cannot find symbol symbol : class Scanner location: class Histo Scanner data = null; ^+
+ Here’s an example of the error message that occurs when you forget to use the new keyword. + Notice that the message is pretty unhelpful. + Java thinks you are trying to call the Method Scanner, but there are two problems. + First Scanner is not really a method it is a constructor.: +
+ +Histo.java:14: cannot find symbol symbol : method Scanner(java.io.File) location: class Histo data = Scanner(new File("test.dat")); ^
+ Histo.java:19: ';' expected System.exit(0); ^+
Note: Histo.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details.+
I started writing this article in 2006 using Python’s restructured text.
- In 2007 I switched to markdown since everything else I was writing used
- markdown. In particular I switched to the variant of markdown used by
- the excellent
+ I started writing this article in 2006 using Python’s restructured text.
+ In 2007 I switched to markdown since everything else I was writing used markdown.
+ In particular I switched to the variant of markdown used by the excellent
If you got this far, I would also like to use this space as a shameless
- plug for two books. At Luther college we use Python for CS1 and CS2.
- When we decided to make the switch to introducing CS with Python we
- wanted to provide our students with two semesters of Python. The reason
- is that after one semester students are just getting comfortable with
- the language and it does not make sense to push them into a brand new
- language just as they are getting some comfort. The second reason is
- that Python really is a great language for teaching data structures. The
- language makes the algorithms evident by clearing away all of the
- syntactic clutter. So we (David Ranum and I) wrote a CS2 book called
-
+ If you got this far, I would also like to use this space as a shameless plug for two books.
+ At Luther college we use Python for CS1 and CS2.
+ When we decided to make the switch to introducing CS with Python we wanted to provide our students with two semesters of Python.
+ The reason is that after one semester students are just getting comfortable with the language and it does not make sense to push them into a brand new language just as they are getting some comfort.
+ The second reason is that Python really is a great language for teaching data structures.
+ The language makes the algorithms evident by clearing away all of the syntactic clutter.
+ So we (David Ranum and I) wrote a CS2 book called
+ Welcome to Java for Python Programmers. + This short ebook is an ongoing project to help Computer Science students who have had one or two semesters of Python learn the Java programming language. + If you are not a part of that audience you may still find this a useful way to learn about Java. + This book is written using the build on what you know philosophy. + In order to help you learn Java I will start with a Python example and then implement the example in Java. + Along the way we will examine the strengths, weaknesses and differences between those two languages. +
+
+ This book does not attempt to replace the many good Java reference books that are available, in fact I use this in my course along with
Welcome to Java for Python Programmers. This short ebook is an ongoing - project to help Computer Science students who have had one or two - semesters of Python learn the Java programming language. If you are not - a part of that audience you may still find this a useful way to learn - about Java. This book is written using the build on what you know - philosophy. In order to help you learn Java I will start with a Python - example and then implement the example in Java. Along the way we will - examine the strengths, weaknesses and differences between those two - languages.
-This book does not attempt to replace the many good Java reference books
- that are available, in fact I use this in my course along with
-
I have published this article using a Creative Commons license to - encourage you to use it, change it, and modify it for your own purposes. - I would appreciate knowing what you think if you do use this book, and I - would love to see any modifications or additions you make.
-Brad Miller
---
- This work is licensed under a Creative Commons Attribution 3.0 - United States License. See http://creativecommons.org
+ I have published this article using a Creative Commons license to encourage you to use it, change it, and modify it for your own purposes. + I would appreciate knowing what you think if you do use this book, and I would love to see any modifications or additions you make. +
-
+ Brad Miller
++ + \ No newline at end of file From 3491daab4b57c5b89c1a6abfaec87544666260fb Mon Sep 17 00:00:00 2001 From: moisedk+
+This work is licensed under a Creative Commons Attribution 3.0 United States License. See http://creativecommons.org +
- One of the great things about Python is that all of the basic data types are objects. - Integers are objects, floating point numbers are objects, lists are objects, everything. - In Java that is not the case. - 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. -
++ One of the great things about Python is that all of the basic data types are objects. + Integers are objects, floating point numbers are objects, lists are objects, everything. + In Java that is not the case. + 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. +
-- 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. -
++ 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. +
-- Let’s look at 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. -
++ Let’s look at 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. +
-
+
+
def main():
fahr = int(input("Enter the temperature in F: "))
cel = (fahr - 32) * 5.0/9.0
print("the temperature in C is: ", cel)
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 {
public static void main(String[] args) {
@@ -95,34 +96,35 @@ public class TempConv {
System.out.println("The temperature in C is: " + cel);
}
}
-
-
+ +
There are several new concepts introduced in this example. We will look at them in the following order: -
+ --
+
+
Import -
-+
Variable Declaration -
-+
Input/Output and the Scanner Class -
-
- 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,
+ 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,
- A point of terminology: Python has both “functions” (
+ A point of terminology: Python has both “functions” (
- Let’s begin by implementing addition in Java: -
++ Let’s begin by implementing addition in Java: +
-
+
+
public Fraction add(Fraction otherFrac) {
Integer newNum = otherFrac.getDenominator() * this.numerator +
this.denominator * otherFrac.getNumerator();
@@ -252,23 +253,23 @@ public Fraction add(Fraction otherFrac) {
Integer common = gcd(newNum, newDen);
return new Fraction(newNum/common, newDen/common);
}
-
-
+
+
- First you will notice that the
+ First you will notice that the
- Second, you will notice that the method makes use of the
+ Second, you will notice that the method makes use of the
+
+
public Fraction add(Fraction otherFrac) {
Integer newNum = otherFrac.getDenominator() * numerator +
denominator * otherFrac.getNumerator();
@@ -276,21 +277,22 @@ public Fraction add(Fraction otherFrac) {
Integer common = gcd(newNum, newDen);
return new Fraction(newNum/common, newDen/common);
}
-
-
+
+
- The addition takes place by multiplying each numerator by the opposite denominator before adding.
- This procedure ensures that we are adding two fractions with common denominators.
- Using this approach the denominator is computed by multiplying the two denominators.
- The greatest common divisor method,
+ The addition takes place by multiplying each numerator by the opposite denominator before adding.
+ This procedure ensures that we are adding two fractions with common denominators.
+ Using this approach the denominator is computed by multiplying the two denominators.
+ The greatest common divisor method,
- Finally on line 6 a new
+ Finally on line 6 a new
+
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
+ The reason is that we have not yet provided a friendly string representation for our
Histo.java:21: cannot find symbol symbol : variable count location: class Histo count = new ArrayList<Integer>(10); ^+
+ Histo.java:21: cannot find symbol + symbol : variable count + location: class Histo + count = new ArrayList<Integer>(10); + ^ ++
Histo.java:9: cannot find symbol symbol : class Scanner location: class Histo Scanner data = null; ^+
+ Histo.java:9: cannot find symbol + symbol : class Scanner + location: class Histo + Scanner data = null; + ^ ++
Histo.java:14: cannot find symbol symbol : method Scanner(java.io.File) location: class Histo data = Scanner(new File("test.dat")); ^
+
+ Histo.java:14: cannot find symbol
+ symbol : method Scanner(java.io.File)
+ location: class Histo
+ data = Scanner(new File("test.dat"));
+ ^
+
+
Histo.java:19: ';' expected System.exit(0); ^+
+ Histo.java:19: + ';' expected + System.exit(0); + ^ ++
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. ++
This book assumes that you are already familiar with the
+ The tool that we use to compile a Java source file into a Java class file
+ is called a
+ You can learn Java by just using the interactive coding panels called
+
+ 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. +
++ 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 (
+ PickCode (
+ Replit (
+ JuiceMind (
+ Github provides many free opportunities for students and teachers (
+ Students will need to sign up for a free Github account (
+ VSCode (
+ DrJava (from
+ BlueJ (
+ jGRASP (
+ IntelliJ (
+ Netbeans (
+ Eclipse (
- I started writing this article in 2006 using Python’s restructured text.
- In 2007 I switched to markdown since everything else I was writing used markdown.
- In particular I switched to the variant of markdown used by the excellent
+ I started writing this article in 2006 using Python’s restructured text.
+ In 2007 I switched to markdown since everything else I was writing used markdown.
+ In particular I switched to the variant of markdown used by the excellent
+
From 2194fc52be978af5986b66afdb05181359c53726 Mon Sep 17 00:00:00 2001
From: Austing767
+ This chapter will cover File IO.
+
+ This error occurs because the variable count is being used without being declared first. We know that the variable count is causing the issue because the error message has an arrow pointing at it. Java doesn't recognize count as a known variable in the class Histo, so it throws a "cannot find symbol" error. To fix this, you need to declare count with a proper type before assigning a value to it.
+
- This error occurs because the variable count is being used without being declared first. We know that the variable count is causing the issue because the error message has an arrow pointing at it. Java doesn't recognize count as a known variable in the class Histo, so it throws a "cannot find symbol" error. To fix this, you need to declare count with a proper type before assigning a value to it.
+ The 'cannot find symbol' error for the variable
+ You may Notice that this error message looks similar to the previous one, however it has an entirely diferent cause. In Java, classes like Scanner that are part of external packages (like
- You may Notice that this error message looks similar to the previous one, however it has an entirely diferent cause. In Java, classes like Scanner that are part of external packages (like
- Here’s an example of the error message that occurs when you forget to use the new keyword.
- Notice that the message is pretty unhelpful.
- Java thinks you are trying to call the Method Scanner, but there are two problems.
- First Scanner is not really a method it is a constructor.:
+ This error message occurs when you forget to use the
- Histo.java:21: cannot find symbol
- symbol : variable count
- location: class Histo
+ Main.java:7: error: cannot find symbol
count = new ArrayList<Integer>(10);
^
+ symbol: variable count
+ location: class Main
Histo.java:9: cannot find symbol
symbol : class Scanner
From 28b7637614ebe9e84bb0755d19b6bcb02874836b Mon Sep 17 00:00:00 2001
From: colin flaherty
Main.java:7: error: cannot find symbol
From aef76c949c5da205257daaf774f71a68ab7244ad Mon Sep 17 00:00:00 2001
From: colin flaherty
- Histo.java:9: cannot find symbol
- symbol : class Scanner
- location: class Histo
+ Histo.java:3: error: cannot find symbol
Scanner data = null;
^
+ symbol: class Scanner
+ location: class Histo
From ee7c7f9dfe9913bf853b5d2ac4bdd036b4e00608 Mon Sep 17 00:00:00 2001
From: colin flaherty
- Histo.java:14: cannot find symbol
- symbol : method Scanner(java.io.File)
- location: class Histo
+ Histo.java:8: error: cannot find symbol
data = Scanner(new File("test.dat"));
- ^
+ ^
+ symbol: method Scanner(File)
+ location: class Histo
+ 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". +
+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 -
-
- Here is where we run into one of the most important differences between Java and Python. Python is a
+ 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
+ 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
- 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.
-
- In the previous section we created a
- On line 11 we use the
- The table below shows some commonly used methods of the
+ In this example, we first create a
Python is a nice language for beginning programming for several reasons. @@ -40,6 +43,7 @@ If you know what is common in languages that is a good place to start.
+
+
+ The error "';' expected" on line 7 of
- Histo.java:19:
- ';' expected
- System.exit(0);
- ^
+ Histo.java:7: error: ';' expected
+ Scanner data = null
+ ^
- 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. +
+
+ Before any code can be written to handle files, the proper classes must be imported. Java includes a class called
+import java.io.File;
+
+ This class provides a lot of functionality for file hanling, however, the
+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;
+
+ This is a compiler warning, not an error, indicating a potential type safety issue. It occurs because you are calling the
+ When
- Note: Histo.java uses unchecked or unsafe operations. Note:
- Recompile with -Xlint:unchecked for details.
+ UncheckedWarningDemo.java:8: warning: [unchecked] unchecked call to add(E) as a member of the raw type ArrayList
+ rawList.add("Hello");
+ ^
+ where E is a type-variable:
+ E extends Object declared in class ArrayList
+
++ The following is intended to be useful in better understanding Java functions coming from a Python background. +
++
+ Short-Circuiting: The logical operators
+ 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,
+ 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
+ F-Strings (Formatted String Literals) simplify embedding expressions and variables directly inside strings. This makes code like
+ Tuple and List Unpacking allows for assigning elements of a sequence to multiple variables in a single line, such as
+ Chained Comparisons make range checks more intuitive and mathematical. You can write
- This book assumes that you are already familiar with the
--
-
+ +- -
+ This book assumes that you are already familiar with the- Data Types -
-Python programming language. + We will use Python as a starting point for our journey intoJava . + 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: + -- -
+- Loops -
-+++
+
- -- +
-+ Data Types +
+- -
+- Reading user input -
-- +
-+ Loops +
+- -
-- Conditionals -
-- +
-+ Reading user input +
+- 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. -
+- +
++ Conditionals +
+
+ +-
-
+ +- -
+ 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. + -- Classes -
-- -
+- Interfaces -
-+++
+
- -- +
-+ Classes +
+- -
+- Collections -
-- +
-+ Interfaces +
+- -
+- Graphical User Interface Programming -
-- +
-+ Collections +
+- -
-- Generic Programming -
-- +
-+ Graphical User Interface Programming +
+- Please note that this book is a work in progress. - I will continue to update and post new versions. -
+- +
++ Generic Programming +
+
+ Please note that this book is a work in progress. + I will continue to update and post new versions. +
+- 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
+ 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. +
-- 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. -
+
+ These languages have some advantages of their own.
+ First, is speed: Java and C++ code will generally give better performance than Python code
- 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. -
-+ 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. +
+ +One of the great things about Python is that all of the basic data types are objects. Integers are objects, floating point numbers are objects, lists are objects, everything. @@ -124,7 +120,6 @@ public class TempConv {
-Conditional statements in Python and Java are very similar. In Python we have three patterns:
-if condition: statement1 statement2 ...diff --git a/source/ch_6_loopsanditeration.ptx b/source/ch_6_loopsanditeration.ptx index 628eb8e..36f8b56 100644 --- a/source/ch_6_loopsanditeration.ptx +++ b/source/ch_6_loopsanditeration.ptx @@ -4,15 +4,13 @@
You have already seen a couple of examples of iteration and looping in Java. - So this section will just serve as a reference for the differences in Syntax. + So this section will just serve as a reference for the differences in syntax.
-
In Python the easiest way to write a definite loop is using the for loop in conjunction with the range function.
diff --git a/source/ch_7_definingclasses.ptx b/source/ch_7_definingclasses.ptx
index c2bf1ff..85cbc0c 100644
--- a/source/ch_7_definingclasses.ptx
+++ b/source/ch_7_definingclasses.ptx
@@ -3,183 +3,185 @@
+ You have already seen how to define classes in Java.
+ It’s unavoidable for even the simplest of programs.
+ In this section we will look at how we define classes to create our own data types.
+ Lets start by creating a fraction class to extend the set of numeric data types provided by our language.
+ The requirements for this new data type are as follows:
+
+
+ Given a numerator and a denominator create a new Fraction.
+
+ When a fraction is printed it should be simplified.
+
+ Two fractions can be added or subtracted
+
+ Two fractions can be multiplied or divided
+
+ Two fractions can be compared
+
+ A fraction and an integer can be added together.
+
+ Given a list of Fractions that list should be sortable by the default sorting function.
+
+
+
+ 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):
+ """
+ :param num: The top of the fraction
+ :param den: The bottom of the fraction
+ """
+ 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)
+ return str(retWhole) + " " + str(retNum) + "/" + str(self.den)
+ else:
+ return str(self.num) + "/" + str(self.den)
+ def show(self):
+ print(self.num, "/", self.den)
+ def __add__(self, other):
+ # convert to a fraction
+ other = self.toFract(other)
+ newnum = self.num * other.den + self.den * other.num
+ newden = self.den * other.den
+ common = gcd(newnum, newden)
+ return Fraction(int(newnum / common), int(newden / common))
+ __radd__ = __add__
+ def __lt__(self, other):
+ num1 = self.num * other.den
+ num2 = self.den * other.num
+ return num1 < num2
+ def toFract(self, n):
+ 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)
+ elif isinstance(n, Fraction):
+ other = n
+ else:
+ print("Error: cannot add a fraction to a ", type(n))
+ return None
+ return other
+ def gcd(m, n):
+ """
+ A helper function for Fraction
+ """
+ while m % n != 0:
+ oldm = m
+ oldn = n
+ m = oldn
+ n = oldm % oldn
+ return n
+ print(sorted([Fraction(5, 16), Fraction(3, 16), Fraction(1, 16) + 1]))
+
+ 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
+ The declarations of instance variables can come at the beginning of the class definition or the end. Cay Horstman, author of
+ public class Fraction {
+ private Integer numerator;
+ private Integer denominator;
+ }
+
+ - You have already seen how to define classes in Java. - It’s unavoidable for even the simplest of programs. - In this section we will look at how we define classes to create our own data types. - Lets start by creating a fraction class to extend the set of numeric data types provided by our language. - The requirements for this new data type are as follows: -
- --
- Given a numerator and a denominator create a new Fraction. -
-- When a fraction is printed it should be simplified. -
-- Two fractions can be added or subtracted -
-- Two fractions can be multiplied or divided -
-- Two fractions can be compared -
-- A fraction and an integer can be added together. -
-- Given a list of Fractions that list should be sortable by the default sorting function. -
-- 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):
- """
- :param num: The top of the fraction
- :param den: The bottom of the fraction
- """
- 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)
- return str(retWhole) + " " + str(retNum) + "/" + str(self.den)
- else:
- return str(self.num) + "/" + str(self.den)
- def show(self):
- print(self.num, "/", self.den)
- def __add__(self, other):
- # convert to a fraction
- other = self.toFract(other)
- newnum = self.num * other.den + self.den * other.num
- newden = self.den * other.den
- common = gcd(newnum, newden)
- return Fraction(int(newnum / common), int(newden / common))
- __radd__ = __add__
- def __lt__(self, other):
- num1 = self.num * other.den
- num2 = self.den * other.num
- return num1 < num2
- def toFract(self, n):
- 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)
- elif isinstance(n, Fraction):
- other = n
- else:
- print("Error: cannot add a fraction to a ", type(n))
- return None
- return other
-def gcd(m, n):
- """
- A helper function for Fraction
- """
- while m % n != 0:
- oldm = m
- oldn = n
- m = oldn
- n = oldm % oldn
- return n
-print(sorted([Fraction(5, 16), Fraction(3, 16), Fraction(1, 16) + 1]))
-
- 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
- The declarations of instance variables can come at the beginning of the class definition or the end. Cay Horstman, author of
-public class Fraction {
- private Integer numerator;
- private Integer denominator;
-}
-
- - 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: -
++ 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;
-
-
+ Fraction f = new Fraction(1,2);
+ Integer y = f.numerator * 10;
+
+ - 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. -
++ 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. +
-
-public Integer getNumerator() {
- return numerator;
-}
-public void setNumerator(Integer numerator) {
- this.numerator = numerator;
-}
-public Integer getDenominator() {
- return denominator;
-}
-public void setDenominator(Integer denominator) {
- this.denominator = denominator;
-}
-
-
+ public Integer getNumerator() {
+ return numerator;
+ }
+ public void setNumerator(Integer numerator) {
+ this.numerator = numerator;
+ }
+ public Integer getDenominator() {
+ return denominator;
+ }
+ public void setDenominator(Integer denominator) {
+ this.denominator = denominator;
+ }
+
+
@@ -20,7 +20,7 @@
-import java.io.File;
+ import java.io.File;
-import java.io.IOException;
+ import java.io.IOException;
-import java.io.IOException;
+ import java.util.Scanner;
+ 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
+ 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
+ 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
+ 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
+ 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");
+ 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 4fc6ea1027173a01d90631376c472c1bff86819a Mon Sep 17 00:00:00 2001 From: logananglin98
- This class provides a lot of functionality for file hanling, however, the
- 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.
- 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 @@
+ The
+ 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
is called a
-
-
+ Thank you to the following people for their hard work and contributions to this book: Dr. Brad Miller for writing the original book; Rob Beezer for creating PreTeXt; Moise Dete-Kpinssounon for converting the original version to PreTeXt; Oscar Levin for developing the reStructuredText-to-PreTeXt transition tool that supported Moise’s conversion work; Berea College for funding interns and supporting independent studies that facilitated the book’s conversion and improvement; and Beryl Hoffman for her impressive work on CSAwesome, which we are leveraging.
- This book does not attempt to replace the many good Java reference books that are available, in fact I use this in my course along with
- I have published this article using a Creative Commons license to encourage you to use it, change it, and modify it for your own purposes. - I would appreciate knowing what you think if you do use this book, and I would love to see any modifications or additions you make. + We have published this article using a Creative Commons license to encourage you to use it, change it, and modify it for your own purposes. + IWe would appreciate knowing what you think if you do use this book, and we would love to see any modifications or additions you make.
-
- Brad Miller
@@ -51,13 +46,16 @@
History of this Book - I started writing this article in 2006 using Python’s restructured text. - In 2007 I switched to markdown since everything else I was writing used markdown. - In particular I switched to the variant of markdown used by the excellent
+pandoc program. + Brad Miller started writing this article in 2006 using Python’s restructured text. + In 2007 I switched to markdown since everything else he was writing used markdown. + In particular he switched to the variant of markdown used by the excellentpandoc program. Pandoc does an excellent job of converting markdown to html, latex, pdf, and other formats. - The markdown source for this article is availablehere . - Finally the document became so big that I usedpandoc to convert it to latex for preparing the final version. - I used Thehtlatex program to generate html for the online version of this document. + + Finally, the document became so big that Brad usedpandoc to convert it to latex for preparing the final version. + He used Thehtlatex program to generate html for an online version of this document. ++ Brad Miller founded Runestone Academy in 2011 during a sabbatical from Luther College, and the original versions of this book was written in ReStructuredText.
We have published this article using a Creative Commons license to encourage you to use it, change it, and modify it for your own purposes. - IWe would appreciate knowing what you think if you do use this book, and we would love to see any modifications or additions you make. + We would appreciate knowing what you think if you do use this book, and we would love to see any modifications or additions you make.
From 473691129e46617934fe14ce1143a89337047624 Mon Sep 17 00:00:00 2001 From: Eun Sung Wang <156254694+esw0624@users.noreply.github.com> Date: Tue, 29 Jul 2025 11:17:56 -0400 Subject: [PATCH 055/424] Fixing and removing section buttons --- source/ch_7_definingclasses.ptx | 3 +++ 1 file changed, 3 insertions(+) diff --git a/source/ch_7_definingclasses.ptx b/source/ch_7_definingclasses.ptx index c2bf1ff..062f477 100644 --- a/source/ch_7_definingclasses.ptx +++ b/source/ch_7_definingclasses.ptx @@ -4,6 +4,8 @@You have already seen how to define classes in Java. @@ -180,6 +182,7 @@ public void setDenominator(Integer denominator) {
+
- The job of the compiler is to turn your java code into language that the Java Virtual Machine (JVM) can understand.
+
+
+
+
+
- You may Notice that this error message looks similar to the previous one, however it has an entirely diferent cause. In Java, classes like
@@ -43,7 +43,7 @@
Here’s an example of the error message that occurs when you forget to use the new keyword.
Notice that the message is pretty unhelpful.
Java thinks you are trying to call the Method Scanner, but there are two problems.
- First Scanner is not really a method it is a constructor.:
+ First, Scanner is not really a method; rather, it is a constructor.:
@@ -77,4 +77,4 @@
+ 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. +
++ 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;
+
+ 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
+ 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
+ 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
+ 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
+ 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");
+
+ The
+ 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
+ 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
+ myWriter.write("File successfully updated!");
+ myWriter.close();
+
+ You may have noticed the
+ 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
+ Speaking of overwriting data, it is important to know that the
+ FileWriter myWriter = new FileWriter("myfile.txt", true); // true enables append mode
+
+ Now, when we use
+ 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
+ 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
+ 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!
+
+ Python is a nice language for beginning programming for several reasons. First the syntax is sparse, and clear. @@ -20,7 +19,7 @@
These languages have some advantages of their own.
- First, is speed: Java and C++ code will generally give better performance than Python code
+
+ 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:
-
-
+ This program reads the file
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
From 1045a4acfe731c161d1b511384677f0527841a55 Mon Sep 17 00:00:00 2001
From: austing767
Date: Tue, 29 Jul 2025 14:02:56 -0500
Subject: [PATCH 061/424] Added a note in 4.3 lists to explain null, also added
it to index, fixes issue #40
---
source/ch_4_javadatatypes.ptx | 5 +++++
1 file changed, 5 insertions(+)
diff --git a/source/ch_4_javadatatypes.ptx b/source/ch_4_javadatatypes.ptx
index 6d097a7..59ba548 100644
--- a/source/ch_4_javadatatypes.ptx
+++ b/source/ch_4_javadatatypes.ptx
@@ -472,6 +472,11 @@ The code will be executed once for each element in the collection .
Here is the Java code needed to write the exact same program:
+
+
+ The Java code below contains the first mention of the null null literal. Similar to Python’s None object, null in Java is used to indicate that a variable does not currently reference any object in memory. This is often used for variables that have not yet been initialized or for methods that return no object.
+
+
From 59186ee6fe4d61f2a3ca2a73a4d9263794ae8c2b Mon Sep 17 00:00:00 2001
From: Tristan-Raz
Date: Tue, 29 Jul 2025 15:08:19 -0400
Subject: [PATCH 062/424] 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 da7cf72d5ee412b2b9eb82171e38920204762f2c Mon Sep 17 00:00:00 2001
From: Jan Pearce
Date: Tue, 29 Jul 2025 15:16:49 -0400
Subject: [PATCH 063/424] simplify ch7 title
---
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 062f477..201af40 100644
--- a/source/ch_7_definingclasses.ptx
+++ b/source/ch_7_definingclasses.ptx
@@ -1,10 +1,10 @@
-
- Defining Classes in Java
+
+ Classes in Java
-
+
Defining Classes in Java
From 185be526f19494fa025994bad24bef298a6d2cc7 Mon Sep 17 00:00:00 2001
From: logananglin98
Date: Tue, 29 Jul 2025 15:28:08 -0400
Subject: [PATCH 064/424] 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 @@
+ + 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
+ 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.
+ 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
- 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:
- 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. -
-
- Before any code can be written to handle files, the proper classes must be imported. Java includes a class called
- import java.io.File;
-
- This class provides a lot of functionality for file handling, however, the
- 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;
-
- 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
- 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
- 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
- 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
- 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");
-
- The
- The Java code below contains the first mention of the
if condition: statement1 statement2 ...
- In Java this same pattern is simply written as: + In Python the simple if statement is written as:
-if (condition) { statement1 statement2 ... }
+
+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) {
+ int score = 70;
+ if (score <= 70) {
+ System.out.println("Needs work!");
+ }
+ }
+ }
+
+ 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 if 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 condition: statement1 statement2 ... else: statement1 statement2 ...-
- In Java this is written as: -
- -if (condition) { statement1 statement2 ... } else { statement1 statement2 ... }
+ The Java equivalent follows the same syntactical rules as before.
+
+ age = 16
+ if age >= 18:
+ print("You can vote.")
+ else:
+ print("You are not yet eligible to vote.")
+
+
+ public class IfElseExample {
+ public static void main(String[] args) {
+ int age = 16;
+ if (age >= 18) {
+ System.out.println("You can vote.");
+ } else {
+ System.out.println("You are not yet eligible to vote.");
+ }
+ }
+ }
+
+ - Thank you to the following people for their hard work and contributions to this book: Dr. Brad Miller for writing the original book; Rob Beezer for creating PreTeXt; Moise Dete-Kpinssounon for converting the original version to PreTeXt; Oscar Levin for developing the reStructuredText-to-PreTeXt transition tool that supported Moise’s conversion work; Berea College for funding interns and supporting independent studies that facilitated the book’s conversion and improvement; and Beryl Hoffman for her impressive work on CSAwesome, which we are leveraging. + Thank you to the following people and organizations for their hard work and contributions to this book: Brad Miller for writing the original version of this book and for creating Runestone Academy; Rob Beezer for creating the PreTeXt language in which this book is authored; Moise Dete-Kpinssounon for converting the original version to PreTeXt; Oscar Levin for developing the reStructuredText-to-PreTeXt transition tool that supported the conversion work from the previous version; Berea College for funding interns and supporting independent studies that facilitated the book’s conversion and improvement; and Beryl Hoffman for her impressive work on CSAwesome, which we are leveraging as a model in several sections that are new to this version.
Learning multiple programming languages helps programmers adapt to different styles and environments.
+Python is a dynamic scripting language that is beginner-friendly, but it is less strict with types and generally slower than compiled languages.
+Languages like Java and C++ are statically typed and offer better performance and maintainability for large-scale projects.
+Java has a simpler syntax than C++ and includes automatic garbage collection, which reduces the complexity of memory management.
+Java’s extensive standard library enables the development of sophisticated programs without relying on external dependencies.
+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.
+ Generic Programming +
+- Generic Programming -
-
In this code, we simply print the contents of the file to the console, but it is easy to imagine how the
+ 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
The error "';' expected" on line 7 of
- The Ternary Operator provides a compact, one-line if-else statement. For instance,
- 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
- F-Strings (Formatted String Literals) simplify embedding expressions and variables directly inside strings. This makes code like
- Tuple and List Unpacking allows for assigning elements of a sequence to multiple variables in a single line, such as
- Chained Comparisons make range checks more intuitive and mathematical. You can write
- The 'cannot find symbol' error for the variable
- Main.java:7: error: cannot find symbol - count = new ArrayList<Integer>(10); - ^ - symbol: variable count - location: class Main -
The error "';' expected" on line 7 of
- Histo.java:7: error: ';' expected - Scanner data = null - ^ -From 0f2643005dd58bc81f314a0f68220c95e24130da Mon Sep 17 00:00:00 2001 From: Tristan-Raz
- In Python the easiest way to write a definite loop is using the for loop in conjunction with the range function.
+ In Python the easiest way to write a definite loop is using the
for i in range(10): print(i)+
+for i in range(10):
+ print(i)
+
+ - In Java we would write this as: + In Java, we would write this as:
-for (Integer i = 0; i < 10; i++ ) { System.out.println(i); }
+
+public class DefiniteLoopExample {
+ public static void main(String[] args) {
+ for (Integer i = 0; i < 10; i++ ) {
+ System.out.println(i);
+ }
+ }
+}
+
+
Recall that the
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.
+ The Java
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: + 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)+
+for i in range(100, -1, -5):
+ print(i)
+
+ In Java we would write this as:
-for (Integer i = 100; i >= 0; i -= 5) System.out.println(i);+
+public class DefiniteLoopBackward {
+ public static void main(String[] args) {
+ for (Integer i = 100; i >= 0; i -= 5) {
+ System.out.println(i);
+ }
+ }
+}
+
+
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
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)+
+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:
+ In Java we can iterate over an
ArrayList<Integer> l = new ArrayList<Integer>(); l.add(1); l.add(1); l.add(2); l.add(3); for (Integer i : l) { System.out.println(i) }
+
+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);
+ l.add(3);
+ l.add(5);
+ l.add(8);
+ l.add(13);
+ l.add(21);
+ for (Integer i : l) {
+ System.out.println(i);
+ }
+ }
+}
+
+
- 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
int l[] = {1,1,2,3,5,8,13,21}; for(int i : l) { System.out.println(i); }
+
+public class ForEachArrayExample {
+ public static void main(String[] args) {
+ int l[] = {1,1,2,3,5,8,13,21};
+ for(int i : l) {
+ System.out.println(i);
+ }
+ }
+}
+
+ To iterate over the characters in a string in Java do the following:
-String t = "Hello World"; for (char c : t.toCharArray()) { System.out.println(c); }
+
+public class StringIterationExample {
+ public static void main(String[] args) {
+ String t = "Hello World";
+ for (char c : t.toCharArray()) {
+ System.out.println(c);
+ }
+ }
+}
+
+
- Both Python and Java support the while loop.
- Recall that in Python the while loop is written as:
+ Both Python and Java support the
+i = 5
+while i > 0:
+ print(i)
+ i = i - 1
+
+ while condition: statement1 statement2 ...
- In Java we add parenthesis and curly braces to get: + In Java we add parenthesis and curly braces. Here is the same countdown loop in Java:
+
+public class WhileLoopExample {
+ public static void main(String[] args) {
+ int i = 5;
+ while (i > 0) {
+ System.out.println(i);
+ i = i - 1;
+ }
+ }
+}
+
+ while (condition) { statement1 statement2 ... }
- Java adds an additional, if seldom used variation of the while loop called the do loop.
- The do loop is very similar to while except that the condition is evaluated at the end of the loop rather than the beginning.
+ Java adds an additional, if seldom used variation of the while loop called the
do { statement1 statement2 ... } while (condition);
+
+public class DoWhileExample {
+ public static void main(String[] args) {
+ int i = 10;
+ do {
+ System.out.println("This runs once, i = " + i);
+ } while (i < 5);
+ }
+}
+
+
import java.util.ArrayList; // Line 1: Import necessary class
public class Main { // Line 3: Class declaration
@@ -22,7 +22,7 @@
} // Line 10: End of main method
} // Line 11: End of class
-
+
The 'cannot find symbol' error for the variable
You may notice that this error message looks similar to the previous one, however, it has an entirely different cause. In Java, classes like
The error "';' expected" on line 7 of
This error message occurs when you forget to use the
- 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.
- 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.
- 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.
- 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.
- 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
+ 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
+ First, lets look at the equivalent Python code:
+
+ Now, let's look at Java code that accomplishes the same task:
+
+ You may have noticed the use of another method from the File 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.
@@ -137,22 +167,52 @@
+ The
+ 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:
+
- 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:
- The
@@ -238,7 +298,7 @@
+ You may have noticed the
- 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:
+
+ And the equivalent Java code:
- 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:
+
+ The completed Java code:
- 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
+ If a file does not already exist (for example, myfile.txt does not exist), the
- Speaking of overwriting data, it is important to know that the
- 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
- 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:
- 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:
+ 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:
+
- 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:
- The
@@ -464,12 +579,34 @@
+ Pay close attention to the details of this code.
- Pay close attention to the details of this code.
- 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:
- 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.
- 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
This is a compiler warning, not an error, indicating a potential type safety issue. It occurs because you are calling the
When
+ Java has some very handy naming conventions.
+
+
+ Class names always start with an upper case letter.
+ For example,
+ Method names always start with a lower case letter, and use camelCase to represent multiword method names.
+ for example
+ Instance variables of a class start with a lower case letter and use camelCase
+
+ Constants are in all upper case letters.
+ for example
+ // Histo.java
+ public class Histo { // Line 2: Class declaration
+ public static void main(String[] args) { // Line 4: Main method declaration
+
+ Scanner data = null; // Line 6: This line will cause the "cannot find symbol" error
+
+ } // Line 8: End of main method
+ } // Line 9: End of class
+
+
- Histo.java:3: error: cannot find symbol
- Scanner data = null;
- ^
- symbol: class Scanner
- location: class Histo
-
-
// Histo.java
import java.util.Scanner; // Line 1
// Line 2
@@ -84,7 +88,7 @@
System.out.println("This line will not compile."); // Line 8
}
}
-
+
+ // Histo.java // Line 1: The filename for this example
+ import java.io.File; // Line 2: Import the File class, needed for file operations
+ import java.util.Scanner; // Line 3: Import the Scanner class, now correctly imported
+
+ public class Histo { // Line 5: Class declaration
+
+ public static void main(String[] args) { // Line 7: Main method declaration
+
+ Scanner data = Scanner(new File("test.dat")); // Line 9: This Line will cause an error
+ } // Line 12: End of main method
+ } // Line 13: End of class
+
+
- Histo.java:8: error: cannot find symbol
- data = Scanner(new File("test.dat"));
- ^
- symbol: method Scanner(File)
- location: class Histo
-
-
- 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.
-
+
+ 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.")
+
- 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;
-
+
- Note: The
+
An error occurred.
java.io.IOException: Permission denied
at java.base/java.io.File.createNewFile(File.java:1040)
at CreateFile.main(CreateFile.java:7)
-
+
+
+ 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()
+
- FileWriter myWriter = new FileWriter("myFile.txt");
+ FileWriter myWriter = new FileWriter("myfile.txt");
- Note: the
+
+ 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()
+
+
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 @@
+ 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()
+
File successfully updated!
File successfully updated!
-
- Note: The myFile File object we created on the first line was passed to the Scanner object created on the second line.
-
+
+ with open("filename.txt", "r") as file_reader:
+ for line in file_reader:
+ print(line.strip())
+
+
+ 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()
+
+
+
+ // UncheckedWarningDemo.java
+ import java.util.ArrayList; // Line 2: Import the ArrayList class
+
+ public class UncheckedWarningDemo { // Line 4: Class declaration
+
+ public static void main(String[] args) { // Line 6: Main method declaration
+
+ // This is where the potential for unchecked operations begins.
+ ArrayList rawList = new ArrayList();//Line 9
+
+ rawList.add("Hello");//Line 11: This is the line that will throw an error
+
+ System.out.println("Element added: " + rawList.get(0));
+ } // Line 14: End of main method
+ } // Line 15: End of class
+
+
- UncheckedWarningDemo.java:8: warning: [unchecked] unchecked call to add(E) as a member of the raw type ArrayList
- rawList.add("Hello");
- ^
- where E is a type-variable:
- E extends Object declared in class ArrayList
-
+
+
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 b6432ffa96f862287143c874f104b3068a890bd7 Mon Sep 17 00:00:00 2001
From: Jan Pearce
Date: Wed, 30 Jul 2025 18:22:34 -0400
Subject: [PATCH 083/424] enhanced explanations and small fixes
---
source/ch_6_loopsanditeration.ptx | 22 +++++++++++-----------
1 file changed, 11 insertions(+), 11 deletions(-)
diff --git a/source/ch_6_loopsanditeration.ptx b/source/ch_6_loopsanditeration.ptx
index 498d2a5..a0650f4 100644
--- a/source/ch_6_loopsanditeration.ptx
+++ b/source/ch_6_loopsanditeration.ptx
@@ -10,8 +10,8 @@
So this section will just serve as a reference for the differences in syntax.
-
- In Python the easiest way to write a definite loop is using the for loop in conjunction with the range function.
+
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:
@@ -47,7 +47,7 @@ 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.
+ 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:
@@ -69,7 +69,7 @@ for i in range(100, -1, -5):
- In Java we would write this as:
+ In Java, we would write this as:
@@ -85,12 +85,12 @@ 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.
+ 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.
- In Python we can iterate over a list as follows:
+ In Python, we can iterate over a list as follows:
@@ -168,8 +168,8 @@ public class StringIterationExample {
Indefinite Loops
-
- Both Python and Java support the while loop.
+
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:
@@ -198,8 +198,8 @@ public class WhileLoopExample {
- Java adds an additional, if seldom used variation of the while loop called the
- Java has some very handy 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 always start with an upper case letter.
- For example,
- Method names always start with a lower case letter, and use camelCase to represent multiword method names.
- for example
- Instance variables of a class start with a lower case letter and use camelCase
+ Instance variables of a class start with a lower case letter and use lowerCamelCase like method names. For example,
- Constants are in all upper case letters.
- for example
+ 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:
+
+ 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.
+
+ Unlike Python, where you can create a new object without explicitly using a keyword, Java requires the
+ A common mistake in Java is to forget that every statement must end with a semicolon (
+ Java is a statically typed language, meaning you must specify the type of objects that can be stored in a container like an Java programs must be compiled before execution, unlike Python which is interpreted directly. Every Java program must define a Each Java program must include a Java enforces that every variable and method must have a clearly defined type, including Statements in Java must end with a semicolon ( Java uses dot notation to access class members, such as The
From 50c44f6a770f10781d49e2c2779abacd8e0b5da3 Mon Sep 17 00:00:00 2001
From: Jan Pearce
import java.util.ArrayList; // Line 1: Import necessary class
@@ -32,7 +36,10 @@
// Histo.java
public class Histo { // Line 2: Class declaration
@@ -53,7 +60,10 @@
// Histo.java // Line 1: The filename for this example
import java.io.File; // Line 2: Import the File class, needed for file operations
@@ -83,7 +93,10 @@
// Histo.java
import java.util.Scanner; // Line 1
@@ -105,7 +118,10 @@
// UncheckedWarningDemo.java
import java.util.ArrayList; // Line 2: Import the ArrayList class
From d0235e33dc7217c0ccba3d9290d183fe2049daf5 Mon Sep 17 00:00:00 2001
From: Elijah Babayemi
+
Which of the following must be true of every Java program?
+It must contain a method called
No. The main method must include a specific parameter:
It must include a
Correct! This is the required entry point for all Java applications.
It must be saved with a
No. Java source files use the
It must be run using the Python interpreter.
No. Java uses its own compiler and Java Virtual Machine (JVM).
What is the purpose of the
To compile Java source code into bytecode
Exactly!
To run a Python program
No. Python programs are run with the
To debug Java programs
No.
To edit Java source files
No. You use a text editor or IDE to edit Java files.
What symbol does Java use to indicate the end of a statement?
+No.
Correct! Java uses semicolons to mark the end of a statement.
+No.
No.
All variables must be declared with their type before use in Java due to static typing.
+Java has primitive types (
The
Java Strings are immutable like Python, but use methods like
Maps (
What is the correct way to declare an ArrayList that will hold String objects in Java?
+ArrayList<String> list;
+Good job!
+ArrayList list;
+No, you must specify the type of objects it will hold using generics.
+ArrayList[String] list;
+No, the syntax for generics uses < > brackets, not [ ].
+ArrayList() list;
+No, this is not a valid declaration.
+The process of automatically converting between primitive types and their Object wrapper classes in Java is called:
+Autoboxing
+Right! Good job!
+Casting
+No, casting is manually converting a type.
+Overloading
+No, overloading refers to methods, not type conversion.
+Unboxing
+No, unboxing is the reverse of autoboxing.
+Which method would you use to get the character at position 3 in a Java String called str?
+str.charAt(3)
+Correct!
+str[3]
+No, Java does not support this type of indexing.
+str.get(3)
+No, this method does not exist in Java.
+str.substring(3)
+No, this will return a substring starting at position 3, not a single character.
+
+ Before we dive into the
+
+
+
+ What does this mean in practice? For objects, the behavior is the same in both languages. When you pass a
+ However, if you reassign the parameter to a completely new object inside the method (e.g.,
Let’s begin by implementing addition in Java:
From ede1af8b1f879bfacbb7af346f82031229a5c174 Mon Sep 17 00:00:00 2001 From: colin flaherty
- import java.util.ArrayList; // Line 1: Import necessary class
+ import java.util.ArrayList; // Import necessary class
- public class Main { // Line 3: Class declaration
- public static void main(String[] args) { // Line 4: Main method declaration
-
- count = new ArrayList<Integer<(10); // Line 6: Attempt to use 'count' without declaration
+ public class Main { // Class declaration
+
+ // Main method declaration
+ public static void main(String[] args) {
- System.out.println("ArrayList created."); // Line 8: This line won't be reached due to the error.
+ // Attempt to use 'count' without declaration
+ count = new ArrayList<Integer<(10);
- } // Line 10: End of main method
- } // Line 11: End of class
+ // This line won't be reached due to the error.
+ System.out.println("ArrayList created.");
+
+ } // End of main method
+ } // End of class
@@ -42,14 +46,14 @@
// Histo.java
- public class Histo { // Line 2: Class declaration
+ public class Histo { // Class declaration
- public static void main(String[] args) { // Line 4: Main method declaration
-
- Scanner data = null; // Line 6: This line will cause the "cannot find symbol" error
+ public static void main(String[] args) { // Main method declaration
+ // This line will cause the "cannot find symbol" error
+ Scanner data = null;
- } // Line 8: End of main method
- } // Line 9: End of class
+ } // End of main method
+ } // End of class
@@ -65,18 +69,18 @@
- // Histo.java // Line 1: The filename for this example
- import java.io.File; // Line 2: Import the File class, needed for file operations
- import java.util.Scanner; // Line 3: Import the Scanner class, now correctly imported
+ // Histo.java // The filename for this example
+ import java.io.File; // Import the File class, needed for file operations
+ import java.util.Scanner; // Import the Scanner class, now correctly imported
- public class Histo { // Line 5: Class declaration
+ public class Histo { // Class declaration
- public static void main(String[] args) { // Line 7: Main method declaration
+ public static void main(String[] args) { // Main method declaration
- Scanner data = Scanner(new File("test.dat")); // Line 9: This Line will cause an error
+ Scanner data = Scanner(new File("test.dat")); // This Line will cause an error
- } // Line 12: End of main method
- } // Line 13: End of class
+ } // End of main method
+ } // End of class
@@ -99,15 +103,15 @@
// Histo.java
- import java.util.Scanner; // Line 1
- // Line 2
- public class Histo { // Line 3
- // Line 4
- public static void main(String[] args) { // Line 5
- Scanner data = null // Line 7: The error will point here
- System.out.println("This line will not compile."); // Line 8
- }
- }
+ 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
@@ -124,20 +128,20 @@
// UncheckedWarningDemo.java
- import java.util.ArrayList; // Line 2: Import the ArrayList class
+ import java.util.ArrayList; // Import the ArrayList class
- public class UncheckedWarningDemo { // Line 4: Class declaration
+ public class UncheckedWarningDemo { // Class declaration
- public static void main(String[] args) { // Line 6: Main method declaration
+ public static void main(String[] args) { // Main method declaration
// This is where the potential for unchecked operations begins.
- ArrayList rawList = new ArrayList();//Line 9
-
- rawList.add("Hello");//Line 11: This is the line that will throw an error
+ ArrayList rawList = new ArrayList();
+ rawList.add("Hello");
+ //This is the line that will throw an error
System.out.println("Element added: " + rawList.get(0));
- } // Line 14: End of main method
- } // Line 15: End of class
+ } // End of main method
+ } // End of class
From e511940389870f09607a2600dd85c158c0610448 Mon Sep 17 00:00:00 2001
From: colin flaherty
+Java also supports the
+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.
- In this example we are using this ternary operator to assign a value to
- Short-Circuiting: The logical operators
- 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,
- The Ternary Operator provides a compact, one-line if-else statement. For instance,
- Java's Stream API is the idiomatic alternative to Python's List Comprehension. Instead of a multi-line loop, you can write
- Java uses methods like
- 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
- Java does not support chained comparisons. Range checks must use logical operators, such as
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. @@ -329,6 +330,7 @@ Hello World! >>> +
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.
+
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 097/424] 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 098/424] 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 if 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 .
The Java equivalent follows the same syntactical rules as before.
- 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. +
-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
-Java also supports a
- Depending on your knowledge and experience with Python you may already be familar and questioning why we are not using the
grade = 100 // 10
def grading(grade):
@@ -191,8 +190,11 @@ Java also supports a switch statement that acts something like the elif s
- The
-The
-The conditionals used in the if statement can be boolean variables, simple comparisons, and compound boolean expressions. +
+
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
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
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
range(stop) -range(start,stop) -range(start,stop,step)+
+ range(stop) + range(start,stop) + range(start,stop,step) +
The Java
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 101/424] 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 @@
-
+ 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
+ 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.
+
+
+ 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:
+ 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
+
+
+ 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! +
+ + +Learning multiple programming languages helps programmers adapt to different styles and environments.
+Python is a dynamic scripting language that is beginner-friendly, but it is less strict with types and generally slower than compiled languages.
+Languages like Java and C++ are statically typed and offer better performance and maintainability for large-scale projects.
+Java has a simpler syntax than C++ and includes automatic garbage collection, which reduces the complexity of memory management.
+Java’s extensive standard library enables the development of sophisticated programs without relying on external dependencies.
+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.
- 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
@@ -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
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
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,
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,
-
-
- First you will notice that the
In Java we can do runtime type checking, but the compiler will not allow us to pass an Integer to the
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
- The instance variables (
@@ -488,7 +488,8 @@ Fraction@6ff3c5b5
- In Java, the equivalent of
- The keyword
By having the
- Java’s answer to this problem is the
- In this example notice that we create a static member variable by using the
- The instance variables (
@@ -146,7 +147,7 @@
- Notice that we have declared the numerator and denominator to be
+
+
+
-
-
- First you will notice that the
@@ -282,7 +290,7 @@ public Fraction add(Fraction otherFrac) {
+
+
-
+
- The keyword
+
+
- Java’s answer to this problem is the
- In this example notice that we create a
- First you will notice that the
-
- 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
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 @@
- Java has some very handy naming conventions.
-
-
- Class names always start with an upper case letter.
- For example,
- Method names always start with a lower case letter, and use camelCase to represent multiword method names.
- for example
- Instance variables of a class start with a lower case letter and use camelCase
-
- Constants are in all upper case letters.
- for example
+ All Java class libraries are documented and available online.
+ Here are two good resources for you to use:
+
+
+
+
-
-
+
+
+ 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 @@ + ++ 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. +
++ 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 (
+ 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
+ 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
+ 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
+ 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
+ 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
+ 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}")
+
+ + 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: +
+
+ Neither language supports
+ 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();
+ }
+ }
+
+ 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.
- 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
- 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. -
-
-
- 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:
- 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
- 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! -
- - -Learning multiple programming languages helps programmers adapt to different styles and environments.
-Python is a dynamic scripting language that is beginner-friendly, but it is less strict with types and generally slower than compiled languages.
-Languages like Java and C++ are statically typed and offer better performance and maintainability for large-scale projects.
-Java has a simpler syntax than C++ and includes automatic garbage collection, which reduces the complexity of memory management.
-Java’s extensive standard library enables the development of sophisticated programs without relying on external dependencies.
-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.
- 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
+
Java’s
To loop over lists or arrays in Java, the enhanced for-each loop uses the syntax
Python’s
Java also supports the
Java’s
To iterate through characters in a Java String, use
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,
foreach i in array:
No, this is not valid Java syntax.
What is a unique characteristic of the Java
It checks the condition before the loop body runs.
No, that describes a regular
It always runs infinitely.
No, a
It guarantees the loop body runs at least once.
Correct! The
It is not supported in Java.
No, Java does support
- All Java class libraries are documented and available online. - Here are two good resources for you to use: -
- --
-
-
- 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. -
-
import java.io.File;
-
@@ -31,7 +31,7 @@
import java.util.Scanner;
-
@@ -41,7 +41,7 @@
import java.io.FileWriter;
-
@@ -51,45 +51,166 @@
- Before we can write code that creates a file, we must first import the necessary classes mentioned in the previous section (
- Next, within the main function, we will create a
+ The next lines consists of a Python code examplethat reads each line of the file passed to the Scanner object.:
+
+ The equivalent Java code:
+
+ The
+ Alternatively, the following code can be used to store the all lines of myfile.txt to one variable:
+
+ Pay close attention to the details of this code.
+ 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:
+
+ And the Java equivalent:
+
+ In this code, we simply print the contents of the file to the console, but it is easy to imagine how the
+ We will now create a
@@ -139,7 +260,7 @@
}
}
}
-
@@ -236,7 +357,7 @@
}
}
-
@@ -254,7 +375,7 @@
@@ -264,7 +385,7 @@
import java.io.IOException;
-
import java.io.FileNotFoundException
-
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) {
}
}
-
File myFile = new File("myfile.txt");
-
+ with open("filename.txt", "r") as file_reader:
+ for line in file_reader:
+ print(line.strip())
+
+
+ while (fileReader.hasNextLine()) {
+ String data = fileReader.nextLine();
+ System.out.println(data);
+ }
+ fileReader.close();
+
+
+ String data = "";
+ while (fileReader.hasNextLine()) {
+ data = data + fileReader.nextLine() + System.lineSeparator();
+ }
+ System.out.println(data);
+ fileReader.close();
+
+
+ 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()
+
+
+
+ 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();
+ }
+ }
+ }
+
+
+ File myFile = new File("myfile.txt");
+
File myFile = new File("C:\\Users\\UserName\\Documents\\myfile.txt");
-
File myFile = new File("/home/UserName/Documents/myfile.txt");
-
- 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 (
@@ -299,7 +420,7 @@
FileWriter myWriter = new FileWriter("myfile.txt");
-
@@ -310,7 +431,7 @@
@@ -368,7 +487,7 @@
print("An error occurred.")
import traceback
traceback.print_exc()
-
@@ -393,7 +512,7 @@
}
}
}
-
@@ -413,7 +532,7 @@
@@ -438,206 +557,51 @@
}
}
}
-
- and then run the program twice, the contents of
- 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:
-
- 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
- This would work fine most of the time, but older Windows programs and operating systems use the
- 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:
- 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:
-
- 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:
-
- 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:
-
- The equivalent Java code:
-
- The
- Alternatively, the following code can be used to store the all lines of myfile.txt to one variable:
-
- Pay close attention to the details of this code.
- 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:
-
- And the Java equivalent:
-
- In this code, we simply print the contents of the file to the console, but it is easy to imagine how the
From 3cd5d5a8f7e24d5b7e0535b7ffb7990d53891db2 Mon Sep 17 00:00:00 2001
From: Tristan-Raz
- 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:
-
- 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:
-
- The next lines consists of a Python code examplethat reads each line of the file passed to the Scanner object.:
-
- The equivalent Java code:
-
- The
- Alternatively, the following code can be used to store the all lines of myfile.txt to one variable:
-
- Pay close attention to the details of this code.
- 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:
-
- And the Java equivalent:
-
- In this code, we simply print the contents of the file to the console, but it is easy to imagine how the
+ 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:
+
+ 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:
+
+ The next lines consists of a Python code examplethat reads each line of the file passed to the Scanner object.:
+
+ The equivalent Java code:
+
+ The
+ Alternatively, the following code can be used to store the all lines of myfile.txt to one variable:
+
+ Pay close attention to the details of this code.
+ 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:
+
+ And the Java equivalent:
+
+ In this code, we simply print the contents of the file to the console, but it is easy to imagine how the
myWriter.write("File successfully updated!");
myWriter.close();
-
- 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())
FileWriter myWriter = new FileWriter("myfile.txt", true); // true enables append mode
-
File successfully updated!File successfully updated!
-
- myWriter.write("File successfully updated! "); // Added space at end
- myWriter.close();
-
myWriter.write("File successfully updated!\n"); // Added newline character
myWriter.close();
-
myWriter.write("File successfully updated!" + System.lineseparator()); // Added newline character
myWriter.close();
-
File successfully updated!
File successfully updated!
-
- 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);
-
- with open("filename.txt", "r") as file_reader:
- for line in file_reader:
- print(line.strip())
-
+
- while (fileReader.hasNextLine()) {
- String data = fileReader.nextLine();
- System.out.println(data);
- }
- fileReader.close();
-
- String data = "";
- while (fileReader.hasNextLine()) {
- data = data + fileReader.nextLine() + System.lineSeparator();
- }
- System.out.println(data);
- fileReader.close();
-
- 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()
-
-
-
- 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();
- }
- }
- }
-
- 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);
-
-
- with open("filename.txt", "r") as file_reader:
- for line in file_reader:
- print(line.strip())
-
-
- while (fileReader.hasNextLine()) {
- String data = fileReader.nextLine();
- System.out.println(data);
- }
- fileReader.close();
-
-
- String data = "";
- while (fileReader.hasNextLine()) {
- data = data + fileReader.nextLine() + System.lineSeparator();
- }
- System.out.println(data);
- fileReader.close();
-
-
- 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()
-
-
-
- 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();
- }
- }
- }
-
-
+ 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);
+
+
+ with open("filename.txt", "r") as file_reader:
+ for line in file_reader:
+ print(line.strip())
+
+
+ while (fileReader.hasNextLine()) {
+ String data = fileReader.nextLine();
+ System.out.println(data);
+ }
+ fileReader.close();
+
+
+ String data = "";
+ while (fileReader.hasNextLine()) {
+ data = data + fileReader.nextLine() + System.lineSeparator();
+ }
+ System.out.println(data);
+ fileReader.close();
+
+
+ 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()
+
+
+
+ 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 Java, every variable must be declared with its type before use; undeclared variables cause compilation errors.
+Java requires explicit import statements for classes from external packages (e.g.,
The
Every Java statement must end with a semicolon (
Java uses generics for type safety in containers like
Compiler error messages may sometimes be misleading; understanding common mistakes helps quickly identify the root cause.
+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
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
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
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
Correct! The
No. Omitting
No. This method does not exist for object creation.
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
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.
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);
+
+
- 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();
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.
-- 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 (
- 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
+ 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
+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
What is the correct way to instantiate a new object of class
Correct! The
No. Omitting
No. This method does not exist for object creation.
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
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 In Java, instance variables must be declared at the top of the class, unlike Python which allows dynamic creation of instance variables anywhere.
+Java uses access modifiers like
Java requires a separate constructor method to initialize objects, using the class name and defining parameters explicitly, whereas Python uses the
Every Java class inherits from the
Java’s
Java supports inheritance through abstract classes like
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
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
Java uses the
No, Java does not have
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
No,
Only override
No, you should override
Java automatically handles content comparison without overrides.
No, default
Override
Yes! This improves output and content-based comparison.
Why does the
To require implementation of methods like
Correct! This integrates
Because
No, Java does not support operator overloading.
To avoid writing constructors.
No, constructors are still needed in subclasses.
Because
No, sorting is handled by interfaces like
- 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.");
+ }
+ }
+ }
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.:
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 130/424] 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
-
@@ -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
+
+ -
+
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 includes a switch statement for checking equality against constant values, which can replace long if-else chains for specific scenarios.
+
+ -
+
+ Java uses the boolean data type to represent logical values true or false , commonly used in conditionals and control flow.
+
+
+
+
+
+
+ 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 131/424] 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 132/424] 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> {
In Java, instance variables must be declared at the top of the class, unlike Python which allows dynamic creation of instance variables anywhere.
-Java uses access modifiers like
Java requires a separate constructor method to initialize objects, using the class name and defining parameters explicitly, whereas Python uses the
Every Java class inherits from the
Java’s
Java supports inheritance through abstract classes like
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
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
Java uses the
No, Java does not have
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
No,
Only override
No, you should override
Java automatically handles content comparison without overrides.
No, default
Override
Yes! This improves output and content-based comparison.
Why does the
To require implementation of methods like
Correct! This integrates
Because
No, Java does not support operator overloading.
To avoid writing constructors.
No, constructors are still needed in subclasses.
Because
No, sorting is handled by interfaces like
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.
+Java uses access modifiers like
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
Every Java class inherits from the
By default, Java’s
Java supports inheritance through abstract classes (like
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
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
Java uses the
No, Java does not have
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
No,
Only override
No, you should override
Java automatically handles content comparison without overrides.
No, default
Override
Yes! This improves output and content-based comparison.
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?
Java has several libraries included for file handling, though, they must be imported. Java includes a class called
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.");
+ }
+ }
+ }
- import java.util.Scanner;
-
- + import java.util.Scanner; +
The
+
import java.io.FileWriter;
-
-
Finally, these last two classes provide error handling and must be used in tandem with the
+
import java.io.IOException;
-
-
- import java.io.FileNotFoundException
-
- + import java.io.FileNotFoundException +@@ -68,10 +70,19 @@
We will now create a
+ 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);
+ }
+ }
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}")
- 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
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 135/424] 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 136/424] 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 137/424] 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 138/424] 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
Let us create the framework for a class that will write to a file. Let's call this class
+ ++
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 140/424] 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
+
+ -
+
In Java, instance variables must be declared at the top of the class, unlike Python which allows dynamic creation of instance variables anywhere.
+
+ -
+
Java uses access modifiers like private to enforce encapsulation, encouraging data hiding and controlled access through getter and setter methods.
+
+ -
+
Java requires a separate constructor method to initialize objects, using the class name and defining parameters explicitly, whereas Python uses the __init__ method.
+
+ -
+
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__ ).
+
+ -
+
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 .
+
+ -
+
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.
+
+
+
+
+
+
+ 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 141/424] 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
-
- -
-
In Java, instance variables must be declared at the top of the class, unlike Python which allows dynamic creation of instance variables anywhere.
-
- -
-
Java uses access modifiers like private to enforce encapsulation, encouraging data hiding and controlled access through getter and setter methods.
-
- -
-
Java requires a separate constructor method to initialize objects, using the class name and defining parameters explicitly, whereas Python uses the __init__ method.
-
- -
-
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__ ).
-
- -
-
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 .
-
- -
-
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.
-
-
-
-
-
-
- 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
+
+ -
+
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.
+
+ -
+
Java uses access modifiers like private to enforce encapsulation, encouraging data hiding and controlled access through getter and setter methods.
+
+ -
+
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.
+
+ -
+
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__ ).
+
+ -
+
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.
+
+ -
+
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.
+
+
+
+
+
+
+
+ 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 142/424] 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 143/424] 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 144/424] 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 145/424] 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 146/424] 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 147/424] 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 148/424] 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 149/424] 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 Object 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 150/424] 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 151/424] 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 152/424] 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
+
+ -
+
To work with files in Java, you must import specific classes like java.io.File , java.io.FileWriter , and handle exceptions such as IOException .
+
+ -
+
You can create a new file using File.createNewFile() , which returns true if the file is created and false if it already exists.
+
+ -
+
Reading from files is done using a Scanner attached to a File , often with a loop using hasNextLine() and nextLine() .
+
+ -
+
To write to a file, use a FileWriter object and call methods like write() and close() to save and finish the output.
+
+ -
+
You can delete a file using the delete() method on a File object, which returns true if successful.
+
+
+
+
+
+ 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 153/424] 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 154/424] 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 155/424] 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 156/424] 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 157/424] 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 158/424] 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 159/424] 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 160/424] 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 161/424] 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 162/424] 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 163/424] 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 164/424] 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 165/424] 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 166/424] 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 167/424] 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 168/424] 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 169/424] 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 170/424] 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 171/424] 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
-
+
-
Learning multiple programming languages helps programmers adapt to different styles and environments.
From c090273ce85b51e8ec724e76e6aeaa4f3d38c9f0 Mon Sep 17 00:00:00 2001
From: colin flaherty
Date: Thu, 7 Aug 2025 13:21:37 -0400
Subject: [PATCH 172/424] 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 173/424] 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 174/424] 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 175/424] 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 176/424] 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 177/424] 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 178/424] 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 179/424] 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 180/424] 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 181/424] 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 182/424] 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 183/424] 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 184/424] 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 185/424] 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 186/424] 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 187/424] 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 188/424] 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 189/424] 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 190/424] 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
-
-
-
+
compiler integrated development environment IDE
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 Code load 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
+ JDK Java development kit Oracle OpenJDK
+ 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
+ GitHub version control Codespaces
+ 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 191/424] 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
JDK Java development kit Oracle OpenJDK
- 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 language static 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 192/424] 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
+
+ -
+
Recursion solves problems by defining a base case and a recursive step; each call reduces the problem size until the base case is reached.
+
+ -
+
Java methods must declare visibility, static/instance context, return type, and parameter types; e.g., public static int factorial(int n) .
+
+ -
+
The recursive logic in Java mirrors Python conceptually, but Java uses curly braces {} and explicit types instead of indentation and dynamic typing.
+
+ -
+
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.
+
+ -
+
Closing over array bounds and indexes in the helper avoids forcing callers to provide implementation details (like a starting index).
+
+ -
+
Deep or unbounded recursion can exhaust the call stack: Python raises RecursionError ; Java throws StackOverflowError .
+
+ -
+
Neither Java nor Python guarantees tail call optimization; prefer iterative solutions for algorithms requiring very deep recursion.
+
+ -
+
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.
+
+
+
+
+
+ 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 193/424] 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.
+
recursion base case recursive 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
-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
- 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 {
- Neither language supports
- 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
@@ -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
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 195/424] 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> {
The recursive logic in Java mirrors Python conceptually, but Java uses curly braces
The helper-method pattern keeps public APIs clean (e.g.,
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.
Deep or unbounded recursion can exhaust the call stack: Python raises
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.
Error signaling differs across languages; for example, a Java factorial that receives a negative
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?
Why use a private helper method (e.g.,
Which statement about recursion limits and errors is accurate?
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?
No. While this handles negative numbers, the base case is incorrect - factorial of 0 should be 1, not 0.
No. Printing results is fine for testing, but a proper factorial method should return the computed value.
Correct. This matches the standard recursive factorial definition in Java.
No. Factorials are for integers, and using
No. Relying on a class field hides the input and makes recursion less flexible.
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.
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
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
Java automatically applies tail call optimization to recursive methods marked as
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.
Increasing a method’s parameter type from
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.
Much like the
- 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
+ import java.io.File; +
The
We will now create a
- 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 200/424] 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 201/424] 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 202/424] 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 203/424] 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,
- Now, when we use
@@ -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
@@ -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
- 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 PearceDate: Tue, 12 Aug 2025 12:06:52 -0400 Subject: [PATCH 204/424] 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 { @@ -235,7 +235,7 @@ Let us create the framework for a class that will write to a file. Let's call this class 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 limits call 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 thecall 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. +RecursionError + The only difference is the name of the error: + StackOverflowError -
+ +- 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 aStackOverflowError . 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 aRecursionError due to overflowing the call stack.From 680f110d466042f825e23311428e03e347384ef6 Mon Sep 17 00:00:00 2001 From: logananglin98Date: Tue, 12 Aug 2025 13:56:00 -0400 Subject: [PATCH 205/424] 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 useimport . Java includes a class calledFile in theio library. This class allows you to createFile objects, and use its public methods. -++import java.io.File; - The
-Scanner class from theutil 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 theScanner class isn't needed unless the program will read from a file, theFileWriter 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, whileFileNotFoundException handles errors when trying to read files.++import java.io.IOException; import java.io.FileNotFoundException; - 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 itmyWriter :++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. Thewrite() 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
++FileWriter myWriter = new FileWriter("myfile.txt", true); // true enables append mode -
Now, when we use
++-
@@ -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
++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 ++
From a226ed067d274a9f2a87344e28af99baec5d34fc Mon Sep 17 00:00:00 2001
From: logananglin98
Date: Tue, 12 Aug 2025 14:22:26 -0400
Subject: [PATCH 206/424] 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 207/424] 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 208/424] 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 209/424] 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 210/424] 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 211/424] 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 212/424] 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 213/424] 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 {
- 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,
- 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,
- Instance variables of a class start with a lower case letter and use lowerCamelCase like method names. For example,
- 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,
From 67450321e7d662f954331f8d064e0ea7ef63307b Mon Sep 17 00:00:00 2001
From: Jan Pearce
- We will now create a
+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);
+ }
+}
+
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 217/424] 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 218/424] 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 219/424] 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 if - else 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 220/424] 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 221/424] 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 222/424] 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 223/424] 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 224/424] 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 225/424] 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 226/424] 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 227/424] 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 228/424] 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 229/424] 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 230/424] 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 231/424] 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 232/424] 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 233/424] 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 switch 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 234/424] 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 235/424] 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 switch 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 236/424] 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 237/424] 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 238/424] 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 239/424] 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 240/424] 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 241/424] 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 242/424] 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 243/424] 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 244/424] 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 245/424] 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 246/424] 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 247/424] 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 248/424] 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 249/424] 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 250/424] 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 251/424] 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 252/424] 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 253/424] 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 254/424] 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 255/424] 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 256/424] 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 257/424] 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 258/424] 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 259/424] 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 260/424] 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 261/424] 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 262/424] 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 263/424] 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 264/424] 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 265/424] 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 266/424] 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 267/424] 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 268/424] 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 269/424] 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 270/424] 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 271/424] 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 272/424] 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 273/424] 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 274/424] 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 275/424] 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 276/424] 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 277/424] 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 278/424] 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 279/424] 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 280/424] 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 281/424] 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 if - else 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 282/424] 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 if - else Statement
- The Java equivalent follows the same syntactical rules as before.
+ shows how Python the if - else statement 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 283/424] 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 if - else Statement
- shows how Python the if - else statement is written in Python.
+ shows how the if - else statement 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 284/424] 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 285/424] 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 286/424] 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 287/424] 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 288/424] 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 289/424] 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 290/424] 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 switch 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 291/424] 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 switch 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 292/424] 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 293/424] 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 294/424] 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 295/424] 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 296/424] 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 297/424] 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 try-catch 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 298/424] 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 299/424] 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 300/424] 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 301/424] 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 302/424] 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 303/424] 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 304/424] 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 305/424] 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 306/424] 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 307/424] 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 308/424] 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 309/424] 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 310/424] 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 311/424] 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 312/424] 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 313/424] 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 if 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 if - else Statement
shows how the if - else statement is written in Python.
@@ -85,9 +84,9 @@ if score >= 90: # Note the colon at the end of the line
-
+
-
+
Can we use elif ?
elif statement
@@ -172,9 +171,9 @@ public class ElseIf {
-
+
-
+
Using the switch 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 314/424] 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 315/424] 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 316/424] 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 317/424] 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 318/424] 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 319/424] 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 320/424] 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 321/424] 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 322/424] 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 323/424] 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 324/424] 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 325/424] 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 326/424] 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 327/424] 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 328/424] 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 329/424] 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 330/424] 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 331/424] 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 332/424] 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 333/424] 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 334/424] 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 335/424] 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 336/424] 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 337/424] 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 338/424] 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 339/424] 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 340/424] 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 341/424] 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 342/424] 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 343/424] 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 344/424] 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 345/424] 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 346/424] 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 347/424] 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 348/424] 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 349/424] 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 350/424] 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 351/424] 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 352/424] 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 353/424] 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 354/424] 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 355/424] 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 356/424] 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"