Data Types
This is a deeper review on data types, wrapper classes and classes specific in preparation for using Data Structures.
Notes
See weekly notes here
Hacks
Early Seed
- Write a sample binary addition 1 + 1 = 10
- Have Java Code cell on screen at start of lecture
See code here
Small Code Excercises
- Write a Jupyter notebook on the primitive data types. Use
arrayand methods likesubstringandrandomas applicable:int,double,boolean,char - Next, convert each of the examples to corresponding Wrapper classes, using arrays
See code here
Key Concepts
Methods
- A method is a block of code which only runs when it's called
- Parameters, or data can be passed into a method
- Methods are used to perform certain actions. Another word for them is a function
- See more information on methods here
Control Structures
- Control structure are blocks of code that can change the path of execution. There are 3 kinds of control structures:
- Condiditional Branches - used for choosing between 2+ paths (
if/elsestatements) - Loops - used it iterate through multiple values/objects and repeatedly run specific code blocks (
for,while, anddo whileloops) - Branching Statements - used to break the flow of control in loops (
breakandcontinue)
- Condiditional Branches - used for choosing between 2+ paths (
- See more information on control structures here
Teacher's Code Examples
DiverseArray Example
- Methods?
- Yes,
DiverseArraydoes contain methods. Examples of methods are:arraySum(),rowSums(), andisDiverse().
- Yes,
- Control Structures?
- Yes,
DiverseArraydoes contain control stuctures. There are examples offorloops andifstatements.
- Yes,
- Fit data types?
- Yes,
DiverseArrayhas data types ofintandboolean. It also hasint[]andint[][].
- Yes,
Matrix Example
- Methods?
- Yes,
Matrixdoes contain methods. Examples of methods are:toString(),reverse(),keypad(), andnumbers().
- Yes,
- Control Structures?
- Yes,
Matrixdoes contain control structures. There are examples offorloops.
- Yes,
- Fit data types?
- Yes,
Matrixhas data types ofint. There are alsoint[][]andString.
- Yes,
Number Example
Math.random()is a static method that returns a floating-point that is ≥ 0 and < 1.- See more information on
Math.random()here
DoNothingByValue Example
- Methods?
- Yes,
DoNothingByValuedoes contain methods. Examples of methods are:changeIt(),changeIt2(), andchangeIt3().
- Yes,
- Control Structures?
- Yes,
DoNothingByValuedoes contain control structures. There are examples offorloops.
- Yes,
- Fit data types?
- Yes,
DoNothingByValuehas data types ofint. There are alsoString,ArrayList, andint[].
- Yes,
IntByReference Example
- Methods?
- Yes,
IntByReferencedoes contain methods. Examples of methods are:toString(),swapToLowHighOrder(), andswapper().
- Yes,
- Control Structures?
- Yes,
IntByReferencedoes contain control structures. There are examples ofifstatements.
- Yes,
- Fit data types?
- Yes,
IntByReferencehas data types ofint. There are alsoString,ArrayList, andint[].
- Yes,
Menu Example
- Find a way to make
Menuwork on a Jupyter Notebook.- View code here
- Are instances of
MenuRowandRunnabledata types and control structures?MenuRow()represents the constructor for the classMenuRow. In the constructor, all varibles in the class are initalized.Runnablerepresents an object. In the methodgetAction(), the return type isRunnable.
- Does
Driverhave control structures? If so, list all the control Structures.- Yes,
Driverhas control structures.whilelooptry/catchstatementsifstatements
- Yes,
College Board FRQ
- Look at 1 unique FRQ per pair/treo on AP Classroom that goes over Methods and Control Structures
- Provide teacher a Jupyter Notebook, Video, and/or Code that cover key concepts
- Make this better than AP Classroom, specifically trying to get these reviews to cover key parts in under Five minutes
- This option could use your PBL project and concepts if they were tailored to Teaching.
- Explore Testing requirements in AP Classroom Video
- Explore AP FRQ that teaches us about Methods and Control Structures FRQ, 18:10
- Make sure that code runs completely, complete any portion of FRQ that is undone. Complete FRQs in a Jupyter notebook with markdown description and comments is a requirement
- Integrate Data Types into the discussion as this is import concept when studying early materials
- Integrate Definition of Methods and Control Structures in comments and definitions.
See code here
Code
Binary Addition
/*
* adds two binary numbers
*/
public class BinaryAddition
{
/*
* tester method
*/
public static void main(String[] Args)
{
String sum;
String binary1 = "0110";
String binary2 = "1011";
// outputs numbers in binary form
System.out.printf("number #1 in binary: \t\t%s\n", binary1);
System.out.printf("number #2 in binary: \t\t%s\n\n", binary2);
// calls addNums method
sum = addNums(binary1, binary2);
// outputs the sum in binary form
System.out.printf("sum in binary: \t\t\t%s", sum);
}
/*
* takes two binary strings, converts them into ints, and
* adds the two numbers together
*/
public static String addNums(String binary1, String binary2)
{
// Integer.parseInt() --> String to int
int num1 = Integer.parseInt(binary1, 2);
int num2 = Integer.parseInt(binary2, 2);
int sum = num1 + num2;
// outputs sum in decimal (number) form
System.out.printf("number #1 in decimal form: \t%d\n", num1);
System.out.printf("number #2 in decimal form: \t%d\n", num2);
System.out.printf("\nsum in decimal form: \t\t%d\n", sum);
// Integer.toBinaryString(sum); --> add numbers and converts the result to the binary String
return Integer.toBinaryString(sum);
}
}
BinaryAddition.main(null);
int[] nums = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
// regular
for(int i = 0; i < nums.length; i+=2)
{
System.out.printf("%d\n", nums[i]);
}
int x;
int y;
double casting1;
double casting2;
x = 10;
y = 15;
casting1 = (double) y / x;
casting2 = y / x;
System.out.printf("With casting: \t\t%.2f\nWithout casting: \t%.2f", casting1, casting2);
boolean a = true;
boolean b = false;
boolean c = a && b;
boolean d = !(a || b);
System.out.printf("%b\n", c);
System.out.printf("%b", d);
char[] letters = {'H', 'E', 'L', 'L', 'O', ' ', 'W', 'O', 'R', 'L', 'D'};
// regular
for(int i = 0; i < letters.length; i++)
{
System.out.printf("%c", letters[i]);
}
String message = "Hello World";
String newMessage = message.substring(6);
System.out.printf("Before substring: \t%s\n", message);
System.out.printf("After substring: \t%s", newMessage);
int max = 5;
int min = 0;
int range = max - min + 1;
for (int i = 0; i < 5; i++) {
int rand = (int)(Math.random() * range) + min;
System.out.printf("#%d: %d\n", i, rand);
}
Wrapper classes
Wrapper classes provide a class for each primitive type in Java. For example, the wrapper class for int is Integer, char is Character, and so on. These wrapper classes extend the object class.
The syntax for a wrapper object is: wrapper class name = value;
Beware, though. Not all data types that start with a capital letter is a wrapper class. For instance, I originally thought that String was a wrapper class. After googling "is String a wrapper class?", the results told me that String is not a wrapper class because it does not have a primitive class that it wraps.
Therefore, wrapper classes only wrap the eight primitive types, which means there are only eight wrapper classes.
The following cells consist of the previous primitive type examples converted into wrapper classes.
Integer[] nums = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
// regular
for(int i = 0; i < nums.length; i+=2)
{
System.out.printf("%d\n", nums[i]);
}
int x;
int y;
Double casting1;
Integer casting2;
x = 10;
y = 15;
casting1 = (double) y / x;
casting2 = y / x;
System.out.println("With casting: " + casting1);
System.out.println("With casting: " + casting2);
Boolean a = true;
Boolean b = false;
Boolean c = a && b;
Boolean d = !(a || b);
System.out.printf("%b\n", c);
System.out.printf("%b", d);
Character[] letters = {'H', 'E', 'L', 'L', 'O', ' ', 'W', 'O', 'R', 'L', 'D'};
// regular
for(int i = 0; i < letters.length; i++)
{
System.out.printf("%c", letters[i]);
}
Where are wrapper classes used?
One example of where wrapper classes are used is in Collection objects, such as ArrayList. ArrayList can not store primitive data types, and as such, need to be configured with wrapper classes.
ArrayList<Integer> nums = new ArrayList<Integer>();
nums.add(1);
nums.add(2);
for (int i = 0; i < nums.size(); i++) {
System.out.println(nums.get(i));
}
DoNothingByValue
Key knowledge
The value of arguments are passed into a method's parameters
Java is pass-by-value, not pass-by-reference for methods
- If you go down the StackOverflow rabbit hole, users claim that everything in java is pass-by-value. Honestly I'm not too sure how this works, but people on StackOverflow really pay close attention to detail so...
Unfortunately I don't have enough time right now to look into it closely. I might in the future though 😃
But basically since everything is pass-by-value, arrays are also passed-by-value. However, the value of an array is its reference. Therefore, when an array is passed into a method, the elements of the array can be changed directly.
- Pass-by-value: The value of a variable is passed
- Pass-by-reference: The variable's reference is passed. This allows the contents of the variable to be changed.
- There can only be 1 return value per method in Java
- Classes and generics allow "pass-by-reference"
Overall explanation of code
This is my thought process as I went through the code. It's easier for me to figure out key knowledge by going through the entire code and documenting what it does.
Anything that I highlight below are included in the key knowledge
Do Nothings
main()
An array called nums is created and set to {1, 3, 4, 5, 5}. The data type is the primitive data type int. An int of name value is also created and set to 6. A data type (but not wrapper class) of String with name name is created and set to blackboard. The code outputs Do Nothings and executes the changeIt method, passing in nums, value, and name.
changeIt()
Within the changeIt method, the argument nums relates to the parameter arr, value to val, and name to word. arr is created to have 5 elements, val is set to 0, and word is set to a substring of the word argumenent of blackboard. As such, word is set to black.
However, before the variables are reassigned to new values, the arguments were passed into the method's parameters. For instance, if I use a for loop to output the values of arr, I get 1, 2, 3, 4, 5, not 0, 0, 0, 0, 0.


The for loop (the actual one in the file) then assigns each element in arr to 0, and outputs it to the terminal. Lastly, the value of word (black) is outputted.
Next thing in main() is changeIt2()
changeIt2()
In changeIt2(), the arguments are passed in as parameters of nums, value, and name. Notice how these parameters have the same name as the arguments. Based on the comment in the file, we can see that the name of the parameter can be the same as the arguments' names.
changeIt2() essentially does the same thing as changeIt()
main()
What's important is that when you go back to main(), the for loop after changeIt2() outputs all of the original values of nums, value, and name. This is because Java is pass-by-value for methods, which means that the variable's values are passed into the method, NOT the reference. On the other hand, pass-by-reference allows you to edit the contents of a variable because the **reference** to the variable is passed.
Limited return
main()
An array named nums2 is assigned to 1, 2, 3, 4, 5. value is assigned to 6, and name is assigned to limited. name is then assigned to the return of changeIt3() and masses in nums2 and name.
changeIt3()
Within the changeIt3() method, you can see that the parameter word (passed in as argument name) is assigned to a new String. A simplified way of writing this would be word = word.substring(0, 5). Both ways work because the shorthand for creating wrapper classes is directly assigning the class to a value; however, behind the scenes, an object is still created.
Within this method, each element of the array is modified to 0, and the word is modified to limit.
main()
Back to main() again, the elements of nums2 are printed out. The edited elements from `changeIt3()` are present because arrays are objects, and the value of an object is its reference.
Do Something with Class
At this point, I got a general understanding of what the code does, so I did not need to write out what each line does.
This section creates a DoNothingByValue object with an object name of doSomething. The constructor runs. Since the object's value is its reference, the constructor can directly edit the variables. As a result, the output in main() shows the changes of the constructor.
Do Something with Generics
This is basically the same thing as class since generics are like objects but are more general, so you can specify different data types.
import java.util.ArrayList;
import java.util.Arrays;
public class FrogSimulation
{
// data type is an integer
private int goalDistance; // distance in inches, from the starting position to the goal
private int maxHops; // max number of hops allowed to reach the goal
// ArrayList is created to store hopdistances
// Data type is wrapper class Integer, the reason is because ArrayLists can only store wrapper types
// and not primitive types
private ArrayList <Integer> hopDistances;
public FrogSimulation(int dist, int numHops)
{
goalDistance = dist;
maxHops = numHops;
}
public void loadHopDistance(ArrayList <Integer> hopDistances)
{
this.hopDistances = new ArrayList <Integer> (hopDistances);
}
private int hopDistance()
{
if(!hopDistances.isEmpty())
{
int hopDistance = hopDistances.get(0);
hopDistances.remove(0);
return hopDistance;
}
return 0;
}
public boolean simulate()
{
int hops = 0;
int currentPosition = 0;
while((currentPosition < goalDistance)
&& ((hops != maxHops)
&& (currentPosition < goalDistance))
&& (currentPosition >= 0))
{
hops++;
currentPosition += hopDistance();
}
if((currentPosition >= goalDistance))
{
return true;
}
return false;
}
public double runSimulations (int num)
{
return 0.0;
}
public static void main(String[] Args)
{
FrogSimulation sim = new FrogSimulation(24, 5);
ArrayList <Integer> frogJumps1 = new ArrayList <Integer>(Arrays.asList(5, 7, -2, 8, 6));
ArrayList <Integer> frogJumps2 = new ArrayList <Integer>(Arrays.asList(6, 7, 6, 6));
ArrayList <Integer> frogJumps3 = new ArrayList <Integer>(Arrays.asList(6, -6, 31));
ArrayList <Integer> frogJumps4 = new ArrayList <Integer>(Arrays.asList(4, 2, -8));
ArrayList <Integer> frogJumps5 = new ArrayList <Integer>(Arrays.asList(5, 4, 2, 4, 3));
sim.loadHopDistance(frogJumps1);
boolean goalReached = sim.simulate();
System.out.printf("𓆏 reached goal? %b.\n", goalReached);
}
}
FrogSimulation.main(null);
1b
public double runSimulations(int num) {
int count = 0;
for (int i = 0; i < num; i++) {
if (simulate()) {
count++;
}
}
return (double)count/num;
}