Unit 1: Primitives (our lesson)

  • Two main types of data in java: primitives (int, boolean, char, double) and objects (Strings, other classes)
  • Primitives can be compared with == while for classes it is necessary to use the .equals() method
  • Primitives do not have methods and properties while these are present in classes (ie. String length() method)
  • Homework N/A since we presented this unit

Casting (Division/Rounding)

  • In order to do division with numbers, casting to double is necessary
  • When casting is done from double to integer, the number is ALWAYS rounded down (truncated)
int a = 5;
int b = 2;
// Without casting (rounds down to 2)
System.out.println(a/b);

// With casting to double (gives correct answer of 2.5)
System.out.println((double)a/(double)b);

double c = 6.7;

// Without casting (shows full decimal)
System.out.println(c);

// WIth casting to integer (rounds down to 6)
System.out.println((int)c);
2
2.5
6.7
6

Wrapper Classes, why wrap int, double.

Wrapper classes are used to convert primitives in a class, necessary for types which use generic (ex. ArrayList)

int a = 6;

// DOES NOT WORK: unexpected type (because primitive)
// ArrayList<int> list = new ArrayList<int>();

// Using "Integer" wrapper class
ArrayList<Integer> list = new ArrayList<Integer>();

// Creating "Integer" from int
Integer a_wrap = new Integer(a);
list.add(a_wrap);

// Using java to automatically cast int to Integer
list.add(a);

// Both elements are there
System.out.println(list);
[6, 6]

Unit 2: Using Objects

  • Objects are just an instance created out of a class created w/ a constructor (which takes in parameters describing the object
  • Methods in objects can be void (returns nothing) or have a return type specified
  • Static methods and properties are tied to class rather than object (ie. same value for all objects)
  • Methods can be overloaded (have different sets of parameters) as long as order of types differs between method definitions even with same name
  • Homework

Concatenation

  • Allows you to combine strings together using + sign
  • If string is added to a non string type, the toString method is used, or for primitives it is automatically converted to string
public class CoolClass {
  public String toString() {
    return "a cool class";
  }
}

String a = "a string";
String b = " and another string ";
int c = 10;
CoolClass d = new CoolClass();

// Adding two strings together
System.out.println(a + b);

// Adding string and primitive (integer);
System.out.println(a + b + c);

// Adding string and other object (uses toString)
System.out.println(a + b + d);
a string and another string 
a string and another string 10
a string and another string a cool class

Math class

  • Math class is useful for many mathematical operations such as square root and power
  • Also useful for random numnber generation, Math.random gives number 0-1 which can be scaled to any set of numbers (see below code)
int n = 10; // random number from 1-n

// 10 random numbers
for (int i = 0; i<10; i++) {
  int random_number = (int)(Math.random() * n + 1); // cast to int ensures resulting output is whole number
  System.out.println(random_number);
}
10
1
10
6
2
5
1
6
8
10

Comparing Numbers/Strings/Objects

  • Numbers can be compared using the "==" operator
  • Objects such as strings must be compared using ".equals()" rather than "==" operator
    • The "==" operator comapres the memory location rather than contents of object
int a = 0;
int b = 0;
int c = 1;

// Comparing two same numbers
System.out.println(a == b);

// Comparing two different numbers
System.out.println(a == c);

String as = new String("crazy");
String bs = new String("crazy");

// Comparing the same string to itself (SAME memory location)
System.out.println(as == as);

// Comparing strings with same content using wrong operator (DIFFERENT memory location)
System.out.println(as == bs);

// Comparing strings with same content using correct .equals()
System.out.println(as.equals(bs));
true
false
true
false
true

Unit 3: Booleans/If statement

  • Booleans store a true/false value (can only be one of these)
  • Booleans can be generated using comparison expressions (equal/==, greater than/>, less than/<, etc.)
  • If statements take in a boolean or boolean expression and run if the expression evaluates to "true"
  • Else & Else if statements can be used in conjunction with if statements to run code if the if statement evaluates to false
  • Homework

Compound Boolean Expression

  • Using combinations of boolean operators, you can make compound boolean expressions
  • Operators that can be used include and (&&), or (||), not (!), as well as parenthesis for grouping purposes
boolean a = true;
boolean b = false;

// Creating a compound expression
boolean compound = !(a && b) && (b || a) && (!b && !a);

// Printing the result
System.out.println(compound);
false

Truth Tables

  • Can be used to see the values of boolean expressions
  • For example, below is truth tables for and/or ### AND X | 0 | 1 |
    0 | 0 | 0 |
    1 | 0 | 1 |
    ### OR X | 0 | 1 |
    0 | 0 | 1 |
    1 | 1 | 1 |

De Morgan's Law

  • Useful for simplifying boolean expresison
  • States that !(a && b) = !a || !b AND !(a || b) = !a && !b (ie. distribute and switch the middle sign)
boolean a = true;
boolean b = false;
boolean c = true;
boolean d = false;

// complicated boolean expression
boolean res1 = !((!(a && b)) || (!(a || b)));

// simplified using De Morgan's Law once
boolean res2 = !((!a || !b) || (!a && !b));

//simplified using De Morgan's Law twice
boolean res3 = !(!a || !b) && !(!a && !b);

// all results are the same
System.out.println(res1 + " " + res2 + " " + res3);
false false false

Unit 4: Iteration

  • While loop runs while a boolean condition is true (be careful with infinite loops!)
  • For loops create a variable which is modified on every loop iteration and has an end condition (useful for iterating through arrays, especially in different ways based on the modification, ie. i += 2 for all even indexes)
  • For & while loops can be nested inside each other to achieve more iteration (really useful with 2D arrays)
  • For each/Enhanced for loops really useful for looping through an array (int val : array) but limited in that they go through all elements from first to last and that cannot be modified
  • Homework

For loop/Enhanced for loop

  • For loops can be used to iterate through an index, and modify it in different ways in the for loop declaration
  • The enhanced for loop is exclusively used for iterating fully through an iterable (such as array)
// looping through even numbers
for (int i = 0; i<10; i+=2) {
  System.out.println(i);
}

int[] arr = {1, 2, 3, 7, 8};

// looping through array with conventional for lopo
for (int i = 0; i<arr.length; i++) {
  System.out.println(arr[i]);
}

// looping through array with enhanced for loop
for (int i : arr) {
  System.out.println(i);
}
0
2
4
6
8
1
2
3
7
8
1
2
3
7
8

While loop versus Do While loop

  • While loops run while a condition is true, the condition is checked before each iteration of the code is run
  • Do while loops also run while a condition is true, but the condition is checked AFTER each iteration of the code is run
    • This means that no matter what the do block runs at least once before the condition is checked
int i = 0;
boolean falseBool = false;

// printing even numbers with while loop
while (i < 10) {
  System.out.println(i);
  i += 2;
}

// if condition is false while loop does not run at all
while (falseBool) {
  System.out.println("inside while loop");
}

// if condition is false in do while, the loop runs once
do {
  System.out.println("inside do-while loop");
} while (falseBool);
0
2
4
6
8
inside do-while loop

nested Loops

  • Loops can be used inside each other for better iteration
  • Especially useful for 2D arrays
int[][] arr = {
  {1, 2, 3},
  {2, 3, 4},
  {4, 5, 6}
};

// using nested for loops for 2D array
for (int i = 0; i<arr.length; i++) {
  for (int j = 0; j<arr[i].length; j++) {
    System.out.print(arr[i][j] + " ");
  }
  System.out.println();
}
1 2 3 
2 3 4 
4 5 6 

Unit 5: Writing Classes

  • Classes can be used for creating objects and have two main things: properties and methods
  • Properties are used to store information about each object of a class (can be made private/public which determines accessibility outside of class)
  • Methods are used to modify the object & do things
  • Getter and Setter Methods can be used to modify properties of a class which are made private
  • Homework

Creating a Class, describe Naming Conventions

  • Class can be created using the class keyword
  • Class should be defined using upper camelcase (camelcase but first letter capital)
// creating a class
class MyClass {

}

Main Method

  • The main method is used to test a class, is automatically called when class ran
  • Usually creates an object and can test methods
class MyClass {
  // main method
  public static void main (String[] args) {
    MyClass obj = new MyClass();
  }
}

MyClass.main(null);

This keyword

  • The "this" keyword allows you to access properties of the class
  • See constructor example to see use of this keyword

Constructor

  • Constructor is called whenver the object is created, usually initializes fields
  • Does not return anything because the object is automatically given to the user when constructor is called
class MyClass {
  int prop1;
  int prop2;

  // Constructor here
  public MyClass (int prop1input, int prop2input) {
    // setting properties using this to reference prop1 & prop2 of the object
    this.prop1 = prop1input;
    this.prop2 = prop2input;
  }

  public static void main (String[] args) {
    MyClass obj = new MyClass(1, 2);
  }
}

MyClass.main(null);

Accessor/Getter methods

  • Used to get properties of an object from the outside the class definition
  • Getters can be applied on only the properties which should be accessed outside the class
class MyClass {
  int prop1;
  int prop2;

  // Constructor here
  public MyClass (int prop1input, int prop2input) {
    // setting properties using this to reference prop1 & prop2 of the object
    this.prop1 = prop1input;
    this.prop2 = prop2input;
  }

  // getter allows outside class to access prop1
  public int getProp1() {
    return this.prop1;
  }

  public static void main (String[] args) {
    MyClass obj = new MyClass(1, 2);

    // using getter to access prop1
    System.out.println(obj.getProp1());
  }
}

MyClass.main(null);
1

Mutator/setter methods

  • These methods allow the properties which should be modifiable to be chagned outside the class definition
  • These methods have a "void" return type since they don't need to return anything, since they are only setting values
class MyClass {
  int prop1;
  int prop2;

  // Constructor here
  public MyClass (int prop1input, int prop2input) {
    // setting properties using this to reference prop1 & prop2 of the object
    this.prop1 = prop1input;
    this.prop2 = prop2input;
  }

  // getter allows outside class to access prop1
  public int getProp1() {
    return this.prop1;
  }

  // setter allows outside class to set prop1
  public void setProp1 (int propVal) {
    this.prop1 = propVal;
  }

  public static void main (String[] args) {
    MyClass obj = new MyClass(1, 2);

    // using getter to access prop1
    System.out.println(obj.getProp1());

    // changing value of prop1
    obj.setProp1(10);

    // using getter to access new value of prop1
    System.out.println(obj.getProp1());
  }
}

MyClass.main(null);
1
10

Access modifiers

  • Access modifiers control whether properties and methods can be accessed outside the class
  • The public means the property/method is accessible outside while if it is private it is not accessible
class MyClass {
  // prop1 cannot be directly accessed
  private int prop1;

  // prop2 can be directly accessed
  public int prop2;

  // Constructor here
  public MyClass (int prop1input, int prop2input) {
    // setting properties using this to reference prop1 & prop2 of the object
    this.prop1 = prop1input;
    this.prop2 = prop2input;
  }

  // getter allows outside class to access prop1
  public int getProp1() {
    return this.prop1;
  }

  // setter allows outside class to set prop1
  public void setProp1 (int propVal) {
    this.prop1 = propVal;
  }

  public static void main (String[] args) {
    MyClass obj = new MyClass(1, 2);

    // would throw error
    // obj.prop1 = 10;

    // works (because public)
    obj.prop2 = 11;
    System.out.println(obj.prop2);
  }
}

MyClass.main(null);
11

Static methods/properties

  • Static properties and methods are part of the class rather than each object
  • Static methods do not require an object, and static properties only have one instance that is the same for all objects
class MyClass {
  // static method
  static String coolMethod (String a) {
    return a + " cool";
  }

  // static property
  static int staticProp = 10;

  public static void main(String[] args) {
    // no object needed for any of this
    System.out.println(MyClass.coolMethod("test"));
    System.out.println(MyClass.staticProp);
  }
}

MyClass.main(null);
test cool
10