Key Terms

  • Reference Data: Reference to memory location, address points to where the variables are actually located. Used to store complex data structures (objects/arrays)
  • Primitives: Local variables, stored directly in memory and passed by value
  • Wrapper Class: A class that wraps a primitive data type into an object

Auto-boxing: Int converting to a class Integer, it does this automatically

// Both of these create new objects
Integer n = 5; // Auto-boxing, Integer n = new Integer(5);
n += 5;  // Auto-boxing, Integer n = new Integer(n + 5);

Examples

// Binary addition example adding 5 and 6

//setting our binary string values
String five = "0101";
String six = "0110";

//converting binary strings to decimal number
int num1 = Integer.parseInt(five, 2);
int num2 = Integer.parseInt(six, 2);

//Adding two decimals together
int sum = num1 + num2;

//Converting decimal to binary string
String eleven = Integer.toBinaryString(sum);

System.out.println("Eleven");
System.out.println(eleven);
Eleven
1011
//passes by value
public class IntByValue {
    
    public static void changeInt(int n) {
        System.out.println("In changeInt method");
        System.out.println("\tBefore n += 10: n = " + n); // prints 5
        n = n += 10;
        System.out.println("\tAfter n += 10: n = " + n); // prints 10
    }

    public static void main(String[] args) {
        //starts with int n
        int n = 5;
        System.out.println("Main method before changeInt(n): n = " + n); // prints 5
        //changes int to 15
        changeInt(n);
        //still prints out 5, because it changeInt uses reference 
        //and makes its own n, which is not the same as the local n in main
        System.out.println("Main method after changeInt(n): n = " + n); // still prints 5
    }
}
IntByValue.main(null);
Main method before changeInt(n): n = 5
In changeInt method
	Before n += 10: n = 5
	After n += 10: n = 15
Main method after changeInt(n): n = 5
//passes by value
public class IntegerByValueOrReference {
    
    public static void changeInteger(Integer n) {
        System.out.println("In changeInteger method");
        System.out.println("\tBefore change: n = " + 
                            n + // prints 5
                            " hash code = " + 
                            n.hashCode()); 

        n += 10;  // behind the scenes, this is:  n = new Integer(n+10)
        
        System.out.println("\tAfter change: n = " + 
                            n + // prints 15
                            " hash code = " + 
                            n.hashCode()); 
    }

    public static void main(String[] args) {
        Integer n = 5;
        System.out.println("Main method before changeInteger(n): n = " + 
                            n + // prints 5
                            " hash code = " + 
                            n.hashCode()); 

        changeInteger(n);
        
        System.out.println("Main method after changeInteger(n): n = " + 
                            n +  // now prints 15
                            " hash code = " + 
                            n.hashCode());     
    }
}
IntegerByValueOrReference.main(null);
Main method before changeInteger(n): n = 5 hash code = 5
In changeInteger method
	Before change: n = 5 hash code = 5
	After change: n = 15 hash code = 15
Main method after changeInteger(n): n = 5 hash code = 5
//passes by reference
//swaps values to low high order
import java.util.concurrent.atomic.AtomicInteger;

public class PassByReference {
    
    public static void changeAtomicInteger(AtomicInteger n) {
        System.out.println("In changeAtomicInteger method");
        System.out.println("\tBefore change: n = " + 
                            n + // prints 5
                            " hash code = " + 
                            n.hashCode()); 
        n.set(n.get() + 10);  // at this point, we are clearly working with reference data type
        System.out.println("\tAfter change: n = " + 
                            n + // prints 15
                            " hash code = " + 
                            n.hashCode()); 
}

    public static void main(String[] args) {
        AtomicInteger n = new AtomicInteger(5); // unlike conventional wrapper class, this requires new
        System.out.println("Main method before changeAtomicInteger(n): n = " + 
                            n + // prints 5
                            " hash code = " + 
                            n.hashCode()); 
        changeAtomicInteger(n);
        System.out.println("Main method after changeAtomicInteger(n): n = " + 
                            n +  // now prints 15
                            " hash code = " + 
                            n.hashCode()); 
    }
}
PassByReference.main(null);
Main method before changeAtomicInteger(n): n = 5 hash code = 558640399
In changeAtomicInteger method
	Before change: n = 5 hash code = 558640399
	After change: n = 15 hash code = 558640399
Main method after changeAtomicInteger(n): n = 15 hash code = 558640399
//passes by reference
public class IntByReference {
    //property/attribute of the class
    private int value;

    public IntByReference(Integer value) {
        this.value = value;
    }

    public String toString() {
        return (String.format("%d", this.value));
    }

    public void swapToLowHighOrder(IntByReference i) {
        if (this.value > i.value) {
            int tmp = this.value;
            this.value = i.value;
            i.value = tmp;
        }
    }

    public static void swapper(int n0, int n1) {
        IntByReference a = new IntByReference(n0);
        IntByReference b = new IntByReference(n1);
        System.out.println("Before: " + a + " " + b);
        a.swapToLowHighOrder(b);  // conditionally build swap method to change values of a, b
        System.out.println("After: " + a + " " + b);
        System.out.println();
    }

    public static void main(String[] ags) {
        IntByReference.swapper(21, 16);
        IntByReference.swapper(16, 21);
        IntByReference.swapper(16, -1);
    }

}
IntByReference.main(null);
Before: 21 16
After: 16 21

Before: 16 21
After: 16 21

Before: 16 -1
After: -1 16

Exploring Datatypes

Method and Control Structures FRQ 2022

Users of a website are asked to provide a review of the website at the end of each visit. Each review, represented by an object of the Review class, consists of an integer indicating the user’s rating of the website and an optional String comment field. The comment field in a Review object ends with a period ("."), exclamation point ("!"), or letter, or is a String of length 0 if the user did not enter a comment.

public class Review
{
    private int rating;
    private String comment;
    /** Precondition: r >= 0
    * c is not null.
    */
    public Review(int r, String c)
    {
        rating = r;
        comment = c;
    }
    public int getRating()
    {
        return rating;
    }
    public String getComment()
    {
        return comment;
    }
    // There may be instance variables, constructors, and methods that are not shown.
}

The ReviewAnalysis class contains methods used to analyze the reviews provided by users. You will write two methods of the ReviewAnalysis class.

public class ReviewAnalysis
{
    /** All user reviews to be included in this analysis */
    private Review[] allReviews;
    /** Initializes allReviews to contain all the Review objects to be analyzed */
    public ReviewAnalysis()
    { /* implementation not shown */ }
    /** Returns a double representing the average rating of all the Review objects to be
    * analyzed, as described in part (a)
    * Precondition: allReviews contains at least one Review.
    * No element of allReviews is null.
    */
    public double getAverageRating()
    { /* to be implemented in part (a) */ }
    /** Returns an ArrayList of String objects containing formatted versions of
    * selected user comments, as described in part (b)
    * Precondition: allReviews contains at least one Review.
    * No element of allReviews is null.
    * Postcondition: allReviews is unchanged.
    */
    public ArrayList<String> collectComments()
    { /* to be implemented in part (b) */ } 
}

(Part A)

Write the ReviewAnalysis method getAverageRating, which returns the average rating (arithmetic mean) of all elements of allReviews. For example, getAverageRating would return 3.4 if allReviews contained the following Review objects.

0 1 2 3 4
4 3 5 2 3
"Good! Thx" "OK site" "Great! "Poor! Bad. " " "
Complete method getAverageRating.
/** Returns a double representing the average rating of all the Review objects to be
* analyzed, as described in part (a)
* Precondition: allReviews contains at least one Review.
* No element of allReviews is null.
*/
public double getAverageRating()
public double getAverageRating(){
    //total sum of ratings
    int totalRating = 0;
    //amount of ratings in allReviews
    int reviewNums = 0;

    for (Review rating : allReviews){
        //adds rating value to total
        totalRating += rating.getRating();
        //adds one to count of total number of ratings
        reviewNums += 1;
    }

    //creates new double value for average
    double averageRating = totalRating / reviewNums; 
    return averageRating;
}

(Part B)

Write the ReviewAnalysis method collectComments, which collects and formats only comments that contain an exclamation point. The method returns an ArrayList of String objects containing copies of user comments from allReviews that contain an exclamation point,formatted as follows. An empty ArrayList is returned if no comment in allReviews contains an exclamation point.

  • The String inserted into the ArrayList to be returned begins with the index of the Review in allReviews.
  • The index is immediately followed by a hyphen ("-").
  • The hyphen is followed by a copy of the original comment.
  • The String must end with either a period or an exclamation point. If the original comment from allReviews does not end in either a period or an exclamation point, a period is added.

The following example of allReviews is repeated from part (a) | 0 | 1 | 2 | 3 | 4 | | -- | -- | -- | -- | -- | | 4 | 3 | 5 | 2 | 3 | | "Good! Thx" | "OK site" | "Great! | "Poor! Bad. " | " " |

public ArrayList<String> collectComments()
{
  //creates new strings arrayList called commentsTotal
  ArrayList<String> commentsTotal = new ArrayList<String>();
  
  //for each review in allReview
  for(int i = 0; i < allReviews.length; i++)
  {
    //gets a comment from allReviews
    String comment = allReviews[i].getComment();
    //gets the index of the ! if there is one
    if(comment.indexOf("!") >= 0)
    {
      //prints index with "-" then comment
      String formatted = i + "-" + comment;
      //creates lastChar, which stores the last character in the formatted string
      String lastChar = formatted.substring(formatted.length() - 1);
      //if the lastChar isn't "!" or "." it adds a period
      if( ! lastChar.equals("!") && ! lastChar.equals("."))
        formatted += ".";
      //adds all the formatted comments into commentsTotal
      commentsTotal.add(formatted);
    }
  }

  return commentsTotal;
}