Type Casting in Java

  • when you assign a value of one primitive data type to another type.

  • two types of casting in Java:

           - Widening Casting (automatically) - converting a smaller type to a larger type size
                 byte -> short -> char -> int -> long -> float -> double
    
           - Narrowing Casting (manually) - converting a larger type to a smaller size type
                 double -> float -> long -> int -> char -> short -> byte

Casting, specifically for Division

  • integer and integer resulting in integer
  • if you want it to become a decimal, make it into a double
  • type promotion (with an integer and a double value) makes it more complicated, resulting in the decimal
//example
public class Variables {
    public static void main (String[] args) {    

    }
}
System.out.println(10.0/15);
0.6666666666666666
public class Variables
{
   public static void main(String[] args)
   {
   }
}

int x=10;
int y=15;
System.out.println(1 / 3);
System.out.println(1.0 / 3);
System.out.println(1 / 3.0);
System.out.println((double) x / y);
//type promote; produces decimal answer
0
0.3333333333333333
0.3333333333333333
0.6666666666666666
//modulus
public class Variables
{
   public static void main(String[] args)
   {
   }}

System.out.println(15%10);
5

Casting, specifically for Truncating or Rounding

  • truncation vs. rounding
  • Rounding a number in the range [2.5, 3.5) returns the number 3
  • Truncating a number in the range [3.0, 4.0) returns the number 3
    • Where a square bracket '[' denotes inclusion in the range, and a parenthesis '(' denotes non-inclusion in the range -- ie. [3.0, 4.0) is the range of all numbers between 3 and 4, including 3 but not including 4.
  • truncation; chops off decimal portion
//truncation
public class truncation
{
   public static void main(String[] args)
{}}
//example
int a, b, c;
double d, e;

//declare variables
a = 5;
b = -13;
d = 2.8;

c = a + (int)d; //typecasting
//truncation, cut off decimal
//d became 2 instead of 2.8, so 2 + 5 = 7

System.out.println("c is: " + c);
c is: 7
//rounding
public class rounding
{
   public static void main(String[] args)
{}}

double number = 2.8;
System.out.println( "before rounding: " + number ); 

number = Math.round(number);
System.out.println( "after rounding: " + number ); 

double number = 2.4;
System.out.println( "before rounding: " + number ); 

number = Math.round(number);
System.out.println( "after rounding: " + number );
before rounding: 2.8
after rounding: 3.0
before rounding: 2.4
after rounding: 2.0

Wrapper Classes

  • Why wrap int, double, etc?
  • way to use primitive data types as objects

q5

  • primitive type and corresponding wrapper class
  • Wrapper classes are used to convert any data type into an object. The primitive data types are not objects; they do not belong to any class; they are defined in the language itself. Sometimes, it is required to convert data types into objects in Java language.
public class wrappers
{
   public static void main(String[] args)
{}}

// int x = 10;
// System.out.println(x.toString()); ------ doesn't work because x is a primitive data type, not a modifiable object
Integer x = new Integer(10);
//to get around this, you define an integer wrapper class
System.out.println(x.toString());
//x is now an object, not a primitive data type


Integer x = new Integer(15);
10

Concatenation

  • appendage of strings
//ex
String firstName = "John ";
String lastName = "Doe";
System.out.println(firstName.concat(lastName));
John Doe
class concatenation
{
    public static void main(String arg[])
    {
        }
}

String str1 = "hello", str2 = " to you", str3 = " too";
str1 = str1 + str2 + str3; // LINE A
System.out.println(str1);
//line a is '+' operator

str2 = str2.concat(str3);
System.out.println(str2); //line B
//concat() method

boolean folklore = true;
boolean evermore = false;
System.out.println("Folklore is a great album." + "\nThis statement is " + folklore); // LINE C
System.out.println("Folklore is a bad album." + "\nThis statement is " + evermore);
//concatenation of a boolean to a string
hello to you too
 to you too
Folklore is a great album.
This statement is true
Folklore is a bad album.
This statement is false

Math Classes (Random Usage)

  • methods to perform math tasks on numbers
  • random() returns a random number between 0 (inclusive) and 1
  • public static double random^
import java.lang.Math;
 
//java.lang.Math.random()
class random {
 
    // driver code
    public static void main(String args[])
    {
    }
}
double rand = Math.random();
System.out.println("Random Number:" + rand);
Random Number:0.7941694146696837

Compound Boolean Expressions

  • test two things to be true before body of conditional is executed
  • '&&' used as logical operator and to join 2 booleans
//ex
//want to play video games, but parents only let you if you've finished your homework and taken a shower

public class compoundBooleans
{
   public static void main(String[] args)
   {
     boolean didHomework = true;
     boolean tookShower = false;
     if (tookShower && didHomework)
     {
         System.out.println("You can play");
     }
     else
     {
         System.out.println("No, you can't play");
     }
   }
}

Truth Tables and De Morgan's Law

  • simplification of booleans through truth tables
  • organized way to define a boolean function
  • De Morgan's law: De Morgan's first law states that the complement of the union of two sets A and B is equal to the intersection of the complement of the sets A and B.

q5 q5

//demorgans law
//has to be back home before 10, and has to walk the dog 

public class demorgans
{
   public static void main(String[] args)
   {
     boolean backby10 = true;
     boolean walkedDog = false;
     if (!(backby10 && walkedDog))
     //means not A OR not B
     {
         System.out.println("True. You were back by 10 but didn't walk the dog");
     }
     else
     {
         System.out.println("You were back in time and walked the dog");
     }}}
public class demorgans
{
   public static void main(String[] args)
   {
     boolean backby10 = true;
     boolean walkedDog = false;

    if (!(backby10 || walkedDog))
//means not A AND not B
{ 
System.out.println("False. You were back by 10 but didn't walk the dog");
}
else
{
 System.out.println("You were back in time and walked the dog");


}
}
}

Comparing Numbers

  • use == or compareTo() method
//comparing numbers
public class wrappers
{
   public static void main(String[] args)
{}}

    int x = 10;
    int y = 14;
    if(x==(y)) {
        System.out.println("Both x and y are equal");
}else {
        System.out.println("x and y are not equal");
}
x and y are not equal
public class wrappers
{
   public static void main(String[] args)
{}}

// int x = 10;
// System.out.println(x.toString()); ------ doesn't work because x is a primitive data type, not a modifiable object
Integer x = new Integer(10);
//to get around this, you define an integer wrapper class
System.out.println(x.compareTo(15));
//x is now an object, not a primitive data type
System.out.println(x.compareTo(5));
//-1 is b/c 10 is less than 15
//1 is because 5 is less than 10
-1
1
int xy = 83;
int yz = 20;

int compare = Integer.compare(xy, yz);

if(compare>0) {
    System.out.println("xy is greater than yz");
}else if (compare<0){
    System.out.println("xy is less than yz");
}else{
     System.out.println("xy and yz are equal");
}
x is greater than y

Comparing Strings

  • use .equals() or ==
  • equals() used to check if 2 strings contain the same content
class comparingStrings{ 

    public static void main(String args[]){  
    }  
   }  
   String s1="hello";  
   String s2="goodbye";  
   String s3=new String("hello");  
   String s4="you're a good friend"; 
   String s5="goodbye";

   if (s2 == s5){
    System.out.println("true");
   }
   System.out.println(s1.equals(s2));  
   System.out.println(s1.equals(s3));  
   System.out.println(s1.equals(s4));
true
false
true
false

Comparing Objects

  • use .equals() or ==
  • checks if an object is null, or if attributes are the same
class Food {
    //attributes
    String cuisine;
    String name;
    int mealsConsumed;


    //constructor
    Food(String cuisine, String name, int mealsConsumed)
    {
        this.cuisine = cuisine;
        this.name = name;
        this.mealsConsumed = mealsConsumed;
    }
}

//objects
Food Dal1 = new Food("Indian", "Mango Dal", 10);
Food Dal2 = new Food("Indian", "Moong Dal", 4);

System.out.println("Dal1 = Dal2 is " + Dal1.equals(Dal2));
Dal1 = Dal2 is false

For, While, Nested Loops

  • while loop
    • executed while something is happening
    • iterates over elements
    • can be infinite if boolean is always true
  • do-while loop

    • condition is checked after executed statements
  • for loop

    • certain amt of loops thru code block
  • nested loop: loop w/in loop

  • for-each loop

    • traverses an array in java

While Loop

int x = 10;

while (i<10) {
    System.out.println(i);

    i++;
}
public class arrays
{
   public static void main(String[] args)
   {
   }}
   public static void main(String[] args) {
    int[] numbers = {2, 4, 6, 8, 10};
    int i = 0;
    while (i < numbers.length) {
        System.out.println(numbers[i]);
        i++;

    }}

Do-While Loop

int i = 0;
do {
  System.out.println(i);
  i++;
}
while (i < 5);
0
1
2
3
4

For/For-Each Loop

for (int i = 5; i < 14; i++) {
    System.out.println(i);
  }

  for (int j = 1; j <= 3; j++) {
    System.out.println(j);
}//nested loop
5
6
7
8
9
10
11
12
13
1
2
3
//for-each loop
int arr[]={10,20,30,40,50};  
for(int j:arr){  
  System.out.println(j);  
}
10
20
30
40
50

Writing Classes

  • blueprint for objects
  • has constructors, methods, variables, attributes
  • objects are instances of a class
  • attributes are components
  • methods are object actions
  • public/private -- accessible/not accessible outside the class
  • constructors initialize instance variables when objects are created
  • Naming Conventions: CamelCase (simple, descriptive, straightforward)
class Food {
    //attributes
    private String cuisine;
    private String name;
    private int mealsConsumed;
//instance variables

    //constructor
    Food(String cuisine, String name, int mealsConsumed)
    {
        this.cuisine = cuisine;
        this.name = name;
        this.mealsConsumed = mealsConsumed;
    }
    public String getName(){
        return name;
    }
}

public class Foodmain {
    public static void main(String[] args) {
        Food newFood = new Food("Indian", "Dal", 20);
        System.out.println(newFood.getName());
        
    }
}
Foodmain.main(null)
Dal
import java.util.Scanner; //allows scanners to be in program

public class averages {
  public static void main(String[] args) {
    
}}
Scanner in = new Scanner(System.in); //creates a scanner

System.out.print("Input 1st number: "); //asks user for input
int num1 = in.nextInt(); //saves number and goes to next int
System.out.println(num1);
System.out.print("Input 2nd number: "); //same as above
int num2 = in.nextInt();
System.out.println(num2);
System.out.println("The average of those numbers are " + (num1 + num2)/(2));

//prints out
//num you want to divide is however many numbers you want to average out

averages.main(null)
Input 1st number: 2
Input 2nd number: 20
The average of those numbers are 11

Constructors

  • no return b/c not directly called
  • called for object creation
  • initialize and set values for objects
public class Main {//main class
    int modelYear;
    String modelName;//attributes
  
    public Main(int year, String name) {//constructor
      modelYear = year;
      modelName = name;
    }
  
    public static void main(String[] args) {
      Main myCar = new Main(1969, "Mustang");//objects
      System.out.println(myCar.modelYear + " " + myCar.modelName);
    }
  }
  
// Outputs 1969 Mustang
Main.main(null);
1969 Mustang

Accessor & Mutator methods

  • accessor methods: return private variable values
    • access to instance variables
    • don't take parameters
    • return type matches type of variable they're accessing
    • getters
  • mutator methods: called setters

    • set the value
    • void return type; no return value
//basic example
public class Person {
    private String name; // private = restricted access
  
    // Getter
    public String getName() {
      return name;
    }
  
    // Setter
    public void setName(String newName) {
      this.name = newName;
    }
  }

Static/Class Variables

  • static variables: common property of all objects; not unique
    • gets memory only once
    • makes memory efficient
import java.util.Scanner;

public class Main {
    //static variables
  private static String[] words = {"words", "to", "put", "in"};
  private static String word = words[(int) (Math.random() * words.length)];
  private static String asterisk = new String(new char[word.length()]).replace("\0","*");
  private static int count = 0;
  
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    
    //create a while loop when count is less than 7 and
    //when asterisk contains *
    while (count < 7 && asterisk.contains("*")) {
      //print guess any letter in the word
      //print asterisk
      //take in guess and scan it in (string guess and take in scan)
      //hang(guess)
      System.out.println("Guess any letter in the word");
      System.out.println(asterisk);
      String guess = sc.next();
      hang(guess);
    }
    sc.close();

}}

Java Recursion

  • the process of making a function call itself
  • provides a way to break complicated problems down into simple problems which are easier to solve
//ads all of the #s up to 10
public class Main {
    public static void main(String[] args) {
      int result = sum(10);
      System.out.println(result);
    }
    public static int sum(int k) {
      if (k > 0) {
        return k + sum(k - 1);
      } else {
        return 0;
      }
    }
  }

pi1

Public, Private, Protected; Access Modifiers

  • private; only accessed within class
  • protected; within/outside package, accessible only through child class
  • public - open access
//public


//Exercise 1: 
//Write a program to reverse the words in a sentence
//example: the strawberry cake
//becomes: cake strawberry the

//hints: use scanner to take in words
//use split to break apart words to reverse them

import java.util.*; //import scanner
public class Main {
  public static String reverse_str_order(String input_sentence) { //
    if (input_sentence == null) {
      throw new IllegalArgumentException("Null"); //no empty strings
    }
    StringBuilder stringBuilder = new StringBuilder();
    String[] words = input_sentence.split(" ");
    for (int i = words.length - 1; i >= 0; i--) {
      stringBuilder.append(words[i]); //place words in order
      if (i != 0) { //keep going until no more words are left
        stringBuilder.append(" ");
      }
    }
    return stringBuilder.toString();
  }
}
public static void main(String[] args) { //prepares for scanning
  Scanner scanner = new Scanner(System.in);
  System.out.print("Input string: "); //asks for user input
  String input = scanner.nextLine(); //takes in next line
  System.out.println("\nResult: " + reverse_str_word(input));
}
//private


//Exercise 1: 
//Write a program to reverse the words in a sentence
//example: the strawberry cake
//becomes: cake strawberry the

//hints: use scanner to take in words
//use split to break apart words to reverse them

import java.util.*; //import scanner
public class Main {
  private static String reverse_str_order(String input_sentence) { //
    if (input_sentence == null) {
      throw new IllegalArgumentException("Null"); //no empty strings
    }
    StringBuilder stringBuilder = new StringBuilder();
    String[] words = input_sentence.split(" ");
    for (int i = words.length - 1; i >= 0; i--) {
      stringBuilder.append(words[i]); //place words in order
      if (i != 0) { //keep going until no more words are left
        stringBuilder.append(" ");
      }
    }
    return stringBuilder.toString();
  }
}
public static void main(String[] args) { //prepares for scanning
  Scanner scanner = new Scanner(System.in);
  System.out.print("Input string: "); //asks for user input
  String input = scanner.nextLine(); //takes in next line
  System.out.println("\nResult: " + reverse_str_word(input));
}
//protected


//Exercise 1: 
//Write a program to reverse the words in a sentence
//example: the strawberry cake
//becomes: cake strawberry the

//hints: use scanner to take in words
//use split to break apart words to reverse them

import java.util.*; //import scanner
public class Main {
  protected static String reverse_str_order(String input_sentence) { //
    if (input_sentence == null) {
      throw new IllegalArgumentException("Null"); //no empty strings
    }
    StringBuilder stringBuilder = new StringBuilder();
    String[] words = input_sentence.split(" ");
    for (int i = words.length - 1; i >= 0; i--) {
      stringBuilder.append(words[i]); //place words in order
      if (i != 0) { //keep going until no more words are left
        stringBuilder.append(" ");
      }
    }
    return stringBuilder.toString();
  }
}
public static void main(String[] args) { //prepares for scanning
  Scanner scanner = new Scanner(System.in);
  System.out.print("Input string: "); //asks for user input
  String input = scanner.nextLine(); //takes in next line
  System.out.println("\nResult: " + reverse_str_word(input));
}

Static methods, Class methods

  • belong to class, not object
  • accessed through class
public class friends
{
   // instance variables
   private String name;
   private String email;
   private String phoneNumber;

   // Static counter variable
   public static int personCounter = 0;

   // static method to print out counter
   public static void printPersonCounter() {
        System.out.println("Person counter: " + personCounter);
   }

   // constructor
   public friends(String initName, String initEmail, String initPhone)
   {
      name = initName;
      email = initEmail;
      phoneNumber = initPhone;
      personCounter++;
   }

   // toString() method
   public String toString()
   {
     return  name + ": " + email + " " + phoneNumber;
   }

   // main method for testing
   public static void main(String[] args)
   {
      // call the constructor to create a new person
      friends p1 = new friends("Sana", "sana@gmail.com", "123-456-7890");
      friends p2 = new friends("Jean", "jean@gmail.com", "404 899-9955");

      friends.printPersonCounter();
   }
}
//class methods
public class Main {
    static void myMethod() {
      System.out.println("Hello World!");
    }
  }  
//methods declared within a class

this Keyword

  • current object in method/constructor
  • eliminates confusion b/w attributes/parameters w/ the same name
//ex
public class Main {
    int x;
  
    // Constructor with a parameter
    public Main(int x) {
      this.x = x;
    }
  //this used to 
    // 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 main code
  • tester method tests main code

ex:

q5

Inheritance, extends

  • extends: extends a class, inherits information from another class
  • subclass; class inherits from another class
  • superclass; parent class being inherited from
//ex
class school {
    protected String brand = "work";         //  attribute
    public void pencil() {                     // method
      System.out.println("write, write!");
    }
  }
  
  class classwork extends school {
    private String modelName = "google doc";    // attribute
    public static void main(String[] args) {
  
      // Create a new school object
      School mySchool = new School();
  
      // Call the pencil() method (from the school class) on the work object
      mySchool.pencil();
  
      // Display the value of the brand attribute (from the Vehicle class) and the value of the modelName from the Car class
      System.out.println(mySchool.brand + " " + mySchool.modelName);
    }
  }

Subclass constructor, super Keyword

  • subclass; inheriting class
  • super: refers to parent objects; calls superclass methods

Overloading a method, same name different parameters

  • java feature allowing classes to have more than one method that is named the same (but it must have different parameters)
  • easier to overload one instead of having to define two identically-functioning methods

Overriding a method, same signature of a method

  • when a subclass has the same method has the parent class
  • implements a certain aspect of method declared by a parent class

Abstract Class, Abstract Method

  • is a method that has just the method definition but no actual implementation
  • can be subclassed, not instantiated

Standard methods: toString(), equals(), hashCode()

  • toString returns string
  • hashCode returns hashCode of a string
public class toString
{
   public static void main(String[] args)
{}}

Integer x = new Integer(10);
System.out.println(x.toString());
System.out.println(x.toString(90));
10
90
public class hashCode
{
   public static void main(String[] args)
{}}
 
Object1 []= "yay!";
System.out.println(str_New.hashCode());
3701712

Late binding of object

  • name of method looked up at runtime
  • compiler doesn't perform argument checks and leaves it up to runtime

Polymorphism

  • class has different implementations of a method
  • same action performed differently

Big O notation for Hash map, Binary Search, Single loop, Nested Loop

  • language for runtime length
  • related to efficiency

  • hashmap: single operation to obtain position of a searched element

    • O(1)
  • binary search

    • O(1)
    • eliminates half the elements each time
  • single loop

    • O(n)
    • The next loop executes N times, if we assume the statement inside the loop is O(1), then the total time for the loop is N*O(1), which equals O(N) also known as linear time
  • nested loop

    • O(N*N)
    • the first loop may execute N times, but for how many first loop executes, the inner loop executes N times