Primitives, References and Wrappers Java has the following types defined as part of the java language; int float double byte char boolean long short These are known as the primitive types, since they are basic storage units built in to java. 1 AP Comp Sci wrapper notesheets
Primitives, References and Wrappers Java simply allocates memory for primitives when they are in scope. Example int input=5, sum; double average; 2 AP Comp Sci wrapper notesheets 5 input 0 sum 0.0 average
Primitives, References and Wrappers References, however, are not part of the java language. They are defined in libraries and start with capital letters JLabel titleLbl; 3 AP Comp Sci wrapper notesheets null JLabel titleLbl = new JLabel(“Hangman”); After the new command, the reference now points to an object JLabel “Hangman” JLabel 8F10
The Integer and Double Wrapper Classes Java has provided wrapper classes for all of the primitive types The AP subset contains two of these java.lang.Integer java.lang.Double These bad boys are both immutable, once given a value, they cannot be changed Creating objects using the wrappers Must set the values when creating the object Double x = new Double(3.14); //you try, create two Integer objects with values Integer i1 = new Integer(1999); Integer i2; i2 = new Integer(2003); //Create your own Double with a value Double myDoub; myDoub = new Double( ); NOTE: to assign a new value, myDoub = new Double(2.7); Methods to use with the wrappers int compareTo(Object other) Write an if statement to compare your two integers if(i1.compareTo(i2) < 0) { SOP(“i1 less than i2”); } 4 AP Comp Sci wrapper notesheets
The Integer and Double Wrapper Classes boolean equals(Object other) equals is the only way to compare the VALUES of two Integer or Double objects == will compare the _____________ memory addresses write a statement to use equals to compare your two Integer objects if(i1.equals(i2)) { SOP(“the two ints are equal”); } 5 AP Comp Sci wrapper notesheets
The Integer and Double Wrapper Classes Methods to use with the wrappers (cont’d) int intValue() Gets the VALUE of the integer from the Integer wrapper int x = i1.intValue() + i2.intValue(); double doubleValue() //You try, create a double primitive and assign into it the product of a Double called d1 and a Double called d2 double product = d1.doubleValue() * d2.doubleValue(); String toString() returns the integer or double in a string 6 AP Comp Sci wrapper notesheets