Learnings

The main thing I learned for unit 1 is the idea of wrapper classes. Wrapper classes help make objects out of primitives, allowing access to many methods. For example, the wrapper class of int is Integer.

Notes

Casting: Changes the primitive data type

Casting is useful in division because if two integers are divided, the places after the decimal are truncated without rounding. To have an accurate division, type cast the integers with (double) to retain the decimal.

To round a number and return the result as an integer, add 0.5 to the number and then typecast it to an integer ((int)).

int a = 1; 
int b = 3; 

System.out.println("Dividing two integers: " + a/b); 

double quotient = (double)a/(double)b;
System.out.println("Dividing two doubles (originally integers): " + quotient); 

System.out.println(); 

// truncating
double c = 5.5; 
System.out.println("The value of double c is: " + c);
System.out.println("Truncating double c: " + (int)c); 

// rounding
int roundedNum = (int)(c+0.5);
System.out.println("Rounding double c: " + roundedNum);
Dividing two integers: 0
Dividing two doubles (originally integers): 0.3333333333333333

The value of double c is: 5.5
Truncating double c: 5
Rounding double c: 6

Wrapper classes

Wrapper classes create objects out of primitives. The wrapper class capitalizes the first letter of the primitive data type and writes out the entire word. For example, the wrapper class of int is Integer.

Because wrapper classes create objects, there are many methods that can be used (shown in the code below).

Note: ArrayLists can only use wrapper classes; they can not use primitives.

toString(): Notice how Integer must be used, while int creates an error.

Integer test = 5; 
String test2 = test.toString(); 

System.out.println(test2);
5
int test = 5; // PROBLEM!!
String test2 = test.toString(); 

System.out.println(test2);
|   String test2 = test.toString();
int cannot be dereferenced

Concatenation

Concatenation combines multiple strings together into one string.

Concatenation can be used with the plus sign: + or with the concat() method.

Below is an example of concatenation using +:

String hello = "hello"; 
String world = "world"; 

System.out.println(hello + " " + world);
hello world

Below is an example of concatenation using concat()

The syntax is: concat(second string to add on to first string)

String hello = "hello"; 
String world = "world"; 

System.out.println(hello.concat(world));
helloworld

Math

One of the Math methods that will be used frequently is random(). Math.random() returns a random number between 0 and 1, including 0 but excluding 1.

System.out.println(Math.random());
0.0758836497465144