Unit 1: Primitive Types

  • Primitives Example:
  • GPA Calculator

  • Primitive Types

    • Boolean
    • Numeric
      • Character
        • char
      • Integral
        • Integer
          • byte
          • short
          • int
          • long
        • FLoating-point
          • float
          • double
  • Wrapper Classes (Non-Primitive)

    • String, Array, etc.
    • Like an object so has methods
  • Additional W1 Notes:

    • Input
      • Scanner input;
      • input = new Scanner(System.in);
      • System.out.print("Enter an integer: ");
      • input.close();
    • Output
      • System.out.println();

Casting for Division

int num1 = 10;
int num2 = 40; 
// use double to cast the answer to a decimal value since dividing the two integers will result in 0.25
double dividedAnswer = (double) num1 / num2;
System.out.println(dividedAnswer);
0.25

Casting for Truncating and Rounding

int num1 = 10;
int num2 = 40; 
// 0.25 rounds to 0
int answerInt = (int) num1 / num2;
double answerDub = (double) num1 / num2;
System.out.println(answerInt);
System.out.println(answerDub);

int num1 = 60;
int num2 = 40; 
// 1.5 rounds to 1
int answerInt = (int) num1 / num2;
double answerDub = (double) num1 / num2;
System.out.println(answerInt);
System.out.println(answerDub);
0
0.25
1
1.5

Wrapper Classes

  • way to use primitive data types as objects (ex: use Integer instead of int)
  • can now use methods to get info about the object
Integer myInt = 50;
Double myDouble = 50.01;
Character myChar = 'M';
System.out.println(myInt);
System.out.println(myDouble);
System.out.println(myChar);

// can now use methods 
System.out.println(myInt.intValue());

// convert Integer to String and then print length
String myString = myInt.toString();
System.out.println(myString.length());
50
50.01
M
50
2

Concatenation

  • combine strings
  • mixed type concatenation - use +
// concatenation
String word1 = "Hello";
String word2 = "World";
System.out.println(word1 + " " + word2);

//mixed type concatenation 
System.out.println(word1 + " " + word2 + " " + 100);
Hello World
Hello World 100

Unit 2: Using Objects

Math Class

  • methods to perform math tasks on numbers
  • random() returns a random number between 0 (inclusive) and 1
Math.random();
// generates random number from 0 to 100
int randomNumber = (int)(Math.random() * 101);  // 0 to 100
System.out.println(randomNumber);
42

Unit 3: Booleans Expressions and if Statements

Compound Boolean Expressions

  • De Morgan's Law - helps simplify boolean expressions
    • De Morgan's Law says that "the complement of the product of all terms is equal to the sum of the complement of each term" and shows how the NOT (!) operator can be distributed. For example, !(A && B) is the same as !A || !B. !(C > D) is the same as C <= D.
  • !(a&&b)= (!a || !b)
  • Truth tables to visualize Boolean identities

De Morgan's Law

//De Morgan's Law Example

boolean cold = false;
boolean windy = true;

//this first if-else statement checks if both booleans are true and then reverse the result 
if (!(cold && windy)) {
    System.out.println("It is not both cold and windy");
} else {
    System.out.println("The condition is false");
}

//this first if-else statement checks if cold is not true or if windy is not true 
if (!cold || !windy) {
    System.out.println("It is not both cold and windy");
} else {
    System.out.println("The condition is false");
}

// Based on De Morgan's Law, both if-else statements provide the same output
It is not both cold and windy
It is not both cold and windy

Comparing Numbers

  • use == or .equals() to see if two numbers are equivalent
int num1 = 10;
int num2 = 40; 
if (num1 == num2) {
    System.out.println("num1 = num2");
}
else {
    System.out.println("num1 != num2");
}
num1 != num2

Comparing Strings

  • use == or .equals() to see if two strings are equivalent
String string1 = "Hello";
String string2 = "Bob"; 
String string3 = "Jello"; 
if (string1.equals(string2)) {
    System.out.println("string1 = string2");
}
else {
    System.out.println("string1 = string2");
}

if (string1 == string3) {
    System.out.println("string1 = string3");
}
else {
    System.out.println("string1 != string3");
}
string1 = string2
string1 != string3

Comparing Objects

  • use == to see if two obj references are aliases for the same obj or to see if an obj is null
  • use .equals() to see if the attributes of two obj are the same
// GFG Example
class Pet {
    // attributes of class1
    String name;
    int age;
    String breed;
 
    // constructor of class 1
    Pet(String name, int age, String breed)
    {
        // Assignment of current attributes
        /// using this keyword with same
        this.name = name;
        this.age = age;
        this.breed = breed;
    }
}
 


    
 // Objects of class1 (auxiliary class)
 // are assigned value */
Pet dog1 = new Pet("Snow", 3, "German Shepherd");
Pet cat = new Pet("Jack", 2, "Tabby");
Pet dog2 = new Pet("Snow", 3, "German Shepherd");
 
// Checking objects are equal and printing output- true/false
System.out.println("dog1 equals cat is " + dog1.equals(cat));
System.out.println("dog1 equals dog2 is " + dog1.equals(dog2));
System.out.println("dog1 equals dog1 is " + dog1.equals(dog1));
dog1 equals cat is false
dog1 equals dog2 is false
dog1 equals dog1 is true

Unit 4: Iteration

While Loops

  • do something while a condition is true
int x = 5;

// The boolean expression in this case is x > 0
while (x > 0) {
    System.out.println(x);
    x--;
}
  • while loops can be used to iterate over elements
int[] array = {3, 7, 0, 2, 4, 5, 9, 1, 3, 6, 3};
int total = 0;
int i = 0;

while (i < array.length) {
    total += array[i];
    i++; 
}

System.out.println(total);
  • infinite while loops - run over and over permanently since boolean condition true at all times
import java.util.Scanner;

Scanner input = new Scanner(System.in);
String choice;

while (true) {
    System.out.println("Would you like to continue: ");
    choice = input.nextLine();
    if (choice.equals("No")) {
        break;
    }
}

Do-while Loop

  • similar to while loop except that the condition is checked after the statements are executed so do-while loop will execute at least once
//do-while loop example
int i = 5;
		do {
			System.out.println(i);
			i++;
		} while (i <= 10);
5
6
7
8
9
10

For loop

  • loop through a block of code for a certain amount of times
for (int i = 0; i < 5; i++) {
    System.out.println(i);
  }
0
1
2
3
4
  • Nested Loops
    • placing a loop inside another loop
// Outer loop
for (int i = 1; i <= 2; i++) {
    System.out.println("Outer: " + i); // Executes 2 times
    
    // Inner loop
    for (int j = 1; j <= 3; j++) {
      System.out.println(" Inner: " + j); // Executes 6 times (2 * 3)
    }
  }
Outer: 1
 Inner: 1
 Inner: 2
 Inner: 3
Outer: 2
 Inner: 1
 Inner: 2
 Inner: 3

Enhanced for loop or for-each loop

  • used to traverse an array, code more readable/reduces chances of bugs
  • but cannot traverse in reverse order, can't skip any element
//declaring an array  
int arr[]={12,13,14,44};  
//traversing the array with for-each loop  
for(int i:arr){  
  System.out.println(i);  
}
12
13
14
44

Unit 5 Writing Classes

Classes basics

  • Class - blueprint to create objects

    • instance variables/attributes (data)
    • constructors
    • methods
      • accessors/getters
      • mutators/setters
      • main method (tester)
  • naming classes w camelCase, simple and descriptive names

  • Objects are instances of a class
  • Methods are what an object can do
  • public means it can be accessed outside the class
  • private means its restricted to accessing it inside the class
  • Constructors
    • initialize instance variables when an object is created

Code examples

public class Cow {

    // instance variables
    private String cowType;
    private String sound;
    private int numMilkings;

    // constructor
    public Cow (String cowType, String sound){
        this.numMilkings = 0;
        this.cowType = cowType;
        this.sound = sound;
    }

    public String getSound(){
        return sound;
    }
}    

public class CowDriver{
    public static void main(String[] args) {
        Cow myCow = new Cow("holstein", "moo");
        System.out.println(myCow.getSound());
        // myCow.sound = "bark!";
    }
}


CowDriver.main(null);
moo
public class Song
{

  /** Verse - prints out a verse of the song
   * @param number - a String like "one", "two", etc.
   * @param rhyme - a String like "thumb", "shoe", etc.
   */
   public void verse(String number, String rhyme)
   {
     System.out.println("This old man, he played " + number);
     System.out.println("He played knick knack on my " + rhyme);
   }

  // The chorus method
  public void chorus()
  {
     System.out.println("With a knick knack paddy whack, give a dog a bone.");
     System.out.println("This old man came rolling home.");
  }

  public static void main(String args[])
  {
      Song mySong = new Song();
      mySong.verse("one", "thumb");
      mySong.chorus();
      mySong.verse("two", "shoe");
      mySong.chorus();
      mySong.verse("three", "knee");
      mySong.chorus();
      mySong.verse("four", "door");
      mySong.chorus();
  }
}

Song.main(null);
This old man, he played one
He played knick knack on my thumb
With a knick knack paddy whack, give a dog a bone.
This old man came rolling home.
This old man, he played two
He played knick knack on my shoe
With a knick knack paddy whack, give a dog a bone.
This old man came rolling home.
This old man, he played three
He played knick knack on my knee
With a knick knack paddy whack, give a dog a bone.
This old man came rolling home.
This old man, he played four
He played knick knack on my door
With a knick knack paddy whack, give a dog a bone.
This old man came rolling home.

Unit 9 - Inheritance

Constructor

  • special method used to initialize objects
  • called when an object of a class is created
  • can be used to set initial values for object attributes

  • constructor doesn't return a value because it's not directly called by your code

// Create a Main class
public class Main {
    int x;  // Create a class attribute
  
    // Create a class constructor for the Main class
    public Main() {
      x = 5;  // Set the initial value for the class attribute x
    }
  
    public static void main(String[] args) {
      Main myObj = new Main(); // Create an object of class Main (This will call the constructor)
      System.out.println(myObj.x); // Print the value of x
    }
  }
  
  // Outputs 5
  Main.main(null);
5
public class Main {
    int modelYear;
    String modelName;
  
    public Main(int year, String name) {
      modelYear = year;
      modelName = name;
    }
  
    public static void main(String[] args) {
      Main myCar = new Main(1969, "Mustang");
      System.out.println(myCar.modelYear + " " + myCar.modelName);
    }
  }
  
// Outputs 1969 Mustang
Main.main(null);
1969 Mustang

Accessor Methods

  • also called get methods or getters
  • return the value of a private variable, provide access to an object's instance variables
  • gives other classes access to that value stored in that variable without have direct access
  • don't take any parameters
  • have a return type that matches the type of the variable they're accessing
public class CheckingAccount{
    private int balance;
    
    //An accessor method
    public int getBalance(){
      return this.balance;
    }
  }
CheckingAccount.main(null);

Mutator Methods

  • also called setters
  • Sets the value
public class Person {
    private String name; // private = restricted access
  
    // Getter
    public String getName() {
      return name;
    }
  
    // Setter
    public void setName(String newName) {
      this.name = newName;
    }
  }
  • The get method returns the value of the variable name.

  • The set method takes a parameter (newName) and assigns it to the name variable. The this keyword is used to refer to the current object.

  • Since the name variable is declared as private, we can't access it from outside this class:

Static variables, Class variables

  • class variables aka static variables are declared w the static keyword in a a class
  • stored in static memory
  • most declared public
import java.io.*;
public class Employee {

   // salary  variable is a private static variable
   private static double salary;

   // DEPARTMENT is a constant
   public static final String DEPARTMENT = "Development ";

   public static void main(String args[]) {
      salary = 1000;
      System.out.println(DEPARTMENT + "average salary: " + salary);
   }
}
Employee.main(null);
Development average salary: 1000.0

Public, Private, Protected - Access Modifiers

  • Private - accessed only within the class, can't be accessed from outside
  • Protected - within the package and outside the package through child class only
  • Public - access level everywhere
//Public
public class Main {
  public String fname = "John";
  public String lname = "Doe";
  public String email = "john@doe.com";
  public int age = 24;
}
//Public
public class Main {
    private String fname = "John";
    private String lname = "Doe";
    private String email = "john@doe.com";
    private int age = 24;
    
    public static void main(String[] args) {
      Main myObj = new Main();
      System.out.println("Name: " + myObj.fname + " " + myObj.lname);
      System.out.println("Email: " + myObj.email);
      System.out.println("Age: " + myObj.age);
    }
  }
Main.main(null);
Name: John Doe
Email: john@doe.com
Age: 24
//Private
public class Main {
    private String fname = "John";
    private String lname = "Doe";
    private String email = "john@doe.com";
    private int age = 24;
    
    public static void main(String[] args) {
      Main myObj = new Main();
      System.out.println("Name: " + myObj.fname + " " + myObj.lname);
      System.out.println("Email: " + myObj.email);
      System.out.println("Age: " + myObj.age);
    }
  }
  Main.main(null);
Name: John Doe
Email: john@doe.com
Age: 24
// Protected
class Person {
    protected String fname = "John";
    protected String lname = "Doe";
    protected String email = "john@doe.com";
    protected int age = 24;
  }
  
  class Student extends Person {
    private int graduationYear = 2018;
    public static void main(String[] args) {
      Student myObj = new Student();
      System.out.println("Name: " + myObj.fname + " " + myObj.lname);
      System.out.println("Email: " + myObj.email);
      System.out.println("Age: " + myObj.age);
      System.out.println("Graduation Year: " + myObj.graduationYear);
    }
  }
  Main.main(null);
Name: John Doe
Email: john@doe.com
Age: 24

Static methods, class methods

  • methods that belong to the class instead of to an instance of the class
  • accessed through the class name instead of with object
class Student 
{ 
int stdId; 
String stdName; 
static String schoolName = "Del Norte"; 
//The following static method , valueChange to change the value of static variable static void valueChange() 
{ 
schoolName = "Del Norte"; 
} 
//The following constructor is used to initialize the variable 
Student(int id, String name){ 
stdId = id; 
stdName = name; 
} 
//The display method to display values 
void display() 
{ 
System.out.println(stdId+"  "+stdName+"  "+schoolName); 
} 
} 
//The class Demo is used to create and display the values of the object 
public class Demo 
{ 
public static void main(String args[]) 
{ 
Student.valueChange();//calling valueChange method 
//creating objects 
Student StudentObj = new Student(10,"Meena"); 
Student StudentObj1 = new Student(11,"Shraddha"); 
Student StudentObj2 = new Student(11,"Madhumita"); 
//calling display method 
StudentObj.display(); 
StudentObj1.display(); 
StudentObj2.display(); 
} 
}

this keyword

  • refers to the current object in a method or constructor
  • can be used to invoke current class constructor, pass an argument, etc
public class Main {
    int x;
  
    // Constructor with a parameter
    public Main(int x) {
      this.x = x;
    }
  
    // Call the constructor
    public static void main(String[] args) {
      Main myObj = new Main(5);
      System.out.println("Value of x = " + myObj.x);
    }
  }

main method, tester methods

  • main method runs code
  • tester method which is a main method useful to test methods/code

Inheritance, extends

  • extends - extends a class, indicates that a class is inherited from another class
  • subclass (child) - the class that inherits from another class
  • superclass (parent) - the class being inherited from
class Vehicle {
    protected String brand = "Ford";         // Vehicle attribute
    public void honk() {                     // Vehicle method
      System.out.println("Tuut, tuut!");
    }
  }
  
  class Car extends Vehicle {
    private String modelName = "Mustang";    // Car attribute
    public static void main(String[] args) {
  
      // Create a myCar object
      Car myCar = new Car();
  
      // Call the honk() method (from the Vehicle class) on the myCar object
      myCar.honk();
  
      // Display the value of the brand attribute (from the Vehicle class) and the value of the modelName from the Car class
      System.out.println(myCar.brand + " " + myCar.modelName);
    }
  }

Subclass constructor, super Keyword

  • super is used to refer to parent class objects
// Base class vehicle
class Vehicle {
    int maxSpeed = 120;
}
 
// sub class Car extending vehicle
class Car extends Vehicle {
    int maxSpeed = 180;
 
    void display()
    {
        // print maxSpeed of base class (vehicle)
        System.out.println("Maximum Speed: "
                           + super.maxSpeed);
    }
}
 
// Driver Program
class Test {
    public static void main(String[] args)
    {
        Car small = new Car();
        small.display();
    }
}

Overloading a method, same name different parameters and Overriding a method, same signature of a method

  • overloading - btwn methods in same class, same name but diff parameters
  • overriding - btwn superclass and subclass, have the same signature

Abstraction

  • Abstraction is hiding certain info and only show what is necessary to the user
  • An abstract class can't be used to make object directly, another class needs to inherit the parent class in order to access the abstract class
  • An abstract method can only be used in an abstract class and the body of the method is given by the child class
abstract class Fruit {
    public abstract void fruitColor();
}

// This code will not work since Fruit is an abstract class
Fruit apple = new Fruit();
|   Fruit apple = new Fruit();
Fruit is abstract; cannot be instantiated
//Apple class inherits the abstract class Fruit 
class Apple extends Fruit {
    public void fruitColor() {
        System.out.println("I am a red fruit");
    }
}

// This code will work
Apple crunchyApple = new Apple();
crunchyApple.fruitColor();
I am a red fruit

super vs this

  • Both used to make constructor calls
  • super() calls Base class constructor (ex: Parent class)
  • this() calls current class constructor

Unit 10 - Recursion

Recursion

  • A function calls itself
public int add(int myNum) {
    if (myNum > 0) {
        return myNum + add(myNum - 1);
    } else {
        return 0;
    }
}

int result = add(15);
// 15 > 0 --> return 15 + add(14) --> return 15 + (14 + add(13)) --> and 
// so on until return 15 + 14 + 13 + 12 + 11 + 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0
System.out.println(result);
120

toString and hashCode

  • toString returns String rep of object
  • hashCode returns the hash code of a string
//toString
Integer x = 5;

System.out.println(x.toString());  
System.out.println(Integer.toString(12));
5
12
//hashCode
String myStr = "Hello";
System.out.println(myStr.hashCode());
69609650

Late Binding

  • name of the method being called looked up at runtime
  • object assigned to a variable declared to be of Object type

Polymorphism

  • when many class related by inheritance
  • uses the inherited methods to preform different tasks
class Animal {
    public void animalSound() {
      System.out.println("The animal makes a sound");
    }
  }
  
  class Pig extends Animal {
    public void animalSound() {
      System.out.println("The pig says: oink");
    }
  }
  
  class Dog extends Animal {
    public void animalSound() {
      System.out.println("The dog says: bark");
    }
  }

  class Main {
    public static void main(String[] args) {
      Animal myAnimal = new Animal();  // Create a Animal object
      Animal myPig = new Pig();  // Create a Pig object
      Animal myDog = new Dog();  // Create a Dog object
      myAnimal.animalSound();
      myPig.animalSound();
      myDog.animalSound();
    }
  }

Big O Notation

  • language for talking about how long an algorithm takes to run
  • used to compare efficiency of different solutions

Unit 6 Arrays

Arrays Team Lesson

Unit 7 ArrayLists

What are ArrayLists

  • mutable and has object references
  • can change their size dynamically unlinke arrays

  • traverse array lists with loops

  • sort in ascending or descending order

Code Example

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

//add to ArrayList
numbers.add(1);
numbers.add(4);
numbers.add(2);
numbers.add(3);

//hasCode and sorting arrayLists

System.out.println("Before Sorting: "+ numbers + ", the hashcode is " + numbers.hashCode());
Collections.sort(numbers, Collections.reverseOrder());
System.out.println("After Sorting: "+ numbers + ", the hashcode is " + numbers.hashCode());
Collections.swap(numbers, 0, numbers.size()-1);
System.out.println("After Sorting and Swapping first and last numbers: "+ numbers + ", the hashcode is " + numbers.hashCode());
Before Sorting: [1, 4, 2, 3], the hashcode is 957221
After Sorting: [4, 3, 2, 1], the hashcode is 1045631
After Sorting and Swapping first and last numbers: [1, 3, 2, 4], the hashcode is 956261

Unit 8 2D Arrays

  • array of arrays, type of multidimensional array
// initialize array
int[][] numbers;
String[][] names;
char[][] letters;

int[][] numbers1 = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};//method 1:
int[][] numbers2 = new int[4][3]; //method 2: Creates array with four rows and 3 columns

Iteration

  • use a for loop to loop through each element
  • nested loop to print each value by going through row and then column within that row
String[][] alphabet = {{"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "="},
{"q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "[", "]", "\\"},
{"a", "s", "d", "f", "g", "h", "j", "k", "l"},
{"z", "x", "c", "v", "b", "n", "m", ",", ".", "/"}};
for(int i = 0;i<alphabet.length;i++){
    for(int j = 0; j < alphabet[i].length;j++){ //nested for loops
        System.out.print(alphabet[i][j]+" ");
    }
    System.out.println(" ");
}
1 2 3 4 5 6 7 8 9 0 - =  
q w e r t y u i o p [ ] \  
a s d f g h j k l  
z x c v b n m , . /  

Accessing elements

  • use row, column
System.out.println(alphabet[1][2])
e