diff --git a/source/ap-java-cheatsheet.ptx b/source/ap-java-cheatsheet.ptx index f272981..7e8f94a 100644 --- a/source/ap-java-cheatsheet.ptx +++ b/source/ap-java-cheatsheet.ptx @@ -10,7 +10,7 @@ The following is intended to be useful in better understanding Java functions coming from a Python background.
-
+Using this operator can make code shorter and more readable in cases where a simple conditional assignment is needed.
-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');
- }
- }
- }
-
-The
+ Rearrange the blocks to create a Java method that calculates shipping costs. Orders over $100 get free shipping ($0.0), while members pay $5.0 and non-members pay $10.0. +
+
- In Python, if you want a program to continue running when an error has occurred, you can use
- 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))
- The Java code that would perform the same task is a little more complex and utilizes the
import java.util.Scanner;
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);
}
}
- 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
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: ")
- 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,
import java.util.Scanner;
import java.util.InputMismatchException;
@@ -302,22 +529,23 @@ 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
}
}
}
}
-
+
Firstly, let's talk about the extra import alongside 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);
- }
- }
-
-
-
- In this example we are using this ternary operator to assign a value to
- Java's
-for i in range(10):
+for i in range(10): # range(10) is a list of integers from 0 to 9
print(i)
- In Java, we would write this as:
+
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);
}
}
}
- Recall that the
++ + ++ + range(stop) range(start,stop) range(start,stop,step) -
- The Java
+- + + + ++ + 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,
-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)
- In Java, we would write this as:
+
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);
}
}
}
In Python, the
- In Python, we can iterate over a list as follows:
+
-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)
- In Java we can iterate over an
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);
}
}
}
- 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) {
- 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);
}
}
}
- To iterate over the characters in a string in Java do the following: -
- +
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);
}
}
}
+ Rearrange the blocks to create a Java method that accepts an upper bound integer
i = 5
-while i > 0:
+while i > 0: # while i is greater than 0
print(i)
- i = i - 1
+ i = i - 1
- In Java we add parenthesis and curly braces. Here is the same countdown loop in Java:
+ In Java, we add parentheses and curly braces.
public class WhileLoopExample {
public static void main(String[] args) {
- int i = 5;
- while (i > 0) {
+ int i = 5;
+ while (i > 0) { // while i is greater than 0
System.out.println(i);
- i = i - 1;
+ i = i - 1;
}
}
}
public class DoWhileExample {
public static void main(String[] args) {
- int i = 10;
- do {
+ int i = 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
}
}
+ Rearrange the blocks to create a Java method that accepts a starting balance and a target amount, then calculates how many years it takes for the balance to reach or exceed the target by doubling each year. +
+
+
+
+
+ The best way to understand classes and objects is to see them in action. Let's define a
+ class Dog:
+ """ A simple Dog class definition. """
+ def __init__(self, name, breed, fur_color):
+ # constructor method to create a Dog object
+ self.name = name
+ self.breed = breed
+ self.fur_color = fur_color
+ self.trained = False # dogs are not trained by default
+ print("Dog named " + self.name + " created!")
+
+ def bark(self):
+ # method to make the dog bark
+ print(self.name + " says woof!")
+
+ def sit(self):
+ # method to make the dog sit
+ if self.trained: # check if the dog has been trained otherwise it will not sit
+ print(self.name + " sits.")
+ else:
+ print(self.name + " has not been trained.")
+
+ def train(self):
+ # method to train the dog, which will set the trained attribute to True
+ self.trained = True
+
+
+ Let's unpack what is going on in
+ The next three blocks of code are the class's methods. These include
+
+ Next, we will use this class to create a new
+ class Dog:
+ """ A simple Dog class definition. """
+ def __init__(self, name, breed, fur_color):
+ # constructor method to create a Dog object
+ self.name = name
+ self.breed = breed
+ self.fur_color = fur_color
+ self.trained = False # dogs are not trained by default
+ print("Dog named " + self.name + " created!")
+
+ def bark(self):
+ # method to make the dog bark
+ print(self.name + " says woof!")
+
+ def sit(self):
+ # method to make the dog sit
+ if self.trained: # check if the dog has been trained otherwise it will not sit
+ print(self.name + " sits.")
+ else:
+ print(self.name + " has not been trained.")
+
+ def train(self):
+ # method to train the dog, which will set the trained attribute to True
+ self.trained = True
+
+ # Create a Dog object called my_dog
+ my_dog = Dog("Rex", "pug", "brown")
+
+
+ In the final line of code in
+ Now that we have created a
+ class Dog:
+ """ A simple Dog class definition. """
+ def __init__(self, name, breed, fur_color):
+ # constructor method to create a Dog object
+ self.name = name
+ self.breed = breed
+ self.fur_color = fur_color
+ self.trained = False # dogs are not trained by default
+ print("Dog named " + self.name + " created!")
+
+ def bark(self):
+ # method to make the dog bark
+ print(self.name + " says woof!")
+
+ def sit(self):
+ # method to make the dog sit
+ if self.trained:
+ print(self.name + " sits.")
+ else:
+ print(self.name + " has not been trained.")
+
+ def train(self):
+ # method to train the dog, which will set the trained attribute to True
+ self.trained = True
+
+
+ my_dog = Dog("Rex", "pug", "brown")
+ my_dog.bark() # call the bark method
+ my_dog.sit() # call the sit method
+
+
+ When running
+ Now, we have a full class definition and have utilized its methods. Class definitions in Java will be covered thoroughly in chapter 6. For now, it is important to know that Python programs can be written without using classes at all. Java, on the other hand, requires all code to reside in a class. This will be discussed later in chapter 6. +
+ +
- Here is a mostly complete implementation of a Fraction class in Python that we will refer to throughout this section:
+
class Fraction:
@@ -76,37 +242,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 +298,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
@@ -126,6 +312,7 @@
print(sorted([Fraction(5, 16), Fraction(3, 16), Fraction(1, 16) + 1]))
- 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;
+ public class Fraction {
+ private Integer numerator; // notice the private modifier
private Integer denominator;
}
+
- 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
-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;
}
+
public Fraction(Integer top, Integer bottom) {
- num = top;
+ num = top; // notice the use of num instead of top
den = 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;
}
- Let’s begin by implementing addition in Java:
+
-public Fraction add(Fraction otherFrac) {
+public Fraction add(Fraction otherFrac) {
Integer newNum = otherFrac.getDenominator() * this.numerator +
- this.denominator * otherFrac.getNumerator();
- Integer newDen = this.denominator * otherFrac.getDenominator();
- Integer common = gcd(newNum, newDen);
+ this.denominator * otherFrac.getNumerator(); // notice the use of this.
+ Integer newDen = this.denominator * otherFrac.getDenominator(); // find the new denominator
+ Integer common = gcd(newNum, newDen); // find the greatest common divisor
return new Fraction(newNum/common, newDen/common);
}
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();
+ 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);
}
The addition takes place by multiplying each numerator by the opposite denominator before adding.
@@ -357,21 +554,22 @@ public Fraction add(Fraction otherFrac) {
To solve the problem of adding an
-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));
}
Notice that the overloading approach can provide us with a certain elegance to our code. @@ -380,21 +578,21 @@ public Fraction add(Integer other) {
- Our full
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;
}
@@ -410,10 +608,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;
@@ -422,76 +620,80 @@ 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));
}
}
- 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,
- 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
Fraction@6ff3c5b5
The reason is that we have not yet provided a friendly string representation for our
+ Rearrange the blocks to create a
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();
+ return numerator.toString() + "/" + denominator.toString(); // convert to a string
}
+
-object1 == object2
+object1 == object2 // this checks to see if the two objects are the same object in memory
- is NOT the same as
+
-object1.equals(object2)
+object1.equals(object2) // this checks to see if the two objects are equal by looking at their instance variables
- Here is an
-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)
@@ -620,6 +825,7 @@ public boolean equals(Fraction other) {
}
One important thing to remember about
- Here is code that makes the
-public class Fraction extends Number {
+public class Fraction extends Number { // fraction class is a child of 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
-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();
}
- 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:
+ Suppose you try to define a method as
public void test(Number a, Number b) {
- a.add(b);
+ a.add(b); // this is a bad idea
}
The Java compiler would give an error because
+ Construct the
-
The
int compareTo(T o)
@@ -794,79 +1034,86 @@ iff y.compareTo(x) throws an exception.)
...
- To make our
-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
...
}
The specification
-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;
}
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
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
+ # 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))
+ s = Student(i,"Student-"+str(i)) # create a new Student object
print('Number of students:', Student.numStudents)
main()
- In Java we would write this same example using a static declaration.
+
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++) {
@@ -877,10 +1124,11 @@ 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;
@@ -905,17 +1157,18 @@ private static Integer gcd(Integer m, Integer n) {
}
- Here is a final version of the
import java.util.ArrayList;
import java.util.Collections;
@@ -1009,6 +1262,7 @@ public class Fraction extends Number implements Comparable<Fraction> {
}
- Let's take the familiar factorial function, which calculates
You may recall mathematical notation using the symbol
Factorial involves multiplication rather than addition, so we use the product symbol
-
- Here is a Python implementation of factorial using just one function:
+
def factorial(n):
# Check for negative numbers
@@ -54,11 +55,17 @@ 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
+
class MTools:
def factorial(self, n):
@@ -81,14 +88,16 @@ def main():
main()
See if you can spot the differences in the Java version below.
- Here is the equivalent Java code:
+
public class MTools {
public static int factorial(int n) {
@@ -112,6 +121,7 @@ public class MTools {
}
Notice the key differences from Python: instead of
- 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.
class ArrayProcessor:
def sum_array(self, arr, index):
@@ -156,11 +167,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,14 +195,16 @@ 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:
+
class ArrayProcessor:
def sum_array(self, arr):
@@ -223,16 +238,20 @@ def main():
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
+import java.util.Arrays;
+
public class ArrayProcessor {
public static int sumArray(int[] arr) {
// Handle empty array
@@ -261,13 +280,14 @@ public class ArrayProcessor {
}
- Compare these improved versions with the earlier problematic ones. Notice how much cleaner the method calls become:
- 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 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.
- The following Python code demonstrates a situation where a function calls itself indefinitely without a base case, leading to a
+
+
+
def cause_recursion_error():
"""
This function calls itself without a base case, guaranteeing an error.
@@ -315,12 +336,14 @@ public class ArrayProcessor {
cause_recursion_error()
+
- The following Java code demonstrates a similar situation, where a method calls itself indefinitely without a base case, leading to a StackOverflowError .
+ The following Java code in demonstrates a similar situation, where a method calls itself indefinitely without a base case, leading to a StackOverflowError .
-
-
+
+
+
public class Crash {
public static void causeStackOverflow() {
// The line below will start the infinite recursion.
@@ -338,6 +361,7 @@ public class ArrayProcessor {
}
+
diff --git a/source/ch8_filehandling.ptx b/source/ch8_filehandling.ptx
index 19ab18f..d9656b0 100644
--- a/source/ch8_filehandling.ptx
+++ b/source/ch8_filehandling.ptx
@@ -7,79 +7,80 @@
Class Imports
- File handling is an integral part of programming. Most programming languages have the ability to create, read from, write to, and delete, files. In Python, most built-in libraries are available without needing to explicitly import additional packages, but some libraries like math do need to be imported. Consider the following.
+ File handling is an integral part of programming. Most programming languages have the ability to create, read from, write to, and delete, files. In Python, most built-in libraries are available without needing to explicitly import additional packages, but some libraries like math do need to be imported. shows an example of importing the math library in Python.
-
+
+
+
import math
- print(math.sqrt(25))
+ print(math.sqrt(25)) # notice the lower case 'm' in math
+
- Delete the first line that says import math and see what happens. The import math is needed. The same program in Java would look like this:
+ Delete the first line that says import math and see what happens. The import math is needed. The same program in Java would look like .
-
+
+
+
import java.lang.Math;
- public class Main {
+ public class SquareRoot {
public static void main(String[] args) {
- System.out.println(Math.sqrt(25));
+ System.out.println(Math.sqrt(25)); // notice the upper case 'M' in Math
}
}
+
+
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 shown in . This class allows you to create File objects, and use its public methods.
-
-
- 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.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.
+ The Scanner class from the util library will need to be imported if there is any need for a program to read a file as shown in . It should be noted that this library is unnecessary if the program will not be reading any data from a file.
-
-
+
+
import java.util.Scanner;
-
+
+
- The FileWriter class can be used to write to files. In the same way that the Scanner class isn't needed unless the program will read from a file, the FileWriter class isn't needed unless the program will write to a file.
+ The FileWriter class can be used to write to files as shown in . In the same way that the Scanner class isn't needed unless the program will read from a file, the FileWriter class isn't needed unless the program will write to a file.
-
+
+
import java.io.FileWriter;
-
+
+
- Finally, these last two classes provide error handling and must be used in tandem with the File class when reading from or writing to files. IOException handles file creation and writing errors, while FileNotFoundException handles errors when trying to read files.
+ Finally, these last two classes provide error handling and must be used in tandem with the File class when reading from or writing to files as shown in . IOException handles file creation and writing errors, while FileNotFoundException handles errors when trying to read files.
-
+
+
import java.io.IOException;
import java.io.FileNotFoundException;
-
-
+
+
+
@@ -87,24 +88,24 @@
- 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 , and we will call our class CreateFileObject . shows the code to create a File object in Java.
-
-
- 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);
- }
- }
+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");
+ // Next, print the file path (just the filename.)
+ System.out.println(myFile);
+ }
+}
+
@@ -114,14 +115,14 @@
- 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.
- First, lets look at the equivalent Python code:
+ shows the equivalent code to create a file in Python.
-
-
+
+
filename = "newfile.txt"
print("Attempting to write to '" + filename + "' using 'w' mode...")
@@ -135,12 +136,13 @@
+
- Now, let's look at Java code that accomplishes the same task:
+ shows the equivalent code to create a file in Java.
-
-
+
+
import java.io.File;
import java.io.IOException;
@@ -163,12 +165,55 @@
}
+
You may have noticed the use of another method from the File class; getName() . This method returns a string containing the name of the file.
+
+
+
+
+ Construct a short Java program that creates a File object for "myfile.txt"
+ and prints it. Drag the blocks into the correct order on the right.
+
+
+
+
+
+ import java.io.File;
+
+
+ import java.io.Scanner;
+
+
+
+
+ public class CreateFile {
+ public static void main(String[] args) {
+
+
+
+
+ File myFile = new File("myfile.txt");
+
+
+ File myFile = new File();
+
+
+
+
+ System.out.println(myFile);
+
+
+
+ }
+ }
+
+
+
@@ -178,9 +223,11 @@
Let’s take a look at how we can use Python to understand how read file contents in Java. In order to read files generally you iterate through each line in the file and read the line's content. In Java, you read files in a very similar way, however in Java we will use the Scanner class in order to iterate through the lines.
- Consider the following Python code example that reads each line of the file and prints it to the console.
+ Consider that reads each line of and prints it to the console.
-
+
+ Data file for reading example
+
1
2
@@ -192,8 +239,9 @@
8
-
-
+
+
+
filename = "myfile.txt"
try:
@@ -207,34 +255,76 @@
print("file could not be opened")
+
- The following Java code functions very similarly to the previous Python. The main difference here is that unlike Python, In Java we use the Scanner object to iterate through and read lines in the file. You will notice that the structure of the Java code is still similar to the Python; Both use a try and catch statement to read the file and catch any errors.
+ functions very similarly to . The main difference here is that unlike Python, in Java we use the Scanner object to iterate through and read lines in the file. You will notice that the structure of the Java code is still similar to the Python; Both use a try and catch statement to read the file and catch any errors.
-
+
+
import java.io.File;
- import java.io.FileNotFoundException;
- import java.util.Scanner;public class Main {
- public static void main(String[] args) {
+ import java.io.FileNotFoundException; // This import is necessary to handle the exception if the file is not found
+ import java.util.Scanner;
+ public class ReadFile {
+ public static void main (String[] args) {
String filename = "myfile.txt";
- try (Scanner fileReader = new Scanner(new File(filename))) {
- while (fileReader.hasNextLine()) {
+ try (Scanner fileReader = new Scanner(new File(filename))) { // try to open the file and create a Scanner object
+ while (fileReader.hasNextLine()) { // while there is a next line in the file
String data = fileReader.nextLine();
System.out.println(data);
}
}
- catch (FileNotFoundException e) {
+ catch (FileNotFoundException e) { // and catch the exception if the file is not found
System.out.println("Error: The file '" + filename + "' was not found.");
}
}
}
+
You may have noticed that there are some new methods you haven't seen yet. The hasNextLine() method checks if there is a next line in the file, and returns false if there isn't. This method allows us to iterate over every line till there is no next line. The nextLine() method of the Scanner object returns the next line in the file as a string.
+
+
+
+
+ Construct the part of a Java program that opens a file with a Scanner and
+ prints each line until there are no more lines. Drag the blocks into the correct order on the right.
+
+
+
+
+
+ try (Scanner fileReader = new Scanner(new File(filename))) {
+
+
+ try (Scanner fileReader = new Scanner(filename)) {
+
+
+
+
+
+ while (fileReader.hasNextLine()) {
+
+
+ while (fileReader.nextLine()) {
+
+
+
+
+ String data = fileReader.nextLine();
+ System.out.println(data);
+
+
+
+ }
+ }
+
+
+
@@ -245,119 +335,118 @@
- Let us create the framework for a class that will write to a file. Let's call this class WriteFile :
+ shows the framework for a class that will write to a file. Let's call this class WriteFile .
-
-
-
+
+
+
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 :
+ Next, we will create a FileWriter object. Let's call it myWriter . shows the code to create a myWriter object in Python.
+
+
+ with open("myfile.txt", "w") as myWriter:
+
+
-
+
+ shows the Java code to create a FileWriter object. Note that the FileWriter object is created with the name of the file to write to as an argument. If the file does not exist, it will be created. If it does exist, it will be overwritten.:
+
+
+
+
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:
+ In this next step, we will use the write() method from the FileWriter class. This method will take any data within the parenthesis and write that data to the file selected. The write() method takes most standard data types. The shows the code to write to a file in Python.
+
+
+ my_writer.write("File successfully updated!")
+
+
-
+
+ shows the Java equivalent. This is almost completely identical except for the second line, which is very important!
+
+
+
+
myWriter.write("File successfully updated!");
myWriter.close();
-
+
- You may have noticed the
- Next, we will again add the required try/catch blocks utilizing the
- 1 - 2 - 3 --
- 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 = "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:
+ And that's it! We will add our code to the foundational code for a complete program. First,
-
try:
with open("myfile.txt", "w") as my_writer:
@@ -369,16 +458,22 @@
traceback.print_exc()
- The completed Java code:
+
import java.io.FileWriter;
import java.io.IOException;
@@ -386,7 +481,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.");
@@ -396,12 +491,10 @@
}
}
}
-
+ ~
- 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. -
+@@ -410,22 +503,30 @@
- 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
import java.io.FileWriter;
import java.io.IOException;
@@ -433,7 +534,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.");
@@ -445,69 +546,110 @@
}
- Then if we run the program twice, the contents of
+++ 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
+- -+ myWriter.write("File successfully updated!\n"); // Added newline character 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
- 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 as
+++ File successfully updated! File successfully updated! -
- 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.
+ 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.
- 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 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
+ }
+ }
}
+ And finally,
+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
- Consider the following example where we have a method that multiplies a number by two. We can add print statements to help us debug the code:
+ Consider the following example where we have a method that multiplies a number by two. We can add print statements to help us debug the code and verify that the method is being called correctly and returning the expected result as shown below in
// DebugExample.java
@@ -45,8 +46,9 @@
}//End of class
- In the example above,
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. @@ -61,6 +63,7 @@
A common mistake in Java is to forget that every statement must end with a semicolon (
// Histo.java
@@ -75,8 +78,9 @@
}//End of class
- The error "';' expected" on line 7 of
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:
+
import java.util.ArrayList; // Import necessary class
@@ -106,17 +111,69 @@
} // End of class
The 'cannot find symbol' error for the variable
+ Based on
Every variable must be declared with a data type before it is used.
+Correct! Java requires a variable to be declared with its type before it can be assigned or referenced.
+The "cannot find symbol" error happens because
Correct! That error means the compiler reached a variable it has no declaration for.
+Writing
Correct! Declaring
Java lets you use a variable without declaring it first, just like Python.
+Incorrect. Unlike Python, Java requires all variables to be declared before use.
+The error can be fixed by adding an import statement.
+Incorrect. The import is already present; the problem is the missing variable declaration, not a missing import.
+
- In Python, many classes are available by default. However, in Java, you must explicitly import most classes from external packages that you want to use.
+ In Python, many classes are available by default. However, in Java, you must explicitly import most classes from external packages that you want to use
@@ -131,8 +188,9 @@
} // End of class
- You may notice that this error message looks similar to the previous one, however, it has an entirely different cause. In Java, classes like
Unlike Python, where you can create a new object without explicitly using a keyword, Java requires the
// Histo.java // The filename for this example
@@ -158,8 +217,9 @@
} // End of class
- This error message occurs when you forget to use the
Java is a statically typed language, meaning you must specify the type of objects that can be stored in a container like an
// UncheckedWarningDemo.java
@@ -194,6 +256,7 @@
} // End of class
This is a compiler warning, not an error, indicating a potential type safety issue. It occurs because you are calling the