COP3337 Module2

¡Supera tus tareas y exámenes ahora con Quizwiz!

If a testbench achieves 100% code coverage and all tests passed, the class must be bug free.

false. 100% code coverage is one goal of testing, but doesn't guarantee correctness. Different input values may yield different behavior for the same line of code.

Given the declaration below, what is the value of table.length? int[][] table = { { 4, 3, 5 }, { 0, 4, 3 } };

2

What output is generated by the program segment below? int[] values = { 1, 3, 5, 3, 7 }; int count = 0; for (int number : values) { if (number > 4) { count++; } } System.out.print(count);

2

What does the array list names contain after the following statements? ArrayList<String> names = new ArrayList<String>; names.add("Bob"); names.add(0, "Ann"); names.remove(1); names.add("Cal");

"Ann", "Cal"

A seat reservation system involving a class, ArrayLists, and methods.

(OJO!!!!!!!!!!!) public class Seat { private String firstName; private String lastName; private int amountPaid; // Method to initialize Seat fields public void reserve(String resFirstName, String resLastName, int resAmountPaid) { firstName = resFirstName; lastName = resLastName; amountPaid = resAmountPaid; } // Method to empty a Seat public void makeEmpty() { firstName = "empty"; lastName = "empty"; amountPaid = 0; } // Method to check if Seat is empty public boolean isEmpty() { return (firstName.equals("empty")); } // Method to print Seat fields public void print() { System.out.print(firstName + " "); System.out.print(lastName + " "); System.out.println("Paid: " + amountPaid); } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public int getAmountPaid() { return amountPaid; } } SeatReservation.java import java.util.ArrayList; import java.util.Scanner; public class SeatReservation { /*** Methods for ArrayList of Seat objects ***/ public static void makeSeatsEmpty(ArrayList<Seat> seats) { int i; for (i = 0; i < seats.size(); ++i) { seats.get(i).makeEmpty(); } } public static void printSeats(ArrayList<Seat> seats) { int i; for (i = 0; i < seats.size(); ++i) { System.out.print(i + ": "); seats.get(i).print(); } } public static void addSeats(ArrayList<Seat> seats, int numSeats) { int i; for (i = 0; i < numSeats; ++i) { seats.add(new Seat()); } } /*** End methods for ArrayList of Seat objects ***/ public static void main (String [] args) { Scanner scnr = new Scanner(System.in); String usrInput; String firstName, lastName; int amountPaid; int seatNumber; Seat newSeat; ArrayList<Seat> allSeats = new ArrayList<Seat>(); usrInput = ""; // Add 5 seat objects to ArrayList addSeats(allSeats, 5); // Make all seats empty makeSeatsEmpty(allSeats); while (!usrInput.equals("q")) { System.out.println(); System.out.print("Enter command (p/r/q): "); usrInput = scnr.next(); if (usrInput.equals("p")) { // Print seats printSeats(allSeats); } else if (usrInput.equals("r")) { // Reserve seat System.out.print("Enter seat num: "); seatNumber = scnr.nextInt(); if ( !(allSeats.get(seatNumber).isEmpty()) ) { System.out.println("Seat not empty."); } else { System.out.print("Enter first name: "); firstName = scnr.next(); System.out.print("Enter last name: "); lastName = scnr.next(); System.out.print("Enter amount paid: "); amountPaid = scnr.nextInt(); newSeat = new Seat(); // Create new Seat object newSeat.reserve(firstName, lastName, amountPaid); // Set fields allSeats.set(seatNumber, newSeat); // Add new object to ArrayList System.out.println("Completed."); } } // FIXME: Add option to delete reservations else if (usrInput.equals("q")) { // Quit System.out.println("Quitting."); } else { System.out.println("Invalid command."); } } } }

Unit testing of a class.

(OJO!!!!!!!!!) Class to test: StatsInfo.java public class StatsInfo { // Note: This class intentionally has errors private int num1; private int num2; public void setNum1(int numVal) { num1 = numVal; } public void setNum2(int numVal) { num2 = numVal; } public int getNum1() { return num1; } public int getNum2() { return num1; } public int getAverage() { return num1 + num2 / 2; } } Testbench: StatsInfoTest.java public class StatsInfoTest { public static void main(String[] args) { StatsInfo testData = new StatsInfo(); // Typical testbench tests more thoroughly System.out.println("Beginning tests."); // Check set/get num1 testData.setNum1(100); if (testData.getNum1() != 100) { System.out.println(" FAILED set/get num1"); } // Check set/get num2 testData.setNum2(50); if (testData.getNum2() != 50) { System.out.println(" FAILED set/get num2"); } // Check getAverage() testData.setNum1(10); testData.setNum2(20); if (testData.getAverage() != 15) { System.out.println(" FAILED GetAverage for 10, 20"); } testData.setNum1(-10); testData.setNum2(0); if (testData.getAverage() != -5) { System.out.println(" FAILED GetAverage for -10, 0"); } System.out.println("Tests complete."); } }

You should be familiar with the implementation of fundamental algorithms so that you can adapt them. We can adapt the algorithm for finding the minimum to yield the position of the minimum. Here is the original algorithm:

(OJO!!!!) Click to hide a program that computes the final score using the adapted algorithm for finding the minimum. public class Student { private double[] scores; private int scoresSize; /** Constructs a student with no scores and a maximum number of scores. @capacity the maximum number of scores for this student */ public Student(int capacity) { scores = new double[capacity]; scoresSize = 0; } /** Adds a score for this student. @param score the score to add @return true if the score was added, false if there was no room to add the score */ public boolean addScore(double score) { if (scoresSize < scores.length) { scores[scoresSize] = score; scoresSize++; return true; } else { return false; } } /** Gets the position of the minimum score. @return the position of the smallest element of values, or -1 if there are no scores. */ public int minimumPosition() { if (scoresSize == 0) { return -1; } int smallestPosition = 0; for (int i = 1; i < scoresSize; i++) { if (scores[i] < scores[smallestPosition]) { smallestPosition = i; } } return smallestPosition; } /** Computes the sum of the scores @return the total score */ public double sum() { double total = 0; for (int i = 0; i < scoresSize; i++) { total = total + scores[i]; } return total; } /** Removes a score at a given position. @param pos the position of the score to remove */ public void removeScore(int pos) { // Remove the element at this position--see Section 7.3.6 scores[pos] = scores[scoresSize - 1]; scoresSize--; } } import java.util.Scanner; /** This program computes a final score for a series of quiz scores: the sum after dropping the lowest score. The program adapts the algorithm for computing the minimum. */ public class ScoreAnalyzer { public static void main(String[] args) { Student fred = new Student(100); System.out.println("Please enter values, Q to quit:"); Scanner in = new Scanner(System.in); while (in.hasNextDouble()) { if (!fred.addScore(in.nextDouble())) { System.out.println("Too many scores."); return; } } int pos = fred.minimumPosition(); if (pos == -1) { System.out.println("At least one score is required."); } else { fred.removeScore(pos); double total = fred.sum(); System.out.println("Final score: " + total); } } }

Fill an array of strings with the twenty-six strings "a" ... "z"

(ojo) import java.util.Arrays; public class Fill { public static void main(String[] args) { String[] letters = new String[26]; for (char ch = 'a'; ch <='z'; ch++) { letters[ch-'a'] = ch+""; } System.out.println(Arrays.toString(letters)); } }

Using Javadoc comments to document the ElapsedTime and TimeDifference classes

(OJO) ElapsedTime.java /** * A class representing an elapsed time measurement * in hours and minutes. * @author Mary Adams * @version 1.0 */ public class ElapsedTime { /** * The hours portion of the time */ private int hours; /** * The minutes portion of the time */ private int minutes; /** * Constructor initializing hours to timeHours and * minutes to timeMins. * @param timeHours hours portion of time * @param timeMins minutes portion of time */ public ElapsedTime(int timeHours, int timeMins) { hours = timeHours; minutes = timeMins; } /** * Default constructor initializing all fields to 0. */ public ElapsedTime() { hours = 0; minutes = 0; } /** * Prints the time represented by an ElapsedTime * object in hours and minutes. */ public void printTime() { System.out.print(hours + " hour(s) " + minutes + " minute(s)"); } /** * Sets the time to timeHours:timeMins. * @param timeHours hours portion of time * @param timeMins minutes portion of time */ public void setTime(int timeHours, int timeMins) { hours = timeHours; minutes = timeMins; } /** * Returns the total time in minutes. * @return an int value representing the elapsed time in minutes. */ public int getTimeMinutes() { return ((hours * 60) + minutes); } } TimeDifference.java import java.util.Scanner; /** * This program calculates the difference between two * user-entered times. This class contains the * program's main() method and is not meant to be instantiated. * @author Mary Adams * @version 1.0 */ public class TimeDifference { /** * Asks for two times, creating an ElapsedTime object for each, * and uses ElapsedTime's getTimeMinutes() method to properly * calculate the difference between both times. * @param args command-line arguments * @see ElapsedTime#getTimeMinutes() */ public static void main (String[] args) { Scanner scnr = new Scanner(System.in); int timeDiff; // Stores time difference int userHours; int userMins; ElapsedTime startTime = new ElapsedTime(); // Staring time ElapsedTime endTime = new ElapsedTime(); // Ending time // Read starting time in hours and minutes System.out.print("Enter starting time (hrs mins): "); userHours = scnr.nextInt(); userMins = scnr.nextInt(); startTime.setTime(userHours, userMins); // Read ending time in hours and minutes System.out.print("Enter ending time (hrs mins): "); userHours = scnr.nextInt(); userMins = scnr.nextInt(); endTime.setTime(userHours, userMins); // Calculate time difference by converting both times to minutes timeDiff = endTime.getTimeMinutes() - startTime.getTimeMinutes(); System.out.println("Time difference is " + timeDiff + " minutes"); } }

Iterating through ArrayLists The program below allows a user to enter 8 numbers, then prints the average of those 8 numbers. The first loop uses the add() method to add each user-specified number to the ArrayList userNums. After adding the numbers to userNums, the size() method can be used to determine the number of elements in userNums. Thus, size() is used in the second for loop to calculate the sum, and in the statement that computes the average. With an ArrayList and loops, the program could easily be changed to support say 100 numbers; the code would be the same, and only the value of NUM_ELEMENTS would be changed to 100.

(OJO) //ArrayLists with loops. import java.util.ArrayList; import java.util.Scanner; public class ArrayListAverage { public static void main (String [] args) { final int NUM_ELEMENTS = 8; Scanner scnr = new Scanner(System.in); ArrayList<Double> userNums = new ArrayList<Double>(); // User numbers Double sumVal; Double averageVal; int i; // Get user numbers and add to userNums System.out.println("Enter " + NUM_ELEMENTS + " numbers..."); for (i = 0; i < NUM_ELEMENTS; ++i) { System.out.print("Number " + (i + 1) + ": "); userNums.add(scnr.nextDouble()); } // Determine average value sumVal = 0.0; for (i = 0; i < userNums.size(); ++i) { sumVal = sumVal + userNums.get(i); // Calculate sum of all numbers } averageVal = sumVal / userNums.size(); // Calculate average System.out.println("Average: " + averageVal); } }

Write a method that returns all strings from an array list of a given length, without changing the original array list. Complete the following code.

(OJO) import java.util.ArrayList; public class ArrayListUtil { /** * Finds the positions of all strings equal to a given string * in an array list of strings. * * @param words an array list of strings * @param searchedWord the word to search for * @return an array list of all matching positions */ public static ArrayList<Integer> findAll(ArrayList<String> words, String searchedWord) { ArrayList<Integer> positions = new ArrayList<Integer>(); for (int i = 0; i < words.size(); i++) { //checking if the current word matches the searched word if (words.get(i).equals(searchedWord)) { // adding current position to the output list positions.add(i); } } return positions;//returning the list } } import java.util.ArrayList; public class Tester { public static void main(String[] args) { ArrayList<String> words = new ArrayList<String>(); words.add("how"); words.add("much"); words.add("wood"); words.add("would"); words.add("a"); words.add("wood"); words.add("chuck"); words.add("chuck"); words.add("if"); words.add("a"); words.add("wood"); words.add("chuck"); words.add("could"); words.add("chuck"); words.add("wood"); System.out.println(ArrayListUtil.findAll(words, "wood")); System.out.println("Expected: [2, 5, 10, 14]"); System.out.println(ArrayListUtil.findAll(words, "a")); System.out.println("Expected: [4, 9]"); System.out.println(ArrayListUtil.findAll(words, "the")); System.out.println("Expected: []"); } }

Make a copy of an ArrayList<String> with an explicit loop. Complete the following code.

(OJO) import java.util.ArrayList; import java.util.Scanner; public class ArrayListCopy { public static void main(String[] args) { ArrayList<String> words = new ArrayList<String>(); Scanner in = new Scanner(System.in); while (in.hasNext()) words.add(in.next()); ArrayList<String> copyOfWords = new ArrayList<String>(); // Use a for loop to copy the contents of words for(String s:words) { copyOfWords.add(s); } words.remove(0); // Shouldn't affect the copy System.out.println(words); System.out.println(copyOfWords); } }

Print person1's kids, call the incNumKids() method, and print again, outputting text as below. End each line with a newline. Sample output for below program: Kids: 3 New baby, kids now: 4

(OJO) public class CallPersonInfo { public static void main (String [] args) { PersonInfo person1 = new PersonInfo(); person1.setNumKids(3); /* Your solution goes here */ System.out.println("Kids: " + person1.getNumKids()); person1.incNumKids(); System.out.println("New baby,kids now: "+person1.getNumKids()); } } public class PersonInfo { private int numKids; public void setNumKids(int personsKids) { numKids = personsKids; } public void incNumKids() { numKids = numKids + 1; } public int getNumKids() { return numKids; } }

Using ArrayList member methods: A player jersey numbers program.

(Ojo!!!!!) import java.util.ArrayList; import java.util.Scanner; public class PlayerManager { // Adds playerNum to end of ArrayList public static void addPlayer (ArrayList<Integer> players, int playerNum) { players.add(playerNum); } // Deletes playerNum from ArrayList public static void deletePlayer (ArrayList<Integer> players, int playerNum) { int i; boolean found; // Search for playerNum in vector found = false; i = 0; while ( (!found) && (i < players.size()) ) { if (players.get(i).equals(playerNum)) { players.remove(i); // Remove found = true; } ++i; } } // Prints player numbers currently in ArrayList public static void printPlayers(ArrayList<Integer> players) { int i; for (i = 0; i < players.size(); ++i) { System.out.println(" " + players.get(i)); } } // Maintains ArrayList of player numbers public static void main (String [] args) { Scanner scnr = new Scanner(System.in); ArrayList<Integer> players = new ArrayList<Integer>(); String userInput; int playerNum; userInput = "-"; System.out.println("Commands: 'a' add, 'd' delete,"); System.out.println("'p' print, 'q' quit: "); while (!userInput.equals("q")) { System.out.print("Command: "); userInput = scnr.next(); if (userInput.equals("a")) { System.out.print(" Player number: "); playerNum = scnr.nextInt(); addPlayer(players, playerNum); } if (userInput.equals("d")) { System.out.print(" Player number: "); playerNum = scnr.nextInt(); deletePlayer(players, playerNum); } else if (userInput.equals("p")) { printPlayers(players); } } } }

Click to hide a program that demonstrates array operations

(ojo) import java.util.Scanner; public class ArrayDemo { public static void main(String[] args) { // An array of five values, initialized in a loop int[] values = new int[5]; for (int i = 0; i < values.length; i++) { values[i] = 2 * i; } // An array of four strings, with initial values specified String[] names = { "Fred", "Amy", "Cindy", "Henry" }; // These loops print the elements in both arrays for (int i = 0; i < values.length; i++) { System.out.print(values[i] + " "); } System.out.println(); for (int i = 0; i < names.length; i++) { System.out.print(names[i] + " "); } System.out.println(); // When you copy an array variable, you get another reference // to the same array. (See Section 7.1.2.) int[] copy = values; values[0] = 42; // We change values[0], which is the same as copy[0] for (int i = 0; i < copy.length; i++) { System.out.print(copy[i] + " "); } System.out.println(); // Here, we read numbers into a partially filled array. // (See Section 7.1.4.) System.out.println("Enter scores, -1 to quit: "); Scanner in = new Scanner(System.in); boolean done = false; int currentSize = 0; final int LENGTH = 100; int[] scores = new int[LENGTH]; while (!done && currentSize < LENGTH) { int score = in.nextInt(); if (score == -1) { done = true; } else { scores[currentSize] = score; currentSize++; } } System.out.println("You entered the following scores:"); for (int i = 0; i < currentSize; i++) { System.out.print(scores[i] + " "); } System.out.println(); } }

Modify the algorithm in this section to use an array of strings, and to find the last match. In this example, a match is a word of a specified length. For example, when asked for the last word of length 3, you should locate "was" at index 7.

(ojo) import java.util.Scanner; public class FindLast { public static void main(String[] args) { String[] words = { "Mary", "had", "a", "little", "lamb", "it's", "fleece", "was", "white", "as", "snow" }; Scanner in = new Scanner(System.in); System.out.print("Word length: "); int wordLength = in.nextInt(); boolean found = false; int pos = 10; while (pos >= 0 && found == false) // loop on array of strings until // found a word { if (words[pos].length() == wordLength) { found = true; } else { pos--; } } if (found) { System.out.println("Found " + words[pos] + " at position " + pos); } else { System.out.println("No word of length " + wordLength); } } }

Define the missing method. Use "this" to distinguish the local member from the parameter name.

// ===== Code from file CablePlan.java ===== public class CablePlan { private int numDays; // FIXME: Define setNumDays() method, using "this" implicit parameter. public void setNumDays(int numDays) { /* Your solution goes here */ this.numDays = numDays; } public int getNumDays() { return numDays; } } // ===== end ===== // ===== Code from file CallCablePlan.java ===== public class CallCablePlan { public static void main (String [] args) { CablePlan house1Plan = new CablePlan(); house1Plan.setNumDays(30); System.out.println(house1Plan.getNumDays()); } } // ===== end =====

Define a constructor as indicated. Sample output for below program: Year: 0, VIN: -1 Year: 2009, VIN: 444555666

// ===== Code from file CarRecord.java ===== public class CarRecord { private int yearMade; private int vehicleIdNum; public void setYearMade(int originalYear) { yearMade = originalYear; } public void setVehicleIdNum(int vehIdNum) { vehicleIdNum = vehIdNum; } public void print() { System.out.println("Year: " + yearMade + ", VIN: " + vehicleIdNum); } // FIXME: Write constructor, initialize year to 0, vehicle ID num to -1. /* Your solution goes here */ public CarRecord(){ yearMade = 0; vehicleIdNum = -1; } } // ===== end ===== // ===== Code from file CallCarRecord.java ===== public class CallCarRecord { public static void main (String [] args) { CarRecord familyCar = new CarRecord(); familyCar.print(); familyCar.setYearMade(2009); familyCar.setVehicleIdNum(444555666); familyCar.print(); } }

Define the missing method. licenseNum is created as: (100000 * customID) + licenseYear. Sample output: Dog license: 77702014

// ===== Code from file DogLicense.java ===== public class DogLicense { private int licenseYear; private int licenseNum; public void setYear(int yearRegistered) { licenseYear = yearRegistered; } // FIXME: Write createLicenseNum() public void createLicenseNum(int customID) { /* Your solution goes here */ licenseNum = (100000 * customID) + licenseYear; } public int getLicenseNum() { return licenseNum; } } // ===== end ===== // ===== Code from file CallDogLicense.java ===== public class CallDogLicense { public static void main (String [] args) { DogLicense dog1 = new DogLicense(); dog1.setYear(2014); dog1.createLicenseNum(777); System.out.println("Dog license: " + dog1.getLicenseNum()); } }

Write a unit test for addInventory(), which has an error. Call redSweater.addInventory() with parameter sweaterShipment. Print the shown error if the subsequent quantity is incorrect. Sample output for failed unit test given initial quantity is 10 and sweaterShipment is 50: Beginning tests. UNIT TEST FAILED: addInventory() Tests complete. Note: UNIT TEST FAILED is preceded by 3 spaces.

// ===== Code from file InventoryTag.java ===== public class InventoryTag { private int quantityRemaining; public InventoryTag() { quantityRemaining = 0; } public int getQuantityRemaining() { return quantityRemaining; } public void addInventory(int numItems) { if (numItems > 10) { quantityRemaining = quantityRemaining + numItems; } } } // ===== end ===== // ===== Code from file CallInventoryTag.java ===== public class CallInventoryTag { public static void main (String [] args) { InventoryTag redSweater = new InventoryTag(); int sweaterShipment; int sweaterInventoryBefore; sweaterInventoryBefore = redSweater.getQuantityRemaining(); sweaterShipment = 25; System.out.println("Beginning tests."); // FIXME add unit test for addInventory redSweater.addInventory(sweaterShipment); /* Your solution goes here */ if (redSweater.getQuantityRemaining() !=sweaterShipment+sweaterInventoryBefore ) { System.out.println(" UNIT TEST FAILED: addInventory()"); } System.out.println("Tests complete."); } }

Constructor overloading. Write a second constructor as indicated. Sample output: User1: Minutes: 0, Messages: 0 User2: Minutes: 1000, Messages: 5000

// ===== Code from file PhonePlan.java ===== public class PhonePlan { private int freeMinutes; private int freeMessages; public PhonePlan() { freeMinutes = 0; freeMessages = 0; } // FIXME: Create a second constructor with numMinutes and numMessages parameters. public PhonePlan(int freeMi, int freeMe){ freeMinutes = freeMi; freeMessages = freeMe; } /* Your solution goes here */ public void print() { System.out.println("Minutes: " + freeMinutes + ", Messages: " + freeMessages); } } // ===== end ===== // ===== Code from file CallPhonePlan.java ===== public class CallPhonePlan { public static void main (String [] args) { PhonePlan user1Plan = new PhonePlan(); // Calls default constructor PhonePlan user2Plan = new PhonePlan(1000, 5000); // Calls newly-created constructor System.out.print("User1: "); user1Plan.print(); System.out.print("User2: "); user2Plan.print(); } } // ===== end =====

Appending a new item to the end of a 1000 element ArrayList requires how many elements to be shifted?

0 The new item is simply added to the end.

What output is generated by the code segment below? int[] values = new int[10]; for (int k = 0; k < values.length; k++) { values[k] = k * 2; } System.out.println(values[5]);

10

Inserting a new item at the beginning of a 1000 element ArrayList requires how many elements to be shifted?

1000 Every element must be shifted to make room at position number 0 for the new item.

Consider the following code segment. What is the value of b[2] after the code executes? int[] a = { 0, 1, 2, 3, 4 }; int[] b = { 0, 1, 4, 9 }; a = b; b = a;

4

What output is generated by the program below? public static void main(String[] args) { int[][] table = { { 4, 3, 5 }, { 0, 6, 3 }, { 1, 2, 2 }, }; for (int k = 0; k < table.length; k++) { System.out.print(table[k][k]); } }

462

7.3 Common Array Algorithms.........

7.3 Common Array Algorithms.........

Mutators and accessors

7.4 Mutators, accessors, and private helpers

Initialization and constructors A good practice is to initialize all variables when declared. This section deals with initializing the fields of a class when a variable of the class type is allocated. Field initialization A programmer can initialize fields in the field declaration. Any object created of that class type will initially have those values.

A class definition with initialized fields. Restaurant.java public class Restaurant { private String name = "NoName"; private int rating = -1; public void setName(String restaurantName) { name = restaurantName; } public void setRating(int userRating) { rating = userRating; } public void print() { System.out.println(name + " -- " + rating); } } RestaurantFavorites.java public class RestaurantFavorites { public static void main(String[] args) { Restaurant favLunchPlace = new Restaurant(); // Initializes fields with values in class definition favLunchPlace.print(); favLunchPlace.setName("Central Deli"); favLunchPlace.setRating(4); favLunchPlace.print(); } } NoName -- -1 Central Deli -- 4

A first linked list

A common use of objects and references is to create a list of items such that an item can be efficiently inserted somewhere in the middle of the list, without the shifting of later items as required for an ArrayList. The following program illustrates how such a list can be created. A class is defined to represent each list item, known as a list node. A node is comprised of the data to be stored in each list item, in this case just one int, and a reference to the next node in the list. A special node named head is created to represent the front of the list, after which regular items can be inserted.

Memory regions: Heap/Stack

A program's memory usage typically includes four different regions: Code — The region where the program instructions are stored. Static memory — The region where static fields are allocated. The name "static" comes from these variables not changing (static means not changing); they are allocated once and last for the duration of a program's execution, their addresses staying the same. The stack — The region where a method's local variables are allocated during a method call. A method call adds local variables to the stack, and a return removes them, like adding and removing dishes from a pile; hence the term "stack." Because this memory is automatically allocated and deallocated, it is also called automatic memory. The heap — The region where the "new" operator allocates memory for objects. The region is also called free store.

Using a class

A programmer can create one or more objects of the same class. Creating an object consists of two steps: declaring a reference variable of the class type, and assigning the variable with an explicitly allocated instance of the class type. A reference variable can refer to an instance of a class. The new operator explicitly allocates an object of the specified class type. Ex: Restaurant favLunchPlace = new Restaurant(); creates a Restaurant object named favLunchPlace. The "." operator, known as the member access operator, is used to invoke a method on an object. Ex: favLunchPlace.setRating(4) calls the setRating() method on the favLunchPlace object, which sets the object's rating to 4.

Private helper methods

A programmer commonly creates private methods, known as private helper methods, to help public methods carry out tasks.

Classes, ArrayLists, and methods: A seat reservation example

A programmer commonly uses classes, methods, and ArrayLists together. Consider a system that allows a reservations agent to reserve seats for people, as might be useful for a theater, an airplane, etc. The below program utilizes several methods and an ArrayList of custom Seat objects to allow the user to reserve seats or print the seating arrangements.

Garbage collection and variable scope

A programmer does not explicitly have to set a reference variable to null in order to indicate that the variable no longer refers to an object. The Java virtual machine can automatically infer a null reference once the variable goes out of scope — i.e., the reference variable is no longer visible to the program. For example, local reference variables that are declared within a method go out of scope as soon as the method returns. The Java virtual machine decrements the reference counts associated with the objects referred to by any local variables within the method.

Suppose a customer of your program finds an error. What action should you take beyond fixing the error?

Add a test case to the test suite that verifies that the error is fixed.

Constructors Java provides a special class member method, known as a constructor, that is called when an object of that class type is created, and which can be used to initialize all fields. A constructor that can be called without any arguments is called a default constructor, like the Restaurant constructor below. The constructor has the same name as the class. The constructor method has no return type, not even void. Ex: public Restaurant() {...} defines a constructor for the Restaurant class. A programmer specifies the constructor that should be called when creating an object. Ex: Restaurant favLunchPlace = new Restaurant(); creates a new Restaurant object and calls the constructor Restaurant(). If a class does not have a programmer-defined constructor, then the Java compiler implicitly defines a default constructor with no statements. The Java compiler also initializes all fields to their default values. Good practice is to explicitly define a default constructor for any class, initializing all fields.

Adding a constructor member method to the Restaurant class. Restaurant.java public class Restaurant { private String name; private int rating; public Restaurant() { // Default constructor name = "NoName"; // Default name: NoName indicates name was not set rating = -1; // Default rating: -1 indicates rating was not set } public void setName(String restaurantName) { name = restaurantName; } public void setRating(int userRating) { rating = userRating; } public void print() { System.out.println(name + " -- " + rating); } } RestaurantFavorites.java public class RestaurantFavorites { public static void main(String[] args) { Restaurant favLunchPlace = new Restaurant(); // Calls the default constructor favLunchPlace.print(); favLunchPlace.setName("Central Deli"); favLunchPlace.setRating(4); favLunchPlace.print(); } } NoName -- -1 Central Deli -- 4

Java Collections Framework

An ArrayList is one of several Collections supported by Java for keeping groups of items. Other collections include LinkedList, Set, Queue, Map, and many more. A programmer selects the collection whose features best suit the desired task. For example, an ArrayList can efficiently access elements at any valid index but inserts are expensive, whereas a LinkedList supports efficient inserts but access requires iterating through elements. So a program that will do many accesses and few inserts might use an ArrayList.

8.1 Introduction to memory management

An ArrayList stores a list of items in contiguous memory locations, which enables immediate access to any element at index i of ArrayList v by using the get() and set() methods — the program just adds i to the starting address of the first element in v to arrive at the element. The methods add(objRef) and add(i, objRef) append and insert items into an ArrayList, respectively. Now recall that inserting an item at locations other than the end of the ArrayList requires making room by shifting higher-indexed items. Similarly, removing (via the remove(i) method) an item requires shifting higher-indexed items to fill the gap. Each shift of an item from one element to another element requires a few processor instructions. This issue exposes the ArrayList add/remove performance problem.

Accessing ArrayList elements The ArrayList's get() method returns the element at the specified list location, and can be used to lookup the Nth item in a list. The program below allows a user to print the name of the Nth most popular operating system. The program accesses the Nth most popular operating system using operatingSystems.get(nthOS - 1);. Note that the index is nthOS - 1 rather than just nthOS because an ArrayList's indices start at 0, so the 1st operating system is at index 0, the 2nd at index 1, etc. An ArrayList's index must be an integer type. The index cannot be a floating-point type, even if the value is 0.0, 1.0, etc.

ArrayList's ith element can be directly accessed using .get(i): Most popular OS program. import java.util.ArrayList; import java.util.Scanner; public class MostPopularOS { public static void main (String [] args) { Scanner scnr = new Scanner(System.in); ArrayList<String> operatingSystems = new ArrayList<String>(); int nthOS; // User input, Nth most popular OS // Source: StatCounter.com, 2018 operatingSystems.add("Windows 10"); operatingSystems.add("Windows 7"); operatingSystems.add("Mac OS X"); operatingSystems.add("Windows 8"); operatingSystems.add("Windows XP"); operatingSystems.add("Linux"); operatingSystems.add("Chrome OS"); operatingSystems.add("Other"); System.out.println("Enter N (1-8): "); nthOS = scnr.nextInt(); if ((nthOS >= 1) && (nthOS <= 8)) { System.out.print("The " + nthOS + "th most popular OS is "); System.out.println(operatingSystems.get(nthOS - 1)); } } }

A linked list is a list wherein each item contains not just data but also a reference — a link — to the next item in the list. Comparing ArrayLists and linked lists:

ArrayList: Stores items in contiguous memory locations. Supports quick access to i'th element via the set() and get() methods, but may be slow for inserts or removes on large ArrayLists due to necessary shifting of elements. Linked list: Stores each item anywhere in memory, with each item referring to the next item in the list. Supports fast inserts or removes, but access to i'th element may be slow as the list must be traversed from the first item to the i'th item. Also uses more memory due to storing a link for each item.

Storing Input Values in an Array List

ArrayList<Double> inputs = new ArrayList<Double>(); while (in.hasNextDouble()) { inputs.add(in.nextDouble()); }

In a single statement, declare and initialize a reference variable for an ArrayList named frameScores that stores items of type Integer.

ArrayList<Integer> frameScores = new ArrayList<Integer>(); Creates an empty ArrayList for Integer objects.

Declare an array list of integers called primes that contains the first five prime numbers (2, 3, 5, 7, and 11).

ArrayList<Integer> primes = new ArrayList<Integer>(); primes.add(2); primes.add(3); primes.add(5); primes.add(7); primes.add(11);

In a single statement, declare and initialize a reference variable called mySeats for an ArrayList of Seat objects.

ArrayList<Seat> mySeats = new ArrayList<Seat>(); A programmer may create ArrayLists for any reference type including user-defined classes.

Here is the proper initialization: ArrayList

ArrayList<String> names = new ArrayList<String>();

Use Arrays for Sequences of Related Items

Arrays are intended for storing sequences of values with the same meaning. For example, an array of test scores makes perfect sense: int[] scores = new int[NUMBER_OF_SCORES]; But an array int[] personalData = new int[3]; that holds a person's age, bank balance, and shoe size in positions 0, 1, and 2 is bad design. It would be tedious for the programmer to remember which of these data values is stored in which array location. In this situation, it is far better to use three separate variables.

Constructor overloading

Basics Programmers often want to provide different initialization values when creating a new object. A class creator can overload a constructor by defining multiple constructors differing in parameter types. When an object is created with the new operator, arguments can be passed to the constructor. The constructor with matching parameters will be called.

Basic garbage collection

Because the amount of memory available to a program is finite, objects allocated to the heap must eventually be deallocated when no longer needed by the program. The Java programming language uses a mechanism called garbage collection wherein a program's executable includes automatic behavior that at various intervals finds all unreachable — i.e., unused — allocated memory locations, and automatically frees such memory locations in order to enable memory reuse. Garbage collection can present the programmer with the illusion of a nearly unlimited memory supply at the expense of runtime overhead. In order to determine which allocated objects the program is currently using at runtime, the Java virtual machine keeps a count, known as a reference count, of all reference variables that are currently referring to an object. If the reference count is zero, then the object is considered an unreachable object and is eligible for garbage collection, as no variables in the program refer to the object. The Java virtual machine marks unreachable objects, and deallocation occurs the next time the Java virtual machine invokes the garbage collector.

The generated API documentation includes private class members by default.

By default, the API documentation only includes class members accessible by external classes (i.e., public and protected members). To document private class members, the programmer must execute the javadoc tool with the -private flag.

eclare a variable called logoChar that refers to a primitive wrapper object with a char value of 'U'.

Character logoChar = 'U'; Primitive wrapper objects can be initialized in the same manner as variables of primitive types.

Defining main() in a programmer-defined class The main() method can be defined within a programmer-defined class and create objects of that class type. The BasicCar class defined in the example below represents a car that keeps track of the number of miles driven. BasicCar has a field that maintains the miles driven and three methods that set, retrieve, and modify the object's field. main() is a static method, which means main() does not have direct access to the class' instance members. A programmer must create objects within main() to call instance methods. Ex: BasicCar's main() creates two objects of type BasicCar and performs operations on those objects.

Class definition with main() method. public class BasicCar { // Total miles driven by the car private int milesDriven; // Constructor assigns initial values to instance variables public BasicCar() { milesDriven = 0; } // Drive the requested miles public void drive(int tripMiles) { milesDriven = milesDriven + tripMiles; } // Return total number of miles driven public int checkOdometer() { return milesDriven; } // Main() creates objects of type BasicCar and // calls methods to operate on the objects public static void main(String [] args) { BasicCar redCorvette = new BasicCar(); BasicCar fordMustang = new BasicCar(); redCorvette.drive(100); fordMustang.drive(75); fordMustang.drive(300); fordMustang.drive(50); } }

Declare a variable called trackCircumference that refers to a primitive wrapper object with a double value of 29.5.

Double trackCircumference = 29.5; Primitive wrapper objects can be initialized in the same manner as variables of primitive types.

Regression testing means to check if a change to an item caused previously-passed test cases to fail.

Even minor changes to an item may unexpectedly introduce bugs. An automated testbench can easily be run when an item is changed, to detect such "regression".

Field initialization is usually preferred over using a constructor. However, sometimes initializations are more complicated, in which case a constructor is needed.

Exploring further: Constructors from Oracle's Java tutorials. Initializing fields from Oracle's Java tutorials

A mutator should not change a class' private fields.

FALSE. A mutator "mutates", meaning changes, a class' private fields.

An accessor method cannot change the value of a private field.

FALSE. Nothing prevents a method from modifying a field. The programmer however should strive to avoid changing fields to prevent unexpected consequences.

The @author block tag can be used to specify a method's author.

FALSE. The @author block tag is only compatible with Doc comments for classes and interfaces.

Commonly, a field has two associated methods: a mutator for setting the value, and an accessor for getting the value, known as a setter and getter method, respectively, and typically with names starting with set or get. Other mutators and accessors may exist that aren't associated with just one field, such as the print() method below.

Figure 7.4.1: Mutator and accessor methods. Restaurant.java public class Restaurant { private String name; private int rating; public void setName(String restaurantName) { // Mutator name = restaurantName; } public void setRating(int userRating) { // Mutator rating = userRating; } public String getName() { // Accessor return name; } public int getRating() { // Accessor return rating; } public void print() { // Accessor System.out.println(name + " -- " + rating); } } MyRestaurant.java public class MyRestaurant { public static void main(String[] args) { Restaurant myPlace = new Restaurant(); myPlace.setName("Maria's Diner"); myPlace.setRating(5); System.out.print(myPlace.getName() + " is rated "); System.out.println(myPlace.getRating()); } } Maria's Diner is rated 5

It isn't actually necessary to remove the minimum in order to compute the total score. Describe an alternative.

Find the minimum value. Calculate the sum. Subtract the minimum value.

Declare a reference variable named flightPlan that can refer to an object of type FlightInfo. Do not create a new object.

FlightInfo flightPlan; Declaring a reference variable does not create an object.

Choosing Between Array Lists and Arrays

For most programming tasks, array lists are easier to use than arrays. Array lists can grow and shrink. On the other hand, arrays have a nicer syntax for element access and initialization. Which of the two should you choose? Here are some recommendations. • If the size of a collection never changes, use an array. • If you collect a long sequence of primitive type values and you are concerned about efficiency, use an array. • Otherwise, use an array list.

Consider the task of rearranging all elements in an array so that the even numbers come first. Otherwise, the order doesn't matter. For example, the array 1 4 14 2 1 3 5 6 23 could be rearranged to 4 2 14 6 1 5 3 23 1 Using coins and paperclips, discover an algorithm that solves this task by swapping elements, then describe it in pseudocode.

Here is one solution. The basic idea is to move all odd elements to the end. Put one paper clip at the beginning of the array and one at the end. If the element at the first paper clip is odd, swap it with the one at the other paper clip and move that paper clip to the left. Otherwise, move the first paper clip to the right. Stop when the two paper clips meet. Here is the pseudocode: i = 0 j = size - 1 While (i < j) If (a[i] is odd) Swap elements at positions i and j. j-- Else i++

If any constructor defined, should define default

If a programmer defines any constructor, the compiler does not implicitly define a default constructor, so good practice is for the programmer to also explicitly define a default constructor so that an object creation like new MyClass() remains supported.

What is wrong with these statements for printing an array with separators? System.out.print(values[0]); for (int i = 1; i < values.length; i++) { System.out.print(", " + values[i]); }

If the array has no elements, then the program terminates with an exception.

If the programmer defines any constructor, then the programmer should define a default constructor. Failing to do so yields a compiler error for a statement like MyClass x = new MyClass();

If the programmer defines any constructor, then the programmer should define a default constructor. Failing to do so yields a compiler error for a statement like MyClass x = new MyClass();

If the programmer doesn't define any constructors, the compiler implicitly defines a default constructor having no statements.

If the programmer doesn't define any constructors, the compiler implicitly defines a default constructor having no statements.

When finding the position of a match, we used a while loop, not a for loop. What is wrong with using this loop instead? for (pos = 0; pos < values.length && !found; pos++) { if (values[pos] > 100) { found = true; } }

If there is a match, then pos is incremented before the loop exits.

In Java, as in C, all programmers must be very careful not to overrun array boundaries. However, in Java, this error causes a run-time exception, and it never corrupts memory outside the array. This is one of the safety features of Java.

In Java, as in C, all programmers must be very careful not to overrun array boundaries. However, in Java, this error causes a run-time exception, and it never corrupts memory outside the array. This is one of the safety features of Java.

Defining a class Private fields

In addition to public member methods, a class definition has private fields: Variables that member methods can access but class users cannot. The private access modifier precedes each private field declaration.

Managing many new items using just a few reference variables.

IntNode.java public class IntNode { private int dataVal; // Node data private IntNode nextNodePtr; // Reference to the next node public IntNode() { dataVal = 0; nextNodePtr = null; } // Constructor public IntNode(int dataInit) { this.dataVal = dataInit; this.nextNodePtr = null; } // Constructor public IntNode(int dataInit, IntNode nextLoc) { this.dataVal = dataInit; this.nextNodePtr = nextLoc; } /* Insert node after this node. Before: this -- next After: this -- node -- next */ public void insertAfter(IntNode nodeLoc) { IntNode tmpNext; tmpNext = this.nextNodePtr; this.nextNodePtr = nodeLoc; nodeLoc.nextNodePtr = tmpNext; } // Get location pointed by nextNodePtr public IntNode getNext() { return this.nextNodePtr; } public void printNodeData() { System.out.println(this.dataVal); } } CustomLinkedList.java public class CustomLinkedList { public static void main (String[] args) { IntNode headObj; // Create IntNode objects IntNode currObj; IntNode lastObj; int i; // Loop index headObj = new IntNode(-1); // Front of nodes list lastObj = headObj; for (i = 0; i < 20; ++i) { // Append 20 rand nums int rand = (int)(Math.random() * 100000); // random int (0-99999) currObj = new IntNode(rand); lastObj.insertAfter(currObj); // Append curr lastObj = currObj; } currObj = headObj; // Print the list while (currObj != null) { currObj.printNodeData(); currObj = currObj.getNext(); } } }

Declare a variable called gameScore that refers to a primitive wrapper object with an int value of 81.

Integer gameScore = 81; Primitive wrapper objects can be initialized in the same manner as variables of primitive types.

Write a statement that converts the text representation of an integer within String numberText, storing the value in an int variable numLanes. numLanes = Integer.parseInt(numberText) ;

Integer.parseInt(numberText); Integer.parseInt() returns an int representing the value encoded in a String argument.

What does this enhanced for loop do? int counter = 0; for (double element : values) { if (element == 0) { counter++; } }

It counts how many elements of values are zero.

What is the purpose of the following method? public static void transform(int[] array) { int minPosition = 0; for (int k = 1; k < array.length; k++) { if (array[k] < array[minPosition]) { minPosition = k; } } int temp = array[minPosition]; array[minPosition] = array[0]; array[0] = temp; }

It finds the smallest array element and swaps its value with the first array element.

Methods with a Variable Number of Arguments

It is possible to declare methods that receive a variable number of arguments. For example, we can write a method that can add an arbitrary number of scores to a student: fred.addScores(10, 7); // This method call has two arguments fred.addScores(1, 7, 2, 9); // Another call to the same method, now with four arguments The method must be declared as public void addScores(int... values) The int... type indicates that the method can receive any number of int arguments. The values parameter variable is actually an int[] array that contains all arguments that were passed to the method. The method implementation traverses the values array and processes the elements: public void addScores(int... values) { for (int i = 0; i < values.length; i++) // values is an int[] { totalScore = totalScore + values[i]; } }

Assuming that values is an array of integer values, what is the purpose of the following code segment? int count = 0; for (int k = 0; k < values.length; k++) { if (values[k] % 2 == 0) { count++; } } System.out.print(count);

It prints the number of array elements that are even.

What does the following code do? a[0] = a[a.length - 1]; a[a.length - 1] = a[0];

It sets the first value of the array a to the last value.

What statement is required to enable a user to utilize the String class?

Java automatically imports the java.lang package, which allows a programmer to use the Strings class and corresponding methods. The class adds numerous methods to ease working with String objects, hiding details from the programmer.

The Javadoc tool generates API documentation for classes and their members.

Javadoc parses source code and Doc comments to produce documentation describing how to interface with said classes.

Use the enhanced for loop if you do not need the index values in the loop body.

Keep in mind that the enhanced for loop has a very specific purpose: getting the elements of a collection, from the beginning to the end. It is not suitable for all array algorithms. In particular, the enhanced for loop does not allow you to modify the contents of an array. The following loop does not fill an array with zeroes: for (double element : values) { element = 0; // ERROR: this assignment does not modify array elements } When the loop is executed, the variable element is set to values[0]. Then element is set to 0, then to values[1], then to 0, and so on. The values array is not modified. The remedy is simple: Use a basic for loop. for (int i = 0; i < values.length; i++) { values[i] = 0; // OK }

Unit testing (classes) Testbenches

Like a chef who tastes food before serving, a class creator should test a class before allowing use. A testbench is a program whose job is to thoroughly test another program (or portion) via a series of input/output checks known as test cases. Unit testing means to create and run a testbench for a specific item (or "unit") like a method or a class.

Parameters of reference types

Methods with reference variables as parameters A reference variable is a variable that points to, or refers to, an object or array. Internally, a reference variable stores a reference, or the memory location, of the object to which it refers. A programmer can only access the data or functionality provided by objects through the use of reference variables. Because reference variables store object locations and not the object data itself, passing a reference variable as a method argument assigns the argument's stored reference to the corresponding method parameter. Similarly, returning a reference variable returns an object reference.

Before inserting an element, move elements to the end of the array starting with the last one

Note the order of the movement: When you remove an element, you first move the next element to a lower index, then the one after that, until you finally get to the end of the array. When you insert an element, you start at the end of the array, move that element to a higher index, then move the one before that, and so on until you finally get to the insertion location. if (currentSize < values.length) { currentSize++; for (int i = currentSize - 1; i > pos; i--) { values[i] = values[i - 1]; } values[pos] = newElement; }

The Enhanced for Loop. You can use the enhanced for loop to visit all elements of an array.

Often, you need to visit all elements of an array. The enhanced for loop makes this process particularly easy to program. Here is how you use the enhanced for loop to total up all elements in an array named values: double[] values = . . .; double total = 0; for (double element : values) { total = total + element; } This loop is equivalent to the following for loop with an explicit index variable: for (int i = 0; i < values.length; i++) { double element = values[i]; total = total + element; }

The programmer first sketched the desired classes, before writing the code seen above.

Planning a program before writing code is good practice.

Regression testing

Regression testing means to retest an item like a class anytime that item is changed; if previously-passed test cases fail, the item has "regressed". A testbench should be maintained along with the item, to always be usable for regression testing. Testbenches may be complex, with thousands of test cases. Various tools support testing, and companies employ test engineers who only test other programmers' items. A large percent, like 50% or more, of commercial software development time may go into testing.

The 'this' implicit parameter An object's member method is called using the syntax objectReference.method(). The compiler converts that syntax into a method call with the object's reference implicitly passed as a parameter. So you can think of objectReference.method(...) getting converted to method(objectReference, ...). The object is known as an implicit parameter of the member method. Within a member method, the implicitly-passed object reference is accessible via the keyword this. In particular, a class member can be accessed as this.classMember. The "." is the member access operator.

ShapeSquare.java: public class ShapeSquare { // Private fields private double sideLength; // Public methods public void setSideLength(double sideLength) { this.sideLength = sideLength; // Field member Parameter } public double getArea() { return sideLength * sideLength; // Both refer to field } } ShapeTest.java: public class ShapeTest { public static void main(String[] args) { ShapeSquare square1 = new ShapeSquare(); square1.setSideLength(1.2); System.out.println("Square's area: " + square1.getArea()); } }

ArrayList introduction

Sometimes a programmer wishes to maintain a list of items, like a grocery list, or a course roster. An ArrayList is an ordered list of reference type items that comes with Java. Each item in an ArrayList is known as an element. The statement import java.util.ArrayList; enables use of an ArrayList. The declaration creates reference variable vals that refers to a new ArrayList object consisting of Integer objects, The ArrayList list size can grow to contain the desired elements. ArrayList does not support primitive types like int, but rather reference types like Integer. A common error among beginners is to declare an ArrayList of a primitive type like int, as in ArrayList<int> myVals, yielding a compilation error: "unexpected type, found : int, required: reference."

Static fields and methods

Static fields The keyword static indicates a variable is allocated in memory only once during a program's execution. Static variables reside in the program's static memory region and have a global scope. Thus, static variables can be accessed from anywhere in a program. In a class, a static field is a field of the class instead of a field of each class object. Thus, static fields are independent of any class object, and can be accessed without creating a class object. Static fields are declared and initialized in the class definition. Within a class method, a static field is accessed using the field name. A public static field can be accessed outside the class using dot notation: ClassName.fieldName.

Declare an array called words that can hold ten elements of type String.

String[] words = new String[10];

Declare an array containing two strings, "Yes", and "No".

String[] words = { "Yes", "No" };

Declare a two-dimensional array for representing a tic-tac-toe board. The board has three rows and columns and contains strings "x", "o", and " ".

String[][] board = new String[3][3];

Given the code segment below, which of the following statements would cause a run-time error? ArrayList colors = new ArrayList(); colors.add("red"); colors.add("white"); colors.add("blue"); System.out.println(colors.get(0)); System.out.println(colors.get(colors.size())); System.out.println(colors.get(colors.size() - 1)); System.out.println(colors.get(colors.size() - 2));

System.out.println(colors.get(colors.size()));

Complete the code fragment below by inserting the statement that makes the most appropriate use of the enhanced for loop. int[] values = { 1, 3, 5, 3, 7 }; for (int number : values) { _________________________ } number = number + 1; System.out.println(number); System.out.println(values[number]); values[number] = 0;

System.out.println(number);

A private field sometimes has a pair of associated set and get methods

TRUE. A pair of associated set and get methods is sometimes, but not always, the case, and depends on whether the field should be known to the class user. Some private fields are completely hidden from the user.

An accessor should not change a class' private fields.

TRUE. An accessor accesses private fields, and then returns some value or carries out some action. An accessor should not change private fields.

The block tag specification below creates a reference to ElapsedTime's printTime() method. @see ElapsedTime#printTime()

The @see block tag can be used to reference a method in another class by appending the class name and the # symbol before the method name, as in @see ElapsedTime#printTime().

Java documentation for classes

The Javadoc tool parses source code along with specially formatted comments to generate documentation. The documentation generated by Javadoc is known as an API for classes and class members. API is short for application programming interface. The specially formatted comments for Javadoc are called Doc comments, which are multi-line comments consisting of all text enclosed between the /** and */ characters. Importantly, Doc comments are distinguished by the opening characters /**, which include two asterisks. The following illustrates.

How does the print() member method's definition begin?

The access modifier indicates that the print method is public. The snippet provided shows the method's return type, name, and arguments. To complete the method declaration, the opening brace, statements, and closing brace are included.

Classes intro: Public member methods

The class construct defines a new type that can group data and methods to form an object. A class' public member methods indicate all operations a class user can perform on the object. The power of classes is that a class user need not know how the class' data and methods are implemented, but need only understand how each public member method behaves. The animation below shows a class' public member method declarations only; the remainder of the class definition is discussed later.

Why is the enhanced for loop not an appropriate shortcut for the following basic for loop? for (int i = 0; i < values.length; i++) { values[i] = i * i; }

The loop writes a value into values[i]. The enhanced for loop does not have the index variable i.

Grouping things into objects

The physical world is made up of material items like wood, metal, plastic, fabric, etc. To keep the world understandable, people deal with higher-level objects, like chairs, tables, and TV's. Those objects are groupings of the lower-level items. Likewise, a program is made up of items like variables and methods. To keep programs understandable, programmers often deal with higher-level groupings of those items known as objects. In programming, an object is a grouping of data (variables) and operations that can be performed on that data (methods).

How is the name field declared?

The private access modifier indicates that member methods can access the field but class users cannot.

public MyClass() { ... } public MyClass(String name) { ... }

The programmer has defined the default constructor (doesn't require any arguments), and another constructor that requires one argument.

A class should be tested individually (as a "unit") before use in another program.

The user expects the class to work, and may not even be able to debug the class. Bugs would also be harder to find.

When inserting an element into an array, we moved the elements with larger index values, starting at the end of the array. Why is it wrong to start at the insertion location, like this? for (int i = pos; i < currentSize - 1; i++) { values[i + 1] = values[i]; }

This loop sets all elements to values[pos].

Basic ArrayList methods

Use of get(), set(), size(), isEmpty(), and clear() should be straightforward.

Element Separators When separating elements, don't place a separator before the first element.

When you display the elements of an array, you usually want to separate them, often with commas or vertical lines, like this: 32 | 54 | 67.5 | 29 | 35 Note that there is one fewer separator than there are numbers. Print the separator before each element in the sequence except the initial one (with index 0) like this: for (int i = 0; i < values.length; i++) { if (i > 0) { System.out.print(" | "); } System.out.print(values[i]); } If you want comma separators, you can use the Arrays.toString method. (You'll need to import java.util.Arrays.) The expression Arrays.toString(values) returns a string describing the contents of the array values in the form [32, 54, 67.5, 29, 35] The elements are surrounded by a pair of brackets and separated by commas. This method can be convenient for debugging: System.out.println("values=" + Arrays.toString(values));

An array list stores a sequence of values whose size can change.

When you write a program that collects inputs, you don't always know how many inputs you will have. In such a situation, an array list offers two significant advantages: • Array lists can grow and shrink as needed. • The ArrayList class supplies methods for common tasks, such as inserting and removing elements.

public class CallPerson { public static void main(String [] args) { String aFirstName; String anotherFirstName; String aLastName; String anotherLastName; aFirstName = "Ann"; anotherFirstName = "Ron"; aLastName = "Stark"; anotherLastName = "Parker"; Person person1 = new Person(); Person person2 = new Person(); person1.setFirstName(aFirstName); person1.setLastName(aLastName); person2.setFirstName(anotherFirstName); person2.setLastName(anotherLastName); System.out.println("You are " + person1.getFullName()); System.out.println("I am " + person2.getFullName()); } } public class Person { private String firstName; private String lastName; public void setFirstName(String firstNameToSet) { firstName = firstNameToSet; } public void setLastName(String lastNameToSet) { lastName = lastNameToSet; } public String getFullName() { return firstName + "-" + lastName; } }

You are Ann-Stark I am Ron-Parker

Using the Enhanced for Loop with Array Lists

You can use the enhanced for loop to visit all elements of an array list. For example, the following loop prints all names: ArrayList names = . . . ; for (String name : names) { System.out.println(name); } This loop is equivalent to the following basic for loop: for (int i = 0; i < names.size(); i++) { String name = names.get(i); System.out.println(name); }

How can you print all positive values in an array, separated by commas?

You need to modify the algorithm in Section 7.3.4. boolean first = true; for (int i = 0; i < values.length; i++) { if (values[i] > 0)) { if (first) { first = false; } else { System.out.print(", "); } } System.out.print(values[i]); } Note that you can no longer use i > 0 as the criterion for printing a separator.

test suite. Regression testing involves repeating previously run tests to ensure that known failures of prior versions do not appear in new versions of the software.

You will be surprised how often a bug that you fixed will reappear in a future version. This is a phenomenon known as cycling. Sometimes you don't quite understand the reason for a bug and apply a quick fix that appears to work. Later, you apply a different quick fix that solves a second problem but makes the first problem appear again. Of course, it is always best to think through what really causes a bug and fix the root cause instead of doing a sequence of "Band-Aid" solutions. If you don't succeed in doing that, however, you at least want to have an honest appraisal of how well the program works. By keeping all old test cases around and testing them against every new version, you get that feedback. The process of checking each version of a program against a test suite is called regression testing.

What output is generated by the program segment below? ArrayList scores = new ArrayList(); scores.add(78); scores.add(87); scores.add(90); scores.add(1,72); scores.set(3,80); scores.remove(2); System.out.println(scores);

[78, 72, 80]

What does this program snippet print? ArrayList a = new ArrayList(); a.add("x"); ArrayList b = a; b.add("y"); a.add("z"); System.out.println(a + " " + b);

[x, y, z] [x, y, z]

Insert the missing statement in the code fragment below. The method should return the result of adding the values in the first row of the two-dimensional integer array received as argument. public static int addFirstRow(int[][] array) { int sum = 0; for (int k = 0; k < array[0].length; k++) { sum = sum + _________________; } return sum; }

array[0][k]

Given the declaration below, which of the following statements would cause a run-time error? int[] array = {4, 3, 5, 2, 0}; array[0] = 1; array[4] = 1; array[5] = 1; array[2] = array[3];

array[5] = 1;

Write a statement that assigns the double representation of the value held by the Integer object numElements to a double variable named calcSize.

calcSize = numElements.doubleValue(); doubleValue returns value of numElements as a primitive double value.

Assign the Integer element at index 8 of ArrayList frameScores to a variable currFrame.

currFrame = frameScores.get(8); The get() method returns the object at the specified index within the ArrayList.

Consider the algorithm to find the largest element in an array.

double largest = 0; for (int i = 0; i < values.length; i++) { if (values[i] > largest) { largest = values[i]; } }

Using Array Algorithms with Array Lists The array algorithms in Section 7.3 can be converted to array lists simply by using the array list methods instead of the array syntax (see Table 3). For example, this code snippet finds the largest element in an array:

double largest = values[0]; for (int i = 1; i < values.length; i++) { if (values[i] > largest) { largest = values[i]; } } Here is the same algorithm, now using an array list: double largest = values.get(0); for (int i = 1; i < values.size(); i++) { if (values.get(i) > largest) { largest = values.get(i); } }

Write an enhanced for loop that multiplies all elements in a double[] array named factors, accumulating the result in a variable named product.

double product = 1; for (double f : factors) { product = product * f; }

Bounds Errors Perhaps the most common error in using arrays is accessing a nonexistent element.

double[] values = new double[10]; values[10] = 5.4; // Error—values has 10 elements, and the index can range from 0 to 9 If your program accesses an array through an out-of-bounds index, there is no compiler error message. Instead, the program will generate an exception at run time.

score1.equals(score3)

equals() methods compares values of objects: 95 = 95

Given the following primitive wrapper objects, determine whether the provided comparisons evaluate to true or false: Integer score1 = 95; Integer score2 = 91; Integer score3 = 95; int maxScore = score1; score1 == score3

false. == operator compares object references. score1 and score3 refer to two different Integer objects.

All static fields can be accessed anywhere in a program.

false. A class' public static fields can be accessed outside the class because the fields are public. But, a private field can only be accessed by the class' methods.

Each constructed class object creates a new instance of a static field

false. A field belongs to the class, not each class object. Memory is only allocated once for a field, not for each object.

A testbench should print a message for each test case that passes and for each that fails.

false. A testbench may have hundreds of test cases. The tester is concerned about cases that FAIL. To make fails most evident, many programmers recommend only printing the fails.

A programmer must explicitly set all reference variables to null in order to indicate that the objects to which the variables referred are no longer in use.

false. Although setting reference variables to null can be a good practice, it is not required. An object's reference count will be updated appropriately whenever any reference variables referring to that object go out of scope.

The programmer wrote one large file containing all the classes.

false. Each class typically gets its own file.

A private helper method may not call another private helper method.

false. No such restriction exists. A private helper can be called from any other method of the class, whether public or private.

A public member method may not call another public member method.

false. No such restriction exists. Such a call can reduce redundant code.

Testbenches are typically disposed of after use.

false. Testbenches are kept, to be used later as the item being tested is updated.

A testbench should test all possible values, to ensure correctness.

false. Testing all possible values is impossible for nearly any class; too many values exist. Instead, some typical values and some border cases should be tested.

The + indicates additional private items.

false. The + is a common convention for public items, not private items.

Assuming itemList is 99 33 55 77 44, then itemList.remove(55) results in: 99 33 77 44

false. The argument to remove() is the position (or object reference) to be erased. To erase 55, the position argument should have been 2.

A default constructor definition in class Seat { ... } is: public class Seat { ... public void Seat() { ... } }

false. The constructor does not have a return type, so void should not be used. The constructor definition should just be public Seat() { }

The following code calls the default constructor once: Seat seat1 = new Seat(); Seat seat2 = new Seat();

false. The default constructor is called for each created Seat object, thus twice.

Only one way exists to decompose a program into classes.

false. Thinking of a program as classes is sometimes helpful, sometimes not, depending on the application. Even when helpful, many ways exist to decompose the program into classes.

score2.compareTo(score1) > 0

false. compareTo() returns a negative value because score2 < score1.

itemList.isEmpty() removes all elements.

false. isEmpty() just returns true if the ArrayList size is 0. clear() removes elements.

The this parameter can be used in a static method to access an object's non-static fields.

false. this refers to a specific class object, but static methods are independent of class objects. So, the this parameter is not passed to static methods, and a static method cannot access non-static fields.

A class' private helper method can be called from main(), which is defined in another class.

false.A class' private methods can only be called from the class' other methods.

Write a statement that creates an object of FlightInfo and assigns the new object to the reference variable flightPlan.

flightPlan = new FlightInfo(); The new operator allocates the memory necessary for the object and returns a reference (memory address) to that object.

Write an enhanced for loop that prints all elements in the array values.

for (double x : values) { System.out.println(x); }

When printing separators, we skipped the separator before the initial element. Rewrite the loop so that the separator is printed after each element, except for the last element.

for (int i = 0; i < values.length; i++) { System.out.print(values[i]); if (i < values.length - 1) { System.out.print(" | "); } } Now you know why we set up the loop the other way.

Suppose values is an Arraylist. What is the equivalent of the following loop? for (double value : values) { sum = sum + value; }

for (int i = 0; i < values.size(); i++) { sum = sum + values.get(i); }

Given the array list primes declared in Self Check 35, write a loop to print its elements in reverse order, starting with the last element.

for (int i = primes.size() - 1; i >= 0; i--) { System.out.println(primes.get(i)); }

Expand the size of ArrayList frameScores by appending an element with an integer value of 9.

frameScores.add(9); The add() method expands the size of the ArrayList by 1. The new element is added at the end of the list.

Assign the value 10 to element at index 2 of ArrayList frameScores.

frameScores.set(2, 10); The set() method sets the ArrayList's element at index 2 to be equal to the integer 10.

You often need to swap elements of an array. For example, you can sort an array by repeatedly swapping elements that are not in order. Use a temporary variable when swapping two elements. Consider the task of swapping the elements at positions i and j of an array values. We'd like to set values[i] to values[j]. But that overwrites the value that is currently stored in values[i], so we want to save that first: double temp = values[i]; ➋ values[i] = values[j]; ➌ Now we can set values[j] to the saved value. values[j] = temp; ➍ Figure 10 shows the process.

https://drive.google.com/file/d/13dxryx8Xj2DJiPTvieoEJDV4mMjajaaG/view?usp=sharing

Two-Dimensional Arrays It often happens that you want to store collections of values that have a two-dimensional layout. Such data sets commonly occur in financial and scientific applications. An arrangement consisting of rows and columns of values is called a two-dimensional array, or a matrix.

https://drive.google.com/file/d/1B1i0phqSdQ0ZbT9BpkOmWKIEiYg4czzP/view?usp=sharing

Private helper member methods.

https://drive.google.com/file/d/1BFj4P4nzPeqKaibHoR6DGMw3T_BLNvgg/view?usp=sharing

Individual elements in a two-dimensional array are accessed by using two index values, array[i][j]. To access a particular element in the two-dimensional array, you need to specify two index values in separate brackets to select the row and column, respectively (see Figure 14): int medalCount = counts[3][1];

https://drive.google.com/file/d/1BYBhyJPY502xU4c6UBAtXiM8Cg5U0i13/view?usp=sharing

Table 7.12.2: Comparing primitive wrapper class objects using relational operators.

https://drive.google.com/file/d/1EkosrCPE4Bd0c-fxG_nGgajWj55QWEjS/view?usp=sharing

Arrays

https://drive.google.com/file/d/1IQJW5ucWkfFV8nDE4JVCcz4HUT8WZ0sC/view?usp=sharing

Assume a is an array of integers. Fill in the following code snippets:

https://drive.google.com/file/d/1JxakXeE-4N7vhRN8MaWTr_lmTSev3QmJ/view?usp=sharing

Working with Array Lists

https://drive.google.com/file/d/1MrcZipUBo00n9E4tEX4ZPNmVD3h_3F7d/view?usp=sharing

Length and Size Unfortunately, the Java syntax for determining the number of elements in an array, an array list, and a string is not at all consistent. It is a common error to confuse these. You just have to remember the correct syntax for every data type.

https://drive.google.com/file/d/1TXgz9GQgxD4SBqK7EARDk0DgOdYU5uje/view?usp=sharing

Memory regions

https://drive.google.com/file/d/1Uj8YBl_GmgPaWH6nioD95oy-yAlcPu29/view?usp=sharing

Converting to and from Strings Primitive wrapper classes feature methods that are useful for converting to and from Strings. Several of these methods are static methods, meaning they can be called by a program without creating an object. To call a static method, the name of the class and a '.' must precede the static method name, as in Integer.toString(16);

https://drive.google.com/file/d/1YaC8sVNBnEY5IAgaHxJkZHBPooypHU-U/view?usp=sharing

: Garbage collection.

https://drive.google.com/file/d/1aKUd7PR88OUxvLcwja33yQlI_Juej7_M/view?usp=sharing

Table 7.12.3: equals() and compareTo() methods for primitive wrapper types.

https://drive.google.com/file/d/1gMtsBWkMtETSAl3xuPOqKlCnVqjf5miB/view?usp=sharing

You can insert an element in the middle of an array list. For example, the call names.add(1, "Ann") adds a new element at position 1 and moves all elements with index 1 or larger by one position. After each call to the add method, the size of the array list increases by 1

https://drive.google.com/file/d/1ohZr2aO9K1eAsFNgKP3ttzPao9Hw_NOY/view?usp=sharing

Carry out the following tasks with an ArrayList a:

https://drive.google.com/file/d/1r9Miqh-N4J2znke9qBZeR0y-GF4pB3mc/view?usp=sharing

Array Lists

https://drive.google.com/file/d/1uujtWcrMvxoV-SWrp4h1vTcD5e3SfInb/view?usp=sharing

Converting to primitive types The Integer, Double, and Long primitive wrapper classes provide methods for converting objects to primitive types. Table 7.12.4: Converting primitive wrapper objects to primitive types.

https://drive.google.com/file/d/1xsTmD2GYH1ds6ph4BdYAqy6STvJfeak5/view?usp=sharing

Common ArrayList methods.

https://drive.google.com/file/d/1zTPX-zxbBEVSL0jde5NshfzAFJVIOlkJ/view?usp=sharing

Modify the existing ArrayLists's contents, by erasing the second element, then inserting 100 and 102 in the shown locations. Use ArrayList's remove() and add() only. Sample output of below program: 100 101 102 103

import java.util.ArrayList; public class ArrayListADT { public static void printArrayList(ArrayList<Integer> numsList) { int i; for (i = 0; i < numsList.size(); ++i) { System.out.print(numsList.get(i)); System.out.print(" "); } System.out.println(""); } public static void main(String [] args) { ArrayList<Integer> numsList = new ArrayList<Integer>(); numsList.add(101); numsList.add(200); numsList.add(103); /* Your solution goes here */ numsList.remove(1); numsList.add(0,100); numsList.add(2,102); printArrayList(numsList); } }

The following program shows how to mark the largest value in a sequence of values stored in an array list. Note how the program is an improvement over the array version in Section 7.3.10. This program can process input sequences of arbitrary length.

import java.util.ArrayList; import java.util.Scanner; /** This program reads a sequence of values and prints them, marking the largest value. */ public class LargestInArrayList { public static void main(String[] args) { ArrayList<Double> values = new ArrayList<Double>(); // Read inputs System.out.println("Please enter values, Q to quit:"); Scanner in = new Scanner(System.in); while (in.hasNextDouble()) { values.add(in.nextDouble()); } // Find the largest value double largest = values.get(0); for (int i = 1; i < values.size(); i++) { if (values.get(i) > largest) { largest = values.get(i); } } // Print all values, marking the largest for (double element : values) { System.out.print(element); if (element == largest) { System.out.print(" <== largest value"); } System.out.println(); } } }

Program illustrating how slow ArrayList add() and remove() operations can be.

import java.util.ArrayList; import java.util.Scanner; public class ArrayListAddRemove { public static void main(String[] args) { Scanner scnr = new Scanner(System.in); ArrayList<Integer> myInts = new ArrayList<Integer>(); // Dummy array list to demo ops int numElem; // User defined array size int numOps; // User defined number of inserts int i; // Loop index System.out.print("\nEnter initial ArrayList size: "); numElem = scnr.nextInt(); System.out.print("Enter number of ArrayList adds: "); numOps = scnr.nextInt(); System.out.print(" Adding elements to ArrayList..."); myInts.clear(); for (i = 0; i < numElem; ++i) { myInts.add(new Integer(0)); } System.out.println("done."); System.out.print(" Writing to each element..."); for (i = 0; i < numElem; ++i) { myInts.set(i, new Integer(777)); // Any value } System.out.println("done."); System.out.print(" Doing " + numOps + " additions at the end..."); for (i = 0; i < numOps; ++i) { myInts.add(new Integer(888)); // Any value } System.out.println("done."); System.out.print(" Doing " + numOps + " additions at index 0..."); for (i = 0; i < numOps; ++i) { myInts.add(0, new Integer(444)); } System.out.println("done."); System.out.print(" Doing " + numOps + " removes..."); for (i = 0; i < numOps; ++i) { myInts.remove(0); } System.out.println("done."); } }

Write a program that reads in words and prints them out in reverse order. Complete this code.

import java.util.ArrayList; import java.util.Scanner; public class ReverseInput { public static void main(String[] args) { ArrayList<String> words = new ArrayList<String>(); Scanner in = new Scanner(System.in); // Read input into words while (in.hasNext()) { words.add(in.next()); } // Reverse input for (int i=words.size()-1; i>=0; i--) { System.out.print(words.get(i) + " "); } } }

Using a for loop, fill the array a with 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2. Complete the code below.

import java.util.Arrays; public class Fill { public static void main(String[] args) { int[] a = new int[18]; for (int i = 0,j=0; i<a.length; i++ ) { a[i]= j++; if(j==3) j=0; } System.out.println(Arrays.toString(a)); } }

Click to hide a program that implements the algorithm that switches the first and second halves of an array.

import java.util.Arrays; public class SwapHalves { /** Swaps the elements of an array at given positions. @param a the array @param i the first position @param j the second position */ public static void swap(int[] a, int i, int j){ int temp =a[i]; a[i]= a[j]; a[j] =temp; } public static void main(String[] args) { int[] values = { 9, 13, 21, 4, 11, 7, 1, 3 }; int i = 0; int j = values.length / 2; while (i < values.length / 2) { // Swap values at positions i and j int temp = values[i]; values[i] = values[j]; values[j] = temp; i++; j++; } System.out.println(Arrays.toString(values)); } }

Array Elements as Counters

import java.util.Random; public class apples { public static void main(String args[]){ Random rand = new Random(); int freq[] = new int[7]; for(int roll=1; roll<1000; roll++){ ++freq[1+rand.nextInt(6)]; } System.out.println("Face\tFrequency"); for(int face=1; face <freq.length; face++) System.out.println(face+"\t"+freq[face]); } } https://www.youtube.com/watch?v=pHxtKDENDdE&list=PLFE2CE09D83EE3E28&index=30

The following program puts these algorithms to work, solving the task that we set ourselves at the beginning of this chapter: to mark the largest value in an input sequence.

import java.util.Scanner; /** This program reads a sequence of values and prints them, marking the largest value. */ public class LargestInArray { public static void main(String[] args) { final int LENGTH = 100; double[] values = new double[LENGTH]; int currentSize = 0; // Read inputs System.out.println("Please enter values, Q to quit:"); Scanner in = new Scanner(System.in); while (in.hasNextDouble() && currentSize < values.length) { values[currentSize] = in.nextDouble(); currentSize++; } // Find the largest value double largest = values[0]; for (int i = 1; i < currentSize; i++) { if (values[i] > largest) { largest = values[i]; } } // Print all values, marking the largest for (int i = 0; i < currentSize; i++) { System.out.print(values[i]); if (values[i] == largest) { System.out.print(" <== largest value"); } System.out.println(); } } }

A program to convert a decimal number to binary

import java.util.Scanner; public class DecimalToBinary { public static void main (String [] args) { Scanner scnr = new Scanner(System.in); int decimalInput; String binaryOutput; System.out.print("Enter a decimal number: "); decimalInput = scnr.nextInt(); binaryOutput = Integer.toBinaryString(decimalInput); System.out.println("The binary representation of " + decimalInput + " is " + binaryOutput); } }

Write a loop that counts how many elements in an array are equal to zero.

int count = 0; for (double x : values) { if (x == 0) { count++; } }

Linear Search You often need to search for the position of a specific element in an array so that you can replace or remove it. Visit all elements until you have found a match or you have come to the end of the array. Here we search for the position of the first element in an array that is equal to 100:

int searchedValue = 100; int pos = 0; boolean found = false; while (pos < values.length && !found) { if (values[pos] == searchedValue) { found = true; } else { pos++; } } if (found) { System.out.println("Found at position: " + pos); } else { System.out.println("Not found"); }

Declare an array of integers containing the first five prime numbers.

int[] primes = { 2, 3, 5, 7, 11 };

Which statement calls a method on a luxuryCar object to drive 300 miles.

luxuryCar.drive(300); The drive() method updates the BasicCar object, by increasing the object's milesDriven field by 300

Given String greetingStr = "Hi", how can a user assign newGreeting with "!" concatenated to greetingStr.

newGreeting = greetingStr.concat("!") The concat() method's comment explains that a new string consisting of the string parameter concatenated to the string will be returned. (How that concatenation occurs is unknown to the class user).

A basic example to introduce linked lists

ntNode.java public class IntNode { private int dataVal; // Node data private IntNode nextNodePtr; // Reference to the next node public IntNode() { dataVal = 0; nextNodePtr = null; } // Constructor public IntNode(int dataInit) { this.dataVal = dataInit; this.nextNodePtr = null; } // Constructor public IntNode(int dataInit, IntNode nextLoc) { this.dataVal = dataInit; this.nextNodePtr = nextLoc; } /* Insert node after this node. Before: this -- next After: this -- node -- next */ public void insertAfter(IntNode nodeLoc) { IntNode tmpNext; tmpNext = this.nextNodePtr; this.nextNodePtr = nodeLoc; nodeLoc.nextNodePtr = tmpNext; } // Get location pointed by nextNodePtr public IntNode getNext() { return this.nextNodePtr; } public void printNodeData() { System.out.println(this.dataVal); } } CustomLinkedList.java public class CustomLinkedList { public static void main (String[] args) { IntNode headObj; // Create intNode objects IntNode nodeObj1; IntNode nodeObj2; IntNode nodeObj3; IntNode currObj; // Front of nodes list headObj = new IntNode(-1); // Insert more nodes nodeObj1 = new IntNode(555); headObj.insertAfter(nodeObj1); nodeObj2 = new IntNode(999); nodeObj1.insertAfter(nodeObj2); nodeObj3 = new IntNode(777); nodeObj1.insertAfter(nodeObj3); // Print linked list currObj = headObj; while (currObj != null) { currObj.printNodeData(); currObj = currObj.getNext(); } } }

Given a class Spaceship with private field numYears and method: public void addNumYears(int numYears) In main(), given variable declaration: Spaceship ss1 = new Spaceship(), which sets ss1's numYears to 5?

numYears is a private field, so cannot be accessed in main() (trick question).

Assign negativeCntr with the number of negative values in the linked list.

ojo) // ===== Code from file IntNode.java ===== public class IntNode { private int dataVal; private IntNode nextNodePtr; public IntNode(int dataInit, IntNode nextLoc) { this.dataVal = dataInit; this.nextNodePtr = nextLoc; } public IntNode(int dataInit) { this.dataVal = dataInit; this.nextNodePtr = null; } /* Insert node after this node. * Before: this -- next * After: this -- node -- next */ public void insertAfter(IntNode nodePtr) { IntNode tmpNext; tmpNext = this.nextNodePtr; // Remember next this.nextNodePtr = nodePtr; // this -- node -- ? nodePtr.nextNodePtr = tmpNext; // this -- node -- next } // Grab location pointed by nextNodePtr public IntNode getNext() { return this.nextNodePtr; } public int getDataVal() { return this.dataVal; } } // ===== end ===== // ===== Code from file CustomLinkedList.java ===== import java.util.Random; public class CustomLinkedList { public static void main (String [] args) { Random randGen = new Random(); IntNode headObj; // Create intNode objects IntNode currObj; IntNode lastObj; int i; // Loop index int negativeCntr; negativeCntr = 0; headObj = new IntNode(-1); // Front of nodes list lastObj = headObj; for (i = 0; i < 10; ++i) { // Append 10 rand nums int rand = randGen.nextInt(21) - 10; currObj = new IntNode(rand); lastObj.insertAfter(currObj); // Append curr lastObj = currObj; // Curr is the new last item } currObj = headObj; // Print the list while (currObj != null) { System.out.print(currObj.getDataVal() + ", "); currObj = currObj.getNext(); } System.out.println(""); currObj = headObj; // Count number of negative numbers while (currObj != null) { /* Your solution goes here */ negativeCntr++; currObj = currObj.getNext(); } System.out.println("Number of negatives: " + negativeCntr); } } // ===== end =====

Write a statement that assigns the int representation of the value held by the Integer object totalPins to a primitive int variable pinScore.

pinScore = totalPins.intValue(); intValue returns value of totalPins as a primitive int value.

You are given a partially filled array prices with a companion variable numberOfPrices indicating the number of elements that are actually used. Which of the following statements increments the last used element in the partially filled array? prices[prices.length - 1]++; prices[prices.length]++; prices[numberOfPrices - 1]++; prices[numberOfPrices]++;

prices[numberOfPrices - 1]++;

A static method is needed to access or mutate a _____ static field from outside of the class.

private. A public static method can be used to access of mutate a private static field.

Using the ElapsedTime class declared above, complete the default constructor so that the hours and minutes fields are both initialized to -1 by making a call to the overloaded constructor. public ElapsedTime() { }

public ElapsedTime() { this(-1,-1); } this(-1, -1) The this keyword allows a programmer to reuse code from another constructor.

Complete the following code to make a copy of the first half of an array of strings.

public class CopyHalf { /** * Copies the first half of an array. If the length is odd, don't copy the * middle value. * * @param values * an array * @return a copy of the first half of values */ public static String[] copyHalf(String[] values) { int halfLength = values.length / 2; String[] result = new String[halfLength]; for (int i = 0; i < halfLength; i++) result[i] = values[i]; return result; } }

The 'this' keyword can also be used in a constructor to invoke a different (overloaded) constructor. In the default constructor below, this(0, 0); invokes the other constructor to initialize both fields to zero. For this example, a programmer could have just set both fields to zero within the default constructor. However, invoking other constructors is useful when a class' initialization routine is lengthy, avoiding rewriting the same code.

public class ElapsedTime { private int hours; private int minutes; // Overloaded constructor definition public ElapsedTime(int timeHours, int timeMins) { hours = timeHours; minutes = timeMins; } // Default constructor definition public ElapsedTime() { this(0, 0); } // Other methods ... }

EnhancedForLoopDemo

public class EnhancedForLoopDemo { public static void main(String[] args) { int[] values = new int[10]; // In this loop, we need the index value, so we can't use // an enhanced for loop. for (int i = 0; i < values.length; i++) { values[i] = i * i; } // In this loop, we don't need the index value. // The enhanced for loop simplifies the code. int total = 0; for (int element : values) { System.out.println(element); total = total + element; } System.out.println("Sum: " + total); } }

Declare a method of a class Lottery that returns a combination of n numbers. You don't need to implement the method.

public class Lottery { public int[] getCombination(int n) { . . . } . . . }

Introduction to Arrays

public class apples { public static void main(String args[]){ int bucky[]={2,4,5,7,9}; System.out.println(bucky[2]); } } https://www.youtube.com/watch?v=L06uGnF4IpY&list=PLFE2CE09D83EE3E28&index=27

Creating an Array

public class apples { public static void main(String args[]){ System.out.println("Index\tValue"); int bucky[]={32,12,18,54,2}; for(int counter=0; counter<bucky.length; counter++){ System.out.println(counter + "\t" + bucky[counter] ); } } } https://www.youtube.com/watch?v=nTF-RcgsV0E&index=28&list=PLFE2CE09D83EE3E28

Summing Elements of Arrays

public class apples { public static void main(String args[]){ int bucky[]={21,16,86,21,3}; int sum=0; for(int counter=0;counter<bucky.length;counter++){ sum+=bucky[counter]; } System.out.println("The sum of these numbers is"+ sum); } } https://www.youtube.com/watch?v=etyrkipdKvc&list=PLFE2CE09D83EE3E28&index=29

Arrays in Methods

public class apples { public static void main(String args[]){ int bucky[]={3,4,5,6,7}; change(bucky); for(int y:bucky) System.out.println(y); } public static void change(int x[]){ for(int counter=0; counter<x.length; counter++) x[counter]+=5; } }

Enhanced for Loop

public class apples { public static void main(String args[]){ int bucky[]={3,4,5,6,7}; int total=0; for(int x: bucky){ total+=x; } System.out.println(total); } }

Multidimensional Arrays

public class apples { public static void main(String args[]){ int firstarray[][] = {{8,9,10,11},{12,13,14,15}}; int secondarray[][] = {{30,31,32,33},{43},{4,5,6}}; System.out.println("This is the first array"); display(firstarray); System.out.println("This is the second array"); display(secondarray); } public static void display(int x[][]){ for(int row=0; row<x.length; row++){ for(int column=0;column<x[row].length;column++){ System.out.print(x[row][column] + "\t"); } System.out.println(); } } } https://www.youtube.com/watch?v=hbot9MQVHOM&index=34&list=PLFE2CE09D83EE3E28

Add a new element of type Seat to an ArrayList called trainSeats.

rainSeats.add(new Seat()); The add() method expands the size of the ArrayList by 1. The new element is added at the end of the list.

Insert the missing statement in the code fragment below. The method should add the bonus value to each list element with a value smaller than 90. public static void addBonus(ArrayList scores, int bonus) { for (int k = 0; k < scores.size(); k++) { if (scores.get(k) < 90) { _____________________ } } }

scores.set(k, scores.get(k) + bonus);

Write a statement that uses the 'this' keyword to initialize the field minutes to 0.

this.minutes = 0; Assigns the value 0 to the field minutes of the object referred to by the this reference. 2)

In addNumYears(), which would add the parameter numYears to the existing value of field numYears?

this.numYears = this.numYears + numYears;

Given a class Spaceship with private field numYears and method: public void addNumYears(int numYears) 1) In addNumYears(), which would set field numYears to 0?

this.numYears refers to the class' field.

In addNumYears(), which would assign the parameter numYears to the field numYears?

this.numYears refers to the field. numYears refers to the parameter.

Write a statement that assigns the String representation of the value held by the Double trackRadius to a String variable called radiusText. radiusText =

trackRadius.toString(); The toString() method returns a String representing the value held by the primitive wrapper object.

Use method chaining to get the element at index 0 in ArrayList trainSeats and make a reservation for John Smith, who paid $44.

trainSeats.get(0).reserve("John", "Smith", 44); trainSeats.get(0) return a references to the Seat object at index 0, and .reserve() calls the reserve() methods on the returned Seat object.

A public static field can be accessed outside of the class using dot notation.

true. Classes use the member access operator (.) to access all member variables and member methods.

Calling every method at least once is a prerequisite for 100% code coverage.

true. If a testbench doesn't call a method, that method's lines of code can't possibly be executed. Multiple calls may be needed for 100% coverage.

Not defining any constructor is essentially the same as defining a constructor with no statements.

true. Not finding any programmer-defined constructor, the compiler generates a constructor with no statements.

An object of type BasicCar must be used within main() to call instance methods.

true. Objects of the correct type must be used to invoke instance methods.

A method's local reference variables automatically go out of scope when the method returns.

true. Once a method returns, all of its local variables are discarded, and thus go out of scope.

A private helper method typically helps public methods carry out their tasks.

true. Private helper methods can lead to cleaner public method definitions.

For commercial software, testing consumes a large percentage of time.

true. Testing that consumes 50% or more is not unheard of. Writing thorough testbenches is a job in itself.

The - indicates a class' private item.

true. The - is a common convention for private items.

Good practice is to explicitly define a default constructor for a class.

true. The constructor should initialize all fields.

The following code calls the default constructor once: Seat mySeat = new Seat();

true. The default constructor is called when an object is created of the class type.

DriveTime timeRoute1 = new DriveTime(); DriveTime timeRoute2; DriveTime bestRoute; timeRoute2 = new DriveTime(); bestRoute = timeRoute1; 1) Variables timeRoute1 and timeRoute2 both refer to valid objects.

true. The statement DriveTime timeRoute1 = new DriveTime(); allocated a new object for timeRoute1, and the statement timeRoute2 = new DriveTime(); allocated a new object for timeRoute2.

Good practice would be to first write the TeamPerson class and then test that class, followed by writing the SoccerTeam class and testing that class.

true. Though not shown above, each class should be tested after being written.

After itemList.clear(), itemList.get(0) is an invalid access.

true. clear() removes all elements. So there is no element 0.

int[] values = new int[10]; write statements to put the integer 10 into the elements of the array values with the lowest and the highest valid index.

values[0] = 10; values[9] = 10; or, better: values[values.length - 1] = 10;


Conjuntos de estudio relacionados

Church History Study Guide Unit 4-3

View Set