Array and ArrayLists Review, OOP Test, Arrays review, Java Methods test, Compsci java test

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

When run, which of the following yields the integer 5?

int[] anotherArray = {5, 10, 15, 20, 25};System.out.println(anotherArray[(anotherArray.length - 2)] - 15);

How do you create an array of 5 ints?

int[] arr = new int[5];

What are the two main categories of numeric data types as stored in computers?

integer and floating point

What package contains the Scanner class?

java.util

What does this method call return? public int tripleInt(int x) { return x * 3; } tripleInt(4);

12

What is the return value of this method call? public static String findTheMiddle(int number) { String stringNum = "" + number; int mid = stringNum.length()/2; if(stringNum.length() % 2 == 1) { return stringNum.substring(mid,mid+1); } else { return stringNum.substring(mid-1,mid+1); } } findTheMiddle(2110890125)

89

What is an instance method?

An instance method is a piece of code called on a specific instance of the class. It is called with a receiver object.

What is an object in Java?

An object is something that contains both state and behavior.

What data structure might you use to store a list of Shoppers in a grocery line, where the number of people in line changes?

ArrayList

How do you create an ArrayList of Strings?

ArrayList list = new ArrayList();

Which of these is a key difference between arrays and ArrayLists?

Arrays are fixed size but ArrayLists can change in size.

What does it mean to be a client of a class?

Being a client of a class means that we can use its methods and functionality without necessarily understanding how it works.

Does the following code snippet have a run time error, compile time error, both, or neither? int x = 3 int y = 4; int sum = x + y;

Compile time error

True or False: You can modify the elements of an array when you traverse it with a for-each loop.

False

Mark the valid way to create an instance of Foo given the following code: public class Foo { int bar; String stoo; public Foo() { this.bar = 0; this.stoo = ""; } public Foo(int bar) { this.bar = bar; stoo = "You."; } }

Foo fee; fee = new Foo();

Consider the following code segment: String str = "I am"; str += 10 + 3; String age = "years old"; System.out.println(str + age); What is printed as a result of executing the code segment?

I am13years old

Given the following definition for the class Athlete: public class Athlete { String first_name; String last_name; int jersey; public Athlete(String first_name, String last_name) { this.first_name = first_name; this.last_name = last_name; this.jersey = 0; } public Athlete(String first_name, String last_name, int jersey) { this.first_name = first_name; this.last_name = last_name; this.jersey = jersey; } }

I and III

Consider the following method that processes an array to find the smallest value in the array. The array has a nonzero length and is initialized with int values. // arr is the array to be processed public static int findMin (int[] arr) { int min = /* some value */; int index = 0; while (index < arr.length) { if (arr[index] < min) min = arr[index]; index++; } return min; } Which replacement(s) for /* some value */ will always result in correct execution of findMin?I. Integer.MAX_VALUE II. Integer.MIN_VALUE III. arr[0]

I and III only

Which of the following are valid arrays? I. int[] coolArray = {1, 2, 3}; II. int[] threeThings = {1.0, 2.0, 3.0}; III. int[] = {"1", "2", "3"};

I only

Which of the following will execute without throwing an exception error?

all of these

Why do we use methods in Java programming?

all of these

Given an instance of the Athlete class called athlete, what is the proper way to get the value of the jersey number? public class Athlete { private String first_name; private String last_name; private int jersey; public int getJersey() { return this.jersey; } public Athlete(String first_name, String last_name, int jersey) { this.first_name = first_name; this.last_name = last_name; this.jersey = jersey; } }

athlete.getJersey()

What is the output of the following program? public class Main { private String str = "bar"; public void run() { Main m = new Main("foo"); System.out.println(m.getString()); } public Main(String str) { str = str; } public String getString() { return str; } }

bar

What is the output of the following code snippet? int[] scores = {80, 92, 91, 68, 88}; for(int score : scores) { System.out.println(score); }

c. 80 92 91 68 88

What will the following code print? ArrayList<String> list = new ArrayList<String>(); list.add("I"); list.add("love"); list.add("coding"); list.add("in"); list.add("Java"); list.remove(3); System.out.println(list.get(3));

d. Java

What will this method call output? public boolean someMethod(int number) { if(number % 2 == 1) { return true; } else { return false; } } someMethod(9990)

false

The return type of an mutator method

is usually void

What is the value of result1 after this code runs? int value1 = 10;int value2 = 4;double result1 = value1 / value2;

2.0

Which Java Data Type would be best suited to represent the amount of money in Barack Obama's bank account.

double

What will this code segment output? System.out.println("Hello");System.out.println("World");

hello world

Which of the following are valid arrays? I. int[] coolArray = {1, 2, 3};II. int[] threeThings = {1.0, 2.0, 3.0};III. int[] = {"1", "2", "3"};

I only

Static methods can access

Only other static instance variables and class methods

Which of the following is true?

Primitives are returned by value. Objects are returned by reference.

Which of the below is a logical operator?

!

The following method public String removeFromString(String old, String frag) removes all occurrences of the string frag from the string old. For example, removeFromString("hello there!", "he") returns "llo tre!" removeFromString("lalalala", "l") returns "aaaa" Which of the following blocks of code will successfully implement removeFromString()?

! . private String removeFromString(String old, String frag) { int index = old.indexOf(frag); for (int i = 0; i < old.length(); i++) { if (index > -1) { String rest = old.substring(index + 1 + frag.length()); old = old.substring(0, index + 1); index = old.indexOf(frag); } } return old; }

Consider the following method that processes an array to find the smallest value in the array. The array has a nonzero length and is initialized with int values. // arr is the array to be processed public static int findMin (int[] arr){ int min = /* some value */; int index = 0; while (index < arr.length) { if (arr[index] < min) { min = arr[index]; } index++; } return min;} Which replacement(s) for /* some value */ will always result in correct execution of findMin?

! II only ! III only II and III only

What will this method call output? public int checkMethod(boolean x, boolean y) { if(!x) { if(y) { return -1; } else { return 1; } } else { return 0; } } checkMethod(false, true)

-1

The following method public String removeFromString(String old, String frag) removes all occurrences of the string frag from the string old. For example, removeFromString("hello there!", "he") returns "llo tre!" removeFromString("lalalala", "l") returns "aaaa" Which of the following blocks of code will successfully implement removeFromString()?

!! private String removeFromString(String old, String frag) { int index = old.indexOf(frag); for (int i = 0; i < old.length(); i++) { if (index > -1) { String rest = old.substring(index + frag.length()); old = old.substring(0, index + 1); index = old.indexOf(frag); } } return old; } private String removeFromString(String old, String frag) { int index = old.indexOf(frag); for (int i = 0; i < old.length(); i++) { if (index > -1) { String rest = old.substring(index + 1 + frag.length()); old = old.substring(0, index + 1); index = old.indexOf(frag); } } return old; }

What is wrong with the following code? ArrayList<int> list = new ArrayList<int>(); list.add(1); System.out.println(list.get(0)); Selected:a. It will throw an IndexOutOfBoundsExcept

!!It will throw an IndexOutOfBoundsException. Nothing. The above code is correct . You need to define the new ArrayList on a new line of code.

What is the output of the following code snippet?String forest = "Amazon Rainforest";System.out.println(forest.indexOf('a'));System.out.println(forest.indexOf('g'));System.out.println(forest.indexOf('n'));

!0-15

What is the output from calling Main.bar(); ? public class Main { private static int n = 0; public static void bar() { Main m1 = new Main(); Main m2 = new Main(); Main m3 = new Main(); m1.foo(); } public Main() { n = n + 1; } public void foo() { System.out.println(n); } }

!1 2

What would be printed by the following code snippet?String lastName = "Vu";String otherLastName = "Lopez";int comparison = lastName.compareTo(otherLastName);System.out.println(comparison);

!A negative number because "Vu" comes after "Lopez" in lexicographical order. A positive number because "Vu" comes before "Lopez" in lexicographical order.

What is the scope of private methods and private instance variables?

!Any class using an object of the declaring class What is the scope of private methods and private instance variables?

Where must a static variable be initialized?

!Outside of the class.

What is the difference between instance variables and static variables? Selected:

!Static variables can be public or private, but instance variables must be private

Which of the following is NOT a proper use of the keyword this?

!as an argument to other methods in the class

The following code is intended to shift all elements to the right by one space and wrap the last element around to the first element. 1: public void shiftRight(int[] arr)2: {3: int lastNum = arr[arr.length - 1];4: 5: for (int i = arr.length - 1; i > 0; i--)6: {7: arr[i] = arr[i - 1];8: }9: arr[0] = lastNum;10: } Which statement is true?

!b. The code will not work as intended. Line 7 should be changed to arr[i-1] = arr[i]; !. The code will not work as intended. Line 5 should be changed to for (int i = 0; i < arr.length; i++) ! The code will not work as intended. Line 5 should be changed to for (int i = arr.length; i > 0; i--)

Question 8 Which of the following is a correctly written method for the class below?public class Timer{ private int startMin; private int length; public Timer(int minute, int duration) { startMin = minute; length = duration; } public Timer(int duration) { startMin = 0; length = duration; }}

!c. public void addFiveMinutes{length = length + 5;}

Which expression is true?

!false || !true

Which of the following correctly uses the this keyword

!public boolean isSame(Bird other) { return this.name.equals(this.other.name); }

Write a method that loops forever until the user inputs the correct secret password or until the user fails to enter the correct password 10 times. The secret password the program should look for is the String "secret" Use readLine(String prompt) for user input

!public void secretPassword() { int count = 0; while(true) { if(count == 10) { System.out.println("You are locked out!"); } if(readLine("Password?").equals("secret")) { System.out.println("Welcome!"); } count++; } }

Consider the follow class:public class Rectangle{ private int width; private int height; public Rectangle(int rectWidth, int rectHeight) { width = rectWidth; height = rectHeight; } public int getArea() { return width * height; } public int getHeight() { return height; } public int getWidth() { return width; } public String toString() { return "Rectangle with width: " + width + " and height: " + height; }} If a new variable Rectangle shape = new Rectangle(10, 20); was initialized, what is the correct syntax for retrieving the area of shape?

!shape.getArea();v

Why can't this be used in static methods?

!this must be initialized in the constructor. Since static methods can be called before calling the constructor, this was never initialized.

If you do not implement a constructor for your class,

!you cannot create objects of that class type

What is the difference between the "==" and "=" operators

"==" tests for equality, "=" is an assignment

The purpose of a wrapper class is to

"Wrap" a primitive value to convert it to an object

What will this method call output? public String yesOrNo(boolean myBoolean) { if(myBoolean == true) { return "Yes"; } else { return "No"; } } yesOrNo(true)

"Yes"

What is returned by this method call: translator("pokemon")? public String translator(String word) { return word.substring(1) + word.charAt(0) + "ay"; }

"okemonpay"

What will this method call output? public String yesOrNo(boolean myBoolean) { if(myBoolean == true) { return "Yes"; } else { return "No"; } } yesOrNo(true)

"yes"

What will this method call print? public void patternGrid(int rows, int columns, char symbol) { for(int m = 0; m < rows; m++) { for(int n = 0; n < columns; n++) { System.out.print(symbol); } System.out.println(); } } patternGrid(3,4,'#');

#### #### ####

What will the code segment output? for (int m = 5; m > 0; m--){ for(int n = m; n > 0; n--) { System.out.print("*"); } System.out.pri

***** **** *** ** *

What will the following code snippet output? int[ ] values = {17, 34, 56, 2, 19, 100}; for (int value : values) { if (value % 2 == 0) System.out.println(value + " is even"); }

. 34 is even56 is even2 is even100 is even

What in this code segment could potentially cause a bug in our program? Scanner keyScan = new Scanner(System.in);System.out.println("What is your name?");String myString = keyScan.nextLine(); if (myString == "Karel") { System.out.println("Hi Karel!"); } else { System.out.println("You're not Karel!"); }

. Comparing Strings with == instead of the .equals method.

int[] numbers = {1, 2, 3, 4};for (int i = 0; i < numbers.length; i++){ numbers[i] += 5;} II. int[] numbers = {1, 2, 3, 4};for (int number : numbers){ number += 5;}

. I will correctly add 5 to the numbers array. II will not correctly add 5 to the numbers array.

Suppose we have the following method in our class: public int sum(int one, int two) Which of the following are valid methods to also have in the class?I: double sum(double one, double two) II: int sum(int one, int two, int three) III: int sum(int x, int y) IV: double sum(int one, double two)

. I, II, and IV

Given the code snippet, public class Pokemon { private String name; private int health; public Pokemon(String name, int health) { name = name; health = health; } }

. Must use this in constructor when the constructor parameters have the same name as instance variables. ie: this.name = name; this.health = health;

What are parameters?

. The formal names given to the data that gets passed into a method.

Given the array: String[] fruit = {"Apple", "Pear", "Pineapple", "Carrot", "Banana", "Lettuce"}; Which code will correctly replace Carrot and Lettuce in the array?

. fruit[3] = "Grape";fruit[5] = "Blueberry";

Which of the following expressions are valid?

. if (6 + 3 > 5)

How do you create an array of 5 ints?

. int[] arr = new int[5];

Classes' access specifier is generally set to

. public so that any user can create and use objects of the class.

After the following statement, what value is stored in the myInteger variable? int myInteger;

0

What will be the output of the following for() loop: for (int i=0; i<10; i+=3){ System.out.print(i * 3 + " ");}

0 9 18 27

Consider the following three string variables: String myString1 = "not so loud!"; String myString2 = "NOT SO LOUD!"; String myString3 = "No thanks"; What are the minimum and maximum valid character index values in myString3?

0 and 8

How many times will the following while() loop execute? boolean done = true; while (!done) { done = false; }

0 times

How many "else if ()" clauses can you have after an if() expression?

0, 1, or more

What does this method call output? public int someMethod(int x, int y) { int sum = 0; while (x < 10) { sum += x % y; x++; y++; } return sum; } someMethod(3,1)

10

What is the result of the following mathematical expression? 2 * ( (6 + 4) / 2)

10

What is the output of this for loop? for(int i = 10; i > 2; i -= 3){ System.out.println(i);}

10 7 4

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

11

Using the rules of operator precedence, what is the result of the following equation? int result = 2 + 4 / 1 * 3 - 1;

13

What does this method call output? public double doubleNumber(double myNumber) { return (double) (int) myNumber * 2; } doubleNumber(7.8);

14.0

What is the output after this code snippet runs? int[] scores = {80, 92, 91, 68, 88}; int i = 0; while (i < scores.length - 1) { System.out.println(scores[i] * 2); i ++; }

160 184 182 136

What will be stored in the variable age after this code snippet executes?public static void main(String[] args){ int age = 16; age++; age--; age++;}

17

int mysteryNumber = 0;String[] mysteryArray = {"Finn", "Jake", "Bubblegum"};for(int i = 0; i < mysteryArray.length; i++){ mysteryNumber += mysteryArray[i].length();}

17

What will this method call print to the screen? public static void formatText(int a, int b, String c) { System.out.println(b + " " + c + ", " + a); } formatText(2018, 17, "Dec")

17 Dec, 2018

public double doubleOrNothing(double myDouble) { return (double) (int) myDouble * 2; } doubleOrNothing(9.9);

18.0

int[] arr = {1, 2, 3, 4, 5};int[] copy = arr;copy[4] = 2; After this code, what is the value of arr[4]?

2

Consider the Circle class below.public class Circle{ private double radius; public Circle(double circleRadius) { radius = circleRadius; } public void setRadius(double newRadius) { radius = newRadius; } public void printDiameter() { double diameter = 2 * radius; System.out.println(diameter); } } What is the output of the main method below?public class MyProgram{ public static void main(String[] args) { Circle pizza = new Circle(12); pizza.printDiameter(); pizza.setRadius(10); pizza.printDiameter(); }}

24.0 20.0

String[] grades = {"A","C","B","A","B", "A"}; int mystery = 0; for (int i = 0; i < grades.length; i++) { if (grades[i].equals("A")) { mystery ++; } } System.out.println(mystery);

3

What will be the output of the following code snippet?public class Calculator{ public static void main(String[] args) { int first = 7; int second = 2; int result = first / second; System.out.println(result);

3

What will this method call output? public int myMethod(String x, char y) { int z = 1; for(int i = 0; i < x.length(); i++) { if(x.charAt(i) == y) { z++; } } return z; } myMethod("Karel The Dog", 'e');

3

What will this method call print to the screen? public void funWithNumbers(double myDouble) { int myInt = (int) myDouble; String myString = ""; while(myInt != 0) { myString = myInt % 10 + myString; myInt /= 10; } System.out.println(myString); } funWithNumbers(314159)

314159

public void funWithNumbers(double myDouble) { int myInt = (int) myDouble; String myString = ""; while(myInt != 0) { myString = myInt % 10 + myString; myInt /= 10; } System.out.println(myString); }

314159

What would this method call output? public int divideByTen(int num) { while(num / 10 >= 10) { num /= 10; } return num; }

34

What would this method call output? public int divideByTen(int num) { while(num / 10 >= 10) { num /= 10; } return num; } divideByTen(340)

34

What will the following code snippet output? int[ ] values = {17, 34, 56, 2, 19, 100}; for (int value : values) { if (value % 2 == 0) System.out.println(value + " is even"); }

34 is even56 is even2 is even100 is even

Given the code below, what is the value stored in result? String myString = "quiz";int result = myString.length();

4

What is the value of x after this code? int x = 5;x = 10;x = 4;

4

What is the value of x after this code? int x = 5;x *= 10;x -= 4;

46

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

5

Refer to this code snippet. public class Main { private static int n = 0; public static void bar() { Main m1 = new Main(); Main m2 = new Main(); Main m3 = new Main(); m1.foo(); } public Main() { n = n + 1; } public void foo() { System.out.println(n); } } Suppose the following method is added: public void setN(int newValue) { n = newValue; } What would be the output of the program if bar() were changed to the following: public static void bar() { Main m1 = new Main(); Main m2 = new Main(); Main m3 = new Main(); m1.setN(5); m3.foo();

5

What is the value of myInteger after this line of code? int myInteger = (int) 5.6;

5

What does the following code snippet output? int[] numbers = {1, 2, 3, 4, 5}; int[] temp = new int[numbers.length]; for (int i = 0; i < numbers.length - 1; i++) { temp[i + 1] = numbers[i]; } temp[0] = numbers[numbers.length - 1]; numbers = temp; for (int i = 0; i < numbers.length; i++) { System.out.print(numbers[i] + " "); }

5 1 2 3 4

What is the result of this expression? 150 % 100

50

What is the output of the following code? for (int i = 5; i <10; i = i + 2){ System.out.print(i);}

579

What is the result of this expression? 5 + 2 / 3 + 1

6

What will the following code print? ArrayList<Integer> list = new ArrayList<Integer>(); list.add(0); list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); int sum = 0; for (int i = 0; i < list.size(); i+= 2) { sum += list.get(i); } System.out.println(sum);

6

What is the value of x after this code? int x = 5;x += 10;x *= 4;

60

What will this while loop do? while(true){ System.out.println("Hello");}

Print Hello in an infinite loop

What will be the output of the following code snippet? int[] scores = {80, 92, 91, 68, 88}; int myIndex = 0; for (int i = 1; i < scores.length; i++) { if (scores[i] < scores[myIndex]) { myIndex = i; } } System.out.println(scores[myIndex]);

68

int[] scores = {80, 92, 91, 68, 88}; for(int score : scores) { System.out.println(score); }

80 92 91 68 88

public static String someWhereInTheMiddle(int number) { String stringNum = "" + number; int middle = stringNum.length()/2; if(stringNum.length() % 2 == 1) { return stringNum.substring(middle,middle+1); } else { return stringNum.substring(middle-1,middle+1); } } someWhereInTheMiddle(188603)

86

Which of these is not a valid Java method name?

8ball find tower

After the following code is run: double num1 = 9.6; int num2 = (int)num1; What is the value in num2?

9

What is the value of x after this code? int x = 5;x = 10;x--;

9

Which of the following is NOT a comparison operator?

?

Which of these is not true about primitives and objects?

A primitive has data and methods associated with it while an object only stores data

A procedure that is defined by the user is called a

A procedure that is defined by the user is called a

What is a String type in Java?

A sequence of characters

Mark the valid way to create an instance of Athlete given the following Athlete class definition: public class Athlete { String first_name; String last_name; int jersey; public Athlete(String first_name, String last_name, int jersey) { this.first_name = first_name; this.last_name = last_name; this.jersey = jersey; } }

Athlete athlete = new Athlete("Dirk", "Nowitzki", 41);

What is casting in Java?

Casting is turning a value of one type into another type.

The following logical expression illustrates what concept? !( A || B) = !A && !B

Demorgan's laws

What does the following code snippet check for? int[] numbers = {1, 2, 3, 3, 4, 5}; boolean mysteryBoolean = false; for (int i = 0; i < numbers.length - 1; i++) { for (int j = i + 1; j < numbers.length; j++) { if (numbers[i] == numbers[j]) { mysteryBoolean = true; } } }

Finds duplicate values in an array

Which of the following will initialize a boolean array of three elements all containing true? I. boolean[] arr = {true, true, true}; II. boolean[] arr = new boolean[3]; III. boolean[] arr = new boolean[3];for (int i = 0; i < arr.length; i ++){ arr[i] = true;}

I and III

Which of these characters can a Java method name start with? (I) Letters (II) Numbers (III) Underscore (IV) $ Sign

I, III, IV

Class members that should be public are I. Constructors II. Instance Variables III. Accessors/Mutators IV. Methods the class uses for itself, but the user does not need V. Methods the user needs to manipulate the objects of the class

I, III, V

Why do we use methods in Java? I. To make code easier to understandII. To define global variablesIII. To avoid repeated codeIV. To simplify codeV. To avoid needing to define them as public or private

I, III, and IV

When would you use a for-each loop instead of a for loop? Selected:

If you want to access every element of an array and want to refer to elements through a variable name instead of an array index.

Which exception will be thrown as a result of running this code snippet? String hello = "hello"; char last = hello.charAt(10);

IndexOutOfBoundsException

What does the following code do when executed? int[] highTemp = {88, 92, 94, 90, 88, 83};int target = 90;int count = 0; for (int temp : highTemp){ if (highTemp >= target) { count ++; }}System.out.println(count);

It will count the number of times the value in the highTemp array exceeds the target value.

The following method is intended to return true if the array element value contains the same number in consecutive array elements. 1: public boolean consecutiveNumbers(int[] nums)2: {3: int i = 1; 4: while (i < nums.length)5: {6: if (nums[i] == nums[i+1]){7: return true; }8: i++;9: } 10: return false;11: } Which of the following are needed to correct the code? I. Change line 3 to: int i = 0;II. Change line 4 to: while (i < nums.length - 1)III. Swap lines 7 and 10

Make both I and II changes

Which of these is an example of calling a static method?

Math.abs(x)

which of the following variable names is invalid

MyScore

Given this code snippet, public class Athlete { public Athlete(String name) { this.name = name; } } what is missing from the class definition?

Need to declare the name instance variable

Will this method correctly traverse an ArrayList and remove all multiples of 3? public void remove3s(ArrayList<Integer> array){ int counter = 0; while(counter < array.size()) { if(array.get(counter) %3 == 0) { array.remove(counter); counter++; } else { counter++; } }}

No, this method is not written correctly, as the counter in the if statement will skip the next value, as the values will shift down in the ArrayList.

Which of the following arrays has a length of 5?

None of these

What is wrong with this method definition? public int printPayAmount(int amount) { System.out.println(amount); }

Nothing is returned from this method

Consider the following three string variables: String myString1 = "not so loud!"; String myString2 = "NOT SO LOUD!"; String myString3 = "No thanks"; What is returned by the expression myString2.substring(1)

OT SO LOUD!

What is the difference between a class and an object?

Objects are instances of classes. The class is the general template, and the object is the specific version.

Strings are immutable. This means that

Once a String variable has been assigned a value, the value cannot be modified but the variable can be assigned to a different value.

What kind of error does this method cause? public void myMethod(String x) { for(int i = 0; i <= x.length(); i++) { System.out.println(x.substring(i, i+1)); } } myMethod("Frog");

Runtime Error: String index out of range

Which statement below successfully initializes a new Scanner object to receive input from the console?

Scanner input = new Scanner(System.in)

What is the correct syntax for creating a Scanner object?

Scanner objectName = new Scanner(System.in)

Which of the following describes the difference between static methods and instance methods?

Static methods can be called without using an object while instance methods need to be called on an object

Which object is used to write output to the console?

System.out

The following code is designed to return true if a target value is present in an array of integers. public boolean search(int[] arr, int target){ for (int number : arr) { if (number != target) { return false; } } return true;} Which of the following statements is true?

The code will not work correctly because the method may return false too soon..

Which of the following statements is valid? Assume that variable arr is an array of i integers and that the following is true: arr[0] != arr[i] for all values from 1 through i - 1

The element arr[0] does not occur anywhere else in the array

Which of the following is NOT a characteristic of a mutator?

The method returns the value of an instance variable

What is the difference between a getter method and an accessor method?

There is no difference. They refer to the same idea

ArrayList<String> list = new ArrayList<String>(); list.add("Hello"); list.add("World"); System.out.println(list[0]);

There will be a compiler error

int sum = 1;System.out.println("Welcome to the adding machine!");while(sum < 10){ sum += sum; System.out.println(sum);}

Welcome to the adding machine! 2 4 8 16

Which of the following is NOT part of the constructor signature?

Which instance variables are initialized

What is the name of the Power object contained in the ImaginaryFriend class after the following code snippet runs? The object friend is an ImaginaryFriend object. One instance variable of friend is a Power object. The method getPower is the Power object's accessor. Power ability = friend.getPower(); ability.setName("X-Ray Vision");

X-Ray Vision

Given an instance of the Athlete class called athlete, what is the proper way to set the value of the jersey number after it has been instantiated? public class Athlete { private String first_name; private String last_name; private int jersey; public int getJersey() { return this.jersey; } public Athlete(String first_name, String last_name, int jersey) { this.first_name = first_name; this.last_name = last_name; this.jersey = jersey; } }

You cannot set the jersey, since jersey is private and there is no setter method.

If the user enters data "awesome" when you prompt for a number, what will happen when you call nextInt() to read the data?

Your program will get an InputMismatchException

What will be the output of the following code snippet and why?public static void main(String[] args){ int num = 2; int dividend = 5; dividend /= num; System.out.println(dividend);

d. The output will be 2 because when two integers are divided in Java, the decimal portion is always truncated.

What will the Array gameBoard contain after this code runs? int WIDTH = 3;int HEIGHT = 3;String[] gameBoard = new String[WIDTH * HEIGHT];for(int m = 0; m < HEIGHT; m++){ for(int n = 0; n < WIDTH; n++) { int someNumber = m * WIDTH + n; if(someNumber % 3 == 0) { gameBoard[someNumber] = "X"; } else { gameBoard[someNumber] = "O"; } }}

["X", "O", "O", "X", "O", "O", "X", "O", "O"]

Which of the below is NOT a Java arithmetic operator?

^ # &

When using an if() statement, what must go within the parentheses?

a logical expression

When would you use a for-each loop instead of a for loop?

a. If you want to access every element of an array and want to refer to elements through a variable name instead of an array index.

What kind of error does this method cause? public void buggyMethod(String x) { for(int i = 0; i <= x.length(); i++) { System.out.println(x.substring(i, i+1)); } } buggyMethod("BUG");

a. Runtime Error: String index out of range

How would you declare and initialize a String variable called "first" that contains "I'm alive!"?

a. String first = "I'm alive!"

What is the name of the method to print out text in Java?

a. System.out.println()

Why do we use for loops in Java?

a. To repeat something for a fixed number of times

What is wrong with this if() statement if "a" and "b" are both ints? if (a = b)

a. You cannot use an assignment statement as a logical expression

Refer to the following code segment: double myDouble = 1/4;System.out.println("1 / 4 = " + myDouble); The output of the code is: 1 / 4 = 0.0 The student wanted the output to be: 1 / 4 = 0.25 Which change to the first line of their code segment would get the student the answer that they wanted?

a. double myDouble = (double) 1/4;

Which for loop will properly print "hello" 10 times?

a. for(int i = 0; i < 10; i++){System.out.println("hello");}

A void method

a. returns no value.

Which of the following is a valid logical expression (assuming "a" and "b" are ints)?

all are valid logical expressions

Which code snippet below will end with num holding the value 15?

all of these

Which of the following update expressions is valid to replace the ??? phrase within the for() loop below?

all of these are valid

What is a boolean in Java?

b. A true or false value

Which of the following for() loops will execute 10 times?

b. All of these will execute 10 times

int[] scores = {80, 92, 91, 68, 88}; for(int i = 0; i < scores.length; i--) { System.out.println(scores[i]); }

b. ArrayIndexOutOfBoundsException

What is the output of this for loop? for(int i = 0; i < 100; i += 2){ System.out.println(i);}

b. The even numbers from 0 to 98, inclusive

Which statement correctly assigns the character value 'x' to the char variable myChar?

b. char myChar = 'x';

Consider the following code snippet. What would the output be? String school = "Rydell High School"; System.out.println(school.substring(8)); System.out.println(school);

b. igh School Rydell High School

Which of the following ways to declare and initialize a for() loop index is valid? a. int index;for (index=0;

both of these are valid

What will this program print if the value of grade is 80? if(grade > 90){ System.out.println("A");}else if(grade > 80){ System.out.println("B");}else if(grade > 70){ System.out.println("C");}

c

What will be returned from the Scanner nextLine() function if the user types the following phrase into the console, followed by the Enter key:

c. A string containing "the quick brown fox jumped over the lazy dog"

What might you want to do before calling one of the Scanner input methods?

c. Print a message to the console so the user knows what to do

What is the output of the following lines? int x = 24;System.out.println("The total is " + x + x);

c. The total is 2424

Given the following array: String[] languages = {"Java", "JavaScript", "Python", "C++"}; Which of the following will produce an ArrayIndexOutOfBoundsException?

c. for (int i = 0; i < languages.length; i++){System.out.println(languages[i-1]);}

Which of the following loops will NOT print every element in an integer array?

c. for (int i = 1; i < array.length; i++){System.out.println(array[i-1]);}

What does void mean?

d. Void means that a method returns no value.

The value that a method outputs is called

d. a return value

Which of the following arrays has a length of 5?

e. None of these

What keyword can be used to execute a block of logic when the tested "if" expression returns false?

else

public class SayHello{ public void run() { String stringArray[] = {"h", "e", "l", "l", "o", "w"}; for(int i=0; i <= stringArray.length; i++) { System.out.print(stringArray[i]); } }}

error

Given the following Circle class public class Circle { private int radius; public Circle(int theRadius) { radius = theRadius; } public void setRadius(int newRadius) { radius = newRadius; } public boolean equals(Circle other) { return radius == other.radius; } } What is the output of the following code snippet? Circle one = new Circle(10); Circle two = new Circle(10); System.out.println(one == two);

false

Given the following code, what is the result of calling myString1.equalsIgnoreCase(myString2)? String myString1 = "a b c d";String myString2 = "ABCD";

false

What will this method call output? public boolean someMethod(int number) { if(number % 2 == 1) { return true; } else { return false; } }

false

public boolean someMethod(int number) { if(number % 2 == 1) { return true; } else { return false; } } someMethod(9990)

false

What keyword do you use to ensure a variable can never change values while your program is running?

final

Which methods of class Foo can be called without an actual instance of the class Foo? public class Foo { public static void foo() { ... }; public void bar() { ... }; public void baz() { ... }; }

foo()

Given the following while loop, which would be the equivalent for loop? int i = 0;while (i < 20){ System.out.print(i); i += 2;}

for (int i = 0; i < 20; i += 2){ System.out.print(i);}

Given the following code snippet int[ ] values = {150, 34, 320, 2, 11, 100}; for (int i=0; i < values.length; i++) { if (values[i] % 10 == 0) System.out.println(values[i] + " is divisible by 10"); } which for-each loop would produce the same output?

for (int value : values) { if (value % 10 == 0) System.out.println(value + " is divisible by 10"); }

Question 6 Given the following code snippet int[ ] values = {150, 34, 320, 2, 11, 100};for (int i=0; i < values.length; i++){ if (values[i] % 10 == 0) { System.out.println(values[i] + " is divisible by 10"); }} which for-each loop would produce the same output?

for (int value : values){ if (value % 10 == 0) System.out.println(value + " is divisible by 10");}

What does the myString variable contain after the following code sequence: String myString = "hello number "; // note the space at the end of the string myString = myString + myString.length();

hello number 13

What would be printed the first time printPhrases was called from main? public class PrintQuestion { private static String phrase = "Hello World!"; public static void printPhrases() { String phrase = "hi"; System.out.println(phrase); phrase = "hello"; } }

hi

The following function computes the hypotenuse of a right triangle. public double findHypotenuse(int side1, int side2){ double hyp = Math.sqrt(side1 * side1 + side2 * side2); return hyp; } The following code found in main throws an error. What is the bug? int side1 = 3; int side2 = 4; findHypotenuse(side1, side2); System.out.println(hyp);

hyp is a local variable. It can only be accessed in findHypotenuse.

Which of the following keywords can be used to test a condition and make decisions in your program?

if

Consider the following code snippet. What would the output be? String school = "Rydell High School"; System.out.println(school.substring(8)); System.out.println(school);

igh School Rydell High Schoo

What is wrong with the following while loop? int i = 0; while (i < 10) { System.out.println(i); }

infinite loop

An object's state is defined by the object's

instance variables and their values

You are working at the frozen yogurt shop in the mall. Your boss asks you to count how many flavors have the word chocolate in their name. You begin going through the list of flavors, but quickly realize that their are over 9000 flavors to check! Luckily, your boss stored all of the different flavors in a Java Array named flavorArray on the company computer. Write a Java program to count the number of flavors that have chocolate in their name.

int chocolateFlavorCount = 0;for(int i = 0; i < flavorArray.length; i++){ if(flavorArray[i].contains("chocolate")) { chocolateFlavorCount++; }}System.out.println(chocolateFlavorCount);

Which of the following is a proper way to declare and initialize a variable in Java?

int myNumber = 10;

Which of the following code snippet gets the THIRD element in the scores array and assigns it to an int called myScore , then sets the FOURTH element in the scores array (previously declared) to 72?

int myScore = scores[2]; scores[3] = 72;

Given this code snippet, public class Person { public String name; public Person(String name) { this.name = name; } public void changeName(String name) { this.name = name; } public void printName() { System.out.println(this.name); } } what will this code print? Person myPerson = new Person("Bob"); myPerson.changeName("Joe"); myPerson.name = "John"; myPerson.printName();

john

Suppose there is a class called Student. One of the methods is given below. It sets the instance variable isHonors to the parameter value.public void setHonorStatus(boolean status){ isHonors = status;} Using the Student object called karel, which of the following is the correct way to set karel's honor status to true?

karel.setHonorStatus(true);

Suppose the class Timer has a method called startTime that prints out the starting time of the Timer.Which of the following correctly uses this method to print out the start time of a Timer object called laundry?

laundry.startTime();

Consider a Dog class that has a default constructor. Suppose a list ArrayList<Dog> is initialized. Which of the following will not cause an IndexOutOfBoundsException to be thrown?

list.add(list.size(), new Dog());

A procedure that is defined by the user is called a

method

A void method

method that returns no value

The return type of an accessor method

must match the type of of the instance variable being accessed

String myString1 = "not so loud!"; String myString2 = "NOT SO LOUD!"; String myString3 = "No thanks"; Which expression will return true if the contents of myString1 are equal to the contents of myString2?

myString2.equals(myString1)

When will the following code print "you can drive" ? if (age >= 16){ System.out.println("you need a learner's permit");}else if (age >= 18){ System.out.println("you can drive");}

never

What Scanner function would you call to get a double (floating point) value from the user input?

nextDouble();

What Scanner function would you call to get a full line of user input?

nextLine();

Write a method that will ask for user input until user inputs the String "no". Allow the user to input any capitalization of the String "no" ("no", "No", "NO", "nO") Also, have the method return the number of loops. Use readLine to get the user input.

not b. public int loopTillNo() { int count = 0; while(!readLine("Again?").equals("no")) { count++; } return count; }

What will the value of yourBankAccount be after the method call? int yourBankAccount = 0; public void depositMoney(int bankAccount, int deposit) { bankAccount += deposit; } depositMoney(yourBankAccount, 1000000);

not: the code will error 1000000

What is the importance of the null value?

null allows a reference variable to be empty and not hold any memory address.

Which of the below is not a primitive type in Java?

num void string

Which of the following variable names follows best practices for naming a variable?

numApples

It is considered good practice to

only modify objects when the method postcondition has specified the modification

The following method public String removeFromString(String old, String frag) removes all occurrences of the string frag from the string old. For example, removeFromString("hello there!", "he") returns "llo tre!" removeFromString("lalalala", "l") returns "aaaa" Which of the following blocks of code will successfully implement removeFromString()?

private String removeFromString(String old, String frag) { int i = old.indexOf(frag); while (i > -1) { String rest = old.substring(i + frag.length()); old = old.substring(0, i); old = old + rest; i = old.indexOf(frag); } return old; }

The Glasses class represents a pair of eyeglasses. One of its instance variables is a Prescription object called script. The Prescription object has instance variables that stores the prescription for the left and right eye. Which of the following constructors for the Glasses class correctly sets the script instance variable correctly? Assume any method calls are valid.

public Glasses(Prescription thePrescription){ script = new Prescription(thePrescription.getLeft(),thePrescription.getRight());}

Write a method that will ask for user input until user inputs the String "no". Allow the user to input any capitalization of the String "no" ("no", "No", "NO", "nO") Also, have the method return the number of loops. Use readLine to get the user input

public int loopTillNo() { int count = 0; while(!readLine("Again?").toLowerCase().equals("no")) { count++; } return count; }

Each of the methods below can be found in the Rectangle class. Which of the following methods would have access to the parameter object's private data and methods?

public void copy(Rectangle other)

Which of these methods will properly traverse two ArrayLists and print any index that have the same value in both ArrayLists?

public void printSharedValues(ArrayList<Integer> array1, ArrayList<E> array2){ int index = 0; int size; if(array1.size() > array2.size()) { size = array2.size(); } else { size = array1.size(); } while(index < size) { if(array1.get(index) == array2.get(index)) { System.out.println(index); } index++; }}

Write a method that loops forever until the user inputs the correct secret password or until the user fails to enter the correct password 10 times. The secret password the program should look for is the String "secret" Use readLine(String prompt) for user input

public void secretPassword() { int count = 0; while(true) { if(count == 10) { System.out.println("You are locked out!"); return; } if(readLine("Password?").equals("secret")) { System.out.println("Welcome!"); return; } count++; } }

Given this Athlete class, which of the following setter methods for the jersey variable is correct? public class Athlete { private String first_name; private String last_name; private int jersey; public int getJersey() { return this.jersey; } public Athlete(String first_name, String last_name, int jersey) { this.first_name = first_name; this.last_name = last_name; this.jersey = jersey; } }

public void setJersey(int jersey) { this.jersey = jersey; }

public void update(String x, int y) { x = x + "Retriever"; y = y * 3; } public void myTest() { String s = "Golden"; int num = 7; update(s, num); /*end of method*/} When a call to myTest() is invoked, what are the values of s and num at the point indicated in by /*end of method*/?

s is the string "Golden"; num = 7

What will this code output? if(true && true && false){ System.out.println("Hello Karel");}if(true && 4 == 2 + 2){ System.out.println("Second if statement!");}

second if statement!

Consider the follow class: public class Rectangle { private int width; private int height; public Rectangle(int rectWidth, int rectHeight) { width = rectWidth; height = rectHeight; } public int getArea() { return width * height; } public int getHeight() { return height; } public int getWidth() { return width; } public String toString() { return "Rectangle with width: " + width + " and height: " + height; } }

shape.getArea();

/*** The Shark class describes a shark.** Every shark has a region where it lives and an age.**/public class Shark{ // Attributes private String habitat; private int age; public Shark(String region, int sharkAge) { habitat = region; age = sharkAge; }}Which of the following choices is a formal parameter of the constructor?

sharkAge

Refer to the Card and Deck classes shown below. public class Card { private String suit; private int value; //13 values for each suit in deck (0 to 12) public Card (String cardSuit, int cardValue) { /* implementation */} public String getSuit() {return suit;} public int getValue() {return value;} public String toString() { String faceValue = ""; if (value >= 2 && value <=10) {return value + " of " + suit;} if (value == 11) {faceValue = "Jack";} else if (value == 12) {faceValue = "Queen"; } else if (value == 0) {faceValue = "King"; } else if (value == 1) {faceValue = "Ace";} else {return faceValue + " of " + suit; } } } public class Deck { private Card[] deck; public final static int NUMCARDS = 52; public Deck() { /* implementation */} /** Shuffle deck. */ public void shuffle() { /* implementation */} //Other methods not shown. } Which of the following is the correct /* implementation */ code for the constructor in the Card class?

suit = cardSuit; value = cardValue;

Which variables are in scope at the point labeled // POINT A? In other words, which variables exist at that point in the code? public class ScopeQuiz extends ConsoleProgram { private int count = 0; public void run() { int sum = 0; // POINT A for(int i = 0; i < 10; i++) { sum += i; } int result = sum + count; } }

sum and count

Given the following while() loop, which statement is true assuming A,B,C,D are int variables and A > B? while ( ( A >= B) || ( (C - D) > 10)){ System.out.println(A + B + C + D);}

the program will never leave the loop body

String myString1 = "not so loud!"; String myString2 = "NOT SO LOUD!"; String myString3 = "No thanks"; Which expression will return true?

they all return true

Which of the following variable names is invalid? a. They are all invalid. b. 1place c. int d. SHOO FLY

they are all invalid

public static void main(String args[]){ final int z; z = 20; z = 30; System.out.println(z);}What value of z is actually printed?

this code gives an error

The purpose of an accessor method is

to return the value of an instance variable

The purpose of a mutator method is

to safely modify an instance variable

Given the code below, is it true that myString1.equals(myString2) and myString2.equals(myString1) will produce the same result?

true

Given the following Circle class public class Circle { private int radius; public Circle(int theRadius) { radius = theRadius; } public void setRadius(int newRadius) { radius = newRadius; } public boolean equals(Circle other) { return radius == other.radius; } } What is the output of the following code snippet? public void run() { Circle one = new Circle(5); Circle two = new Circle(10); foo(two); System.out.println(one.equals(two)); } public void foo(Circle x) { x.setRadius(5); }

true

Given the following code, what is the result of calling myString1.equals(myString2)?

true

Given the following code, what is the result of calling myString1.equalsIgnoreCase(myString2)? String myString1 = "abc";String myString2 = "ABC";

true

If "A" is true, short-circuiting would prevent the "B" expression from being evaluated in this overall expression:

true

If "a = 3" and "b = 5", what is the result of the following logical expression? (a > b) || (b == 5)

true

What does this Java expression evaluate to? true && !false

true

Given the code below, what is the value stored in result? String myString = "quiz";String result = myString.substring(1,4);

uiz

What will the values of x and y be after this code segment runs? int x = 100;int y = 100;if (x <= 100){ if (y > 100) { x = 200; } else { x = 99; }}else{ x++;}y = x + y;

x = 99 y = 199

What are the memory values associated with the variables x, y, and z after the code snippet below executes?int x = 7;double y = 2.0;boolean z = false;x = x + 3;z = true;

x holds the int value 10, y holds the double value 2.0 and z holds the boolean value true.

Which expression returns the 1's place of an integer x?

x%10

In the following line of code: boolean shortCircuit = true && (5 / 0 == 0); Will the 5 / 0 == 0 operation be evaluated?

yes

What happens if you call Scanner.nextInt() and the user has entered "abc"?

your program will throw an exception

Given the code below, what is the value stored in result? String myString = "quiz";char result = myString.charAt(3);

z

private int[ ] arr = {-17, -14, 3, 9, 21, 34}; public void mystery(){ for (int i = 0; i < arr.length / 2; i += 2) { arr[i] = arr[i] * 2; }}

{-34, -14, 6, 9, 21, 34}

What values will the array contain after the following the code is run? int[] someArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};for (int i = someArray.length - 2; i >= 0; i-=2){ someArray[i] = someArray[i] - 5;}

{1, -3, 3, -1, 5, 1, 7, 3, 9, 5, 11}

int[] someArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};for (int i = someArray.length - 2; i >= 0; i-=2){ someArray[i] = someArray[i] - 5;}

{1, -3, 3, -1, 5, 1, 7, 3, 9, 5, 11}


Ensembles d'études connexes

six trig functions for theta 30/45/60 degrees

View Set

Chapter 13 The Heart and Heart Disease

View Set

Unit Circle - Radians Sine and Cosine

View Set