Vocab Terms Units 1-10 (Some Code, Some Notes {Mostly Code})
//Code Snippet #1
// Covers casting, specifically for division
// Covers casting, specifically for truncating or rounding
public class Main {
public static void main(String[] args) {
double Double = 9.78d;
int Int = (int) Double;
System.out.println(Double);
System.out.println(Int);
System.out.println(7/Double);
}
}
Main.main(null);
// Code Snippet #2
// Covers Wrapper Classes
// Covers String Concatenation with Mixed Types
// Covers Random usage in math Class
// Covers Public access modifier
// Covers static methods, class methods
// Covers creating a class, describing naming conventions
import java.util.Random;
import java.lang.Math.*;
public class Main {
public static void main(String[] args) {
Integer Int = 2;
Double Double = 7.99;
Character Char = 'B';
System.out.println(Int);
System.out.println(Double);
System.out.println(Char);
//////////////////////////////////
String str = "Hello";
int num = 5;
var str1 = str + num;
System.out.println(str1);
//////////////////////////////////
Random rand = new Random();
int a = 30;
int random = rand.nextInt(a);
System.out.println(random);
}
}
Main.main(null);
// Code Snippet #3
// Covers while loop versus do while loop
// Covers nested loops
// Covers Private access modifier
// Covers for loop, enhanced for loop
// Covers main method, tester method
// Covers Inheritance (through other methods established like isZero)
private void enterGrades() {
Scanner input;
// What is a do-while loop? The do-while loop is very similar to that of the while loop. But the only difference is that this loop checks for the conditions available after we check a statement.
while (true) {
input = new Scanner(System.in);
System.out.print("Enter a double, 0 to exit: ");
try {
double sampleInputDouble = input.nextDouble();
System.out.println(sampleInputDouble);
if (isZero(sampleInputDouble)) break; // exit loop on isZero
else this.grades.add(sampleInputDouble); // adding to object, ArrayList grades
} catch (Exception e) { // if not a number
System.out.println("Not an double (form like 9.99), " + e);
}
input.close();
}
}
import java.util.ArrayList;
ArrayList<String> color = new ArrayList<String>();
color.add("red apple");
color.add("green box");
color.add("blue water");
color.add("red panda");
for(int i = 0; i < color.size(); i++) {
if(color.get(i).contains("red")){
color.remove(i);
}
}
System.out.println(color);
// Code Snippet #4
// Covers Comparing Strings
// Covers Comparing Objects
// Covers Comparing Numbers
// Covers Constructors
// Covers Accessor methods
// Covers Mutator methods
// Covers static variables, class variables
package com.nighthawk.spring_portfolio.mvc.person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.*;
import java.text.SimpleDateFormat;
@RestController
@RequestMapping("/api/person")
public class PersonApiController {
/*
#### RESTful API ####
Resource: https://spring.io/guides/gs/rest-service/
*/
// Autowired enables Control to connect POJO Object through JPA
@Autowired
private PersonJpaRepository repository;
/*
GET List of People
*/
@GetMapping("/")
public ResponseEntity<List<Person>> getPeople() {
return new ResponseEntity<>( repository.findAllByOrderByNameAsc(), HttpStatus.OK);
}
/*
GET individual Person using ID
*/
@GetMapping("/{id}")
public ResponseEntity<Person> getPerson(@PathVariable long id) {
Optional<Person> optional = repository.findById(id);
//static variables vs class variables
if (optional.isPresent()) { // Good ID
Person person = optional.get(); // value from findByID
return new ResponseEntity<>(person, HttpStatus.OK); // OK HTTP response: status code, headers, and body
}
// Bad ID
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
@GetMapping("/getBMI/{id}")
public double getWeightCalculation(@PathVariable long id) {
Optional<Person> optional = repository.findById(id);
if (optional.isPresent()) { // Good ID
Person person = optional.get(); // value from findByID
double bmi = person.getBMI();
return bmi;
}
// Bad ID
return 0;
}
/*
DELETE individual Person using ID
*/
@DeleteMapping("/delete/{id}")
public ResponseEntity<Person> deletePerson(@PathVariable long id) {
Optional<Person> optional = repository.findById(id);
if (optional.isPresent()) { // Good ID
Person person = optional.get(); // value from findByID
repository.deleteById(id); // value from findByID
return new ResponseEntity<>(person, HttpStatus.OK); // OK HTTP response: status code, headers, and body
}
// Bad ID
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
/*
POST Aa record by Requesting Parameters from URI
*/
@PostMapping( "/post")
public ResponseEntity<Object> postPerson(@RequestParam("email") String email,
@RequestParam("password") String password,
@RequestParam("name") String name,
@RequestParam("dob") String dobString,
@RequestParam("height") double height,
@RequestParam("weight") double weight,
@RequestParam("bmi") double bmi) {
Date dob;
try {
dob = new SimpleDateFormat("MM-dd-yyyy").parse(dobString);
} catch (Exception e) {
return new ResponseEntity<>(dobString +" error; try MM-dd-yyyy", HttpStatus.BAD_REQUEST);
}
// A person object WITHOUT ID will create a new record with default roles as student
Person person = new Person(email, password, name, dob, height, weight, bmi);
repository.save(person);
return new ResponseEntity<>(email +" is created successfully", HttpStatus.CREATED);
}
/*
The personSearch API looks across database for partial match to term (k,v) passed by RequestEntity body
*/
@PostMapping(value = "/search", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> personSearch(@RequestBody final Map<String,String> map) {
// extract term from RequestEntity
String term = (String) map.get("term");
// JPA query to filter on term
List<Person> list = repository.findByNameContainingIgnoreCaseOrEmailContainingIgnoreCase(term, term);
// return resulting list and status, error checking should be added
return new ResponseEntity<>(list, HttpStatus.OK);
}
/*
The personStats API adds stats by Date to Person table
*/
@PostMapping(value = "/setStats", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Person> personStats(@RequestBody final Map<String,Object> stat_map) {
// find ID
long id=Long.parseLong((String)stat_map.get("id"));
Optional<Person> optional = repository.findById((id));
if (optional.isPresent()) { // Good ID
Person person = optional.get(); // value from findByID
// Extract Attributes from JSON
Map<String, Object> attributeMap = new HashMap<>();
for (Map.Entry<String,Object> entry : stat_map.entrySet()) {
// Add all attribute other thaN "date" to the "attribute_map"
if (!entry.getKey().equals("date") && !entry.getKey().equals("id"))
attributeMap.put(entry.getKey(), entry.getValue());
}
// Set Date and Attributes to SQL HashMap
Map<String, Map<String, Object>> date_map = new HashMap<>();
date_map.put( (String) stat_map.get("date"), attributeMap );
person.setStats(date_map); // BUG, needs to be customized to replace if existing or append if new
repository.save(person); // conclude by writing the stats updates
// return Person with update Stats
return new ResponseEntity<>(person, HttpStatus.OK);
}
// return Bad ID
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
}
Vocab Definitions
Compound Boolean Expression: Combinations of variables and values that produce a Boolean value as a result.
Truth Tables: A truth table has one column for each variable, one row for each possible combination of variable values, and a column that specifies the value of the function for that combination.
De Morgan's Law: Laws that define how we can negate an AND statement and how we can negate an OR statement.
Polymorphism: In Java, polymorphism refers to the ability of a class to provide different implementations of a method, depending on the type of object that is passed to the method.
Big O notation:
- Hash map: O(1)
- Binary Search: O(log N)
- Single Loop: O(n)
- Nested Loop O(n^2)
// Code Snippet #5
// Covers protected access modifier
// Covers this keyword
// Covers super keyword
// Covers standards methods: toString(), equals(), hashCode()
// Covers late binding of object
class yool {
protected boolean asdff(int a) {
this.a = a;
int b = 12;
if(a.equals(12)) {
return false;
} else {
b.hashCode();
b.toString();
}
}
}
class Animal { // Superclass (parent)
public void animalSound() {
System.out.println("The animal makes a sound");
}
}
class Dog extends Animal { // Subclass (child)
public void animalSound() {
super.animalSound(); // Call the superclass method
System.out.println("The dog says: bow wow");
}
}
public class Main {
public static void main(String args[]) {
Animal myDog = new Dog(); // Create a Dog object
myDog.animalSound(); // Call the method on the Dog object
}
}
// Code Snippet #6
// Covers method overloading
// Covers method overriding
// Covers abstract class
static int plusMethod(int x, int y) {
return x + y;
}
static double plusMethod(double x, double y) {
return x + y;
}
public static void main(String[] args) {
int myNum1 = plusMethod(8, 5);
double myNum2 = plusMethod(4.3, 6.26);
System.out.println("int: " + myNum1);
System.out.println("double: " + myNum2);
}
abstract class Animal {
public abstract void animalSound();
public void sleep() {
System.out.println("Zzz");
}
}