Unit 1 Primitives

  • Casting: changing one data type to another data type (ie. int to double, char to String)

    • In division, the result will be cast to a float
    • In truncating or rounding, an int will be cast to a float
  • Wrapper Class: a way to use primitive data types as an object (int => Integer, boolean => Boolean)

Wrapper classes can be used to create in ArrayList, which cannot store primitive data types:

ArrayList<Integer> numbers = new ArrayList<Integer>();

Since Wrapper classes can create objects, we can run methods on them:

Integer myInt = 5;

System.out.println(myInt.intValue()); // 5

System.out.println(myInt.toString()); // "5"

System.out.println(myInt.toString().length()); // 1
  • Concatenation: combining two strings to form a new string
String str1 = "Hello";
String str2 = "World!";

System.out.println(str1 + " " + str2); // "Hello World!"

Concatenation also works between mixed types:

int int1 = 1;
String str1 = "Cat";

System.out.println(int1 + " " + str1); // "1 cat"

Unit 2 - Using Objects

Math class:

  • The math class can be used to perform operations on numbers
double x = 25;
double y = 9;

// find max of the numbers
System.out.println(Math.max(x, y));

// find square root
System.out.println(Math.sqrt(x));

// find y to the power of 3
System.out.println(Math.pow(y, 3));

Java can also be used to generate a random double number greater than or equal to 0.0 and less than 1.0. To increase the range, you can multiply the randomly generated number by

// generate a random number between 0 and 10
int random = (int)(Math.random() * 10);

System.out.println(random);

Unit 3: Boolean Expressions and if Statement

Boolean Expressions

  • an expression that evaluates as either true or false
1==1;                    // is true, because 1 will always be equal to 1
"paper" == "good";       // is false, because “paper” is not equal to “good”
  • A complex boolean expression combines multiple boolean expressions by joining them with an and (&&) or or (||) operator.

  • DeMorgan's Laws help us evaluate complex boolean expressions by showing how to deal with the negation of a conditional

    • !true == false
    • !false == true
    • !&& == ||
  • We can use truth tables to organize what a boolean expression will evaluate to.

A B A \ \ B
T T T
T F T
F T T

Unit 4: Iteration and Loops

  • for loop: will iterate over a block of code while a test condition is true
for(int i = 0; i<=5; i++) { // starts variable i at 0, will stop after i is 5
    System.out.println(i); // prints numbers from 0 to 5
}

A for-each loop can be used to iterate over an array. Syntax:

for(datatype item : array) {
    // code
}

Example:

int[] numbers = {0, 1, 2, 3, 5}; // array of integers

int sum = 0; // variable to keep track of sum

for(int number : numbers) {
    sum += number;
}

System.out.println(sum); // will print sum of all ints in array

Say we have a 2d array. We can use a nested loop to access its attributes.

int[][] numbers = {
    {0, 0, 0, 0, 0},
    {1, 1, 1, 1, 1},
};

for(int i = 0; i < numbers.length; i++) { // access each row
    for(int number : numbers[i]) { // access individual elements of row
        System.out.println(number);
    }
}

While Loops: Repeat code while boolean expression evaluates to true.

  • Useful for cases when an infinite loop is needed, such as a menu.
boolean runMenu = true;

while(runMenu) {
    System.out.println("Select an option");
}

Do-While Loop: Similar to a whie loop, but will check the condition after the code has been run, which is the opposite of a while loop

do {
    // code
} while(condition);

Unit 5: Creating Classes

Constructor: Sets initial values of an object. There is no return because it initializes object's properties.

public class Number {
    int x;

    public Number() { //constructor
        x = 5;
    }
}

Number newNumber = new Number(); // create instance of number class using the constructor, no arguments are passed

System.out.println(newNumber.x);
5

Getters and Setters

  • Accessor Methods: Or getters, they return an object's properties. They are non-void an include a return type.
  • Mutator Method: Or setters. Usually a void variable that changes static variables.

Keywords

  • this: refers to instance variables in a class, specific to object instance
  • static: makes a variable or method attached to a class, not an instance of the object. They are not dependent on instance creation.
static void setWheels(int wheels) {
    Car.wheels = wheels; // references class, not object
}

Access Modifiers

  • Default: Can access in same class and package, but not in different packages
  • Public: Can access practically everywhere
  • Protected: Cannot access in non-subclass in different package
  • Private: Can only access in same class

Testing

  • main method: entry point for executing a Java class, can be used as a tester method to verify that object is working as intended
  • toString: will return a string from an object's properties
  • hashCode: returns an integer value generated by a hashing algorithm
public String wheelsToString() {
    return "wheels: " + this.wheels;
}
  • equals: compares two strings, returns true if they are equal

Example:

public class Car {
    private int wheels; // create wheels attribute, cannot be directly modified outside class due to private

    public Car(int wheels) { // initialize number of wheels with constructor
        this.wheels = wheels; // accessing wheel instance variable
    }

    public int getWheels() { // getter, has return type, can be used outside class
        return this.wheels; // return wheels attribute for car
    }

    public void setWheels(int wheels) { // setter, is void and takes an argument, can be used outside class
        this.wheels = wheels;
    }

    public static void main(String[] args) { // static keyword
        Car lambo = new Car(4);
        System.out.println("My lambo has " + lambo.getWheels() + " wheels!"); // using getter and concatenation
    }
}

Car.main(null);
My lambo has 4 wheels!

Polymorphism

  • Inheritance: An object can inherit the characteristics of a parent object (ie. methods, variables). Must use a subclass constructor and the super keyword
public class Lambo extends Car{
    public Lambo() {
        super();
    }
}
  • method overloading: having a method with the same name, but different signatures/paramenters
public int sum(int x, int y) {
    return x+y;
}

public static int sum(int x, int y, int z) {
    return x + y + z;
}
  • late binding: reference a superclass object when creating a new object
Car lambo = new Lambo();
  • abstract class: a restricted class that cannot be used to create objects, but it can be used as a template by inheriting it
  • abstract method: used in an abstract class, body is specified in the subclass

Fibo example:

abstract class Fibo {
    int steps;
    ArrayList<Integer> sequence;
    
    public abstract void generateSequence();

    public void getInput() {
        Scanner input = new Scanner(System.in);
        
        System.out.println("How many terms do you want to generate? (greater than 2)");
        steps = input.nextInt();
        System.out.println(steps);
    }
}
class FiboFor extends Fibo {
    public FiboFor() {
        super();
    }

    public void generateSequence() {
        for(int i = 2; i<steps; i++) {
            sequence.add(sequence.get(i-2) + sequence.get(i-1));
        }
        System.out.println(sequence);
    }

    public static void main(String[] args)  {
        FiboFor myFibo = new FiboFor();
        myFibo.getInput();
        myFibo.generateSequence();
    }
}

Big O Notation

Big O notation describes the complexity of your code algebraically.

(most efficient to least efficient) Hash Map: O(1), Constant Binary Search: O(log n), Logarithmic Single Loop: O(n), Linear Nested Loop: O(n^2), Quadratic