Computer Science A

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

What comes before || or &&

&&

Insertion Sort Algorithm

- look at the second item in a list - compare it to all items before it and insert the item into the right place - repeat the second step for the rest of the items until the last item in the list has been inserted into the correct place

When is autoboxing applied?

- primitive passed as parameter to method expecting an object of corresponding wrapper class - primitive assigned variable of corresponding wrapper class

double d = 0.25; int i = 3; double diff = d - i; System.out.print((int)diff - 0.5); What is printed as a result of this statement?

-2.5

Examples of syntax errors

-misspelled keywords -unmatched quotation marks -missing semicolons -invalid options

When is unboxing applied?

-wrapper class object passed as parameter instead of primitive type -wrapper class object assigned variable of primitive type

Insertion sort algorithm (code)

/* * Insertion sort takes in an array of integers and * returns a sorted array of the same integers. */ private static void insertionSort(int[] arr) { System.out.println(Arrays.toString(arr)); // note: we start with 1 instead of 0 for (int i = 1; i < arr.length; i++) { int curNumber = arr[i]; // Set index to be place to the left int curIndex = i-1; // We are still inbounds and the current number // is less than the current index while ( curIndex >= 0 && arr[curIndex] > curNumber) { // Shift the value at curIndex to the right one place arr[curIndex+1] = arr[curIndex]; curIndex--; } // Put this number in the proper location arr[curIndex + 1] = curNumber; System.out.println(Arrays.toString(arr)); } }

String str1 = "Grand Theft Auto"; String str2 = "Assassin Creed"; String str3 = "Call of Duty"; String str4 = "Need for Speed"; String str5 = "Grand Theft Auto"; System.out.println(str1.compareTo(str2)); System.out.println(str2.compareTo(str3)); System.out.println(str3.compareTo(str4)); System.out.println(str4.compareTo(str1)); System.out.println(str1.compareTo(str5));

// Since 'A' is greater than 'G' by 6 characters, so it will return 6 // Since 'C' is smaller than 'A' by 2 characters, so it will return -2 //Since 'N' is smaller than 'C' by 11 characters, so it will return -11 //Since 'G' is Greater than 'N' by 7 characters, so it will return 7 //Strings are equal

What is the result of 2 / 5 % 3

0

for(int i = 0; i < 4; i += 4) { System.out.println(i); } What is the output?

0

Bit size of boolean

1

Consider the following code segment. int[] arr = {4, 3, 2, 1, 0}; int total = 0; for (int k = 0; k <= total; k++) { if (arr[k] % 2 == 0) { total += arr[k]; } else { total -= arr[k]; } } System.out.print(total); What, if anything, is printed as a result of executing the code segment?

1

int[][] arr = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {3, 2, 1}}; for (int j = 0; j < arr.length; j++) { for (int k = j; k < arr[0].length; k++) { System.out.print(arr[j][k] + " "); } System.out.println(); }

1 2 3 5 6 9

double myDouble = 1/4; System.out.println("1 / 4 = " + myDouble); What is the output of this code?

1/4 = 0.0

What will be display as a result of executing this code (0,5,10, 20, or code will not compile)? public class ExampleTwo{ private int current; public ExampleTwo(int c){ current = c; } public void reset(int amt){ amt += 5; int current = amt; } public int getCurrent(){ return current; } } In a different class: ExampleTwo obj = new ExampleTwo(10); obj.reset(15); System.out.println(obj.getCurrent());

10

What is the result of this expression? 4 + 8 * 3 / 4 + 5 % 2

11

What is the output when this program is executed? public class Logic { public static void incrementParam (int a){ a++; System.out.println(a); } public static void main(Strings[] args){ int x = 33; incrementParam(x); System.out.println(x); } }

34 33 Needs private instance variable

Bit size of int

4 byes (32 bits)

Consider the following code segment. int count = 0; int number = 20; while (number > 0) { number = number / 2; count++; } What will be the value of count after executing the code segment?

5

How many times will the loop execute? int i = 0; while(i < 50) { System.out.println(i); i += 10; }

5

Bit size of double

8 byes (64 bits)

What comes before == or &&

== does

Consider the following code segment, which is intended to create and initialize the two-dimensional (2D) integer array num so that columns with an even index will contain only even integers and columns with an odd index will contain only odd integers. int[][] num = /* missing code */; Which of the following initializer lists could replace /* missing code */ so that the code segment will work as intended? A {{0, 1, 2}, {4, 5, 6}, {8, 3, 6}} B {{1, 2, 3}, {3, 4, 5}, {5, 6, 7}} C {{1, 3, 5}, {2, 4, 6}, {3, 5, 7}} D {{2, 1, 4}, {5, 2, 3}, {2, 7, 6}} E {{2, 4, 6}, {1, 3, 5}, {6, 4, 2}}

A

object

A specific instance of a class with a specific set of values for its own attributes that is able to execute any methods defined in its class.

selection sort algorithm

An algorithm for sorting a collection of values that repeatedly finds the largest or smallest values in the unsorted section of the list and swaps them with an element in the correct position. This method uses a helper method to perform the swap because variables can only hold 1 value at a time.

Consider the following class definition. public class Beverage { private int numOunces; private static int numSold = 0; public Beverage(int numOz) { numOunces = numOz; } public static void sell(int n) { /* implementation not shown */ } } Which of the following best describes the sell method's level of access to the numOunces and numSold variables? A Both numOunces and numSold can be accessed and updated. B Both numOunces and numSold can be accessed, but only numOunces can be updated. C Both numOunces and numSold can be accessed, but only numSold can be updated. D numSold can be accessed but not updated; numOunces cannot be accessed or updated. E numSold can be accessed and updated; numOunces cannot be accessed or updated. Answer B Incorrect. sell is a static method and therefore can neither access nor update instance variables like numOunces.

Answer B Incorrect. sell is a static method and therefore can neither access nor update instance variables like numOunces.

Consider the following method, which is intended to return the number of strings of length greater than or equal to 3 in an array of String objects. public static int checkString(String[] arr) { int count = 0; for (int k = 0; k < arr.length; k++) { if (arr[k].length() >= 3) { count++; } } return count; } Which of the following code segments compile without error? checkString(new String[]); checkString(new String[0]); String[] str = {"cat", "dog"};checkString(str); A II only B III only C I and III only D II and III only E I, II, and III

Answer D Correct. The size of an array must be established when the array is created, either explicitly by specifying the size within the brackets or implicitly by using an initializer list. Statement I does not compile because the array size is missing. Statement II compiles because it correctly creates an array of size 0. Statement III compiles because it creates an array of size 2, using an initializer list.

How do you initialize an ArrayList?

ArrayList name = new ArrayList<Integer>();

(a && (b || !a)) == a && b Which of the following best describes the conditions under which the expression will evaluate to true? A Only when a is true B Only when b is true C Only when both a and b are true D The expression will never evaluate to true. E The expression will always evaluate to true.

B

Consider the following code segments, which differ only in their loop header. Code Segment I for (int i = 0; i < 10; i++) { System.out.print( "*" ); } Code Segment II for (int i = 1; i <= 10; i++) { System.out.print( "*" ); } Which of the following best explains how the difference in the two loop headers affects the output? A The output of the code segments is the same because the loops in each code segment terminate when i is 10. B The output of the code segments is the same because the loops in both code segments iterate 10 times. C The output of the code segments is different because code segment I iterates from i = 0 to i = 9 and code segment II iterates from i = 1 to i = 10. D The output of the code segments is different because code segment I iterates from i = 0 to i = 10 and code segment II iterates from i = 1 to i = 11. E Neither code segment produces output because both loop conditions are initially false.

B

Consider the following method definition. The method isReversed is intended to return true if firstList and secondList contain the same elements but in reverse order, and to return false otherwise. /** Precondition: firstList.size() == secondList.size() */ public static boolean isReversed(ArrayList<Integer> firstList, ArrayList<Integer> secondList) { for (int j = 0; j < firstList.size() / 2; j++) { if (firstList.get(j) != secondList.get(secondList.size() - 1 - j)) { return false; } } return true; } The method does not always work as intended. For which of the following inputs does the method NOT return the correct value? A When firstList is {1, 3, 3, 1} and secondList is {1, 3, 3, 1} B When firstList is {1, 3, 3, 1} and secondList is {3, 1, 1, 3} C When firstList is {1, 3, 5, 7} and secondList is {5, 5, 3, 1} D When firstList is {1, 3, 5, 7} and secondList is {7, 5, 3, 1} E When firstList is {1, 3, 5, 7} and secondList is {7, 5, 3, 3}

C

Consider the following statement, which is intended to create an ArrayList named numbers that can be used to store Integer values. ArrayList<Integer> numbers = /* missing code */; Which of the following can be used to replace /* missing code */ so that the statement works as intended? new ArrayList() new ArrayList<Integer> new ArrayList<Integer>() A III only B I and II only C I and III only D II and III only E I, II, and III

C

Which of the following is equivalent to this expression? (x && !y) a. (!x || y) b. (!x && y) c. !(!x || y) d. !(!x && y) e. (x || !y)

C

int[] arr = {10, 20, 30, 40, 50}; for(int x = 1; x < arr.length - 1; x++) { arr[x + 1] = arr[x] + arr[x + 1]; } Which of the following represents the contents of arr after the code segment has been executed? A {10, 20, 30, 70, 120} B {10, 20, 50, 90, 50} C {10, 20, 50, 90, 140} D {10, 30, 60, 100, 50} E {10, 30, 60, 100, 150}

C

What is the logic behind creating an equals method that compares objects?

Compare the attributes (instance variables) between the user input (other) and the object before the . (this)

Unboxing

Copying a value from inside a wrapper class object and storing it into a primitive data type variable (Integer to int, Double to double)

Consider the following code segment. int[] oldArray = {1, 2, 3, 4, 5, 6, 7, 8, 9}; int[][] newArray = new int[3][3]; int row = 0; int col = 0; for (int index = 0; index < oldArray.length; index++) { newArray[row][col] = oldArray[index]; row++; if ((row % 3) == 0) { col++; row = 0; } } System.out.println(newArray[0][2]); What is printed as a result of executing the code segment? A 3 B 4 C 5 D 7 E 8

D

Consider the following correct implementation of the insertion sort algorithm. public static void insertionSort(int[] elements) { for (int j = 1; j < elements.length; j++) { int temp = elements[j]; int possibleIndex = j; while (possibleIndex > 0 && temp < elements[possibleIndex - 1]) { elements[possibleIndex] = elements[possibleIndex - 1]; possibleIndex--; // line 10 } elements[possibleIndex] = temp; } } The following declaration and method call appear in a method in the same class as insertionSort. int[] arr = {10, 8, 3, 4}; insertionSort(arr); How many times is the statement possibleIndex--; in line 10 of the method executed as a result of the call to insertionSort ? A 0 B 1 C 4 D 5 E 6

D

Consider the following method substringFound, which is intended to return true if a substring, key, is located at a specific index of the string phrase. Otherwise, it should return false. public boolean substringFound(String phrase, String key, int index) { String part = phrase.substring(index, index + key.length()); return part.equals(key); } Which of the following is the best precondition for index so that the method will return the appropriate result in all cases and a runtime error can be avoided? A 0 <= index < phrase.length() B 0 <= index < key.length() C 0 <= index < phrase.length() + key.length() D 0 <= index < phrase.length() - key.length() E 0 <= index < phrase.length() - index

D

Example of exception errors

Dividing by 0

Declare and Instantiate a Double and Integer variable

Double score = new Double(89.45); Integer score = new Integer(8);

Assume that the int variables a, b, c, and low have been properly declared and initialized. The code segment below is intended to print the sum of the greatest two of the three values but does not work in some cases. if (a > b && b > c) { low = c; } if (a > b && c > b) { low = b; } else { low = a; } System.out.println(a + b + c - low); For which of the following values of a, b, and c does the code segment NOT print the correct value? A a = 1, b = 1, c = 2 B a = 1, b = 2, c = 1 C a = 1, b = 2, c = 3 D a = 2, b = 2, c = 2 E a = 3, b = 2, c = 1

E

Consider the following code segment. for (int j = 0; j < 4; j++) { for (int k = 0; k < j; k++) { System.out.println("hello"); } } Which of the following best explains how changing the inner for loop header to for (int k = j; k < 4; k++) will affect the output of the code segment? A The output of the code segment will be unchanged. B The string "hello" will be printed three fewer times because the inner loop will iterate one fewer time for each iteration of the outer loop. C The string "hello" will be printed four fewer times because the inner loop will iterate one fewer time for each iteration of the outer loop. D The string "hello" will be printed three additional times because the inner loop will iterate one additional time for each iteration of the outer loop. E The string "hello" will be printed four additional times because the inner loop will iterate one additional time for each iteration of the outer loop.

E

Consider the following two code segments, which are both intended to determine the longest of the three strings "pea", "pear", and "pearl" that occur in String str. For example, if str has the value "the pear in the bowl", the code segments should both print "pear" and if str has the value "the pea and the pearl", the code segments should both print "pearl". Assume that str contains at least one instance of "pea". I. if (str.indexOf("pea") >= 0) { System.out.println("pea"); } else if (str.indexOf("pear") >= 0) { System.out.println("pear"); } else if (str.indexOf("pearl") >= 0) { System.out.println("pearl"); } II. if (str.indexOf("pearl") >= 0) { System.out.println("pearl"); } else if (str.indexOf("pear") >= 0) { System.out.println("pear"); } else if (str.indexOf("pea") >= 0) { System.out.println("pea"); } Which of the following best describes the output produced by code segment I and code segment II? A Both code segment I and code segment II produce correct output for all values of str. B Neither code segment I nor code segment II produce correct output for all values of str. C Code segment II produces correct output for all values of str, but code segment I produces correct output only for values of str that contain "pear" but not "pearl". D Code segment II produces correct output for all values of str, but code segment I produces correct output only for values of str that contain "pearl". E Code segment II produces correct output for all values of str, but code segment I produces correct output only for values of str that contain "pea" but not "pear".

E

Consider the following code segment, which is intended to display 6.0. double fact1 = 1 / 2; double fact2 = 3 * 4; double product = fact1 * fact2; System.out.println(product); What is the error in this code?

Either the numerator or the denominator of the fraction 1 / 2 should be cast as double.

What happens if you call a substring with an index the same as str.length()

Empty string, not error

If the borrow object is null, what does this code output? borrow.getName();

Error

What is the result of (6/5(double)) ?

Error, Double needs to be before num

What is the output of the following code? String myName = "Moo"; String hisName = "cow"; System.out.print(myName!=hisName);

Errror, String objects should be compared with .equals() or .compareTo()

false==true&&false&&(true||false)

False

What is an integer overflow error?

Incorrect value within allowed range

incrementing Integer.MAX_VALUE and decreasing Integer.MIN_VALUE by 1 results in what?

Incorrect value within allowed range

How do you access the maximum int value?

Integer.MAX_VALUE

How do you access the minimum int value?

Integer.MIN_VALUE

When a subclass's constructor does not explicitly call a superclass's constructor using super, Java does what?

It inserts a call to the superclass's no argument constructor (no parameter constructor) and initializes those instance variables, then goes back to the subclass and initailizes it's own instance variables.

What will Java do if no constructor is provided?

Java will make default constructor which sets all instance variables to default values

What is the output of the code? int age = 16; boolean isLate = false; if (age > 10) if (isLate) System.out.print("Line 1"); else System.out.print("Line 2"); else System.out.print("Line 3"); System.out.print("Line 4");

Line 2Line 4

Can a constructor have a different name than the class?

No

Can you call private methods from a different class in the main tester class or any other classes

No

Can you initialize a static variable in the constructor of a class?

No

Can subclasses directly access private instance variables of a superclass?

No, only through super()

Are Strings mutable (able to be changed)

No, you need to create a newString instead.

What would be the output if a is less than or equal to 30? if (a>30) if (a < 60) System.out.println("a is greater than 30 and less than 60"); else System.out.println("???");

Nothing, dangling else belongs to the closest if statement // this fixes the code to make the else belong to first if statement if (a>30){ if (a < 60) System.out.println("a is greater than 30 and less than 60"); } else System.out.println("???");

Lamp lamp3; lamp3.turnOn(); WHat does this result in?

NullPointerException (refering to null reference)

Order of operations in Java

PE MMD(mod, mult, div) AS

Create an array of 8 Pizza objects and initialize the 5th pizza given the constructor header public Pizza(String name)

Pizza[] arr = new Pizza[8]; Pizza[4] = new Pizza("Cheese");

Logic Error

Program runs but does the wrong thing

Exception Error

Program terminates abnormally

What type of parameters do ArrayList take in?

Reference type, objects, Integer, Double

What are the ways to decare a String?

String name = ""; String name = new String(""); String name = new String(name);

An ArrayList named str has the values {"cow", "chicken", "goose"}, set the last element equal to "star" and store and print the former element at the last index.

String old = str.set(str.size()-1, "star");

Write an algorithm that reverses the characters in a String

String str = "food"; String newStr = ""; for (int i = 0; i < str.length(); i++){ newStr += str.substring(str.length()-i-1, str.length() -i); } System.out.print(newStr);

Is the substring method inclusive or exclusive?

String substring (int from, int to), to is exclusive but from is inclusive

Declare and Initialize a 2D array with type String and 5 columns and 8 rows

String[][] arr = new String[8][5];

Write code to print each row on a different line in String[][] grid = new String[4][5];

String[][] grid = new String[4][5]; for (int row = 0; row < grid.length; row++){ for (int col = 0; col < grid[0].length; col++){ System.out.print(grid[row][col]); } System.out.println(); }

Write code to print the random number from 1 to 100 (inclusive)

System.out.print((int)(Math.random() * 100 + 1));

Write code to print the random number from 31 to 64 (exclusive)

System.out.print((int)(Math.random() * 33 + 31));

What happens to the range if the question is asking to print random number inclusively?

Take the range and add 1

string literal

Text enclosed by double quotes.

A store sells rope only in whole-foot increments. Given three lengths of rope, in feet, the following code segment is intended to display the minimum length of rope, in feet, that must be purchased so that the rope is long enough to be cut into the three lengths. For example, for lengths of 2.8 feet, 3 feet, and 5 feet, the minimum length of rope that must be purchased is 11 feet. For these inputs, the code segment should display 11. As another example, for lengths of 1.1 feet, 3.2 feet, and 2 feet, the minimum length of rope that must be purchased is 7 feet. For these inputs, the code segment should display 7. double len1; double len2; double len3; double total = len1 + len2 + len3; int minLength = (int) (total + 0.5); System.out.print(minLength); With what values does the code not work?

The code segment works as intended but only when the sum of the three lengths is an integer or the decimal part of the sum of the three lengths is greater than or equal to 0.5.

Overloading

The process of creating multiple methods of the same name but different parameters

What does this code result in? public double secret(int x, double y) { return x / 2.0; } double result = secret(4.0, 4);

This statement attempts to pass a double value to the int parameter x. This will cause a compile-time error.

Does an object have a toString method?

Yes

What happens to the range if the question is asking to print random number exclusively?

You can just take the range and not add 1

What is the output of this code? double sumOfScores = 0.0; int numberOfScores = 0; if (numberOfScores > 0 && sumOfScores/numberOfScores >= 80.0){ System.out.print("You have a high average"); } else{ System.out.print("You do not have a high average"); }

You do not have a high average, doesn't check second half of if statement which means it doesnt result in dividingByZero error. Short-circuit happens meaning the left side was already false so it went to else statement without checking right side.

How do you print a double quote (")?

\" (backslash double quote)

How do you print a backslash character (\)?

\\ (backslash backslash)

How do you print a new line?

\n (backslash n)

During the iterations of a for each loop, the elements can't be ___, ___, or ___ to the ArrayList

added, removed, or modified

if a double is changed to (int), what happens

anyhting after decimal place is truncated.

&& ; < > <= >= ; == != ; ||

arrange these in order 1. < > <= >= ; 2. == != 3. && 4. ||

instance variable

attributes

Compareto lowercase vs capital

capital first lowercase

What is wrong with this statement: system.out.prntln("food)

capitalize system, println, match quotation mark, end statement with ;

primitive variables

copy of the primitive itself is passed

Declare a variable

defining it's type

What does this display? String str = "the"; System.out.print(str.substring(2,3));

e

false&&true==true&&false

false

What is returned by the code? House myHouse = new House("Green", 1850, 3); House annasHouse = new House("Green", 1850, 3); House bobsHouse; House momsHouse = myHouse; if (myHouse == annasHouse) return true; else return false;

false, they are not aliases for the same house object, they just have similar attributes

Write an algorithm that returns true if the String subStr is in String word.

for (int i = 0; i <= word.length() - sub.length(); i++){ String portion = word.substring(i, i+sub.length()); if(portion.equals(sub)){ return true; } }

Write code for this: ArrayList <Double> grades should have all grades below 70.0 removed

for (int i = grade.size()-1; i >= 0; i--){ if (grades.get(i) < 70) grades.remove(i); }

Display each of these numbers with a whitespace using a for each loop int[] values = {5, 2, 1, 3, 8};

for(int v: values){ System.out.print(v + " "); }

class

formal implementation/blueprint of attributes and behaviors of an objecct

How do you find the number of rows in a 2d array grades

grades.length

How do you find the number of columns in a 2d array grades

grades[0].length

How do you access the element in the last row and column of the 2d array grades?

grades[grades.length-1][grades[0].length-1]

return true if the myCat object, myCat("mister nyan"), is not null

if (myCat != null) return true;

How would you remove elements via forward loop in an ArrayList?

if (myList.get(i).equals(searchedValue)){ myList.remove(i); i--; }

What are the elements of a boolean, int, String, Object, and double array intialized with?

int = 0, double = 0.0, boolean = false, String = null, Object = null

Write an algorithm that counts the number of vowel occurrences in a String word

int count = 0; for (int i = 0; i < word.length(); i++){ String letter = word.substring(i, i+1); if (letter.equals("a") || letter.equals("e") || letter.equals("i") || letter.equals("o") || letter.equals("u")){ count++; } System.out.print(count);

For loop condition to traverse through an ArrayList arr backwards

int i = arr.size()-1; i>=0; i--;

Write an algorithm using a while loop to sum the digits in number, 5384.

int number = 5384 int sum = 0; while (number > 0){ sum += number%10; number /= 10; }

Create a random number from 4 to 10 (inclusively) and if the number is less than 7, print "rip"

int randValue = (int)(Math.random() * 7 + 4); if (randValue < 7) System.out.print("rip");

How do you round positive doubles to next integer?

int roundedNum = (int) (num1/num2 + 0.5)

How do you round negative doubles to next integer?

int roundedNum = (int) (num1/num2 - 0.5)

How do you initialize an array?

int[] array = {3,4,6}; int[] array = new int[10];

Overloading

more that 1 constructor with different parameters

Can static methods access/change instance variables?

no

No-argument constructor

no parameters, sets instance variables for object to default values

If no constructor is written, what will Java set String instance variables and Objects equal to?

null

How do you check if an object is null?

object==null

What is the result of this code? int num = 3.5; System.out.print(num);

possible lossy conversion from double to int error

What is the result of this code? int randNum = Math.random(); System.out.print(randNum);

possible lossy conversion from double to int error

short circuit evaluation

process in which the computer evaluates a logical expression from left to right and stops as soon as the value of the expression is known.

Make a default constructor for the Snack class Each snack has a name and numCalories

public Snack () { name = ""; numCalories = 0; }

What is wrong with this constructor? public class Sport { private String name; private int numAthlete; public Sport (String name){ this.name = name; } }

public Sport (String name){ this.name = name; numAthlete = 0; }

What is the equals method header?

public boolean equals(Object obj)

What is the format of a class?

public class Name (First letter capitalized)

Write a program that computes the sum from the integers a to b. The method you want to write is public int sumFrom(int a, int b) For example, sumFrom(1, 10) returns 55 since the sum from 1 to 10 inclusive is 55

public int sumFrom(int a, int b) { int sum = 0; for (int i = a; i <= b; i++){ sum+=i; } return sum; }

Write code to duplicate the elemenets of ArrayList given method header: public static ArrayList<Integer> display(ArrayList<Integer> myList, int n)

public static ArrayList<Integer> display(ArrayList<Integer> myList, int n){ ArrayList<Integer> temp = new ArrayList<Integer>(); for (int i = 0; i < n; i++){ for (Integer value : myList){ temp.add(value); } } }

Write a linear search algorithm for method header below public static int linearSearch(int[] array, int key)

public static int linearSearch(int[] array, int key) { for(int i = 0; i < array.length; i++) { int element = array[i]; if(element == key) { return i; } } return -1; }

selection sort algorithm (code)

public static int[] selectionSort(int[] arr) { int numSwaps = 0; int currentMinIndex; for (int i = 0; i < arr.length - 1; i++) { currentMinIndex = i; for (int j = i + 1; j < arr.length; j++) { if(arr[j] < arr[currentMinIndex]) { currentMinIndex = j; } } // swap numbers if needed if (i != currentMinIndex) { int temp = arr[currentMinIndex]; arr[currentMinIndex] = arr[i]; arr[i] = temp; // swap occurs here^ numSwaps++; } } // Print out the number of swaps that took place here // before returning arr System.out.println(numSwaps); return arr; }

Write code to swap the consecutive elements in the method public static void swapConsecutive which takes in an ArrayList<Double> named myList as a parameter.

public static void swapConsecutive (ArrayList<Double> myList){ for (int i = 0; i < myList.size()-1; i+=2){ double temp = myList.get(i); myList.set(i, myList.get(i+1)); } }

Write the mutator method for String name.

public void setName(String n){ name = n; }

What does Math.random() do?

returns double of number greater than or equal to 0.0 and less than 1.0

What variables can static methods access?

static not instance variables

How do you access the last character of a string?

str.substring(str.length()-1, str.length())

Autoboxing

the automatic conversion between a primitive value and a corresponding wrapper object (int to Integer, double to Double)

Initialize a variable

to assign a starting value to a variable

true||false&&false==true&&false!=true

true

Syntax Error

will not compile or error

!(x > 0) equals what?

x<=0

!(x<=0)

x>0

What is !(x<-5 || x>10) ?

x>=-5 && x<=10


Conjuntos de estudio relacionados

TestBank 6 (evolution of the brain)

View Set

Layers of the Earth Based on Physical Properties

View Set

Chapter 3: Investigating Identity and Access Management

View Set

Chpt 30 Assessment of the Cardiovascular system Study guide

View Set

Chapter 55: Management of Patients With Urinary Disorders

View Set