Midterm Vocab Eric & AK - yajatyadav/intellijs GitHub Wiki

Casting, for truncating or rounding or division

Java will always round down, or truncate, automatically, but it will always cast up.

public class Main {
  public static void main(String[] args) {
    int a = 20;
    long b = a;     // automatic casting from int to long 20
    double c = b;   // automatic casting from long to double 20.0

    System.out.println(a);
    System.out.println(b);
    System.out.println(c);
  }
}

If we want to cast down, we must use the () operator. Casting down results in data loss due to rounding down. Below is a code segment that can truncate to whole numbers through the (int) operator.

public class Main  {  
  public static void main(String args[])  {  
    double d = 20.22;  
    int i = (int)d;  // narrowing casting from long to int data type
    System.out.println(d);  
    System.out.println(i);  // the decimal part is lost, output will now be 20
  }  
}

For applying it to division, all decimals will be rounded down or truncated, so 0.999 will rounded to 0. However, because Java always casts up, if we use at least one double (using 1.0, 2.0, instead of 1, 2) then Java will cast all values to doubles.

public class Main {
  public static void main(String[] args) {
    double a = 3/4;     // 
    double b = 3.0/4;   // casted to double, prints out 0.75
    double c = 3/4.0;   // casted to double, prints out 0.75
    double d = 3.0/4.0  // both use doubles, prints out 0.75

    System.out.println(a);
    System.out.println(b);
    System.out.println(c);
    System.out.println(d);
  }
}

For rounding up, the Math.ceil() function can be called to round up on any number.

public class Main {
  public static void main(String[] args) {
    int a = 142;
    System.out.println(a / 100);
    System.out.println(Math.ceil(a / 100));
    System.out.println(a / 100.0);
    System.out.println(Math.ceil(a / 100.0));
    System.out.println((int) Math.ceil(a / 100.0));
   }
}

Wrapper Classes

The purpose of wrapper classes it to be able to use primitive data like ints and doubles as functions for autoboxing. It is useful in arraylists that do not accept primitive data types and only take objects.

import java.util.ArrayList;
class Autoboxing
{
    public static void main(String[] args)
    {
        char ch = 'a';
  
        // Autoboxing- primitive to Character object conversion
        Character a = ch;
  
        ArrayList<Integer> arrayList = new ArrayList<Integer>();
  
        // Autoboxing because ArrayList stores only objects
        arrayList.add(25);
  
        // printing the values from object
        System.out.println(arrayList.get(0)); // prints out 25
    }
}

FRQ example:

int coins = Integer.parseInt(scan.nextLine()):
System.out.println("Input a max number of rounds");
int rounds = Integer.parseInt(scan.nextLine()):
CoinGame game = new CoinGame(coins, rounds);
game.playGame();

Concatenation, rules on mixed type Concatenation

Concatenation is the act of joining two strings together. The + operator is used. String literals must be enclosed in quotes, variables must not.

Example of mixed string literals and variables from PBL:

    else {
    PasswordGenerator pwd = new PasswordGenerator
    (digit_response);
    System.out.println("Generated password: " + pwd.pwGen() + ", total passwords generated: " + pwd.pwCount());
    }

Math random

Math random generates a random double between 0 and 1. Example below:

class Main {
    public static void main(String[] args) {
    double number = Math.random();
    System.out.println("Random number: " + number);
    }
}

Coin game FRQ Example:

class Player1 {
    public int getPlayer1Move() {
    return (int)(Math.random() * 3) + 1;
    }
    if(Math.abs(player1spent - player2spent) == 2) {
    player1coins = player1coins + 2;
    }
    else {
    player2coins++;
    }
}

Compound Boolean Expressions

Compound boolean expressions can be combined very well with if statements to check if conditions are true and produce a result. The most common operators are &&, either ||, or not !.

PBL example

public class Recommendation
{
   public static void main(String[] args)
   {
     boolean GPAminreq = true;
     boolean SATminreq = true;
     if (GPAreq && SATreq)
     {
     System.out.println("You should apply.");
     }
     else if (GPAreq || SATreq)
     {
     System.out.println("You can apply, but chances are low");
     }
     else
     {
     System.out.println("You should not apply.");
     }
   }
}

Truth Tables

Truth Tables use boolean logic to use all the combinations of different scenarios being true to determine an outcome.

FRQ Example

public int getPlayer2Move(int round)

{
   int result = 0;
  
   //If round is divided by 3
   if(round%3 == 0) {
       result= 3;
   }
   //if round is not divided by 3 and is divided by 2
   else if(round%3 != 0 && round%2 == 0) {
       result = 2;
   }
   //if round is not divided by 3 or 2
   else {
       result = 1;
   }
  
   return result;

}

De Morgan's Laws

De Morgan's Laws are a set of boolean logic that are used to handle complex conditionals like conditions with %%, ||. Ultimately, it simplifies code and makes it more readable.

The two most significant are that:

  1. the negation of a disjunction is the conjunction of the negations --> not (A or B) = (not A) and (not B)
  2. the negation of a conjunction is the disjunction of the negations --> not (A and B) = (not A) or (not B),

PBL example expressed with And's (!a && !b && !c). This requires that at least either a username, user id, or user email must be provided.

boolean userName = true;
boolean userId = flase;
boolean userEmail = true;
if(!userName && !userId && !userEmail)) {
  throw new Error('At least one user identifier must be passed');
}

But we can also write it with Or's !(a || b || c). This fulfills the same purpose that at least either a username, user id, or user email must be provided.

boolean userName = true;
boolean userId = false;
boolean userAlias = true;
if(!(userName || userId || userAlias)) {
  throw new Error('At least one user identifier must be passed');
}

However, if we want to require all of them, we can express it the following ways using De Morgan's laws, using both And's and Or's.

Using And's

boolean requirementA = true;
boolean requirementB = false;
boolean requirementC = true;
if(!(requirementA && requirementB && requirementC)) {
  throw new Error('All of the requirements must be met');
}

Using Or's

boolean requirementA = true;
boolean requirementB = false;
boolean requirementC = true;
if(!requirementA || !requirementB || !requirementC) {
  throw new Error('All of the requirements must be met');
}

Comparing Numbers, Strings, and Objects

Comparison operators can be used easily for numbers: ==, !=, >, <, >=, <= can all be used with if statements.

Comparing Numbers FRQ example:

if(player1coins = player2coins) {
    System.out.println("tie game");
    }
else if(player1coins > player2coins) {
    System.out.println("player 1 wins")
    }
else if(player1coins < player2coins) {
    System.out.println("player 2 wins")
    }

Comparing Strings:

Example:

class stringcomaprison{  
 public static void main(String args[]){  
   String s1="Eric";  
   String s2="Eric";  
   String s3=new String("AK");  
   System.out.println(s1==s2);// true 
   System.out.println(s1==s3);// false 
 }  
}

FRQ excerpt example:

for (int x = 0; x < str.length(): x++) {
    if (!str.substring(x,x+1).equals(previous(){
    current = "";
}

Comparing Objects:

FRQ example:

public class Unit6EW {
    public static void main(String[] args) {
    //initialize array
    String words[] = {"ten", "fading", "post", "card", "thunder", "hinge", "trailing", "batting"};
    //enhanced for loop to loop through the array
    for (String word : words) {
    //lastIndexOf() method returns the position of the last found occurrence of the substring specified in a string
    if (word.lastIndexOf("ing") == word.length() - 3) {
    System.out.println(word);
        }
    	}
   }
}

For loops and enhanced for loops + nested loops

For loops follow the syntax:

for (statement 1; statement 2; statement 3) {
//do this
}

Self explanatorily, it iterates a block of code for a certain amount of times.

FRQ example:

for (int i = 1; i < itemsSold.length ; i++) {
sumOfItemsSold += itemsSold[i];
  
if(itemsSold[i] > highest)
highest = itemsSold[i];
  
if(itemsSold[i] < lowest )
lowest = itemsSold[i];
}

Enhanced for loops can iterate only in increment order

FRQ example:

public class Unit6EW {
    public static void main(String[] args) {
    //initialize array
    String words[] = {"ten", "fading", "post", "card", "thunder", "hinge", "trailing", "batting"};
    //enhanced for loop to loop through the array
    for (String word : words) {
    //lastIndexOf() method returns the position of the last found occurrence of the substring specified in a string
    if (word.lastIndexOf("ing") == word.length() - 3) {
    System.out.println(word);
        }
    	}
   }
}

Nested loops are just loops in another for or while loop.

Example:

class Main {
  public static void main(String[] args) {

    int weeks = 3;
    int days = 7;

    // outer loop prints weeks
    for (int i = 1; i <= weeks; ++i) {
      System.out.println("Week: " + i);

      // inner loop prints days
      for (int j = 1; j <= days; ++j) {
        System.out.println("  Day: " + j);
      }
    }
  }
}

While loops and do while loops

While loops are used to iterate a part of the program repeatedly until a boolean condition is met.

Syntax:

while (condition) {
  // code block to be executed
}

FRQ example:

while (round <= maxRounds) {
    if(player1coins < 3 || player 2 coins < 3) {
         break;
    }

    int player1spent = getPlayer1Move();
    player1coins -= player1spent

    int player2spent = getPlayer2Move(round);
    player2coins -= player2spent;

    if(Math.abs(player1spent - player2spent) ==2) {
        player1coins = player1coins + 2;
    }
    else {
        player2coins++
    }
    round++
}

Do while loops are essentially have the same purpose. The main difference is that while loop check condition before iteration of the loop. On the other hand, the do-while loop verifies the condition after the execution of the statements inside the loop.

FRQ example

do {
    if(player1coins < 3 || player 2 coins < 3) {
         break;
    }

    int player1spent = getPlayer1Move();
    player1coins -= player1spent

    int player2spent = getPlayer2Move(round);
    player2coins -= player2spent;

    if(Math.abs(player1spent - player2spent) ==2) {
        player1coins = player1coins + 2;
    }
    else {
        player2coins++
    }
    round++
} while (round <= maxRounds);

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

Big O notation is used as the universal notation of analyzing the performance and efficiency of code.

Loops : O(n) - time dependent on number of iterations (times a constant) Nested loops: O(n2) - time dependent on number of iterations ^ 2 (times a constant) Hash maps: O(1)- the hash function is constant, so finding the location of where a certain item and looking up the value is will be O(1) Binary searches: O(log n) - As the number of items in an array doubles, one extra split is added. Since scaling by powers of 2 (exponential) causes a linear increase, the complexity is log n

Creating a Class:

  • Every class includes constructors, methods, and data fields.

  • An object that belongs to a class is called an instance of that class.

  • Constructors describes how to create an object of a class and initialize the object's instance variables.

  • It must match the name of its class.

  • A method is a function that is defined within a class.

Example:

public class Puppy {
   int puppyAge;

   public Puppy(String name) {
      // This constructor has one parameter, name.
      System.out.println("Name chosen is :" + name );
   }

   public void setAge( int age ) {
      puppyAge = age;
   }

   public int getAge( ) {
      System.out.println("Puppy's age is :" + puppyAge );
      return puppyAge;
   }

   public static void main(String []args) {
      /* Object creation */
      Puppy myPuppy = new Puppy( "tommy" );

      /* Call class method to set puppy's age */
      myPuppy.setAge( 2 );

      /* Call another class method to get puppy's age */
      myPuppy.getAge( );

      /* You can access instance variable as follows as well */
      System.out.println("Variable Value :" + myPuppy.puppyAge );
   }
}

Web API, Web API, REST, FETCH, Async, Request, Response, CRUD

Constructor, describe why there is no return

The purpose of a Java constructor is to initializes the newly created object before it is used. No return because it’s purpose is to construct the instance of the object

public class CoingameAP {
    private int startingCoins; // starting number of coins
    private int maxRounds; // maximum number of rounds played

    public CoingameAP(int s, int r) // overloaded constructor 
    {
        startingCoins = s; // set startingCoins to s 
        maxRounds = r;
    }

}  

Accessor methods and relation to getters

Allows safe access to instance variables Method name: get(name of the variable)

public int getPlayer1Move()
    {
        Random rand = new Random();
        int result = rand.nextInt(3) + 1;
        System.out.println("Player 1 spends:" + result);
        return result;
    }

}  

another ex

class Student {

  //Instance variable name
  private String name;

 
  public String getName()
  {
     return name;
  }

Mutator methods, relationship to setter, describe void return type

If there is a need for a different class to modify the instance variables, we need mutator methods Can change instance variables to the value of the parameters

class Student {

   //Instance variable name
   private String name;

   /** setName sets name to newName
    *  @param newName                */
   public void setName(String newName)
   {
      name = newName; // change name to the value of the parameter 
   }

   public static void main(String[] args)
   {
      // To call a set method, use objectName.setVar(newValue)
      Student s = new Student();
      s.setName("John");
   }
 
}  

Static variables, Class variables

Static variables are the same thing as class variables! static variables belong to the class and all the objects of the class share a single static variable. only a single copy of static variable is created and shared among all the instances of the class.We are able to access numberofcirlces inside the method getnumberodgirlce because it was a static variable.

static int numberofcircles; 
static int getnumberofcircles () {
      return numberofcircles; 

Static methods, Class methods

Static methods cant access the value of static variables. https://docs.google.com/document/d/1mZjaS2o231TclRTTpPlUk59qvbLcMOdmVDoRfgfIddY/edit?usp=sharing mport java.io.*;

This key word

The key work "this" refers to the object the called the current method or constructor. other dog breed is the parameter here. this.breed is is referred to the object same bread. Makes the code a lot more cohesive. https://docs.google.com/document/d/1mZjaS2o231TclRTTpPlUk59qvbLcMOdmVDoRfgfIddY/edit?usp=sharing

this.variable = variable

Main method tester method

Tests are methods of the test class where each test tests an individual unit

 public void setRsvp1(boolean newRsvp1) { this.rsvp1 = newRsvp1; }
    public void setRsvp2(boolean newRsvp2) {
        this.rsvp2 = newRsvp2;
    }

Inheritance and extends

Extends: In Java, the extends keyword is used to indicate that the class which is being defined is derived from the base class using inheritance. So basically, extends keyword is used to extend the functionality of the parent class to the subclass.

class One {
    public void methodOne()
    {
  
        // Some Functionality
    }
}
  
class Two extends One {
  
    public static void main(String args[])
    {
        Two t = new Two();
  
        // Calls the method one
        // of the above class
        t.methodOne();
    }
}

Subclass constructor, super Keyword

A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses. The super keyword in Java is a reference variable which is used to refer immediate parent class object. https://docs.google.com/document/d/1mZjaS2o231TclRTTpPlUk59qvbLcMOdmVDoRfgfIddY/edit?usp=sharing

public class Employee extends Person
{
    public Employee()
    {
        super(); // calls the Person() instance variable 
    }
    public Employee(String theName)
    {
        super(theName); // calls Person(theName) instance variable 
    }
}

Overloading a method, same name different parameters

Overloading happens when you have two methods with the same name but different signatures (or arguments).

public class Area {
    public double area(double s) {
        double area = s * s;
        return area;
    }

    public double area(double l, double b) {
        double area = l * b;
        return area;
   }
}

have 2 double areas

Overriding a method, same signature of a method

Overriding is a feature that happens when a public method in a sub class has the same method signature as the super class. The perform in the superclass will be overridden in this case. https://docs.google.com/document/d/1mZjaS2o231TclRTTpPlUk59qvbLcMOdmVDoRfgfIddY/edit?usp=sharing

Abstract Class, Abstract Method

Abstract Class: a restricted class that can’t create objects – Uses inheritance instead. Abstract Method: can only be used inside of abstract classes and they don’t have bodies – they are provided by the subclass instead The use for abstract classes and methods are for security because they hide some details and only show important detail.

 abstract class Animal {
  public abstract void animalSound();
  public void sleep() {
    System.out.println("Zzz");
  }

Object superclass methods: toString(), compare(), clone()

A toString() is an in-built method in Java that returns the value given to it in string format. Hence, any object that this method is applied on, will then be returned as a string object.

 }
    @Override
    public String toString() {
        return String.format(String.valueOf(rsvp1), rsvp2, selection1, selection2);
    }

Late binding of object, referencing superclass object,

ie Animal a = new Chicken(); Animal b = new Goat(); An object is late bound when it is assigned to a variable declared to be of type Object. Objects of this type can hold references to any object, but lack many of the advantages of early-bound objects.

Polymorphism

A reference variable is polymorphic when it can refer to objects from different classes at different points in the code. Inheritance lets us inherit attributes and methods from another class. Polymorphism uses those methods to perform different tasks. This allows us to perform a single action in different ways. code: For example, think of a superclass called Animal that has a method called animalSound(). Subclasses of Animals could be Pigs, Cats, Dogs, Birds - And they also have their own implementation of an animal sound (the pig oinks, and the cat meows, etc.):

 }
    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: wee wee");
  }
}

class Dog extends Animal {
  public void animalSound() {
    System.out.println("The dog says: bow wow");
  }
}
    }
⚠️ **GitHub.com Fallback** ⚠️