Data Types
Data types
- Java Binary Addition
- Primitive Types and Pass by Value
- Methods and Control Structures
- Looking at the Diverse Arrays/Matrix
- Math.random
- DoNothingByValue.java
- Java Methods
- Java Control Structures
- IntByReference
public static String addBinary(){
String num1 = "1";
String num2 = "1";
int num1Binary = Integer.parseInt(num1, 2);
int num2Binary = Integer.parseInt(num2, 2);
int sum = + num1Binary + num1Binary;
return Integer.toBinaryString(sum);
}
addBinary();
public class PrimitiveTypes {
public int a;
public double b;
public boolean c;
public char d;
public PrimitiveTypes(int a, double b, boolean c, char d) {
this.a = a;
this.b = b;
this.c = c;
this.d = d;
}
public void ChangePrimitiveTypes(int newInt, double newDouble, boolean newBool, char newChar) {
this.a = newInt + 1;
this.b = newDouble + 1;
this.c = !newBool;
this.d = 'z';
}
public static void main(String[] args) {
PrimitiveTypes PT = new PrimitiveTypes(5, 10.5, false, 'd');
int aDuplicate = PT.a;
double bDuplicate = PT.b;
boolean cDuplicate = PT.c;
char dDuplicate = PT.d;
System.out.println("Integer is: " + PT.a);
System.out.println("Double is: " + PT.b);
System.out.println("Boolean is: " + PT.c);
System.out.println("Char is: " + PT.d);
System.out.println();
PT.ChangePrimitiveTypes(PT.a, PT.b, PT.c, PT.d);
System.out.println("Changed Integer is: " + PT.a);
System.out.println("Changed Double is: " + PT.b);
System.out.println("Changed Boolean is: " + PT.c);
System.out.println("Changed Char is: " + PT.d);
System.out.println();
System.out.println("Duplicated Integer is: " + aDuplicate);
System.out.println("Duplicated Double is: " + bDuplicate);
System.out.println("Duplicated Boolean is: " + cDuplicate);
System.out.println("Duplicated Char is: " + dDuplicate);
}
}
PrimitiveTypes.main(null);
Above, we see an integer, double, boolean, and char all being defined in a Java class and assigned values through the constructor. We pass in these values to the ChangePrimitiveTypes function, which modifies each value. In Java, primitive types are passed by value, which means that the variable stores an actual value. We can visualize this through the above class. After we assign initial values to the variables in the class, we create 4 new variables and assign their values to be the same as the values of the variables in the class. Now, we print the original values of the 4 variables in the class. Then, we change all of the values of the variables in the class, and print the variables again. We see that the new values are printed. However, when we print the 4 new variables we created at the start, they still contain the original values we assigned. This is because these 4 variables contained actual values, and since we never modified those variables the values never changed.
import java.util.ArrayList;
public class ReferenceTypes {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4};
int[] arr2 = arr1;
System.out.print("Arr1 original: ");
System.out.println(Arrays.toString(arr1));
System.out.print("Arr2 original: ");
System.out.println(Arrays.toString(arr2));
arr1[0] = 5;
System.out.println();
System.out.print("Arr1 Changed: ");
System.out.println(Arrays.toString(arr1));
System.out.print("Arr2 Changed: ");
System.out.println(Arrays.toString(arr2));
ArrayList<Integer> list = new ArrayList<>();
for (int i : arr1) {
list.add(i);
}
System.out.println();
System.out.print("ArrayList: ");
System.out.print(list.toString());
}
}
ReferenceTypes.main(null);
While int is a primitive type, Integer is a wrapper class for integer and is a reference type. In the above class, we see this wrapper class being necessary to pass in primitive type values to an array list.
We also visualize the behavior of reference types in the above class. Arr1 is assigned to a value, and Arr2 is assigned to Arr1. Both Arr1 and Arr2 are different variables, but they both point to the same address in memory for the value of the array. Therefore, when Arr1 is changed, Arr2 also appears to change, because they reference the same value.
Note: For Strings, although they are considered reference types, this behavior is not seen. The reason for this is that Strings are immutable in Java.
- Methods in overall coding are blocks of code that can be called upon and reused when needed within anywhere of the code.
- When defining methods, one should be aware of the variable type that the method would return, parameters it takes in, of course the code, and then its implementation in calling.
-
2D Arrays are slightly tricky - the outer int[][] array is considered a non-primitive data type, meaning that values like null can be stored. However, within each array only primitive data types of the respective variable type can be stored.
-
Within Mort's code he defines various methods within the Diverse array class, beginning with the arraySum method. It takes in an array, and finds the sum of the integers in the array.
public class DiverseArray { public static int arraySum(int[] arr) { int sum = 0;
for (int num : arr) {
sum += num;
System.out.print(num + "\t");
}
return sum;
}
- Next, he creates the sum of 2d arrays. Within the method he uses the other method defined previously to return a list of the sums of each row of the 2d array.
public static int[] rowSums(int[][] arr2D) {
int rows = arr2D.length;
int[] sumList = new int[rows];
for (int i = 0; i < rows; i++) {
sumList[i] = arraySum(arr2D[i]);
System.out.println("= \t" + sumList[i]); // debug
}
return sumList;
} z
- The final method simply checks if the rows are similar to each other
- Math.random generates a random value from 0 to 1. When multiplied by a range it generates a value in that range.
- In Number.java, it is used like so
public Number() {
int SIZE = 36; int MIN = 3; int RANGE = SIZE - MIN + 1; // constants for initialization
this.number = (int)(Math.random()*RANGE) + MIN; // observe RANGE calculation and MIN offset
this.index = Number.COUNT++; // observe use of Class variable COUNT and post increment
}
- Here a range is set with variables so that it could be easily altered. Also be sure to cast the number as an integer so that a decimal value doesn't occur.
-
Overall, the DoNothingByValue demonstrates several methods of passing arguments.
-
The DoNothings method does nothing, it just shows how to pass in arguments
-
Within the changeIt method, functions are done locally to the variables, however in the end, the arr outside the method is not altered, and thus is not changed.
public static void changeIt(int [] arr, int val, String word) {
arr = new int[5]; val = 0; word = word.substring(0, 5);
System.out.print("changeIt: "); // added for (int k = 0; k < arr.length; k++) {
arr[k] = 0;
System.out.print(arr[k] + " "); // added
} System.out.println(word); // added
}
- The changeIt2 demonstrates the creation of non primitive data type, even though the data type has the same name, they can be referred differently with different alterations to the array while still keeping its original values in a seperate one. If you print 'arr' it will be the original list.
public static void changeIt2(int [] nums, int value, String name) {
nums = new int[5]; // new creates new memory address value = 0; // primitives are pass by value
name = name.substring(0, 5); // all wrapper classes have automatic "new", same as word = new String(word.substring(0, 5));
// this loop changes nums locally
System.out.print("changeIt2: ");
for (int k = 0; k < nums.length; k++) {
nums[k] = 0;
System.out.print(nums[k] + " ");
}
System.out.println(name);
}
- In changeIt3 'arr' is actually modified, and the original is modified. However, since a new string object for word was created, the original 'word' will not be modified because now it is a localized variable to the method.
public static String changeIt3(int [] arr, String word) {
word = new String(word.substring(0, 5)); // wrapper class does a "new" on any assignment
System.out.print("changeIt3: ");
for (int k = 0; k < arr.length; k++) {
arr[k] = 0; // int array is initialized to 0's, not needed
System.out.print(arr[k] + " ");
}
System.out.println(word);
return word;
}
- For changeIt4, first the Triple type should be explained. Simply put, Triple can store three values within the data structure, each can be with a different data type. They are referred by left, middle, and right.
- This simply shows how to modify an object passed by parameter.
public static Triple<int[], Integer, String> changeIt4(Triple<int[], Integer, String> T) {
T.setOne(new int[5]); T.setTwo(0); // primitives are pass by value
T.setThree(T.getThree().substring(0, 5)); // all wrapper classes have automatic "new", same as word = new String(word.substring(0, 5));
// this loop changes nums locally
System.out.print("changeIt4: ");
for (int i : T.getOne()) {
System.out.print(i + " ");
}
System.out.println(T.getThree());
return T;
}
-
a method is a block of code that performs a specific task and can be called by other parts of the program
-
a method consists of a method signature, which includes the method name, return type, and parameter list, and a method body, which contains the code that is executed when the method is called
public int addNumbers(int num1, int num2) {
int sum = num1 + num2;
return sum;
}
System.out.println(addNumbers(10, 20));
-
control structures are constructs that allow you to control the flow of execution in a program
-
they let you execute specific statements or blocks of code based on certain conditions
-
some examples: if-else, for loop, while loop, switch case
-
The IntByReference class uses the integer primitive and its function is swapping the two inputted numbers, if the first is greater than the second
-
A wrapper class is used to change a primitive int into an Integer object
-
the Integer object is turned back into a primitive type "tmp" to switch values
public class IntByReference {
// sets primitive
private int value;
//wrapper class
public IntByReference(Integer value) {
this.value = value;
}
public String toString() {
return (String.format("%d", this.value));
}
// function to swap the values
public void swapToLowHighOrder(IntByReference i) {
// if first value larger than second, then swap
if (this.value > i.value) {
//sets the first value back to a primitive type
int tmp = this.value;
this.value = i.value;
i.value = tmp;
}
}
public static void swapper(int n0, int n1) {
IntByReference a = new IntByReference(n0); // creates objects with wrapper class using primitive int
IntByReference b = new IntByReference(n1);
System.out.println("Before: " + a + " " + b);
a.swapToLowHighOrder(b); //calls method
System.out.println("After: " + a + " " + b);
System.out.println();
}
public static void main(String[] ags) {
IntByReference.swapper(21, 16);
IntByReference.swapper(16, 21);
IntByReference.swapper(16, -1);
}
}
IntByReference.main(null);