Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 20: Wrapper Classes and More Loops

Similar presentations


Presentation on theme: "Lecture 20: Wrapper Classes and More Loops"— Presentation transcript:

1 Lecture 20: Wrapper Classes and More Loops
Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp Copyright (c) Pearson All rights reserved.

2 Wrapper Classes A wrapper class takes an existing value of primitive type and “wraps” or “boxes” it in an object, and provides a new set of methods for that type. It can be used in Java container classes that requires the item to be objects. (Arraylist)

3 Wrapper Classes The wrapper class allows
The construction of an object from a single value(wrapping or boxing the primitive in a wrapper object. The retrieval of a primitive value(unwrapping or unboxing from a wrapper object.)

4 Wrapper Classes Java allows wrapper object for each of its primitive types. The two that will be on the AP Exam are Integer and Double classes. Primitive Type Wrapper Type int Integer double Double char Character boolean Boolean

5 Integer Class The Integer class wraps a value of type int in an object. This class has only one instance variable whose type is int. Here are its methods: Integer(int value): Constructs an Integer object from an int(boxing). int compareTo(Integer other): Returns 0 if the value of this Integer is equal to the value of the other, a negative integer if it is less than the value of other and a positive integer if it is greater than the value of other.

6 Integer Class int intValue(): Returns the value of this Integer as an int(unboxing). boolean equals(Object obj): Returns true if and only if this Integer has the same int value as obj. This method overrides the equals method from class Object. This method throws a ClassCastException if obj is not an Integer. String toString(): Returns a String representing the value of this Integer.

7 Double Class The Double class wraps a value of type double in an object. This class has only one instance variable whose type is double. Here are its methods: Double(double value): Constructs an Double object from an double(boxing). int compareTo(Double other): Returns 0 if the value of this Double is equal to the value of the other, a negative integer if it is less than the value of other and a positive integer if it is greater than the value of other.

8 Double Class double doubleValue(): Returns the value of this Double as a double(unboxing). boolean equals(Object obj): Returns true if and only if this Double has the same double value as obj. This method overrides the equals method from class Object. This method throws a ClassCastException if obj is not a Double. String toString(): Returns a String representing the value of this Double.

9 Examples Integer intObj=new Integer(6);//boxes 6 in Integer object
int j=intObj.intValue(); //unboxes 6 from Integer object System.out.println(“Integer value is ”+intObj); //calls toString() for intObj //output is Integer value is 6

10 Examples Object a=new Integer(5); int j=4; Integer b=new Integer(5);
int k=b.intValue(); if(a==b) //false if(a.equals(b)) //true, polymorphism, which equals version? if(a.intValue()==b.intValue()) //error, Object has no intValue if(k==b.intValue()) //ok,comparing primitives if(k.equals(j)) //error, j and k not objects if(b.compareTo(a)<0) //error, need to cast if(b.compareTo((Integer)a)<0)//ok

11 Examples Double dObj=new Double(2.5);//boxes 2.5 in Double object
double d=dObj.doubleValue(); //unboxes 2.5 from Double object Object object=new Double(7.3); Object intObj=new Integer(4); if(dObj.compareTo((Double)object>0) //remember to cast if(dObj.compareTo(intObj)>0) //class cast exception //can’t compare Integer //with Double

12 Auto-Boxing and Unboxing
Auto-boxing is the automatic wrapping of primitive types in their wrapper classes. To retrieve the value of an Integer(or Double), the intValue() (or doubleValue()) method must be invoked(unwrapped). Auto- unboxing is the automatic conversion of a wrapper class to its corresponding primitive type. This means you don’t need to explicitly call the intValue() or doubleValue().

13 Auto-Boxing and Unboxing
Auto-boxing and unboxing reduce code clutter but are still performed behind the scenes and can decrease run time efficiency. When possible, use arrays of integers rather than arraylist of Integers.

14 Examples Integer a=new Integer(5); int x=a; //auto unboxing
Integer b=7; //auto-boxing int y=a+x; //auto-unboxing NOTE: Autoboxing and unboxing will not be test on the AP Exam. However, it is ok to use these features of Java in writing your answers to the free response section.

15 For-Each Loop

16 For-Each Loop The for-each or enhanced for loop is used to iterate over an array or arraylist. The general form of the loop is for(SomeType element: collection) { ... } How would we print a multiplication table? try printing each of the following inside the inner loop: System.out.print(i + " "); System.out.print(j + " "); System.out.print((i * j) + " ");

17 For-Each Loop int[] arr={1,4,3,5}; for(int i=0;i<arr.length;i++)
System.out.println(arr[i]); //for each for(int element : arr) System.out.println(element); The for-each loop cannot be used for replacing or removing elements as you traverse. The loop hides the index variable that is used with arrays. How would we print a multiplication table? try printing each of the following inside the inner loop: System.out.print(i + " "); System.out.print(j + " "); System.out.print((i * j) + " ");

18 For-Each Loop What is the output of the following code? int[] arr={1,4,3,5}; for(int element : arr) element=7; System.out.println(Arrays.toString(arr)); Output: [1,4,3,5] The for-each loop cannot be used for replacing or removing elements as you traverse! In this case, element is a temporary variable and does not refer to any element in the array. How would we print a multiplication table? try printing each of the following inside the inner loop: System.out.print(i + " "); System.out.print(j + " "); System.out.print((i * j) + " ");

19 For-Each Loop For each is the same for both an array and an arraylist.
String[] array=new String[2]; array[0]=“hello”; array[1]=“goodbye”; ArrayList<String> list=new ArrayList<String>(); list.add(“hi”); list.add(“hello”); for(String s: array) System.out.println(s); for(String s: list) How would we print a multiplication table? try printing each of the following inside the inner loop: System.out.print(i + " "); System.out.print(j + " "); System.out.print((i * j) + " ");

20 For Each The for-each construction is the same for objects.
Point[] pts={new Point(),new Point(1,2),new Point(-1,4)}; for(Point element : pts) System.out.println(element+” “); //toString() How would we print a multiplication table? try printing each of the following inside the inner loop: System.out.print(i + " "); System.out.print(j + " "); System.out.print((i * j) + " ");

21 For Each The for-each construction can be used with 2D arrays. Use nested for each loops. int[][] matrix={{1,5,6}{-3,-1,7},{0,1,-1}} int sum=0; for(int[] row: matrix){ for(int element: row) sum+=element;} for(int i=0;i<matrix.length;i++) for(int j=0;j<matrix[0].length;j++) sum+=matrix[i][j]; How would we print a multiplication table? try printing each of the following inside the inner loop: System.out.print(i + " "); System.out.print(j + " "); System.out.print((i * j) + " ");

22 Lab 3 Write the Test class with the instance variables and methods listed below. If necessary, modify the Question class written previously. public class Test{ private ArrayList<Question> questions; private int[] points; public Test(ArrayList<Question> questions) {…} public int totalPoints(){…} public void printTest() {…} public void printAnswers() {…} public void setPoints(int mcPoints, int shortPoints) {…} public boolean addChoice(int questionNumber, String choice) {…} public void scrambleTest() {…} }

23 Lab 3 A Test consists of an arraylist of questions and an array of point value for each question. public Test(ArrayList<Question> questions) The Test class has one constructor to initialize the arraylist questions. This constructor must call setPoints(int mcPoints, int shortPoints) to initialize the points array. Each multiple choice is worth 5 points and each short answer 10 points. public int totalPoints() This method returns the total number of points for the test. public void printTest() This method prints the entire test with proper numbering of the questions.

24 Lab 3 public void printAnswers()
This method prints a numbered list of answers to each question on the test. It should also prints the point value for each question. For example, (5 points) B: George Washington. (10 points) Teddy Roosevelt. etc.. public void setPoints(int mcPoints, int shortPoints) This method initializes the points array. Each multiple choice question is worth mcPoints and each short answer question is worth shortPoints. public boolean addChoice(int questionNumber, String choice) This method adds a choice to the question given by questionNumber. Returns true if added properly and false otherwise.

25 Lab 3 public void scrambleTest(); This method scrambles the test questions. You must create a new temporary arraylist of questions. The method must pick a random question from the instance variable arraylist questions, remove it and add it to the temporary arraylist. You must use Math.random(). In addition, the method updates the arraylist questions and the points array.


Download ppt "Lecture 20: Wrapper Classes and More Loops"

Similar presentations


Ads by Google