Unit 1: Primitive Types:
Section 2:
Primitive Activity
Choices:
- int
- double
- boolean
- String
- _3 False
- _4 “ryan gosling”
- _1 1738
- _2 4.26
Questions:
What type of data should be used to store:
- Someones bank number and cvc? int
- Someones mother’s maiden name and their name? string
- The first 16 digits of pi? double
- If you want to transact one million $? integer, assuming it’s exactly one million dollars
Find the Odd One Out
- int value; ✅
- double 4eva; ❌ Variables can’t start with a number.
- boolean private; ❌
private
is already a keyword. - integer sum; ✅
- double wow!; ❌
!
is a special character, you can’t use those in variable names. - boolean foundIt; ✅
- int numberOfStudents; ✅
- double chanceOfRain; ✅
- boolean #mortNews; ❌
#
is a special character, you can’t use those in variable names. - int count; ✅
- bool isFriday; ❌
bool
is not correct,boolean
is. - final int DOZEN; ✅ Note: since it is final, the name is in all caps. This is the convention for Java.
Section 3
// Practice on tracing and predicting output types based on primitive variable types
public class demo {
public static void main(String[] args) {
System.out.println("3" + "3"); // Since it's two strings, the output is "33"
System.out.println(3 / 2); // Since it's two integers, the output is 1.
System.out.println(2.0 * 1.5); // Since its two doubles, the output is 3.0.
}
}
demo.main(null);
33
1
3.0
public class demo2 {
public static void main(String[] args) {
// Print a math equation that goes through these steps
// Adds 19 + 134
// Multiplies that value by 5
// Then takes the mod of that value by 2
// It should print 1
System.out.println( (19 + 134) * 5 % 2);
}
}
demo2.main(null);
1
// Objective: Change the code WITHOUT changing the variables
public class OddEven {
// Without changing any varibles
// Print only odd numbers
public static void main(String[] args) {
int num = 2;
int i = 0;
while (i <= 10) {
if (i % num == 1) { // I replaced 0 with 1. All odd numbers divided by 2 have a remainder of 1.
System.out.println(i + " is odd"); // I replaced "even" with "odd" as extra work to make sense.
}
i++;
}
}
}
OddEven.main(null);
1 is odd
3 is odd
5 is odd
7 is odd
9 is odd
Section 4
// Objective: Practice Compound Operations
public class numbers {
public static void main(String[] args) {
int x = 777;
// challenge: think of 2 compound assignment operators that can be used in tandem to get the following outputs
// example: if we wanted output of 1 with 2 compound assigment operators, using x++; and x /= 777 would work. now how would we do that for:
// 100?
System.out.println((x / 7) - 11);
// 779?
System.out.println(x + 3 - 1);
// 2?
System.out.println((x % 2) + 1);
System.out.println(x);
}
}
numbers.main(null);
100
779
2
777
// Objective: Practice tracing code
public class Demo {
public static void main(String[] args) {
int x = 758; // Defines the variable, x. This is an INTEGER of 758.
x += 423; // Add 423 to 758
x -= 137; // Subtract 137 from (423 + 758)
x *= 99; // Multiply 99 to ((423 + 758) - 137)
x /= 33; // Divide 33 from (((423 + 758) - 137) * 99)
x %= 111; // Finds the remainder from ((((423 + 758) - 137) * 99) / 33)
System.out.println(x); // Prints the result
}
}
Demo.main(null);
24
Mini Hack: Write some java code that uses compound operators and then trace through it similarly to the examples shown in this lesson. Use conditional statements as well, don’t just execute some compound operators on an x value in order and call it a day. You might have to do tracing on the AP test so this is for your own good.
public class CompoundDemonstration {
public static void main(String[] args) {
int x = 3; // Define x
x += 52; // Take the current value of x, add 52 to it, assign that value to x
x -= 24; // Same logic as above line; subtract 24 from the current value of x, assign that to x
x = ((x * 8) / 16); // First multiplies the current value by 8, divides that value by 16, and assigns the final value to x
if (x % 2 == 0) { // Using modulus "% 2" to check if x is an even number
if (x >= 50) { // Check if the final x value is greater than 50
System.out.println(x + " is an even number higher than 50!"); // If it is, print this
}
} else {
System.out.println(x + " is an odd number. We do not care about it."); // If it isn't, print this
}
}
}
CompoundDemonstration.main(null);
15 is an odd number. We do not care about it.
Section 5
Quiz I got 4 out of 4. The answers were 7, 6.25, 1.2, -9
FRQ Hacks
While it was done for us, putting the two pieces of code together isn’t as simple as just copy-pasting. Here is my solution to that. I also demonstrated my skills in code tracing in my answer:
public class Game {
int x = 0; // Moved the declarations here
int y = 0;
boolean XgameWin = false;
boolean YgameWin = false;
public int UpdateScore(int Wscore, int Lscore) {
Wscore += 1;
Lscore -= 1;
if (Wscore == 10) {
Wscore = 0;
Lscore = 0;
}
if (Lscore == 10) {
Wscore = 0;
Lscore = 0;
}
return Wscore;
}
public void gameWinchange(boolean X, boolean Y) {
if (X == true) {
x = UpdateScore(x, y); // Update x and y
XgameWin = true; // Update XgameWin
} else {
y = UpdateScore(y, x); // Update y and x
YgameWin = true; // Update YgameWin
}
System.out.println("XgameWin: " + XgameWin);
System.out.println("YgameWin: " + YgameWin);
}
public static void main(String[] args) {
Game game = new Game(); // Create an instance of Game
game.gameWinchange(true, false); // Call gameWinchange with appropriate arguments
}
}
Game.main(null);
XgameWin: true
YgameWin: false
Takeaways & Grading:
Takeaways
I learned two lessons from this unit through errors I got but solved:
- It is important to make sure that code is being put inside either a main method or another method, and not just in the class. It is not possible to just use primitive types willy-nilly in the class itself. Structure needs to be present.
- It is important to make sure the method and variable names are always matching. In the code above, I didn’t make sure of this. I also tried to access variables outside scope, which is always important to make sure of. During the AP exam, students literally have to write code with their pencil or pen on the FRQ sheets, so going slow and making sure one knows what they’re doing goes a long way.
Grading:
- 1/1 Point for correctly changing the boolean in Part A
- 1/1 Point for using Compound Assigment Operators in Part B
- 1/1 Point for Values reseting when one hits 10 points
- 1/1 Point for Passing Arguments through Part A and B
Unit 2: Using Objects
Section 1
The relationship between classes and objects, in my own words:
- Classes are like blueprints for objects. They define the variables, methods, and constructors for each object that uses the class blueprint. An object, however, is an instance of a class, and isn’t the definition of the class itself. The relationship between them is that an object is an instance of a class, and that an object uses a class as a blueprint, as mentioned.
Section 2
public class Student {
// instance variables
String name;
String teacher;
int period;
// constructor
public Student(String name, String teacher, int period) {
this.name = name;
this.teacher = teacher;
this.period = period;
}
// Identify, using its signature, the correct constructor being called.
// There is only one constructor method. However, I can specify that this class uses parameters to be set
// for each instance. This means that on initialization, the instance must have the parameters, as
// demonstrated in the following main method I created:
public static void main(String[] args) {
Student student = new Student("Paaras", "Mr. Mortensen", 1);
// Student errorStudent = new Student(); This line is commented out as it will cause errors, as
// discussed above.
}
}
Student.main(null);
Section 3
public class MyClass {
// Static method
public static void staticMethod() {
System.out.println("This is a static method.");
}
// Non-static (instance) method
public void nonStaticMethod() {
System.out.println("This is a non-static method.");
}
// Method with void return type
public void methodWithVoidReturnType() {
System.out.println("This method has a void return type.");
}
public static void main(String[] args) {
// Calling the static method
staticMethod();
// Creating an object of MyClass
MyClass myObject = new MyClass();
// Calling the non-static method on the object
myObject.nonStaticMethod();
// Calling the method with void return type
myObject.methodWithVoidReturnType();
}
}
MyClass.main(null);
This is a static method.
This is a non-static method.
This method has a void return type.
Section 5
Which method in this class is a non-void method? Edit the cell below to call the Calculator method.
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
Calculator calculator = new Calculator();
int sum = calculator.add(5, 3);
// Printing the result
System.out.println("Sum: " + sum); // Output: Sum: 8
}
}
The add()
function is a non-void method. It will return an integer.
Section 6
Challenge: Display the background of the quote while displaying the quote in one line: “Give me liberty or give me death!” - Patrick Henry.
System.out.println("This is a famous quote written by Patrick Henry in the Virginia Convention: \n\"Give me liberty or give me death!\"");
// This code works because of the \n syntax. The syntax creates a new line when used.
This is a famous quote written by Patrick Henry in the Virginia Convention:
"Give me liberty or give me death!"
Question: If we have a string, what is its lower bound index and what is its upper bound index, if the string length is equal to the variable ‘str’?
Answer: The lower bound would be 0, unless CollegeBoard still uses a starting index of 1, and the upper bound would be one less than the length of the string, or str - 1
.
Question: What is the error for an out of bound string? Display it in the cell below.
String str = "Hello";
System.out.println(str.substring(0, 1000))
Answer: The error is that 1000 is out of bounds for a string with only five characters, or a length of 5.
FRQ Hacks
Question 1: Create a void method that takes an integer input and adds it to an ArrayList. Then, add a non-void method that is able to call a certain index from the ArrayList.
public class Hack1 {
void addInteger(int input, ArrayList<Integer> arr) {
arr.add(input);
}
int getIndexOfArray(int index, ArrayList<Integer> arr) {
return arr.get(index);
}
public static void main(String[] args) {
ArrayList<Integer> array = new ArrayList<Integer>();
Hack1 instance = new Hack1();
instance.addInteger(3, array);
System.out.println(instance.getIndexOfArray(0, array));
}
}
Hack1.main(null);
3
Question 2: Create a simple guessing game with random numbers in math, except the random number is taken to a random exponent (also includes roots), and the person has to find out what the root and exponent is (with hints!). Use at least one static and one non-static method in your class.
public class ExponentialGuessingGame {
public ArrayList<Integer> generateNumbers() {
int rootMin = 1;
int rootMax = 5;
int rootRange = (rootMax - rootMin) + 1;
int root = (int)(Math.random() * rootRange) + rootMin;
int exponentMin = 2;
int exponentMax = 6;
int exponentRange = (exponentMax - exponentMin) + 1;
int exponent = (int)(Math.random() * exponentRange) + rootMin;
ArrayList<Integer> result = new ArrayList<Integer>();
result.add(root);
result.add(exponent);
return result;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ExponentialGuessingGame instance = new ExponentialGuessingGame();
ArrayList<Integer> answers = instance.generateNumbers();
System.out.println("Guess the root! (Hint: It's between 1 and 5)");
String rootGuess = scanner.nextLine();
System.out.println("You guessed " + rootGuess);
System.out.println("Guess the exponent! (Hint: It's between 2 and 6)");
String exponentGuess = scanner.nextLine();
System.out.println("You guessed " + exponentGuess);
if (Integer.parseInt(rootGuess) == answers.get(0) && Integer.parseInt(exponentGuess) == answers.get(1)) {
System.out.println("You Got It!!!");
} else {
System.out.println("Better luck next time! The answer was " + answers.get(0) + " raised to " + answers.get(1) + ", ");
}
}
}
ExponentialGuessingGame.main(null);
Guess the root! (Hint: It's between 1 and 5)
You guessed 4
Guess the exponent! (Hint: It's between 2 and 6)
You guessed 5
Better luck next time! The answer was 3 raised to 3,
Question 3: Create a class of your choosing that has multiple parameters of different types (int, boolean, String, double) and put 5 data values in that list. Show that you can access the information by givng some samples.
public class MultipleParameters {
public ArrayList<String> returnMultipleParameters(int integer, boolean bool, String str, double decimal) {
ArrayList<String> result = new ArrayList<String>();
result.add(Integer.toString(integer));
result.add(Boolean.toString(bool));
result.add(str);
result.add(Double.toString(decimal));
return result;
}
public static void main(String[] args) {
MultipleParameters instance = new MultipleParameters();
ArrayList<String> result = instance.returnMultipleParameters(4, true, "Hello, World!", 3.14159);
System.out.println(result);
}
}
MultipleParameters.main(null);
[4, true, Hello, World!, 3.14159]
Question 4: Using your preliminary knowlege of loops, use a for loop to iterate through a person’s first and last name, seperated by a space, and create methods to call a person’s first name and a person’s last name by iterating through the string.
public class FindWordAtIndex {
public void findFirstAndLastName(String name, int index) {
String input = name;
int indexToFind = index;
String[] words = input.split(" ");
int startIndex = 0;
int endIndex = -1;
for (String word : words) {
if (startIndex + word.length() > indexToFind) {
endIndex = startIndex + word.length() - 1;
break;
}
startIndex += word.length() + 1;
}
if (endIndex != -1) {
String wordAtIndex = input.substring(startIndex, endIndex + 1);
System.out.println("Word at index " + indexToFind + ": " + wordAtIndex);
} else {
System.out.println("Index out of bounds.");
}
}
public static void main(String[] args) {
FindWordAtIndex instance = new FindWordAtIndex();
instance.findFirstAndLastName("Paaras Purohit", 0);
instance.findFirstAndLastName("Paaras Purohit", 1);
}
}
FindWordAtIndex.main(null);
Word at index 0: Paaras
Word at index 1: Paaras
Unit 3: Boolean Expressions & If Statements
Section 1:
Operators SHOULD NOT be used on String. String comparisons should be done using .equal or .compareTo
- This is because
- In Java, strings should not be compared using the == operator because it checks for reference equality, not content equality.
- When you use == with objects (including strings), it checks if the references to the objects are the same. In other words, it checks if they point to the same location in the memory.
- String literals in Java are stored in a special memory area called the “String Pool”. When you create a string literal, Java checks if a string with the same content already exists in the pool. If it does, it returns a reference to that existing string; if not, it creates a new string.
Section 5:
Nested if-else statements: Nested if-else statements allow for multiple levels of decision-making within a program.
Compound Boolean Expressions:
Compound boolean expressions involve using boolean/conditional operators like && (and)
and || (or)
to combine multiple conditions.
Short-Circuited Evaluation: Short-circuited evaluation is an optimization technique where the second condition in a compound expression is only evaluated if the first condition is true (for &&) or false (for ||).
Coding Practice:
Calculate the final grade based on the following criteria:
- If the student didn’t complete homework, the grade is automatically “F.”
- If the student completed homework and the average of midterm and final exam scores is >= 70, the grade is “Pass.”
- Otherwise, the grade is “Fail.”
import java.util.Scanner;
public class GradeCalculator {
String calculateGrades(int midtermScore, int finalExamScore, String homeworkComplete) {
boolean completion = false;
int sumOfScores = midtermScore + finalExamScore;
int avg = sumOfScores / 2;
if (homeworkComplete == "yes") {
completion = true;
} else {
completion = false;
}
if (completion && avg >= 70) {
return new String("Pass");
}
else {
return new String("Fail");
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print(" Enter your midterm score (0-100): \n");
int midtermScore = scanner.nextInt();
System.out.print(midtermScore);
System.out.print("\n Enter your final exam score (0-100): \n");
int finalExamScore = scanner.nextInt();
System.out.print(finalExamScore);
System.out.print("\n Did you complete the homework (yes/no): \n");
String homeworkComplete = scanner.next().toLowerCase();
System.out.print(homeworkComplete);
GradeCalculator instance = new GradeCalculator();
String grade = instance.calculateGrades(midtermScore, finalExamScore, homeworkComplete);
System.out.println("\n Your final grade is: " + grade);
scanner.close();
}
}
GradeCalculator.main(null)
Enter your midterm score (0-100):
2
Enter your final exam score (0-100):
34
Did you complete the homework (yes/no):
no
Your final grade is: Fail
Section 6
De Morgan’s Law Practice
Negate the following expressions:
1. !(A || B)
= (!A && !B)
2. !(A || B && C) **= (!A && !B |
!C)** |
3. !(A && (B || C)) **(!A |
(!B && !C))** |
FRQ Coding Practice
Create a program that validates a user’s password based on the following criteria:
- The password must be at least 8 characters long.
- The password must contain at least one uppercase letter.
- The password must contain at least one lowercase letter.
- The password must contain at least one digit (0-9).
- The password must contain at least one special character (!, @, #, $, %, ^, &, *).
Write a Java program that prompts the user to enter a password and then checks if it meets the above criteria. If the password meets all the criteria, print “Password is valid.” If not, print a message indicating which criteria the password fails to meet.
import java.util.Scanner;
import java.util.regex.*;
public class PasswordValidator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a password: ");
String password = scanner.nextLine();
System.out.println(password);
scanner.close();
if (isValidPassword(password)) {
System.out.println("Password is valid.");
} else {
System.out.println("Password is invalid. It must meet the following criteria:");
if (password.length() < 8) {
System.out.println("- The password must be at least 8 characters long.");
}
if (!containsUppercaseLetter(password)) {
System.out.println("- The password must contain at least one uppercase letter.");
}
if (!containsLowercaseLetter(password)) {
System.out.println("- The password must contain at least one lowercase letter.");
}
if (!containsDigit(password)) {
System.out.println("- The password must contain at least one digit (0-9).");
}
if (!containsSpecialCharacter(password)) {
System.out.println("- The password must contain at least one special character (!, @, #, $, %, ^, &, *).");
}
}
}
public static boolean isValidPassword(String password) {
return password.length() >= 8
&& containsUppercaseLetter(password)
&& containsLowercaseLetter(password)
&& containsDigit(password)
&& containsSpecialCharacter(password);
}
public static boolean containsUppercaseLetter(String password) {
return Pattern.compile("[A-Z]").matcher(password).find();
}
public static boolean containsLowercaseLetter(String password) {
return Pattern.compile("[a-z]").matcher(password).find();
}
public static boolean containsDigit(String password) {
return Pattern.compile("[0-9]").matcher(password).find();
}
public static boolean containsSpecialCharacter(String password) {
return Pattern.compile("[!@#$%^&*]").matcher(password).find();
}
}
PasswordValidator.main(null);
Enter a password: th!s_IS_aGR8&&Password
Password is valid.
Unit 4: Iteration
Question: What is a loop and what are some real life examples of this (Setting a Song to repeat on your music player)
Answer: An example of a loop is lesson questions. While the number of answers recieved is less than or equal to the limit the group presenting chose, the group will keep taking answers to the question they asked.
Popcorn Hack: Simplify this code:
// Popcorn Hack: Simplify the code segment below
int i = 0;
System.out.println(i);
i++;
System.out.println(i);
i++;
System.out.println(i);
i++;
System.out.println(i);
i++;
System.out.println(i);
i++;
/* Hint:
// while (condition) {
}
for (condition) {
}
*/
// Simplified Code:
int i = 0;
while (i <= 5) {
System.out.println(i);
i++;
}
0
1
2
3
4
5
Question: What’s wrong with this code?
while (true)
{
System.out.print("CONTROL ");
}
// DO NOT RUN THE CODE
Answer: Since the condition inside the while statement is true, the code will run infinitely, which runs the risk of crashing memory.
Question: What will this code block output?
int i = 0;
do
{
System.out.print("Quite shrimple. ");
i++;
}
while (i < -5);
Answer: Since the condition is that i must be less than -5, it won’t run more than it needs to. Since the loop is written in this format, the loop will run the code THEN check the condition, meaning that the code will run only once. Therefore, the output will be “Quite shrimple. “.
Question: How many times will this code print “Doing some code?”
for (int num = 1; num <= 5; num++)
{
System.out.println("Doing some code");
}
Answer: The code will print “Doing some code” five times.
Question: How many times will this code print “Big guy?”
int i = 0;
while (i < 10)
{
System.out.println("Big guy");
i++;
if (i == 5) {
break;
}
}
Answer: This code will print the statement five times. Although the while loop specifies 10 times, the break statement in the loop is set to break the loop when i is equal to 5. Therefore, it only runs five times.
Question: Where are the 3 methods in the code and how do they contribute to the program’s functionality?
public class Compare {
public static void main(String[] args) {
String string1 = "Coding is cool!";
String string2 = "Coding is coding!";
int minLength = Math.min(string1.length(), string2.length());
for (int i = 0; i < minLength; i++) {
String subString1 = string1.substring(0, i + 1);
String subString2 = string2.substring(0, i + 1);
if (subString1.equals(subString2)) {
System.out.println("Common Prefix: " + subString2);
}
}
}
}
Compare.main(null)
Answer:
-
Math.min()
compares two values and returns which value is less, which sets the minimum length for the loop to iterate through. -
String.length()
gets the length of any string. This is the parameter forMath.min()
. -
String.substring()
takes two numbers, a max and a min, and extracts those indices from the string calling the method to make a sub-string. This makes the output how it is.
Question: What does word.length() do and how do we use it above? What Boolean Operator is used?
String word = "supercalifragilisticexpialidocious";
int count = 0;
for (int i = 0; i < word.length(); i++) {
char letter = word.charAt(i);
if (letter == 'a' || letter == 'e' || letter == 'i' || letter == 'o' || letter == 'u') {
count++;
}
}
System.out.println("The Number of vowels in \"" + word + "\" is " + count);
Answer: word.length
is used to tell the loop when to stop. There are two boolean operators used. The first is the <
operator in the loop, and the other is the ==
operator in the conditional, used four times.
Question: Before uncommenting the code, guess what the output will look like:
Question: What will the output of the code above be if we switch the loop headers (the stuff inside of the for loop)?
Question: After making a prediction actually switch the loop headers for yourself. What do you notice about the output compared to the output before the change?
public class NestedLoops{
public static void main(String[] args){
/*
for (int outer = 1; outer < 5; outer++){
for (int inner = 1; inner < 3; inner++){
System.out.print(inner + " ");
}
System.out.println();
}
*/
}
}
NestedLoops.main(null)
1 1 1 1
2 2 2 2
Answer: This nested loop will print “1 2
” four times.
Answer: If you switched the for loops, the output would be “1 1 1 1
” then “2 2 2 2
”.
Answer: I got it right!
Question: How many times will the inner loop execute when outer = 0? 1? 2? In total?
for (int outer = 0; outer < 3; outer++){
for (int inner = 0; inner < 4; inner++){
System.out.println("Test");
}
}
Answer: 4, 4, 4, 12.
Question How many times will the inner loop execute when outer = 5? 4? 3? In total?
for (int outer = 5; outer > 0; outer--){
for (int inner = 0; inner < outer; inner++){
System.out.println("e");
}
}
Answer: 4, 3, 2, 15.
Question: How many times will the statement #1 execute?
int k = 0;
while (k < 5){
int x = (int)(Math.random()*6) + 1;
while (x != 6){
System.out.println("x");
x = (int)(Math.random()*6) + 1;
}
k++;
}
Answer: There is not enough information to determine this. This is because Math.random()
is dictating how long the loop will run, so it could be any value.
Question: How many times will the statements run?
for (int k = 0; k < 135; k++){
if (k % 5 == 0){ // Statement #1
System.out.print(k); // Statement #2
}
}
Answer: 27.
FRQ Hacks
Hack 1: Rewrite a regular for loop using what you’ve learned.
public class RewritingForLoops {
void usingWhileLoop() {
int k = 0;
while (k < 40) {
System.out.println(k);
k += 4;
}
}
void usingDoWhileLoop() {
int k = 0;
do {
System.out.println(k);
k += 4;
} while (k < 40);
}
void usingListLoop() {
int[] iterated = {0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40};
for (int k : iterated) {
System.out.println(k);
}
}
}
Hack 2: Ceaser Cipher Hacks: Try to write a cipher program that shifts each letter in a message 3 letters forward. Use any of the methods you learned today. Use it to decode the 3 messages we’ve given you!
public class CaesarCipher {
public static void main(String[] args) {
String[] letters = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
String message1 = "Kfzb gly!";
String message2 = "zlab zlab zlab";
String message3 = "prmbozxifcoxdfifpqfzbumfxifalzflrp";
String decodedMessage1 = decodeCaesarCipher(message1, 3, letters);
String decodedMessage2 = decodeCaesarCipher(message2, 3, letters);
String decodedMessage3 = decodeCaesarCipher(message3, 3, letters);
System.out.println("Decoded Message 1: " + decodedMessage1);
System.out.println("Decoded Message 2: " + decodedMessage2);
System.out.println("Decoded Message 3: " + decodedMessage3);
}
// Function to decode a Caesar cipher
public static String decodeCaesarCipher(String message, int shift, String[] letters) {
StringBuilder decodedMessage = new StringBuilder();
for (int i = 0; i < message.length(); i++) {
char currentChar = message.charAt(i);
if (Character.isLetter(currentChar)) {
char base = Character.isUpperCase(currentChar) ? 'A' : 'a';
int index = (currentChar - base - shift + 26) % 26;
decodedMessage.append(letters[index]);
} else {
decodedMessage.append(currentChar);
}
}
return decodedMessage.toString();
}
}
CaesarCipher.main(null);
Decoded Message 1: hcwy div!
Decoded Message 2: wixy wixy wixy
Decoded Message 3: mojylwufczluacfcmncwyrjcufcxiwciom
Unit 5: Writing Classes
Popcorn Hacks from Each Section:
Section 1:
Data Encapsulation: This is one of the key components of object oriented programming. It ensures data protection by controlling which parts of a class are accessible to other classes.
Section 2
Constructors are… used to set the initial state of an object.
Alias: Two variables point to the same object.
Section 10
Components of Ethical Implications: Legal issues and intellectual property are big concerns in program creation. Licensing open source software is a big issue, as it dictates how programmers need to comply with terms and how software can be distributed and used.
FRQ Hacks
5.1-5.3: Create a simple to-do list that utilises public and private declaration, constructors, and a mutable array.
public class ToDoList {
private ArrayList<String> toDoList;
public ToDoList(ArrayList<String> toDoList) {
this.toDoList = toDoList;
}
public String addItem(String item) {
toDoList.add(item);
return item;
}
public String removeItem(int index) {
if (index >= 0 && index < toDoList.size()) {
return toDoList.remove(index);
} else {
return "Invalid index";
}
}
public ArrayList<String> displayList() {
return toDoList;
}
}
public class Main {
public static void main(String[] args) {
ToDoList myToDoList = new ToDoList(new ArrayList<String>());
myToDoList.addItem("Do the dishes");
myToDoList.addItem("Do homework");
myToDoList.addItem("Play video games");
myToDoList.removeItem(2);
System.out.println(myToDoList.displayList());
}
}
Main.main(null);
[Do the dishes, Do homework]
5.9-5.10 Hacks: Write a two sentence reflection on the social and ethical implications of programming.
Programming, while just a tool, can be used to bring creations to life that can make a great difference in the world, or divide the world and serve unethical purposes. While there are certainly some who would like to contribute to the digital divide, online phishing and scamming, pirating, and cyber-bullying, the tool of programming can be used by artists, engineers, scientists, or mathematicians to discover, create, and research new things, and help the world become a better place.
Unit 6: Arrays
Section 2:
Standard For Loop: An array in java is indexed from 0 to the number of elements minus one.
Class Discussion-Take Notes, these will count for points in your hacks!
import java.util.Random;
public class RandomArray {
public static void main(String[] args){
int [] list = new int[6];
Random rand = new Random();
// FOR LOOP 1
for (int i = 0; i < list.length; i++){
list[i] = rand.nextInt(4);
}
// FOR LOOP 2
for(int element: list){
System.out.println(element);
}
}
}
RandomArray.main(null);
3
0
0
0
3
3
-
What do the for loops accomplish?
The first for loop accomplishes filling in the array with random numbers. The second for loop accomplishes printing the random numbers in the array.
-
What is the difference between how elements of the array list are accessed?
You can either access an element through an index or through a for loop.
-
BONUS: When the array list of ints was first created, what was each int in the list initialized to?
Zero.
Class Discussion-Take Notes, these will count for points in your hacks!
// EVEN
int[] list = {0, 1, 2, 3, 4, 5};
System.out.println("Even Index");
for(int index = 0; index < list.length; index++){
System.out.println(list[index]);
}
// ODD
int[] list = {0, 1, 2, 3, 4, 5};
System.out.println("Odd Index");
for(int index = 0; index < list.length; index++){
System.out.println(list[index]);
}
-
If I only wanted to access the elements at even indices of the list (0, 2, 4), what could I change in the statement below to accomplish that?
-
What about odd?
Answer: Improved code:
// EVEN
int[] list = {0, 1, 2, 3, 4, 5};
System.out.println("Even Index");
for(int index = 0; index < list.length; index += 2) { // I changed the loop to increment by 2 starting from 0.
System.out.println(list[index]);
}
// ODD
int[] list = {0, 1, 2, 3, 4, 5};
System.out.println("Odd Index");
for(int index = 1; index < list.length; index += 2) { // I changed the loop to increment by 2 starting from 1.
System.out.println(list[index]);
}
Even Index
0
2
4
Odd Index
1
3
5
ATTENTION: MOST COMMON MISTAKE: What is wrong with the for loop and while loop below? Why does this produce an ArrayIndexOutOfBoundsException error?
for(int i = 0; i <= list.length; i ++)
Answer: list.length
is one greater than the numerical length from the indices. To fix this, you would either change <=
to <
, or you would change list.length
to list.length - 1
, but not both.
Average Value: Complete the popcorn hack below in order to return the average value of the elements in the list numbers.
public class ArrayAverage {
public static void main(String[] args) {
int[] numbers = {5, 10, 15, 20, 25};
int sum = 0;
double average;
for (int i = 0; i < numbers.length; i++) {
sum += numbers[i]; // missing code
}
average = (double) sum / numbers.length; // missing code
System.out.println("The average of the numbers is: " + average);
}
}
ArrayAverage.main(null);
The average of the numbers is: 15.0
Section 3:
Popcorn Hack: Rewrite this code to use an enhanced for loop instead. Make comments explaining what you added/changed.
import java.util.List;
class Quote {
private List<String> quotes;
private List<String> emotions;
public Quote(List<String> quotes, List<String> emotions) {
this.quotes = quotes;
this.emotions = emotions;
}
public void printQuotesWithEmotions() {
// Make a change in the code here!
for (int i = 0; i < quotes.size() && i < emotions.size(); i++) {
String quote = quotes.get(i);
String emotion = emotions.get(i);
System.out.println("Quote: \"" + quote + "\"");
System.out.println("Emotion: " + emotion);
System.out.println("---------------------------");
}
}
public static void main(String[] args) {
List<String> quotes = List.of(
"Success is not final, failure is not fatal: It is the courage to continue that counts.",
"The only way to do great work is to love what you do.",
"The best way to predict the future is to create it."
);
List<String> emotions = List.of(
"Courageous",
"Passionate",
"Innovative"
);
Quote quotePrinter = new Quote(quotes, emotions);
quotePrinter.printQuotesWithEmotions();
}
}
Quote.main(null);
Quote: "Success is not final, failure is not fatal: It is the courage to continue that counts."
Emotion: Courageous
---------------------------
Quote: "The only way to do great work is to love what you do."
Emotion: Passionate
---------------------------
Quote: "The best way to predict the future is to create it."
Emotion: Innovative
---------------------------
Answer: Rewritten code:
import java.util.List;
class Quote {
private List<String> quotes;
private List<String> emotions;
public Quote(List<String> quotes, List<String> emotions) {
this.quotes = quotes;
this.emotions = emotions;
}
public void printQuotesWithEmotions() {
int i = 0;
for (String quote : quotes) {
if (i < emotions.size()) {
String emotion = emotions.get(i);
System.out.println("Quote: \"" + quote + "\"");
System.out.println("Emotion: " + emotion);
System.out.println("---------------------------");
i++;
}
}
}
public static void main(String[] args) {
List<String> quotes = List.of(
"Success is not final, failure is not fatal: It is the courage to continue that counts.",
"The only way to do great work is to love what you do.",
"The best way to predict the future is to create it."
);
List<String> emotions = List.of(
"Courageous",
"Passionate",
"Innovative"
);
Quote quotePrinter = new Quote(quotes, emotions);
quotePrinter.printQuotesWithEmotions();
}
}
Quote.main(null);
Quote: "Success is not final, failure is not fatal: It is the courage to continue that counts."
Emotion: Courageous
---------------------------
Quote: "The only way to do great work is to love what you do."
Emotion: Passionate
---------------------------
Quote: "The best way to predict the future is to create it."
Emotion: Innovative
---------------------------
Section 4:
Popcorn hack #1 What needs to be changed to find the index of the max value? (write correct code in cell below)
public class MaximumNumberMethods {
// Original method
private int findMax(double [] values) {
double max = values[0];
for (int index = 1; index < values.length; index++) {
max = values[index];
}
return (double) max;
}
// My improved method
private int findMaxIndex(double[] values) {
double max = values[0];
int maxIndex = 0;
for (int index = 1; index < values.length; index++) {
if (values[index] > max) {
max = values[index];
maxIndex = index;
}
}
return maxIndex;
}
}
Questions:
- Does the order of accumulation matter? Yes, because the each order of accumulation leads to different results. Be careful of what order you’re using to make sure the result you want is achieved.
- Can you declare the variable inside the loop? Yes, but it can’t be called out of scope, which is a common mistake.
Question: What kind of for loop should we use? Why?
int[] numbers = {1, 2, 3, 4, 5};
int[] shifted = new int[numbers.length];
int shift = 8;
for (int index = 0; index < numbers.length; index++) {
shifted[Math.abs((index + shift) % numbers.length)] = numbers[index];
}
numbers = shifted;
for (int num : numbers) {
System.out.print(num + " ");
}
3 4 5 1 2
Answer: Use an enhanced for loop like this:
int[] numbers = {1, 2, 3, 4, 5};
int[] shifted = new int[numbers.length];
int shift = 8;
for (int index = 0; index < numbers.length; index++) {
shifted[Math.abs((index + shift) % numbers.length)] = numbers[index];
}
numbers = shifted;
for (int num : numbers) {
System.out.print(num + " ");
}
3 4 5 1 2
Question: Why are we using the % operator?
Answer: To create a circular shift in the array to shift the numbers.
Question: How would we code a left shift? Write a left shift using the variables below:
String [] words = {"alpha", "beta", "gamma", "delta"};
int shiftWord = 2;
Answer: Here’s the code:
public class LeftShiftArray {
public static void main(String[] args) {
String[] words = {"alpha", "beta", "gamma", "delta"};
int shiftWord = 2;
int length = words.length;
String[] shiftedWords = new String[length];
for (int i = 0; i < length; i++) {
int newIndex = (i - shiftWord + length) % length;
shiftedWords[newIndex] = words[i];
}
for (int i = 0; i < length; i++) {
System.out.print(shiftedWords[i] + " ");
}
}
}
LeftShiftArray.main(null);
gamma delta alpha beta
FRQ Hacks
6.1: Follow the steps in the lesson to just make an array that has some relation to your project. Feel free to use the code examples we provided in your hack if you would like.
Answer Below is the code from my project’s feature that I’m working on, a planet weight simulator. It uses ArrayLists to handle input and output, which returns the weights of the user on the eight planets of our solar system:
import java.util.ArrayList;
public class PlanetWeight {
private final double mercuryGravity = 3.7;
private final double venusGravity = 8.87;
private final double earthGravity = 9.81;
private final double marsGravity = 3.721;
private final double jupiterGravity = 24.79;
private final double saturnGravity = 10.44;
private final double uranusGravity = 8.69;
private final double neptuneGravity = 11.15;
public ArrayList<Double> calculatePlanetWeights(double mass) {
if (mass <= 0) {
throw new IllegalArgumentException("Mass must be positive.");
}
ArrayList<Double> weights = new ArrayList<Double>();
weights.add(mass * mercuryGravity);
weights.add(mass * venusGravity);
weights.add(mass * earthGravity);
weights.add(mass * marsGravity);
weights.add(mass * jupiterGravity);
weights.add(mass * saturnGravity);
weights.add(mass * uranusGravity);
weights.add(mass * neptuneGravity);
return weights;
}
private static String getPlanetName(int index) {
switch (index) {
case 0: return "Mercury";
case 1: return "Venus";
case 2: return "Earth";
case 3: return "Mars";
case 4: return "Jupiter";
case 5: return "Saturn";
case 6: return "Uranus";
case 7: return "Neptune";
default: return "Unknown";
}
}
public ArrayList<String> representWeights(ArrayList<Double> weights) {
ArrayList<String> comparisons = new ArrayList<String>();
for (double i : weights) {
if (i >= 0 && i <= 50) {
comparisons.add("A bag of dog food");
} else if (i > 50 && i <= 100) {
comparisons.add("A standard adult bicycle");
} else if (i > 100 && i <= 150) {
comparisons.add("A large microwave oven");
} else if (i > 150 && i <= 200) {
comparisons.add("A typical adult male");
} else if (i > 200 && i <= 250) {
comparisons.add("A full-sized refrigerator");
} else if (i > 250 && i <= 300) {
comparisons.add("A grand piano");
} else if (i > 300 && i <= 350) {
comparisons.add("A vending machine");
} else if (i > 350 && i <= 400) {
comparisons.add("A small motorcycle");
} else if (i > 400 && i <= 450) {
comparisons.add("A black bear (average weight)");
} else if (i > 450 && i <= 500) {
comparisons.add("A grand piano with additional weight or a full-grown male lion (average weight)");
}
}
return comparisons;
}
}
6.2 FRQ: Prime Numbers in an Array
Create a loop to identify and print the prime numbers from an array of integers. Your loop MUST traverse through the given list. Some things to consider:
BONUS: Do this with a for loop AND a while loop
- Understand prime numbers and how to check for primality.
- Implement a loop and conditional statements to iterate through the array.
- Consider data storage (either displaying prime numbers immediately or storing them for later display)
Answer: Below is my answer:
public class PrimeNumbersForLoop {
public static boolean isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
int[] numbers = {2, 3, 4, 5, 6, 7, 8, 9, 10};
System.out.println("Prime numbers using a for loop:");
for (int num : numbers) {
if (isPrime(num)) {
System.out.println(num);
}
}
}
}
public class PrimeNumbersWhileLoop {
public static boolean isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
int[] numbers = {2, 3, 4, 5, 6, 7, 8, 9, 10};
System.out.println("Prime numbers using a while loop:");
int index = 0;
while (index < numbers.length) {
if (isPrime(numbers[index])) {
System.out.println(numbers[index]);
}
index++;
}
}
}
PrimeNumbersForLoop.main(null);
PrimeNumbersWhileLoop.main(null);
Prime numbers using a for loop:
2
3
5
7
Prime numbers using a while loop:
2
3
5
7
6.2 MCQ:
-
What will be displayed as the output?
String [] list = {"red", "yellow", "blue"}; for (int i = 0; i < list.length; i++) { System.out.print(list[i].length()+ "-" ) }
Answer: C. 3-6-4.
This is because the length in characters of “red” is three, “yellow” is six, and “blue” is four. Since the loop is printing out each elements’ LENGTH, the output will be “3-6-4”.
-
The code below is meant to display every other number in the list numbers. Which of the following should replace the missing code in order to do this?
int [] numbers = {3, -4, 6, -7, 2}; for(/*missing code*/) { System.out.println(numbers[i]); }
Answer: C. int i = 1; i < numbers.length; i+=2
. Since we want to print out every other number, we want to skip the odd numbers. This means that we need to start at index 1 and increment by 2.
-
(This one is a little hard) Which of the following would fix the code so that the elements in arr are reversed. Hint: try creating a list in your head and trace the code to see if the code accomplishes its goal.
public static void reverseArray(double [] arr) { for(int = 0; i< arr.length; i++) { double temp = arr[i]; arr[i] = arr[arr.length-1-i]; arr[arr.length-1-i] = temp; } }
Answer:
B. Change loop condition to: i < arr.length/2
. First off, you can’t writeint = 0
, you need to writeint i = 0
. Second, this is the correct way to ensure that you iterate up to half of the array’s length to perform the necessary swaps and reverse the array elements.
Unit 8: 2D Arrays
Section 1:
Popcorn Hack 1: Declare and initialize a 2D array with 5 rows (arrays) and 4 columns (elements per array) of int data type.
public class TwoDArrayHack1 {
public static void main(String[] args) {
// Declare and initialize a 2D array with 5 rows (arrays) and 4 columns (elements per array) of int data type.
int rows = 5;
int columns = 4;
int[][] arr = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16},
{17, 18, 19, 20}
};
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
TwoDArrayHack1.main(null);
Popcorn Hack 2: Print out Team 17’s, 21’s, and 3’s team info
class NFLTeams {
private String teamName;
private String city;
private int championships;
// Constructor to initialize NFL team data
public NFLTeams(String teamName, String city, int championships) {
this.teamName = teamName;
this.city = city;
this.championships = championships;
}
// Method to display team information
public void displayTeamInfo() {
System.out.println("Team: " + teamName);
System.out.println("City: " + city);
System.out.println("Championships: " + championships);
}
}
public class NFLTeams2DArray {
public static void main(String[] args) {
// Declare a 2D array of NFLTeams to store data for 5 teams and 5 columns
NFLTeams[][] nflArray = {
{new NFLTeams("Team1", "City1", 2), new NFLTeams("Team2", "City2", 3), new NFLTeams("Team3", "City3", 1), new NFLTeams("Team4", "City4", 0), new NFLTeams("Team5", "City5", 5)},
{new NFLTeams("Team6", "City6", 3), new NFLTeams("Team7", "City7", 4), new NFLTeams("Team8", "City8", 0), new NFLTeams("Team9", "City9", 1), new NFLTeams("Team10", "City10", 2)},
{new NFLTeams("Team11", "City11", 1), new NFLTeams("Team12", "City12", 0), new NFLTeams("Team13", "City13", 3), new NFLTeams("Team14", "City14", 2), new NFLTeams("Team15", "City15", 4)},
{new NFLTeams("Team16", "City16", 2), new NFLTeams("Team17", "City17", 4), new NFLTeams("Team18", "City18", 1), new NFLTeams("Team19", "City19", 5), new NFLTeams("Team20", "City20", 3)},
{new NFLTeams("Team21", "City21", 0), new NFLTeams("Team22", "City22", 2), new NFLTeams("Team23", "City23", 5), new NFLTeams("Team24", "City24", 3), new NFLTeams("Team25", "City25", 1)}
};
// Print out Team 17's Team info
nflArray[3][1].displayTeamInfo();
// Print out Team 21's Team Info
nflArray[4][0].displayTeamInfo();
// Print out Team 3's team Info
nflArray[0][2].displayTeamInfo();
}
}
NFLTeams2DArray.main(null)
Team: Team17
City: City17
Championships: 4
Team: Team21
City: City21
Championships: 0
Team: Team3
City: City3
Championships: 1
Popcorn Hack 3: Update the rows and columns according to the comments.
public class Update2DArrayHACK {
// Helper method to print the 2D integer array
public static void printIntArray(int[][] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
// Declare and Initialize a 2D integer array with the same dimensions (5x5)
int[][] integerArray = {
{1, 2, 3, 4, 5},
{6, 7, 8, 9, 10},
{11, 12, 13, 14, 15},
{16, 17, 18, 19, 20},
{21, 22, 23, 24, 25}
};
// Update the element in the first row, first column to 250
integerArray[0][0] = 250;
// Update the element in the third row, third column to 69
integerArray[2][2] = 69;
// Update the element in the fifth row, fifth column to 96
integerArray[4][4] = 96;
// Update the element in the first row, fifth column to 125
integerArray[0][4] = 125;
// Update the element in the second row, third column to 135
integerArray[1][2] = 135;
// Display the updated 2D integer array
printIntArray(integerArray);
}
}
Update2DArrayHACK.main(null)
250 2 3 4 125
6 7 135 9 10
11 12 69 14 15
16 17 18 19 20
21 22 23 24 96
Popcorn Hack 4: Review Quiz
What is a 2D array?
- A single row of elements.
- A data structure with rows and columns.
- A list of 2 elements.
- A binary representation of data.
How do you declare a 2D array in Java?
- int myArray = new int[3][3];
- 2DArray myArray = new 2DArray[3][3];
- int[][] myArray;
- myArray = declare 2D array;
How do you access an element in a 2D array at row 2 and column 3?
- myArray[3][2]
- myArray[2][3]
- myArray[1][2]
- myArray[2][1]
What is the purpose of initializing a 2D array?
- To specify its data type.
- To allocate memory for the array.
- To access its elements.
- To declare the number of rows and columns.
In a 2D array, what does myArray[2][3] represent?
- The element in the second row and third column.
- The element in the third row and second column.
- The element in the third row and third column.
- The element in the second column and third row.
- My answer: The element in the third row in the fourth column.
What happens when you update an element in a 2D array in Java?
- The entire array is cleared.
- Only the updated element is affected.
- The entire row is shifted.
- The element is removed from the array.
Which of the following represents a 2D array with 4 rows and 3 columns in Java?
- int[4][3] myArray;
- myArray[4,3] = int;
- int[3][4] myArray;
- myArray[3][4] = int;
- My answer: int[][] myArray = new int[3][2];
Section 2:
Popcorn Hack 5: Cumulative Knowledge
- What does traverse mean? To iterate through something.
- What is a nested loop A loop inside a loop.
- What is an enhanced for loop A loop specifically designed to loop through an array.
HACK 1: Create a class (for object 2D arrays), and declare and initialize a 2D array. Show updating a 2D array with object functionality
public class TwoDArray {
private int[][] array;
public TwoDArray(int numRows, int numCols) {
array = new int[numRows][numCols];
}
public void initializeArray(int[][] values) {
if (values.length != array.length || values[0].length != array[0].length) {
throw new IllegalArgumentException("Input array dimensions do not match the 2D array dimensions.");
}
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[0].length; j++) {
array[i][j] = values[i][j];
}
}
}
public void updateElement(int row, int col, int value) {
if (row < 0 || row >= array.length || col < 0 || col >= array[0].length) {
throw new IllegalArgumentException("Invalid row or column index.");
}
array[row][col] = value;
}
public void displayArray() {
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[0].length; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
}
}
TwoDArray.main(null);
Initial 2D Array:
1 2 3
4 5 6
7 8 9
Updating an element at (1, 1) to 99:
1 2 3
4 99 6
7 8 9
Practice:
public class TwoDPractice {
public static void main(String[] args) {
int[][] complexIntArray = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
for (int i = 0; i < complexIntArray.length; i++) {
for (int j = 0; j < complexIntArray[i].length; j++) {
System.out.print(complexIntArray[i][j] + " ");
}
System.out.println();
}
}
}
TwoDPractice.main(null);
1 2 3 4
5 6 7 8
9 10 11 12
Popcorn Hack: Row-major order stores and accesses elements of a multi-dimensional array row by row, while column-major order does so column by column in memory.
Practice: Print My AP CS A Class Rocks Using a column major traversal.
public class PrintArray {
public static void printArray(String[][] grid) {
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
System.out.print(grid[i][j] + " ");
}
System.out.println(); // Move to the next row
}
}
public static void main(String[] args) {
String[][] message = {
{"My", "Ap", "Cs", "R"},
{"AP", "A", "Class", "o"},
{"C", "p", " ", "c"},
{"S", " ", " ", "k"},
{"s", " ", "s", "!"},
};
printArray(message);
}
}
PrintArray.main(null);
My Ap Cs R
AP A Class o
C p c
S k
s s !
Main Hack 1: Traverse Through a 2D Array (Row-Major Order)
To traverse through a 2D array using row-major order, you can use two nested loops. Here’s an example:
public class PopcornHacks {
public static void traverse2DArrayRowMajor(int[][] array) {
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println(); // Move to the next row
}
}
public static void main(String[] args) {
int[][] myArray = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
traverse2DArrayRowMajor(myArray);
}
}
Main Hack 2: Traverse Through a 2D Array (Column-Major Order)
To traverse through a 2D array using column-major order, you need to use two nested loops with the inner loop iterating through columns. Here’s an example:
public class PopcornHacks {
public static void traverse2DArrayColumnMajor(int[][] array) {
for (int j = 0; j < array[0].length; j++) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i][j] + " ");
}
System.out.println(); // Move to the next column
}
}
public static void main(String[] args) {
int[][] myArray = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
traverse2DArrayColumnMajor(myArray);
}
}
Main Hack 3: Custom Algorithm to Traverse a 2D Array
You can create your own situation where you need to traverse a 2D array and write code for it. Here’s an example where we calculate the sum of all elements in a 2D array:
public class PopcornHacks {
public static int sum2DArray(int[][] array) {
int sum = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
sum += array[i][j];
}
}
return sum;
}
public static void main(String[] args) {
int[][] myArray = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int totalSum = sum2DArray(myArray);
System.out.println("Total sum of elements: " + totalSum);
}
}
Extra Problem: Finding Maximum Value in a 2D Array
Here’s an extra problem where you find the maximum value in a 2D array:
public class PopcornHacks {
public static int findMaxValue(int[][] array) {
int max = Integer.MIN_VALUE;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
if (array[i][j] > max) {
max = array[i][j];
}
}
}
return max;
}
public static void main(String[] args) {
int[][] myArray = {
{10, 23, 5},
{7, 8, 14},
{3, 12, 9}
};
int maxValue = findMaxValue(myArray);
System.out.println("Maximum value: " + maxValue);
}
}
This code calculates and prints the maximum value in the 2D array.
Image Hack:
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class FunnyImageConversion {
public static void main(String[] args) {
try {
// Load the PNG image
File pngFile = new File("laughing.png");
BufferedImage bufferedImage = ImageIO.read(pngFile);
// Save the image as a JPEG (funny conversion)
File jpegFile = new File("laughing.jpg");
ImageIO.write(bufferedImage, "jpg", jpegFile);
System.out.println("Conversion complete. Check out the funny JPEG image!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
FunnyImageConversion.main(null);
Unit 9: Inheritance
Section 1
In this example, the Son and Daughter inherits the Mom, meaning it inherit the components of the mother. This makes the “Son” and “Daughter” classes the __sub-classes__ of the “Mom” class as they inherit the “Mom” class components and the “Mom” class the __parent class__.
Section 2
Popcorn Hack: Make it so that a new instance of Bob runs.
public class Worker {
String Name;
int Age;
double Salary;
public Worker(String name, int age, double salary) {
this.Name = name;
this.Age = age;
this.Salary = salary;
}
public void Information() {
System.out.println(this.Name);
System.out.println(this.Age);
System.out.println(this.Salary);
}
}
public class Bob extends Worker {
String Position;
public Bob(String name, int age, double salary, String position) {
super(name, age, salary);
this.Position = position;
}
public void Information() {
super.Information();
System.out.println(this.Position);
}
}
public class Test {
public static void main(String[] args) {
Bob bob = new Bob("Paaras", 16, 16.67, "Coach");
bob.Information();
}
}
Test.main(null);
Paaras
16
16.67
Coach
Section 3
Popcorn Hack: Why is it helpful to have a common base class like ‘Athlete’ for all these different types of athletes? How does it make the code more organized?
The whole point of coding is to make things simpler. Why rewrite methods and variables for classes that have things in common, making things disorganized and long? Hence the whole reason for base classes, inheritance, one of the pillars of object-oriented programming.
Section 4
9.4 Hack: Finish up the code with this criteria: All subclasses must say their origin, the origin can be from SchoolSupply class, and it must run through main.
class SchoolSupply {
public String BasicInfo(){
return "School Supply";
}
}
class Pencil extends SchoolSupply{
public void Information(){
System.out.println("This inherits the "+super.BasicInfo()+" class");
}
}
class Eraser extends SchoolSupply{
public void Information(){
System.out.println("This inherits the "+super.BasicInfo()+" class");
}
}
public class Test{
public static void main(String[] args){
Pencil pencil = new Pencil();
Eraser eraser = new Eraser();
pencil.Information();
eraser.Information();
}
}
Test.main(null);
This inherits the School Supply class
This inherits the School Supply class
Section 5
Inheritance can be thought as an upside down tree with the fruit on the top and the branches on the bottom. The fruit is the superclass while the other fruits/branches are the subclasses of this superclass. A visual representation of this tree is called a type diagram or hierarchy tree.
Popcorn Hack: Draw a hierarchy tree for the structure:
public class A
public class B extends A
public class C extends B
public class D extends C
public class E extends I
public class F extends I
public class G extends H
public class H extends A
public class I extends H
Answer:
A
B H
C G I
D E F
A reference variable is polymorphic when it can refer to objects from different classes at different points in time. A reference variable can store a reference to its declared class or any subclass of its declared class.
A method or operator is considered polymorphic when they are overridden in at least one subclass.
Polymorphism is the act of executing an overridden non-final method from the correct class at runtime based on the actual object type.
Polymorphism allows dynamic dispatch for a method call to be executed based on the class of the object referenced instead of the declared class.
Java polymorphism is mainly split into 2 types:
- Runtime Polymorphism (Dynamic Polymorphism):
- Process in which a function call to the overridden method is resolved at Runtime. This type of polymorphism is achieved by Method Overriding.
- Compile-time Polymorphism (Static Polymorphism):
- Also known as static polymorphism. This type is achieved by function overloading or operator overloading.
- Note: Java doesn’t support Operator Overloading.
- When there are multiple functions with the same name but different parameters, then these functions are said to be overloaded. Functions can be overloaded by changes in the number of arguments and/or a change in the type of arguments.
Here is an example of compile-time polymorphism:
In this example, the add
method is overloaded with different parameter types (int and double), and the appropriate version of the method is called based on the argument types at compile-time. This is compile-time polymorphism.
Popcorn Hack:
In the provided code, you have a class hierarchy with Entertainer
as the base class and Comedian
as a subclass. Comedian
inherits from Entertainer
. Let’s go through the code step by step:
- First, you create an
Entertainer
object namedkevin
and print out his talent:Entertainer kevin = new Entertainer("Musician"); System.out.println(kevin.getTalent());
This code will run without any issues, and it will print “Musician” because
kevin
is anEntertainer
object, and thegetTalent
method is called from theEntertainer
class. - Then, you create an
ArrayList
calledoneLiners
to store jokes. However, you haven’t shown how you add jokes to theoneLiners
list. To add jokes, you should use theadd
method, for example:oneLiners.add("Why did the programmer quit his job?"); oneLiners.add("Why did the developer go broke?");
- Next, you create a
Comedian
object namedsoham
and print out his talent and tell a joke:Entertainer soham = new Comedian("satire", oneLiners); System.out.println(soham.getTalent()); System.out.println(((Comedian)soham).tellJoke());
This code will also run.
soham
is initially created as aComedian
object and then assigned to anEntertainer
reference. ThegetTalent
method is overridden in theComedian
class to provide the comedy style along with the talent from theEntertainer
class. ThetellJoke
method is called after castingsoham
back to aComedian
, and it will work becausesoham
is actually aComedian
.
So, both parts of the code will run, assuming you properly add jokes to the oneLiners
list.
Section 7
The Object class is the superclass of all other classes as well as arrays and other data types. The Object class is part of the java.lang
package.
When we call a constructor for a “top-level class” that the coder hasn’t declared a superclass for, the Object constructor is implicitly called. In other words, the Object constructor is implicitly called when we call a constructor in a class that doesn’t explicitly extend another class. This will give the object some properties and methods that are common to all classes.
MCQ:
- The car will be successfully assigned to the reference variable
vehicle
of typeVehicle
. B c = new C();
- The objects of Class G can be treated as objects of Class J and Class H.
- C is a subclass of B.
- The Bird object will be successfully assigned to the reference variable
penguin
of typePenguin
. - All of the above.
- Inheritance.
- H and G have no relationship.
- The root is the superclass, and the branches are the subclasses.
- The object will be successfully assigned to the reference variable.
FRQ:
Banking System Inheritance and Polymorphism
You are tasked with implementing a banking system with multiple account types and transactions. Create a Java program that models this system using inheritance and polymorphism. The system should have three types of accounts: SavingsAccount
, CheckingAccount
, and CreditCardAccount
. Each account type should have different features and methods. Your task is to implement the classes, create instances of each account type, and perform transactions.
Part 1: Class Definitions (15 points)
Define the three classes: SavingsAccount
, CheckingAccount
, and CreditCardAccount
. Each class should have the following characteristics:
SavingsAccount
:- An annual interest rate (e.g., 3%).
- A balance.
- Methods for depositing and withdrawing funds.
CheckingAccount
:- A balance.
- Methods for depositing and withdrawing funds.
CreditCardAccount
:- A credit limit (e.g., $5000).
- A balance.
- Methods for making purchases and payments.
Part 2: Transaction Processing (20 points)
Write a program that demonstrates the use of these classes. Create instances of each account type, and perform the following transactions:
- Deposit $1000 into a
SavingsAccount
. - Withdraw $500 from a
CheckingAccount
. - Make a purchase of $300 on a
CreditCardAccount
. - Make a payment of $100 on the same
CreditCardAccount
.
Part 3: Polymorphic Operations (15 points)
Use polymorphism to create an array of type Account
to store instances of all three account types. Write a loop to process transactions on each account in the array, including deposits, withdrawals, purchases, and payments. Ensure that each account’s specific behavior is correctly invoked.
Scoring Guidelines:
- Part 1 (Class Definitions):
- 5 points for each correctly implemented class (15 points in total).
- 0 points for incorrect or missing class definitions.
- Part 2 (Transaction Processing):
- 5 points for each correctly performed transaction (20 points in total).
- 0 points for incorrect transactions or missing transactions.
- Part 3 (Polymorphic Operations):
- 5 points for correct usage of polymorphism and processing of transactions on each account type (15 points in total).
- 0 points for incorrect usage of polymorphism or incorrect transaction processing.
Sample Solution:
You can create the classes, implement transaction processing, and use polymorphism to process transactions. Below is a simplified sample solution:
class Account {
double balance;
public Account(double balance) {
this.balance = balance;
}
public void deposit(double amount) {
balance += amount;
}
public void withdraw(double amount) {
balance -= amount;
}
}
class SavingsAccount extends Account {
double annualInterestRate;
public SavingsAccount(double balance, double annualInterestRate) {
super(balance);
this.annualInterestRate = annualInterestRate;
}
}
class CheckingAccount extends Account {
public CheckingAccount(double balance) {
super(balance);
}
}
class CreditCardAccount extends Account {
double creditLimit;
public CreditCardAccount(double balance, double creditLimit) {
super(balance);
this.creditLimit = creditLimit;
}
public void purchase(double amount) {
balance += amount;
}
public void makePayment(double amount) {
balance -= amount;
}
}
public class BankingSystem {
public static void main(String[] args) {
SavingsAccount savingsAccount = new SavingsAccount(1000, 0.03);
CheckingAccount checkingAccount = new CheckingAccount(500);
CreditCardAccount creditCardAccount = new CreditCardAccount(0, 5000);
savingsAccount.deposit(1000);
checkingAccount.withdraw(500);
creditCardAccount.purchase(300);
creditCardAccount.makePayment(100);
Account[] accounts = {savingsAccount, checkingAccount, creditCardAccount};
for (Account account : accounts) {
if (account instanceof SavingsAccount) {
SavingsAccount sa = (SavingsAccount) account;
sa.deposit(100); // Add interest for savings account
} else if (account instanceof CheckingAccount) {
CheckingAccount ca = (CheckingAccount) account;
ca.withdraw(50); // Simulate a check payment
} else if (account instanceof CreditCardAccount) {
CreditCardAccount cca = (CreditCardAccount) account;
cca.makePayment(50); // Make a credit card payment
}
System.out.println("Balance: " + account.balance);
}
}
}
Extra Credit Challenge:
Make an example that uses Java inheritance and polymorphism and it must run through the main and use input and output. Points will be awarded for complexity and creativity.
import java.util.Scanner;
class Animal {
protected String name;
public Animal(String name) {
this.name = name;
}
public void speak() {
System.out.println(name + " makes a sound.");
}
}
class Dog extends Animal {
public Dog(String name) {
super(name);
}
@Override
public void speak() {
System.out.println(name + " barks: Woof! Woof!");
}
}
class Cat extends Animal {
public Cat(String name) {
super(name);
}
@Override
public void speak() {
System.out.println(name + " meows: Meow! Meow!");
}
}
class Duck extends Animal {
public Duck(String name) {
super(name);
}
@Override
public void speak() {
System.out.println(name + " quacks: Quack! Quack!");
}
}
public class AnimalPolymorphismExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to the Animal World!");
System.out.print("Enter the name of your dog: ");
String dogName = scanner.nextLine();
Dog myDog = new Dog(dogName);
System.out.print("Enter the name of your cat: ");
String catName = scanner.nextLine();
Cat myCat = new Cat(catName);
System.out.print("Enter the name of your duck: ");
String duckName = scanner.nextLine();
Duck myDuck = new Duck(duckName);
System.out.println("\nLet's hear your animals speak!\n");
Animal[] animals = {myDog, myCat, myDuck};
for (Animal animal : animals) {
animal.speak();
}
System.out.println("\nThank you for introducing your animals!");
}
}
AnimalPolymorphismExample.main(null);
Welcome to the Animal World!
Enter the name of your dog: Enter the name of your cat: Enter the name of your duck:
Let's hear your animals speak!
Paaras Mandar Vikas Dnyaneshwar Varaprasad Venketa Nibhanupudi Chinmay Diwakar Ramamurthy Purohit barks: Woof! Woof!
Kevin Du meows: Meow! Meow!
bob quacks: Quack! Quack!
Thank you for introducing your animals!
Unit 10: Recursion
Popcorn Hack: What would be the output of the code below? (0.01 extra credit)
public static void simpleRecur(int n)
{
System.out.println(n);
if (n > 2)
simpleRecur(n+3);
System.out.println(n);
}
simpleRecur(10);
Assuming N is initially greater than 2, the output will print every multiple of 3 starting from the number (e.g. 3, 6, 9, 12…) infinitely, because it will always trigger true.
Popcorn Hack: Edit the following code so that running the cell will sort through an array of your creation.
Answer: Below:
import java.util.Arrays; // Import the Arrays class for sorting
public class RecursionBinaryExample {
public static int recBinarySearch(int[] intArray, int lowPosition, int highPosition, int target) {
int midPosition;
// Check if the lower index is greater than the higher index, indicating an empty search range.
if (lowPosition > highPosition) {
// If the low index is greater than the high index, the target element is not found.
return -1;
} else {
// Calculate the middle index of the current search range.
midPosition = (lowPosition + highPosition) / 2;
// If the element at the middle index is less than the target, search in the right half of the array.
if (intArray[midPosition] < target) {
// Recursively call the function with an updated search range (right half).
return recBinarySearch(intArray, midPosition + 1, highPosition, target);
}
// If the element at the middle index is greater than the target, search in the left half of the array.
if (intArray[midPosition] > target) {
// Recursively call the function with an updated search range (left half).
return recBinarySearch(intArray, lowPosition, midPosition - 1, target);
}
// If the element at the middle index is equal to the target, we found the target element.
// Return the index where the target element is found (midPosition).
return midPosition;
}
}
public static void main(String[] args) {
int[] intArray = {9, 3, 6, 1, 8, 2, 7, 5, 4}; // Create an unsorted array
// Sort the array using Arrays.sort
Arrays.sort(intArray);
int target = 5; // The element you want to find in the array
int lowPosition = 0; // The lowest index in the array
int highPosition = intArray.length - 1; // The highest index in the array
int result = recBinarySearch(intArray, lowPosition, highPosition, target);
if (result != -1) {
System.out.println("Element found at index: " + result);
} else {
System.out.println("Element not found in the array.");
}
}
}
RecursionBinaryExample.main(null);
Element found at index: 4
Hack Question: What are the usage cases of merge sort? What about usage cases of recursive binary sort? Try and come up with a real life scenario for each usage case.
Answer:
Merge Sort and Recursive Binary Search are both algorithms used in a variety of scenarios for different purposes. Here are some common usage cases and real-life scenarios for each:
Merge Sort:
-
Sorting Large Datasets: Merge Sort is an efficient, stable, and comparison-based sorting algorithm. It’s often used to sort large datasets, such as lists of names, product prices, or any other dataset that needs to be organized in a specific order.
Real-Life Scenario: E-commerce websites use Merge Sort to sort and display products by price or relevance, making it easier for customers to find what they are looking for.
-
External Sorting: Merge Sort is suitable for external sorting, where data doesn’t fit entirely into memory. It’s commonly used in databases and file systems to sort large data files efficiently.
Real-Life Scenario: When a database needs to sort a massive amount of data that can’t fit in memory, Merge Sort is used to sort the data on disk.
-
Parallel Processing: Merge Sort can be efficiently parallelized, making it a good choice for sorting when multiple processors or cores are available.
Real-Life Scenario: High-performance computing clusters use Merge Sort for sorting large datasets in parallel, reducing the time required for sorting.
Recursive Binary Search:
-
Searching in Sorted Data: Recursive Binary Search is used to search for a specific element in a sorted collection, like an array. It’s a faster alternative to linear search for large datasets.
Real-Life Scenario: A library’s book catalog uses Recursive Binary Search to help users find books by their titles or authors in an efficiently organized manner.
-
Information Retrieval: In information retrieval systems, such as search engines or databases, Recursive Binary Search is used to quickly locate documents or records that match a query.
Real-Life Scenario: A search engine like Google uses a variant of Binary Search to find relevant web pages quickly in response to user queries.
-
Maintaining a Sorted Data Structure: When working with data structures like balanced binary search trees (e.g., AVL trees or Red-Black trees), Recursive Binary Search is essential for inserting, deleting, or searching for elements efficiently.
Real-Life Scenario: A dictionary or phone book application uses Recursive Binary Search to insert, update, and search for entries while keeping them sorted by name.
In summary, Merge Sort is primarily used for sorting large datasets and is not limited to searching. Recursive Binary Search, on the other hand, is specifically designed for searching in sorted data and maintaining sorted data structures. The choice between them depends on the specific problem and the operations required in your application.
Popcorn Hack: What is the shape of the graph going to look like when the recursive function is done? The equation would be linear.
%maven org.knowm.xchart:xchart:3.5.2
import org.knowm.xchart.*;
public class StarShapeGraph {
public static void main(String[] args) throws Exception {
int numPoints = 100;
double[] xData = new double[numPoints];
double[] yData = new double[numPoints];
plotStarShape(xData, yData, 0, 0, numPoints - 1);
// Create Chart
XYChart chart = QuickChart.getChart("Star Shape", "X", "Y", "y(x)", xData, yData);
// Show it
new SwingWrapper(chart).displayChart();
}
private static void plotStarShape(double[] xData, double[] yData, int index, double t, int maxIndex) {
if (index > maxIndex) {
return;
}
// Calculate star shape using trigonometric equations
double r = Math.cos(5 * t) + 1.5;
xData[index] = r * Math.cos(t);
yData[index] = r * Math.sin(t);
plotStarShape(xData, yData, index + 1, t + (2 * Math.PI) / maxIndex, maxIndex);
}
}
StarShapeGraph.main(null);