Unit 1 Notes
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);
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);
int test = 5; // PROBLEM!!
String test2 = test.toString();
System.out.println(test2);
String hello = "hello";
String world = "world";
System.out.println(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));
System.out.println(Math.random());