Collegeboard Unit Lessons
Unit Lesson Notes from Class Presentations
- Unit 1: Primitive Types
- Unit 2: Using Objects
- Unit 3: Booleans Expressions and if Statements
- Unit 4: Iteration
- Unit 5 Writing Classes
- Unit 9 - Inheritance
- Constructor
- Accessor Methods
- Mutator Methods
- Static variables, Class variables
- Public, Private, Protected - Access Modifiers
- Static methods, class methods
- this keyword
- main method, tester methods
- Inheritance, extends
- Subclass constructor, super Keyword
- Overloading a method, same name different parameters and Overriding a method, same signature of a method
- Abstraction
- super vs this
- Unit 10 - Recursion
- Unit 6 Arrays
- Unit 7 ArrayLists
- Unit 8 2D Arrays
Unit 1: Primitive Types
- Primitives Example:
-
Primitive Types
- Boolean
- Numeric
- Character
- char
- Integral
- Integer
- byte
- short
- int
- long
- FLoating-point
- float
- double
- Integer
- Character
-
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();
- Input
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);
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);
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());
// concatenation
String word1 = "Hello";
String word2 = "World";
System.out.println(word1 + " " + word2);
//mixed type concatenation
System.out.println(word1 + " " + word2 + " " + 100);
Math.random();
// generates random number from 0 to 100
int randomNumber = (int)(Math.random() * 101); // 0 to 100
System.out.println(randomNumber);
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 asC <= D
.
- 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)= (!a || !b)
- Truth tables to visualize Boolean identities
//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
int num1 = 10;
int num2 = 40;
if (num1 == num2) {
System.out.println("num1 = num2");
}
else {
System.out.println("num1 != num2");
}
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");
}
// 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));
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 example
int i = 5;
do {
System.out.println(i);
i++;
} while (i <= 10);
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
- 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)
}
}
//declaring an array
int arr[]={12,13,14,44};
//traversing the array with for-each loop
for(int i:arr){
System.out.println(i);
}
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
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);
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);
// 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);
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);
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);
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:
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);
//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);
//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);
// 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);
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();
}
}
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);
}
}
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);
}
}
// 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();
}
}
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();
//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();
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);
//toString
Integer x = 5;
System.out.println(x.toString());
System.out.println(Integer.toString(12));
//hashCode
String myStr = "Hello";
System.out.println(myStr.hashCode());
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();
}
}
//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());
// 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
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(" ");
}
System.out.println(alphabet[1][2])