. Integer belongs to the Java.lang package that can be found in the [API documentation](https://docs.oracle.com/en/java/javase/14/docs/api/index.html) that we reviewed in a prior lesson.
**What are the advantages of using Wrapper Classes**
- They convert primitive data types into objects. Objects are needed if we want to modify arguments passed to a method.
- The classes in `java.util` package only handles objects thus wrapper classes are appropriate to use.
- Data structures such as an ArrayList, store only objects and not primitive types.
- We can call multiple methods like compareTo(), equals(), toString()
Wrapper Classes
| Primitive Data Type | Wrapper Class |
| ----------- | ------------ |
| byte | Byte |
| short | Short |
| int | Integer |
| long | Long |
| float | Float |
| double | Double |
| boolean | Boolean |
| char | Character |
| Integer Class Constructors and Methods | Explanation |
| --------------------- | --------- |
| Integer(int value) | Constructs a new Integer object that represents the specified int value. |
| Integer.MIN_VALUE | The minimum value represented by int or Integer. |
| Integer.MAX_VALUE | The maximum value represented by int or Integer. |
| int intValue() | Returns the value of this Integer as an int. |
The program below retrieves the value wrapped by an Integer and stores it in a primitive int before using that value.
Modify the program so that it stores the value of int1 in int2.
```java
public class Main
{
public static void main(String[] args)
{
Integer int1;
Integer int2;
int primitiveInt;
int1 = new Integer(20);
int2 = new Integer(int1.intValue()); // solution 1
int2 = int1.intValue(); // solution 2
System.out.println("int2 value is: " + int2.intValue());
}
}
```
**Sample Output**
`int2 value is: 20`
| Double Class Constructors and Methods | Explanation |
| ----------------- | ------------ |
| Double(double value) | Constructs a new Double object that represents the specified double value. |
| double doubleValue() | Returns the value of this Double as a double. |
```java
public class Main
{
public static void main(String[] args)
{
Double d = new Double(1.5); // instantiates a Double
// Uses the doubleValue method in a print statement
System.out.println("d value is: " + d.doubleValue());
}
}
```
**Sample Output**
`d value is: 1.5`
**Autoboxing/ Unboxing**
In the program below the JVM did some extra work at lines 5 and 6. Java automatically converted from the int and double primitive types to their corresponding object reference types. This is called **autoboxing**, an automatic conversion that the Java compiler makes between primitive types and their corresponding object wrapper classes.
```java
1 public class Main
2 {
3 public static void main(String[] args)
4 {
5 Integer integerInstance = 5;
6 Double doubleInstance = 2.0;
7 // Newlines are allowed around operators
8 System.out.println("integerInstance: " + integerInstance.intValue() +
9 " doubleInstance: " + doubleInstance.doubleValue());
10 }
11 }
```
**Note:** Autoboxing is the automatic conversion that the Java compiler makes between primitive types and their corresponding object wrapper classes, including int to Integer, double to Double, and boolean to Boolean.
The program below demonstrates the opposite of autoboxing called **unboxing**. Java automatically converted the Integer reference types to its corresponding int primitive types.
```java
public class Main
{
public static void main(String[] args)
{
unboxInt(new Integer(42));
unboxDouble(new Double(3.14159));
unboxBoolean(new Boolean(true));
}
public static void unboxInt(int i)
{
System.out.println(i);
}
public static void unboxDouble(double d)
{
System.out.println(d);
}
public static void unboxBoolean(boolean b)
{
System.out.println(b);
}
}
```
**Sample Output**
```java
42
3.14159
true
```
**Note:** Unboxing is the automatic conversion that the Java compiler makes from the wrapper class to the primitive type.
This includes converting an Integer to an int and a Double to a double.
The Java compiler applies unboxing when a wrapper class object is:
i. Passed as a parameter to a method that expects a value of the corresponding primitive type.
ii. Assigned to a variable of the corresponding primitive type.
In the program below, which line of code contains an example of *autoboxing*?
In the program below, which line of code contains an example of *unboxing*?
```java
1 public class Main
2 {
3 public static void main(String[] args){
4 Integer cardboardWidth = new Integer(4);
5 Integer cardboardHeight = new Integer(5);
6
7 Box cardboardBox = new Box(cardboardWidth, cardboardHeight);
8 cardboardBox.changeDimensions(2,3);
9 System.out.println("Ending box dimensions: " + cardboardBox.getWidth()
10 + " x " + cardboardBox.getHeight());
11 }
12
13 private static class Box
14 {
15 private int width, height;
16
17 public Box(int w, int h){
18 width = w;
19 height = h;
20 }
21
22 public void changeDimensions(Integer w, Integer h){
23 width = w.intValue();
24 height = h.intValue();
25 }
26
27 public int getWidth(){
28 return width;
29 }
30 public int getHeight(){
31 return height;
32 }
33 }
34 }
```
Answer
**Unboxing** occurs on *line 7* when Integer parameters are automatically converted to ints
in the constructor.
**Autoboxing** occurs on *line 8* when int parameters are automatically converted to Integers
in the method.
**Sample Output**
```java
Ending box dimensions: 2 x 3
```
### Activity 2.8.1 Wrapper Classes
Create a program that contains an example of each of the following. Add in-line comments to describe each example.
- [ ] An Integer constructor
- [ ] The intValue method
- [ ] A Double constructor
- [ ] The doubleValue method
- [ ] The maximum double value
- [ ] The minimum double value
- [ ] Autoboxing
- [ ] Unboxing
## 2.9 Using the Math Class
- [ ] Use methods from the Math package
- [ ] I will be able to write programs using math methods
- [ ] I will write a segment of code that will convert an annuity into java
- [ ] Incorporate randomness into a program
- [ ] I will be able to write a program using random method
The Math class can be found in the java.lang package. The Math class contains only static methods. Some of the more commonly use Math methods are listed below.
Oracle Java Methods & Classes
Navigate to and review the information that can be found at [Java API Specification](https://docs.oracle.com/en/java/javase/14/docs/api/index.html).
| Navigation |
| ---------- |
| Select java.base > java.lang |
| Scroll through `Class Summary` until you find `Math` |
| Review Math class description |
| Click on `Math` class link to explore the class |
| |
| Click on 'Method Summary' for **All Methods** to explore how you can call the implement a method |
| Click on a 'Method' to view the Method Summary |
| Math Class Methods | Explanations |
| ----------- | --------- |
| int abs(int x) | Returns the absolute value of an int value |
| double abs(double x) | Returns the absolute value of a double value |
| double pow(double base, double exponent) | Returns the value of the first parameter raised to the power of the second parameter |
| double sqrt(double x) | Returns the positive square root of a double value |
| double random() | Returns a double value greater than or equal to 0.0 and less than 1.0 |
| round() | Returns the round of the decimal number to the nearest value |
| ceil() | Returns a double greater than or equal to the original number |
| floor() | Returns a double less than or equal to the orignal number |
--------------------------------------------------------------------------------------------------------------------------------------------
Math Method: Primitive Type Returned
**Math.round:**
- Math.round is designed to round a floating-point number to the nearest integer. Its purpose is to convert a floating-point value to an integer value, effectively removing the decimal part. Rounding to the nearest integer makes sense because it's often used in scenarios where you need an integer result. For example, if you have a floating-point number that represents a measurement and you want to round it to the nearest whole number, Math.round is a convenient function to use.
- The return type of Math.round is long, but if you want an integer result, you can cast it to int or store it in an int variable. This is because rounding can result in a value that may not fit into the range of a 32-bit integer, so it's safer to return a long.
**Math.sqrt:**
- Math.sqrt is designed to calculate the square root of a number, which may not always result in an integer value. In many cases, the square root of a number is a decimal value (a double in Java). This is because not all numbers have integer square roots. For example, the square root of 25 is exactly 5, but the square root of 26 is approximately 5.09901951359.
- To accommodate the fact that square roots can have decimal parts, Math.sqrt returns a double by default to provide a precise and flexible result. If you know that the input value will always have an integer square root and you want the result as an integer, you can cast the result to an int.
**Math.ceil:**
- Math.ceil is a method in the Math class that is used to round a floating-point number up to the nearest integer greater than or equal to the original number (the "ceiling"). This means that it always returns a double value. The result will have a decimal part of 0.0 if the input is already an integer.
**Math.floor:**
- Math.floor is another method in the Math class, and it is used to round a floating-point number down to the nearest integer less than or equal to the original number (the "floor"). Like Math.ceil, Math.floor also returns a double value.
**Math.round**
- Round is a another method in the Math class which returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result after adding 1/2, and casting the result to type long. If the argument is NaN, the result is 0.
--------------------------------------------------------------------------------------------------------------------------------------------
Having seen the Math method `abs` method in use, refer to the Java Quick Reference to predict
how you could use the `pow` method to raise a base of 2 to the exponent 10 (210 ).
Answer
```java
Math.pow(2, 10)
```
--------------------------------------------------------------------------------------------------------------------------------------------
How would you write the `sqrt` method to get the square root of 9.
Answer
```java
Math.sqrt(9)
```
--------------------------------------------------------------------------------------------------------------------------------------------
How would you write the `round` method to get the round of 79.52.
Answer
```java
Math.round(79.52)
```
--------------------------------------------------------------------------------------------------------------------------------------------
**The random Method**
For programs that require some amount of randomness, such as games, security, simulations, and statistics, Java’s Math class provides a random method. This method returns a double value that falls in the range from 0.0 to 1.0 non-inclusive, expressed mathematically as (0.0, 1.0\] to indicate that it includes 0.0 but that its highest value is .999999999999999. With random values from 0 to .99..., you can mathematically generate any random number you may need. As you will see, you can manipulate the results in a variety of ways to fit your needs.
```java
public class Main
{
public static void main(String[] args)
{
int rnum = (int) (Math.random() * 24 );
// This program produces a random integer between 0 and 23 inclusive.
System.out.println(rnum);
}
}
```
You can also create a range using the random method in the formula below.
Math.random() * n1 + m2
1 = Number of integers included in range
2 = Lowest integer in range
Use the `Math.random` method to generate a double value greater than or equal to 10.0 (inclusive) and less than 15.0 (exclusive).
```java
public class Main
{
public static void main(String[] args)
{
System.out.println(Math.random() * 5 + 10);
}
}
```
How would you modify a program to produce `int` values between **70** inclusive and **100** exclusive?
```java
System.out.println(Math.random() * 30 + 70);
```
As stated above, Math methods are static. This means that you do not use an object reference like you did with non-static methods (cat.length()). Instead, you reference the class name itself followed by the static method. Some examples are listed below.
| Math Method Examples |
| --------- |
| Math.abs(-5) |
| Math.abs(2.3) |
| Math.sqrt(4) |
| Math.random() |
If you were to write your program using a constructor and reference the object your program will return an error.
```
Math m = new Math();
m.random();
```
Take a look at the program below.
```java
public class Main
{
public static void main(String[] args)
{
int path1 = -1; // The car drives West 1 block
int path2 = -1; // The car drives West 1 block
int path3 = -1; // The car drives West 1 block
int path4 = 3; // The car drives East 3 blocks
// Added calls to Math.abs in the print statement below.
System.out.println(Math.abs(path1) + Math.abs(path2) + Math.abs(path3) + Math.abs(path4));
}
}
```
Review the Math Class Methods in the table above and determine the correct syntax to execute each print statement.
```java
1 public class MathPractice
2 {
3 public static void main(String[] args)
4 {
5 // Find 8x8x8x8
6 System.out.println( );
7 // Find the square root of 64
8 System.out.println( );
9 // Find the square root of 65
10 System.out.println( );
11 // Find the square root of the absolute value of the difference
12 // between 12 squared and 5 squared.
13 System.out.println( );
14 }
15 }
```
8x8x8x8 answer
```java
System.out.println(Math.pow(8, 4));
```
square root of 64 answer
```java
System.out.println(Math.sqrt(64));
```
square root of 65 answer
```java
System.out.println(Math.sqrt(65));
```
difference between 12 squared and 5 squared answer
```java
System.out.println(Math.sqrt(Math.abs(Math.pow(12, 2) - Math.pow(5, 2))));
```
### Activity 2.9.1 - Math Class Worksheet 1 & 2
In pairs, work on worksheet 1 in class. We will review your work in class.
**Download:** [mathclassworksheet1.docx](https://github.com/AP-CSA-JAVA/CSA_JAVA-Course/files/9778281/mathclassworksheet1.docx)
**ascii Table:** [ascii-table-characters.pdf](https://github.com/AP-CSA-JAVA/CSA_JAVA-Course/files/9737398/ascii-table-characters.pdf)
Complete worksheet 2 for homework. We will review your work next class.
**Download:** [mathClassWorksheet2.docx](https://github.com/AP-CSA-JAVA/CSA_JAVA-Course/files/9778287/mathClassWorksheet2.docx)
**An example of single vs double quotes**
Click Here
```java
class Main {
public static void main(String[] args) {
System.out.println( "a" + (char)1 ); // output is a
System.out.println( "a" ); // output is a
System.out.println( 'a' + (char)1 ); // output is 98
System.out.println( "a" + 1 ); //output a1
System.out.println( 'a' + 1 ); //output 98
}
}
```
**Prefix & Postfix Operators**
Click Here
***++ and - - used as a prefix or as a postfix***
Assume for what is being discussed that what works for increment operators(`++`) will also work with decrement operators(`--`). I will only use increment operators for the sake of brevity.
If you use the `++` operator as a prefix like: `++var`, the value of `var` is incremented by 1; then it returns the value.
If you use the `++` operator as a postfix like: `var++`, the original value of `var` is returned first; then `var` is incremented by 1.
```java
class Main {
public static void main(String[] args) {
int var1 = 5, var2 = 5;
// 5 is displayed
// Then, var1 is increased to 6.
System.out.println(var1++); //output is 5
// var2 is increased to 6
// Then, var2 is displayed
System.out.println(++var2); //output is 6
System.out.println(var1); // output is now 6
System.out.println(var2); // output is still 6
}
}
```
As a wrap-up, consider the ++ operator as:
- x = x++; //Post-increment
- x = ++x; //Pre-increment
-------------------------------------------------------------------------------
### Activity 1.2.9 - Race Car
Starter Files: [Activity129RaceCar.zip](https://github.com/AP-CSA-JAVA/CSA_JAVA-Course/files/9757289/Activity129RaceCar.zip)
Complete the computeTime method and the comments in main.java
```java
//Length of the track in meters
double distance = 2414; // ~ 1.5 miles
// Generate a random acceleration (integer)
// for each car from 20 - 50 (inclusive)
// Create two Racecar objects
// Compute the finishing times for both cars
// Print times of each car
```
You will need to complete the methods and toString within Racecar.java
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Free Response Question (FRQ)
**Free Response Question**
Students will work in pairs during this activity.
In this part of the activity, you and a partner will answer your first Free Response Question (FRQ). FRQs define a set of requirements that an algorithm must meet. You provide answers to the FRQ in the form of handwritten Java code.
FRQs are also great ways to apply the knowledge and skills you have learned. They are also on the College Board’s AP exam, representing approximately 45 percent of the Exam. You should practice hand writing your answers to FRQs since this is the format you will use on the exam.
As to the structure of FRQs, the one you will complete now is a shortened version of an FRQ you might see on an exam. Other FRQs in this course will be longer and more like the FRQs you will see in an exam. In general, FRQs describe a scenario and specific requirements that your code must meet. Sometimes FRQs provide code to enhance. They can also omit irrelevant code, using comments similar to `/* implementation not shown */`.
Your first FRQ is titled Annuity. It requires you to write expressions using a Math method you learned in this activity and to use a return statement to return a value from a method.
Your teacher will distribute the Annuity FRQ. Work together with a partner to write your solution.
Once you complete the FRQ, ask your teacher for the scoring guidelines and with the guidelines in hand, join another team of two. Exchange solutions and grade each other’s FRQs according to the canonical (most well-established or ideal) solution.
________________________________________________________________________________________________________
## Project Mad Libs
- [ ] Apply coding concepts you have learned up to this point.
- [ ] Apply the programming development process to create a project.
- [ ] Capture your project and communicate how each part of your program works.
**Requirements of this project**
Give a Mad Lib with three user inputs, create a user-generated story with the correct parts of speech.
Your program should allow a user to enter values that change the output of a story. Specifically, it should include:
- [ ] a class definition header that matches the file name
- [ ] a main method for the program
- [ ] the use of camelCase when appropriate
- [ ] comments describing the algorithms
- [ ] a variable containing the incomplete Mad Lib
- [ ] methods from String class
- [ ] algorithm(s) that process user input
- [ ] algorithm(s) to parse for the parts of speech to replace
- [ ] algorithm(s) to parse for sections to include
- [ ] various prompts to keep the user on track
- [ ] a final print statement to display the completed story
**Penalty:**
- [ ] Appropriate sentence structure & syntax
- [ ] Code that causes errors