60 likes | 81 Views
Wrapper Classes. More than just a song and dance. What. They are objects that store primitive variable values: Integer – stores an int Double – stores a double Character – stores a char Boolean – stores a boolean. Why?.
E N D
Wrapper Classes More than just a song and dance.
What • They are objects that store primitive variable values: • Integer – stores an int • Double – stores a double • Character – stores a char • Boolean – stores a boolean
Why? • Sometimes you want a primitive value stored as an object. This allows you to: • Store primitives in complex data structures such as ArrayLists • They are pass by reference instead of pass by copy • They provide some additional helper methods
Helpful Methods • parseInt(String s) – takes in a String and converts it into the corresponding Integer • toHexString(inti) – converts an integer to a hexadecimal String • toBinaryString(inti) – converts an integer to a binary String
Implementation //Declaring variables Integer x = 5; Double y = 6.7; Character z = 'z'; Boolean flag = false; //Using parseInt String numInText = "29274"; Integer a = Integer.parseInt(numInText); //Performing operation Integer b = x + a; System.out.println(b);
Use in ArrayLists ArrayList <Integer> numbers = new ArrayList<Integer>(); numbers.add(3); numbers.add(5); numbers.add(7); System.out.println(numbers);