Unit 1 - Primitives

  • Basic data types in Java. Boolean, float, double, and short are just some examples.
  • Primitives are lowercase but non Primitives are uppercase
  • Casting allows you convert one type to a different type
  • You can convert a double or int to a String to display in System.out.println()

2006 FRQ 2a

public double purchasePrice() {
    total = 0;
    total = getListPrice() * (1+ taxRate);

    return total;
}

2006 FRQ 3a

public int compareCustomer(Customer other) {
    int numberCompare = getName().compareTo(other.getName());
    if (numberCompare == 0) {
        return this.getID() - other.getID();
    } else {
        return numberCompare;
    }
}

Unit 2 - Using Objects

  • OOP is an object oriented programming language
  • classes are blueprint
  • objects are an instance of the created class

Goblin Game

public class Goblin {
    private String name;
    private int HP;
    private int DMG;
    private double hitChance;
    private double criticalHitChance;

    public String getName() {
        return name;
    }

    public int getHP() {
        return HP;
    }

    public int getDMG() {
        return DMG;
    }

    public double getHitChance() {
        return hitChance;
    }

    public double getCriticalHitChance(){
        return criticalHitChance;
    }

    public boolean isAlive() {
        if (this.HP > 0) {
            return true;
        } else {
            return false;
        }
    }

    public void setName(String newName) {
        this.name = newName;
    }

    public void setHP(int newHP) {
        this.HP = newHP;
    }

    public void takeDMG(int takenDamage) {
        this.HP -= takenDamage;
    }

    public void setDMG(int newDMG) {
        this.DMG = newDMG;
    }

    public void setHitChance(double newHitChance) {
        this.hitChance = newHitChance;
    }

    public void setCriticalHitChance(double newCriticalHitChance) {
        this.criticalHitChance = newCriticalHitChance;
    }
}
import java.lang.Math;

public class Duel {

    public static void attack(Goblin attackerGoblin, Goblin attackeeGoblin) {

        System.out.println(attackerGoblin.getName() + " attacks " + attackeeGoblin.getName() + "!");
        if (Math.random() < attackerGoblin.getHitChance()) {
            if (Math.random() < attackerGoblin.getCriticalHitChance()){
                attackeeGoblin.takeDMG(2*attackerGoblin.getDMG());
                System.out.println(attackerGoblin.getName() + " lands a critical hit!");
                System.out.println(attackeeGoblin.getName() + " takes " + 2*attackerGoblin.getDMG() + " damage");
            }
            else{
                attackeeGoblin.takeDMG(attackerGoblin.getDMG());
                System.out.println(attackerGoblin.getName() + " hits!");
                System.out.println(attackeeGoblin.getName() + " takes " + attackerGoblin.getDMG() + " damage");
            }   
        } else {
            System.out.println(attackerGoblin.getName() + " misses...");
        }

        System.out.println(attackeeGoblin.getName() + " HP: " + attackeeGoblin.getHP());
        System.out.println();
    }

    public static void fight(Goblin goblin1, Goblin goblin2) {
        while (goblin1.isAlive() && goblin2.isAlive()) {
            
            attack(goblin1, goblin2);

            if (!goblin1.isAlive()) {
                System.out.println(goblin1.getName() + " has perished");
                break;
            }

            attack(goblin2, goblin1);

            if (!goblin2.isAlive()) {
                System.out.println(goblin2.getName() + " has perished");
                break;
            }
        }
    }

    public static void main(String[] args) {
        Goblin goblin1 = new Goblin();
        goblin1.setName("jeffrey");
        goblin1.setHP(12);
        goblin1.setDMG(2);
        goblin1.setHitChance(0.50);
        goblin1.setCriticalHitChance(0.1);

        Goblin goblin2 = new Goblin();
        goblin2.setName("Gunther the great");
        goblin2.setHP(4);
        goblin2.setDMG(1);
        goblin2.setHitChance(1);
        goblin1.setCriticalHitChance(0.5);

        fight(goblin1, goblin2);
    }
}

Duel.main(null);
jeffrey attacks Gunther the great!
jeffrey lands a critical hit!
Gunther the great takes 4 damage
Gunther the great HP: 0

Gunther the great attacks jeffrey!
Gunther the great hits!
jeffrey takes 1 damage
jeffrey HP: 11

Gunther the great has perished

Unit 3 - Boolean expressions

  • If statement is a conditional statement that when true it runs code in the code block
  • If statements have an else condition, where it will run if the code block in the beginning if statement is not True
  • Switch statements can replace a long if/else loop

2009 FRQ 3b

public int getChargeStartTime(int chargeTime) {
    int time = 0;
    for (int i =1; i< 24; i++) {
        if (this.getChargingCost(i, chargeTime) < this.getChargingCost(time, chargeTime)) {
            time =i;
        }
    }

    return time;
}

2017 FRQ 1b

public boolean isStrictlyIncreasing() {
    for (int i =1; i < digitList.size(); i++) {
        if (digitList.get(i-1) < digitList.get(i)) {
            return true;
        } else {
            return false;
        }
    }
}

2019 FRQ 3b

public boolean isBalanced(ArrayList<String> delimiters) {

    int numOpen =0;
    int numClosed = 0
    for (int i =0; i <delimiters.size(); i++) {
        if (delimiters.get(i).equals(openDel)) {
            numOpen++;
        }

        if (delimiters.get(i).equals(closeDel)) {
            numOpen++;
        }
    }

    if (numClosed == numOpen) {
        return true;
    } else {
        return false;
    }

}

Unit 4 - Iteration

  • While Loop
  • For Loop
  • Recursive Loop
  • Used in most FRQ to help solve the overall goal

Part 1

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.JOptionPane;

public class Gui implements ActionListener {
    JFrame frame = new JFrame();
    JPanel panel = new JPanel();
    JButton submitButton = new JButton("Submit");
    JTextField fieldString = new JTextField(20);
    JLabel label = new JLabel();
    int numGuesses = 1;
    boolean numCorrect = false;
    Random rand = new Random();
    int randomNumber = rand.nextInt(100);

    void go() {
        frame.add(panel);
        panel.add(fieldString);
        panel.add(submitButton);
        panel.add(label);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        submitButton.addActionListener(this);
        frame.setSize(new Dimension(500, 500));
        label.setText("Enter a number between 1 and 100");
    }

    public static void main(String[] args) {
        Gui gui = new Gui();
        gui.go();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        int field = Integer.parseInt(fieldString.getText());
        System.out.println(randomNumber);
        System.out.println(field);

        if (numCorrect == false) {
            if (field > randomNumber) {
                JOptionPane.showMessageDialog(null, "Guess too high, try again. Amount of Guesses: " + numGuesses);
                numGuesses += 1;
                fieldString.setText("");
            } else if (field < randomNumber) {
                JOptionPane.showMessageDialog(null, "Guess too low, try again. Amount of Guesses: " + numGuesses);
                numGuesses += 1;
                fieldString.setText("");
            } else if (field == randomNumber) {
                JOptionPane.showMessageDialog(null, "Correct Guess. Amount of Guesses: " + numGuesses);
                numCorrect = true;
                System.exit(0);
            }
        }
    }

}

Gui.main(null);

Part 2

Score

Unit 5 - Writing Classes

  • Object is the instance of a class
  • Class is the overall blueprint of the thing
  • Methods are functions or behaviors that the objects do
  • Constructors initiailize some of the private variables and creates object
  • Some variables might be private so you need getter and setter methods to access and modify the data

2021 1a

public int scoreGuess (String guess) {
    int count = 0;
    for (int i = 0; i <= secret.length() - guess.length(); i++) {
        if (secret.substring(i, i + guess.length()).equals(guess)) {
            count++;
        }
    }

    return count * guess.length() * guess.length();
}

2021 3a

public void addMembers(String[] names, int gradYear ) {
    for( String n : names ) {
        memberList.add(new MemberInfo( n, gradYear, true) );
    }
}

Unit 6 - Arrays

  • ArrayList in java
  • Use a for loop to acces an array
  • bound errors or uninitialized and unfilled arrays are usual errors
  • Enhanced loop to traverse array
  • int[] array = new int[5]; int[] array = [10, 2, 3, 4, 5];
  • CollegeBoard will usually have a for loop and skip iterations and change the value of variable
import java.util.ArrayList;

public class ArrayHW {
    ArrayList<Integer> values = new ArrayList<Integer>();

    public void initialize() {
        for (int i = 0; i < 10; i++) {
            values.add(i);
        }
    }

    public void printEven() {
        for (int i = 0; i < values.size(); i++) {
            if (values.get(i) % 2 == 0) {
                values.set(i, 0);
                System.out.print(values.get(i));
            } else {
                System.out.print(values.get(i));
            }
        }
    }

    public void swap(){
        int lastElement = values.get(values.size()-1);
        values.set(values.size()-1, values.get(0));
        values.set(0, lastElement);
        for (int i = 0; i < values.size(); i++) {
            System.out.print(values.get(i));
        }
    }

    public void print() {
        for (int i = 0; i < values.size(); i++) {
            System.out.print(values.get(i));
        }
    }

    public static void main(String[] args) {
        ArrayHW arrayHW = new ArrayHW();
        System.out.println("Initializing");
        arrayHW.initialize();
        arrayHW.print();
        System.out.println("\nPrinting Even");
        arrayHW.printEven();
        System.out.println("\nSwapping Elements");
        arrayHW.swap();

    }
}
ArrayHW.main(null);
Initializing
0123456789
Printing Even
0103050709
Swapping Elements
9103050700

Unit 7 - Arraylists

  • ArrayList name = new ArrayList();</li>
  • name.add(value)
  • name.remove(value)
  • name.size()
  • Collections.sort(name)
  • You can use iteration to traverse the arraylist and find values
  • </ul> </div> </div> </div>
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Random;
    
    ArrayList<Integer> arr = new ArrayList<>();
    Random rand = new Random();
    for (int i =0; i< 10; i++) {
        int random_int = rand.nextInt(10);
        arr.add(i * random_int);
    }
    
    public void print(ArrayList<Integer> idk) {
        for (int i = 0; i < idk.size(); i++) {
            System.out.print(idk.get(i) + " ");
        }
        System.out.println();
    }
    
    print(arr);
    
    // HashCode DIsply
    System.out.println("Hash map before operation: "+ arr.hashCode());
    Collections.sort(arr);
    System.out.println("Hash map after operation: "+ arr.hashCode());
    
    // Swap first and last element
    int temp = arr.get(0);
    int temp2 = arr.get(arr.size() -1);
    arr.set(0, temp2);
    arr.set(arr.size() - 1, temp);
    System.out.print("Swapped First and Last Element: ");
    print(arr);
    
    // sort in descending order
    Collections.sort(arr, Collections.reverseOrder());
    System.out.print("Sort in Descending: ");
    print(arr);
    
    0 9 0 18 16 30 36 63 24 9 
    Hash map before operation: -1602069450
    Hash map after operation: 876473092
    Swapped First and Last Element: 63 0 9 9 16 18 24 30 36 0 
    Sort in Descending: 63 36 30 24 18 16 9 9 0 0 
    

    Unit 9 - Inheritance

    • Super class: takes attribute from the super class
    • Polymorphism: gives a method a way to be in different forms for each class
    • public class A
    • public class B extends A
    public class Worldcup { //superclass
        int wins = 0;        
        int losses = 0;                   
        boolean cool;
        public Worldcup(int wins, int losses, boolean cool){
            this.wins = wins;
            this.losses = losses;
            this.cool = cool;
        }
    
        public String toString(){
            return "Wins: " + this.wins + ", Losses: " + this.losses + ", Cool?: " + this.cool;
        }
    
      }
    
    public class Argentina extends Worldcup {
        public Argentina(int wins, int losses, boolean cool) {
            super(wins, losses,cool);
        }
    
        public static void main(String[] args) {
            Argentina argobj = new Argentina(3,1,true);
            System.out.println(argobj.toString());
        }
    }
    
    public class Brazil extends Worldcup {
        public Brazil(int wins, int losses, boolean cool) {
            super(wins, losses,cool);
        }
    
        public static void main(String[] args) {
            Argentina argobj = new Argentina(4,2,true);
            System.out.println(argobj.toString());
        }
    }
    
    
    Argentina.main(null);
    Brazil.main(null);
    
    Wins: 3, Losses: 1, Cool?: true
    Wins: 4, Losses: 2, Cool?: true
    
    public class Person {
        private String name;
        private int age;
    
        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        public String getName() {
            return this.name;
        }
    
        public int getAge() {
            return this.age;
        }
    }
    
    public class Student extends Person {
        private String extra;
        public Student(String name, int age, String extra) {
            super(name, age);
            this.extra = extra;
        }
    
        public String getExtra() {
            return this.extra;
        }
    
       @Override
       public String toString(){
          return "Name: " + getName() + ", Age: " + getAge() + ", Extra: " + getExtra();
       }
    }
    
    public class Main{
        public static void main(String[] args){
           Student bro = new Student("bro", 16, "Basketball");
           System.out.println(bro.toString());
           
        }
     }
     
     Main.main(null);
    
    Name: bro, Age: 16, Extra: Basketball
    
    </div>