23 Sep 2024
•
AP CSA
7.7: Ethical issues around Data Collection
Learning Objectives:
- Explaining the risks of privacy from collecting and storing personal data on computer systems.
Essential Knowledge:
- Data Collection: Methods (cookies, tracking, etc.)
- Ethical Data Use: Identifying Personal data (Personal Identifiable Information, Sensitive Personal Information)
- Security Practices: Data Encryption, Data Anonymization, Data Minimization
Privacy Protection mechanisms
- Encryption: Encode data for only authorized users to access.
- Anonymization: Remove personal information from data.
- Data Minimization: Collect only necessary data.
- User Control: Allowing users to control how their data is used
// Example string data
String originalData = "mySecretPassword123";
// Generate a hash code for the string
int hash = originalData.hashCode();
// Display the original data and its hash
System.out.println("Original Data: " + originalData);
System.out.println("Hash Code: " + hash);
// Demonstrate that the same string always produces the same hash
String sameData = "mySecretPassword123";
int sameHash = sameData.hashCode();
System.out.println("Same Data Hash: " + sameHash);
// Demonstrate that a small change in data produces a different hash
String modifiedData = "mySecretPassword124";
int modifiedHash = modifiedData.hashCode();
System.out.println("Modified Data: " + modifiedData);
System.out.println("Modified Data Hash: " + modifiedHash);
Original Data: mySecretPassword123
Hash Code: 1107444891
Same Data Hash: 1107444891
Modified Data: mySecretPassword124
Modified Data Hash: 1107444892
Uses of Hashing
- Hashing is used to store passwords securely but it is not enough for large scale industries.
- Hashing is used to conceal sensitive information like credit card information but not enough to protect it entirely.
Hashing with Salt
As we talked about earlier in the hashing section, hashing is a one-way function. This means that once you hash a value, you can’t get the original value back. This is useful for storing passwords, but it also means that if two users have the same password, they will have the same hash. This is a problem because if an attacker gets access to the hash, they can use a rainbow table to look up the hash and find the original password.
Thus, we use Hasing with Salt which means that even if 2 users have the same password, they will have different hashes because we add a random value to the password before hashing it. This random value is called a salt.
Homework
Homework Problem: Exploring Hashing and Privacy Protection (Extra Credit)
Problem:
Write a Java program that simulates how hashing works in protecting passwords. You will implement the following tasks:
- Task 1: Basic Password Hashing
- Write a program that accepts a user’s password input and generates a hash using the
hashCode()
method.
- Display the original password and the hash to show how the same input always produces the same hash.
- Task 2: Salting the Password
- Enhance the program by generating a random salt for the password. Append the salt to the password before hashing, and display both the salt and the hashed password.
- Store the salt separately and demonstrate that the same password with a different salt produces a different hash.
- Task 3: Verifying the Password
- Write a method that simulates logging in by taking a password and salt as input, hashing them again, and comparing the result to the previously stored hash.
- If the hash matches, display “Login Successful”; otherwise, display “Login Failed.”
- Research and use the
MessageDigest
class in Java to implement password hashing with a more secure algorithm like SHA-256. Modify your program to use this instead of hashCode()
.
import java.util.Scanner;
import java.util.Random;
boolean done = false;
int hash;
String salt = "";
String savedPassword = "";
String savedSalt = "";
Scanner scan = new Scanner(System.in);
Random random = new Random();
while (!done) {
System.out.println("What would you like to do?\nA: Generate Password\nB: Verify Password");
String action = scan.nextLine();
if (action.charAt(0) == 'A') {
System.out.println("Enter Password: ");
String plaintext = scan.nextLine();
StringBuilder saltBuilder = new StringBuilder();
int saltLength = 16;
String saltCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (int i = 0; i < saltLength; i++) {
saltBuilder.append(saltCharacters.charAt(random.nextInt(saltCharacters.length())));
}
salt = saltBuilder.toString();
hash = (salt + plaintext).hashCode();
savedPassword = Integer.toString(hash);
savedSalt = salt;
System.out.println("Hash and salt generated. Salt: " + salt);
} else if (action.charAt(0) == 'B') {
if (savedPassword.isEmpty()) {
System.out.println("No password has been set.");
} else {
System.out.println("Enter Password to Verify: ");
String plaintext = scan.nextLine();
int verifyHash = (savedSalt + plaintext).hashCode();
if (savedPassword.equals(Integer.toString(verifyHash))) {
System.out.println("Login Successful!");
} else {
System.out.println("Login failed.");
}
}
} else {
System.out.println("Action not found.");
}
System.out.println("Would you like to exit? [Y/N]: ");
String response = scan.nextLine();
if (response.charAt(0) == 'Y') {
done = true;
}
}
scan.close();
What would you like to do?
A: Generate Password
B: Verify Password
Action not found.
Would you like to exit? [Y/N]:
What would you like to do?
A: Generate Password
B: Verify Password
Enter Password:
Hash and salt generated. Salt: wrujh6irvSGJlIWG
Would you like to exit? [Y/N]:
What would you like to do?
A: Generate Password
B: Verify Password
Enter Password to Verify:
Login failed.
Would you like to exit? [Y/N]:
What would you like to do?
A: Generate Password
B: Verify Password
Action not found.
Would you like to exit? [Y/N]:
23 Sep 2024
•
AP CSA
7.6 Sorting
Two of the following sorting algorithms will be on the AP exam.(merge sort is discussed in Unit 10)
- Selection sort: Look for the smallest element, swap with first element. Look for the second smallest, swap with second element, etc…
- Insertion sort: Build an increasingly large sorted front portion of array.
All sorting algorithms have…
- comparison-based sorting, which determines order of elements by comparing them to each other. Ways to compare are:
Selection Sort
Process: Orders a list of values by repeatedly putting the smallest or largest unplaced value into its final position.
- Look through the list to find the smallest value.
- Swap it so that it is at index 0.
- Look through the list to find the second-smallest value.
- Swap it so that it is at index 1.
- …
- Repeat until all values are in their proper places.
Visualize this diagram as you go through the code
Code Implementation:
import java.util.ArrayList;
public static void selectionSort(ArrayList<Integer> elements)
{
// outer loop to iterate through every element in the ArrayList
for (int j = 0; j < elements.size() - 1; j++)
{
// set the current value being compared
int minIndex = j;
// INNER LOOP TO ITERATE EVERY ELEMENT AFTER THE minIndex VALUE
for (int k = j + 1; k < elements.size(); k++)
{
// FIND THE SMALLEST ELEMENT IN THE LIST AND SET IT TO THE minINDEX
if (elements.get(k) < elements.get(minIndex))
{
minIndex = k;
}
}
// swap minIndex value with new smaller value
int temp = elements.get(j);
elements.set(j, elements.get(minIndex));
elements.set(minIndex, temp);
}
}
// test cases
ArrayList<Integer> arr1 = new ArrayList<>();
arr1.add(3);
arr1.add(86);
arr1.add(-20);
arr1.add(14);
arr1.add(40);
System.out.println(arr1.toString());
selectionSort(arr1);
System.out.println(arr1.toString());
[3, 86, -20, 14, 40]
[-20, 3, 14, 40, 86]
Insertion Sort
Process: Shift each element into a sorted sub-array.
- To sort a list of n elements.
- Loop through indices i from 1 to n – 1:
- For each value at position i, insert into correct position in the sorted list from index 0 to i – 1.
Visualize this GIF as you go through the code:
Code Implementation:
import java.util.ArrayList;
public static void insertionSort(ArrayList<Integer> elements)
{
// outer loop to iterate through every element in the list
// notice how it starts at 1 because the 0 index is considered "sorted"
for (int j = 1; j < elements.size(); j++) {
// store current element in a temporary variable
int temp = elements.get(j);
// initialize the possible index where the current element might be inserted
int possibleIndex = j;
// shift elements to the right until the correct position for temp is found
while (possibleIndex > 0 && temp < elements.get(possibleIndex - 1))
{
// move previous element to the right
elements.set(possibleIndex, elements.get(possibleIndex - 1));
// decrement index to check values to the left
possibleIndex--;
}
// insert current element into correct position
elements.set(possibleIndex, temp);
}
}
// test cases
ArrayList<Integer> arr1 = new ArrayList<>();
arr1.add(3);
arr1.add(86);
arr1.add(-20);
arr1.add(14);
arr1.add(40);
System.out.println(arr1.toString());
insertionSort(arr1);
System.out.println(arr1.toString());
[3, 86, -20, 14, 40]
[-20, 3, 14, 40, 86]
Helpful Resources
Watch these if you’re still unsure about selection and insertion sort. These helped me a lot.
Homework
- You’re a teacher for a computer science class at Rancho Bernardo. You have a list of all the grades of the students in your class but its hard to see who has the highest and lowest grade. Use either insertion sort or selection sort to sort the ArrayList so the grades are easy to see.
import java.util.ArrayList;
public static ArrayList e(ArrayList<Integer> a) {
for (int b = 1; b < a.size(); b++) {
int c = a.get(b);
int d = b;
while (d > 0 && c < a.get(d - 1)) {
a.set(d, a.get(d - 1));
d--;
}
a.set(d, c);
}
return a;
}
ArrayList<Integer> arr1 = new ArrayList<>();
arr1.add(85);
arr1.add(92);
arr1.add(76);
arr1.add(88);
arr1.add(67);
arr1.add(94);
arr1.add(73);
arr1.add(89);
arr1.add(91);
arr1.add(82);
arr1.add(78);
arr1.add(88);
arr1.add(95);
arr1.add(60);
arr1.add(84);
arr1.add(77);
arr1.add(91);
arr1.add(68);
arr1.add(97);
arr1.add(83);
System.out.println(e(arr1).toString());
[60, 67, 68, 73, 76, 77, 78, 82, 83, 84, 85, 88, 88, 89, 91, 91, 92, 94, 95, 97]
23 Sep 2024
•
AP CSA
Binary and Linear Search
There are two search algorithms you will see on the AP exam:
- Linear Search
- Binary Search
Linear(Sequential) Search

Search Process
- Remember iteration and selection? Its the same for ArrayLists: a for loop with an if statement inside.
- The for loop parameter uses comparison operators to compare an item inside the ArrayList to the desired searched value
- Keep repeating 1 and 2 until we find the desired searched value
Binary Search

Search Process
- Before anything, the ArrayList HAS to be sorted
- Set the initial minimum, middle, and max of the ArrayList. Your target value is the value you want to find
- Check middle value in comparison with the minimum and maximum
- If the middle value is less than the target value, only check the right half of the ArrayList
- If the middle value is greater than the target value, only check the left half of the ArrayList
Yes its very confusing but just look at the GIF
Now lets look at an example of Linear Search
Visualize this while going through the code

- A for loop will go through each index and its corresponding value until it finds the desired value.
Code
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
// missing 3, 6, 7, and 10
numbers.add(1);
numbers.add(2);
numbers.add(4);
numbers.add(5);
numbers.add(8);
numbers.add(9);
Scanner scanNumber = new Scanner(System.in);
System.out.println("Enter a number 1-10");
Integer desiredNumber = scanNumber.nextInt();
for (int index = 0; index < numbers.size(); index++) {
// notice how the == operator is used to compare integers
if (numbers.get(index) == desiredNumber) {
System.out.println(desiredNumber + " is in the list");
scanNumber.close();
} else {
System.out.println(desiredNumber + " is not in the list.");
scanNumber.close();
}
}
}
}
Things to Remember
To remember linear searching, think:
- Iteration and Selection
- Iteration
- Iteration is the process of repeating a step multiple times; In this case, we keep searching for a desired value until it is found
- Selection
- Selection is the process of finding a specific element within a list. We do this using comparison operators
- When comparing
int
values, use the == operator.
- When comparing
Object
values, use the .equals()
method to compare values.
Popcorn Hack #1(0.2 mins)

What does each hop or jump represent? What code(look above) is used to achieve this?
Each hop represents a check of one element.
Code below:
if (numbers.get(index) == desiredNumber) {
System.out.println(desiredNumber + " is in the list");
scanNumber.close();
} else {
System.out.println(desiredNumber + " is not in the list.");
scanNumber.close();
}
Now lets look at an example of Binary Search
Visualize this while going through the code

- Repeatedly divide the search range in half until the target is found or the range is empty
- this is a great GIF to visualize binary searching
Code
import java.util.ArrayList;
import java.util.Collections;
public static int binarySearch(ArrayList<Integer> elements, int target)
{
// min and max is the RANGE of the ArrayList
int min = 0;
int max = elements.size() - 1;
// while loop will ensure the array continues to be split in half until target is found
while (min <= max)
{
// this middle value is the INDEX not VALUE.
int middle = (min + max) / 2;
// now we check if the middle VALUE is less than the number we want.
// *remember* the list is sorted so...
// if middle is less than the target, you want to split the array into the UPPER HALF
// if middle is more than the target, you want to split the array into the LOWER HALF
if (elements.get(middle) < target) { // too low
min = middle + 1;
} else if (elements.get(middle) > target) { // too high
max = middle - 1;
} else if (elements.get(middle) == target) { // just right
return middle;
}
}
return -1;
}
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(-20);
numbers.add(3);
numbers.add(15);
numbers.add(81);
numbers.add(432);
// binary searches HAVE to be sorted
Collections.sort(numbers);
int index = binarySearch(numbers, 15);
System.out.println(index);
index = binarySearch(numbers, -20);
System.out.println(index);
index = binarySearch(numbers, 432);
System.out.println(index);
index = binarySearch(numbers, 53);
System.out.println(index);
Homework
- Imagine you’re an online E-store that sells video games. Use linear searching to help Aidan find if the game, Grand Theft Auto V, is offered in the E-store. If it is, tell him the price. If it isn’t, tell him where he can find it
import java.util.ArrayList;
boolean found = false;
ArrayList<String> videoGames = new ArrayList<String>();
videoGames.add("Roblox");
videoGames.add("Fortnite");
videoGames.add("Valorant");
videoGames.add("Apex Legends");
videoGames.add("GTA V");
for (String videoGame : videoGames) {
// notice how the == operator is used to compare integers
if (videoGame == "GTA V") {
System.out.println("GTA V is offered. It costs 120391203 dollars");
found = true;
}
}
if (!found) {
System.out.println("Not offered. Go away.");
}
GTA V is offered. It costs 120391203 dollars