---
marp: true
title: 13 October 2020
---

# <!-- fit --> CS 199 EMP

## <!-- fit --> Even More Practice

---

# <!-- fit --> Attendance Link:

https://forms.gle/8yto1LvJ4hntiKNu7

---

# 2 meetings every week Tuesday and Thursday

* Early CST - Early risers and Eastern timezones

* Evening CST - Western timezones (and really late Eastern folks)

* Calendar contains zoom links

* Attend 7 sessions for credit, attendence via google form.

---

# Format

* 3 practice problems every session

* focused on practical understanding of concepts covered recently in class

* slides and material available after class

--- 

# How to follow along

* Small breakout rooms of working together 

* Work for 10-15 minutes together, feel free to use paper, whiteboards, online share tools.

* Use the code playground on the 125 homepage for the interactive running

---

# <!-- fit --> Libraries and Imports

---

# Libraries

* Libraries are code other people write that you can use

* Programs are shorter and easier to read.

* They are also well tested so you don't have to worry as much about bugs.

* We use `import name.of.package`

---

# `import`

```java
import java.util.Date;

var date = new Date();
System.out.println(date);
// print today's date and time
```

---

# Documentation

* to understand what a library is doing we use documentation and web search

* For example for the last slide we can use [Official Javadoc for Date](https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/util/Date.html)

* It's often helpful to look for example code of usage of the library and trying out simple examples first

---

# External vs Java Standard Library

* Java itself has an extensive library written by the language creators. To import them all you need to do is `import java.whatever` 

* External libraries are more complicated since you need to install them on your system. After that the import will look something like `import com.fasterxml.jackson.databind.ObjectMapper;`

---

# Problem (10 minutes)

* Import a class `UUID` from `java.util`. UUID is a form of unique id

* Reading the [documentation](https://docs.oracle.com/javase/8/docs/api/java/util/UUID.html) and other online sources to create a single UUID (either random or fixed amount) and print it out on the screen.

* No starter code but also don't overthink it. This should be 3-4 lines of code.

---

# <!-- fit --> Type Inference

---

* Type inference is Java compiler smartly understanding data types without having to specify it. 

* At first glance it can seem similar to scripting languages like `Python`, `JavaScript` and `Ruby` which guess the data type.

* Unike scripting languages, type inference is mathematically correct so it doesn't innvolve guess work and retains type safety. 

---

* This is especially helpful for people learning to program, since it makes code simpler and faster to write.

* Becoming more popular in newer languages like `C++`, `Rust`, `Kotlin`, `Swift`, `TypeScript`

* Note: Type inference is only for local variables not functions paramters, returns or class/instance variables.

---

* To use type inference use `var` instead of the variable type.

```java
var integer = 5; // int
var doubleBoi = 3.14159; // double
var intArray = new int[5]; // int[]
var array3d = new float[5][5][5]; // float[][][]
var randomObject = new StringBuilder(); // StringBuilder
var netid = "hdeep2"; // String
```

---

* It can also infer the result of computations

```java
var radiusWithoutBorder = Integer.parseInt("3"); // int
var radius = radiusWithoutBorder + 1; // int
var area = 3.14 * radius * radius; // double
System.out.println(area);
```

---

```java
int[][][] array3d = {{{0, 1},
                      {1, 0}},
                     {{1, 0},
                      {0, 1}}};  
var sum = 0;
// useful in for loops
for (var matrix: array3d) { // int[][]
  for (var vector: matrix) { // int[]
    for (var num: vector) {
      sum += num;
    }
  }
}
System.out.println(sum);
```

--- 

# Problem (10 minutes)

* Convert the following class to use as much type inference as possible

* Remember that local variables can use `var` but instance+class variables and function params+returns can't

---

```java
class Sphere {
  public double r = 0.0;
  private static double pi = 3.14159;
  
  double volume() {
    double frac = 4.0 / 3;
    double cubed = r * r * r;
    return frac * pi * cubed;
  }
  
  double increaseRadius(int inc) {
    double oldRadius = r;
    r = r + inc;
    return oldRadius;
  }
}
```

---

# <!-- fit --> Serialization

---

# Deserialization problem

* Note: The Sept 24 Covers CSV Deserialization (Parsing) as well as two different homework problems.

* Feel free to use that for practice.

* Here I will focus on serialization

---

# Serialized Data Formats

* Over the internet and communicating between applications, we use serialized data formats to talk between programs and computers. Often between different programming languages too.

* The data format is just text, so often represented by `String`. 

* Each format has it's own rules and limitations, for example `CSV` has each entry in a new line and fields seperated by commas. 

* Popular formats exist like `JSON`, `CSV`, `XML`, `YAML`.

* Libraries exist for all these formats, and usually you'd just use those.

---

# Serialization 

* Process of converting data in our program to some format so we can transmit it somewhere.

* In Java it can mean converting some variable or object into the data format `String`

---

# Deserialization

* It's the reverse process of taking the data (in JSON, CSV, YAML etc.) and parsing it for our program.

* This means taking the `String` input and converting it to our variables and objects.

---

# Problem (10 minutes)

* Serialize an array of `QuizScore` into `CSV`

* Return it as a `String`. 

* You can use `+` to add Strings together.

---

```java
public class QuizScore {
  String name;
  int score;
  public QuizScore(String setName, int setScore) {
    name = setName;
    score = setScore;
  }
  
  public static String toCSV(QuizScore[] scores) {
    return null; // TODO:
  }
}

QuizScore[] results = {new QuizScore("Quiz 1", 97), new QuizScore("Quiz 2", 9)};
System.out.println(QuizScore.toCSV(results));
```

---
# <!-- fit --> Solutions

Spoilers

---

### 1)

```java
import java.util.UUID;

var date = UUID.randomUUID();
System.out.println(date);
```

---

### 2)

```java
class Sphere {
  public double r = 0.0;
  private static double pi = 3.14159;
  
  double volume() {
    var frac = 4.0 / 3;
    var cubed = r * r * r;
    return frac * pi * cubed;
  }
  
  double increaseRadius(int inc) {
    var oldRadius = r;
    r = r + inc;
    return oldRadius;
  }
}
```

---

```java
public class QuizScore {
  String name;
  int score;
  public QuizScore(String setName, int setScore) {
    name = setName;
    score = setScore;
  }
  public static String toCSV(QuizScore[] results) {
    var csv = "";
    for (var result: results) {
      var lineCSV = result.name + ", " + result.score + "\n";
      csv += lineCSV;
    }
    return csv;
  }
}
```