CS180 Practice Questions

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

2.4 What is the output of the following code? String str = "Hello, world!"; str.replaceAll("l", "1"); System.out.println(str.substring(str.indexOf(",")));

", world!"

11. What is the output of the following code? String str = "Hello, world!"; str.replaceAll("l", "1"); System.out.println(str.substring(str.indexOf(",")));

", world!" Strings are immutable. You have to reassign the value back to the variable.

12.4 Given a canvas, the coordinate of the upper left is _?

(0, 0)

8. T is called a generic Element, Key, Type, Object

Type

Turkstra 6. What is displayed? Public class Quiz { Public static void main(String[] args) { Char z = 'A', char _ = 'a'; Double result = z / _; System.out.printf("%.2f", result); } }

0.00

5. What is the 2's complement of 23?

00010111 11101001

15. What is the output of the following code? Integer one = 5; Integer two = new Integer(5); if(one == two) System.out.printf("%010d", one + two); Else System.out.printf("%05d", one * two); 0000000010 00025 01010 0525 000010001

00025. If both were set using = 5, that would use the constant pool and be 0000000010.

5.2 What is the output of the following code? Double[] my List = {1, 5, 5, 5, 5, 1} Double max = myList[0]; Int indexOfMax = 0; for(int i = 1; i < myList.length; i++) { if(myList[i] > max) { Max = myList[i]; IndexOfMax = i; }} System.out.println(indexOfMax);

1

5.4 What is the output of the following code? Int[] myList = {1, 2, 3, 4, 5, 6}; for(int i = myList.length - 2; i >= 0; i--) myList[i+1] = myList[i]; for(int e : myList) System.out.print(e + " ");

1 1 2 3 4 5

2.2 When appropriately called, the following method prints _ and returns _? Public int increment() { Int a = 0; Int i = (++a) + (++a) + (--a); System.out.println(a); Return i }

1, 4

4.1 How many times will the following code print "Welcome to CS180"? int count = 0; while (count++ < 10) System.out.println("Welcome to CS180");

10

4.2 How many times will the following code print "Welcome to CS180"? int count = 0; do { System.out.println("Welcome to CS180"); count++; } while (count < 10);

10

Turkstra 12. The output is... int[] myInts = new int[10]; for(int i = 0; i < 10; i++) myInts[i] = i*2; System.out.println(myInts[5]);

10

Dunsmore 2. What is the two's complement representation of -37 using an 8-bit word? 37 (base 10) = 100101

11011011

1.2. What is the value of len after the following executes? String s1 = "Hey, CS180s!"; Int len = s1.length();

12

2.3 The result from the following expression is _ value and _ type? "" + (int)(7.0 + 8);

15. String

3.3 What is y after the following switch statement is executed? Int x = 3; int y = 4; switch(x + 3) { Case 6: y = 0; Case 7: y = 1; Default: y = y+1; }

2

1.3. What is the value of pos after the following code executes? String s1 = "ac ded ca"; Int pos = s1.indexOf("d");

3

Turkstra 15. The output is... public class Quiz { Private int k = 3; Void doIt(int k) { k = 7; } Public static void main(String[] args) { Quiz q = new Quiz(); q.doIt(12); System.out.println(q.k); } }

3

Turkstra 4. What is the value of i after the following statements are executed? int i = 5; i -= 2 * i++/(15-2*--i);

3

10. What is the output of the following code? Public class MyClass { Public static void main(string[] args) { Int z = 102, y = 3; If (z < 100 && (y=10)<5) z++; System.out.printf("%d, %d%n", y, z)

3, 102. It is short circuiting. The first one evaluates as false so the second is never evaluated.

Turkstra 9. The output is... int i, sum=0; for(i = 0; i < 3; i++) sum+=i; System.out.println(sum + ", " + i);

3, 3

6. How many layers of abstraction does Java have for file I/O?

3. File, FileReader, BufferedReader

2.1. What is the value of "j" after executing the following code? Int j = 5 & 4;

4

6. What will the last value printed to the console be? for(int i = 0; i < 5; ++i) System.out.println(i);

4

Turkstra 18. The output is... Public class DoIt { Void naow(int[] a) { a[0] = 5; } Public static void main(String[] args) { DoIt d = new DoIt(); Int[] a = new int[5]; A[0] = 1; d.naow(a); System.out.println(a[0]); } }

5

Turkstra 35. Given a queue, what is the value produced by the last operation? enqueue(5); enqueue(7); enqueue(8); value = dequeue();

5

Turkstra 3. What does the following code output? Public class Wheel { Double radius; Wheel(double radius) { this.radius = radius; } Double getRadius() { return this.radius; } Double getCircumference() { return 2.0 * Math.PI * this.radius; } Double getArea() { return Math.PI * this.radius * this.radius; } Public static void main(String[] args) { Wheel w = new Wheel(5.0); System.out.println(w.getRadius)); } }

5.0

10.3 The server listens for a connection request from a client using the following statement Socket s = new Socket(Servername, port); Socket s = serverSocket.accept(); Socket s = serverSocket.getSocket(); Socket s = new Socket(ServerName);

Socket s = serverSocket.accept();

Dunsmore 1. What is the most important aspect of the von Neumann architecture that allows computer software to run so fast?

Software is stored in memory along with data.

Dunsmore 10. Which statement below is not true? While loops are most often used for indefinite iteration. For loops are most often used for definite iteration. Do-while loops are used when the body of the loop must be executed at least once. It is common practice when looping n times to go from 0 to n-1. The body of a for loop must be executed at least once.

The body of a for loop must be executed at least once.

12.1 Where is the best place to run a JFrame? On the event dispatch thread. On the main program thread. On the SwingUtilities thread On the ActionListener Interface

on the EDT.

Dunsmore 30. Where is the best place to run the JFrame? A. on the Event Dispatch thread B. on the main program thread C. on the SwingUtilities thread D. on the ActionListener interface E. anywhere is fine

on the Event Dispatch Thread

7. Which of the following is NOT a valid overloaded method for the method below? public static int max (int x, int y) {}

public static double max (int x, int y)

3.2 Analyze the following code Boolean even = false; If (even = true) System.out.println("It is even!"); The program has a compile error, runtime error, runs but displays nothing, or displays "It is even!"

runs and displays "It is even!"

11.4 Which is not a method of JOptionPane class? showMessageDialog showInputDialog showConfirmDialog showDialog

showDialog

Turkstra 27. Which of the following would be the best choice for notifying the user that an unavoidable error in your program has occurred? showMessageDialog, showConfirmDialog, showInputDialog, showOptionDialog

showMessageDialog

Dunsmore 9. What statement or statements will be executed repeatedly as long as x is less than y? 1. while(x < y) 2. x+=7; 3. y-=4; 4. Z = 5; 5. X = x-5;

statement 2

6.1 Variables that are shared by every instance of a class are _. Public Private Instance Static

static.

11.2 The keyword to synchronize methods in Java is _.

synchronized.

9.2 What should go in the black to cause the run method to run? Public class Test implements Runnable { Public static void main(String[] args) { Thread t= new Thread(new Test()); } Public void run() {}}

t.start();

Dunsmore 12. The variable name temp is the name of an array of doubles. Which of the following tells you how many storage locations have been set aside for temp?

temp.length

Dunsmore 7. If x and y originally contain two different int values, what will x always contain after this is statement? if(x <= y) x = y;

the larger of the two values x and y.

Dunsmore 13. Suppose that the two dimensional array travel has been created and has values in it. What tells you the number of elements (columns) in row i of the travel array?

travel[i].length

1. What is the value of this expression? true != true != true

true

2. A class can implement more than one interface

true

Dunsmore 5. What will the method Character.isLetter(gender) return? Char gender = 'F';

true

Turkstra 28. Changing the background color of a JFrame must be done in the Event Dispatch Thread

true

Turkstra 31. repaint() can be invoked from threads that are not the EDT

true

Turkstra 33. The output is... Interface Walkable {} Abstract class Animal implements Walkable {} Class Dog extends Animal {} Public class Quiz { Public static void main(String[] args) { Dog d = new Dog(); System.out.println(d instanceof Walkable); } }

true

Turkstra 34. It is possible to append to the end of a linked list without keeping track of the tail

true

2. new Object().equals(new Object()) is equivalent to new Object() == new Object()

true. Default .equals() checks if the references are the same, which is the equivalent of ==.

3.4 Suppose x = 1, y = -1, and z = 1. What will be displayed by the following statement? if(x > 0) if(y > 0) System.out.println("x > 0 and y > 0"); Else if (z > 0) System.out.println("x < 0 and z > 0");

x < 0 and z > 0

3.1 What is the output of the following code? Int x = 0; if(x< 4) x = x + 1; System.out.println("x is " + x);

x is 1

1.1. Given the following code segment, what is the string referenced by s1? String s1 = "xy"; String s2 = s1; S1 = s1 + s2 + z;

xyxyz;

Turkstra 11. What is displayed? public final class Quiz { Public static void main(String... args) { int one = (int) Math.log(1.0); for(int = 0; i < one; i++) System.out.print("#"); System.out.println("}"); } }

}

6.2 Given the declaration Circle x = new Circle(), which of the following statements is the most accurate? X contains an int value. X contains an object of the Circle type. X contains a reference to a Circle object. You can assign an int value to x.

X contains a reference to a Circle object.

4.3 Do the following two statements in (I) and (II) result in the same value in sum? (I) - for (int i = 0; i<10; ++i) { sum += i; } (II) - for (int i = 0; i<10; i++) { sum += i;}

Yes

13.4 Can an abstract class define both abstract methods and non-abstract methods? No. It must have all one or all the other. No. It must have all abstract methods. Yes. But the child class must override all methods from the abstract class. Yes. The child classes inherit both.

Yes. The child classes inherit both.

7.4 Look at the following interface. Is the interface correct? Interface Test { int year = 1; double calculate(); } No because it contains a variable and interfaces cannot contain variables. No because the interface cannot contain a method that returns a value. Yes. year will automatically be a constant since it is in an interface. Yes. the method body will automatically be filled in.

Yes. year will automatically be a constant since it is in an interface.

17. What is the value of the boolean variable output? boolean output = (4 > 5 && 5-6 < 0) || false; (a) true (b) false

b

11. Which of the following statements is/are true? (a) You can store double values in a float without losing precision. (b) You can store float values in a double without losing precision. (c) You can store short values in an int without losing information (d) (a), and (c) (e) (b), and (c)

e

12. What is the value of the variable num? double num = 3 / 4; (a) 0.75 (b) 1 (c) 0 (d) 1.0 (e) 0.0

e

23. How many times does the following loop iterate? for (double d = 1/8; d < 1; d *= 2) { //Do something } (a) 8 (b) 6 (c) 4 (d) 3 (e) Infinite loop

e

24. Consider the statement: Scanner input = new Scanner(System.in); (a) input is of type int (b) input is of type double (c) input is of type String (d) input can be of type int, double or String (e) input is of type Scanner

e

30. How many base cases does a recursive function have? (a) 1 (b) 2 (c) None (d) At most 2 (e) At least 1

e

5. Given the declaration: int [][]a = {{2}, {6,8,10}, {0,4}}; Which of the following statements both compiles and executes without error? (a) a[2][3] = a[3][2]; (b) a[1][3] = a[3][1]; (c) a[0][1] = a[1][0]; (d) a[2][0] = a[0][2]; (e) a[1][2] = a[2][1];

e

Dunsmore 34. In the Linked List method... public void add(String s) { Node node = new Node(s); node.link = head; head = node; } ... what does the line... node.link = head; ... accomplish? A. makes the new first item in the linked list point to what was the first item B. makes the head of the linked list point to the first item C. makes the first item in the linked list always have a null pointer D. makes the second item in the linked list point to the first item E. creates the first item in the linked list

makes the new first item in the linked list point to what was the first item

Turkstra 7. The output is... int i = 6; if(i++==7||--i==5) System.out.println("Yes!"); else System.out.println(i);

6

Turkstra 10. The output is... int i, sum=0; for(i = 0; i < 5; i++) { if(i==2) continue; sum+=i; } System.out.println(sum);

8

Turkstra 13. The output is... int[] array = { 1, 2, 3, 4, 5}, sum = 0; for(int element: array) { if (element % 2 == 0) continue; sum += element; } System.out.println(sum);

9

14. What is a class? An object A data structure A blueprint for an object A singleton An enumeration

A blueprint for an object. A class is used to instantiate an object. A class might be a data structure, but not are. A singleton is one reference to an object that is passed around.

Dunsmore 20. What does it mean that Java is a "single inheritance" language? A. A class can only extend one other class. B. A class can either implement an interface or extend a class. It cannot do both. C. A class can inherit only one instance variable from its superclass. D. A class can inherit only one method from its superclass. E. A class that extends another class can create only one object

A class can only extend one other class.

7.3 What is an interface? A collection of constants and method declarations. Exactly the same as a Java class. Something that is used by saying "public class Henway uses Doable". The collection of public methods of any class.

A collection of constants and method declarations.

9. Which of the following assertions about method overriding is true? The signature of the overridden method must be different from the signature of the original method. Overriding is the same as overloading. A derived class can override a method of the base class. A method can be overridden only in the same class where the original method is defined. None of the above

A derived class can override a method of the base class. Cannot be overridden if the method is marked final.

7.2 Java's ArrayList remove(int index) is used for removing an element at the specified index from a list. It removes the element from the ArrayList, moves all the other elements up one position, and returns the element removed. With that in mind, what will be displayed by the following code? List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("C"); list.add("D"); for(int i = 0; i < list.size(); i++) System.out.println(list.remove(i));

AC

12.5 Which type of listener can be used on Buttons? MouseMotionListener, ItemListener, KeyListener or ActionListener

ActionListener.

13. Consider the following code. Private class Point { Private int x, y; Public Point() { This.x = 0; this.y = 0; } } Public class PointRunner { Public static void main(String args) { Point p = new Point(); P.x = 2; P.y = 2; System.out.printf(p.x + " " + p.y); } 0, 0 2, 2 Null, null Compile-time Runtime error

Compile time. It is incorrect syntax. Those variables do not exist in that scope.

Dunsmore 22. Searching for a Purdue student in one of four files simultaneously is an example of...? A. File Decomposition B. Task Decomposition C. Domain Decomposition D. Search Decomposition E. Thread Decomposition

Domain Decomposition.

Turkstra 14. What function tests if the elements of arrays are equal?

Arrays.equals(arr1, arr2)

Dunsmore 23. Why is it necessary in the race condition example in class today to have a synchronized block of code in the run() method? A. Because the class implements Runnable. B. Because the main method calls the join() method for each thread. C. Because a run() method must always have a synchronized block of code. D. Because each thread increments the same counter. E. Because each thread increments a different counter.

Because each thread increments the same counter.

Dunsmore 19. In what way are arrays and ArrayLists alike? A. Both require their elements to be reference objects B. Both have a size() method to report their current size C. Both use accessor and mutator methods to view and modify items D. Both implement the Iterable interface E. Both are dynamic and change size as

Both implement the Iterable interface.

12.3 What class is not in the javax.swing packet? JFrame JOptionPane JPanel Canvas

Canvas

9.1 Analyze the following code. Public abstract class Test implements Runnable { public void doSomething() {}} Class Test needs a start() method Class test needs a join() method Class test needs a run() method Class test will run fine with no additional methods.

Class test needs a run() method

Turkstra 19. The output is... Interface A { int theInt = 5; } Interface B { int theInt = 6; } Public class Q2 implements A, B { Public static void main(String[] args) { System.out.println(theInt); } }

Compile Error

Turkstra 21. Given a non-numeric input, the output is... Public class Quiz { Public static void main(String[] args) { Scanner s = new Scanner(System.in); Int i; String str = s.next(); Try { i = Integer.parseInt(str); } catch(Exception e) { System.out.println("A"); } catch(NumberFormatException e) { System.out.println("B") } } }

Compile error because the NumberFormatException has already been caught.

8. Consider the following program. Public class Runner implements Runnable { Private String name; Public Runner(String name) { This.name = name; } Public void run() { System.out.print(name); } Public static void main(String[] args) { Thread quick = new Thread(new Runner("Quick")); Thread slow = new Thread(new Runner("Slow)); quick.start(); slow.start(); } }

Either QuickSlow or SlowQuick. Three threads are running.

Turkstra 20. Failed to load pdf document.

Failed to load pdf document.

Turkstra 8. The output is... int i = 4; switch(i) { case 2: System.out.println("Two"); case 4: System.out.println("Four"); case 6: System.out.println("Six"); default: System.out.println("I'm sorry Dave, I'm afraid I can't do that"); }

FourSixI'm sorry Dave, I'm afraid I can't do that

1.4. What is the value of s1 after the following code executes? String s1 = "Hey"; String s2 = s1.substring(0, 1); String s3 = s2.toLowerCase();

Hey

Turkstra 17. What does `new Blah(3)` display? Public class Blah { Public Blah() { System.out.print("Hi"); } Public Blah(int x) { this(); System.out.print(x); } }

Hi3

Dunsmore 21. If method F throws an exception, where is the appropriate Exception Handler usually located? A. In the Object class. B. In the Exception class. C. In a method G called by method F. D. In method F. E. In a method that calls a method that calls a method ... that calls method F

In a method that calls a method that calls a method ... that calls method F

5. What does it mean when a class's field (instance variable) is private?

It can be directly accessed only in the class it is defined in.

Dunsmore 15. If a method has return type void, which of the following is true? It must have no "return;" statements. It must have exactly one "return;" statement. It can have any number of return statements (including none), but all must be "return;". It must have exactly one "return expression;" statement. It can have any number of return statements (one or more), but all must be "return expression;"

It can have any number of return statements (including none), but all must be "return;".

Dunsmore 16. Based only on the line below, what do you know about the compare method of the Arrays class? Arrays.compare(int[] a, int[] b)

It is a static method.

Turkstra 29. What method is used to display an input dialog?

JOptionPane.showInputDialog(...)

12.2 What does MVC stand for in GUI?

Model-View-Controller

Dunsmore 18. All of these are correct about accessor and mutator methods except which one...? A. Mutator methods allow "controlled" change of fields B. Mutator methods must begin with the word "set" C. Fields are usually private requiring accessor methods to provide these values D. Accessor methods usually begin with the word "get" E. Accessor methods allow read-only access

Mutator methods must begin with the word "set"

Dunsmore 35. In the RPN evaluator is a line... int op2 = stack.pop(); int op1 = stack.pop(); Suppose we change that to... int op1 = stack.pop(); int op2 = stack.pop(); What would happen? A. Everything would be fine. No problem. B. This would throw a RuntimeException. C. No mathematical operations would work correctly. D. No additions or multiplications would work correctly. E. No subtractions or divisions would work correctly.

No subtractions or divisions would work correctly.

Turkstra 32. Not a question

Not a question

13.1 What is the name of the class that is the ancestor to every other class in Java?

Object

9.3 Which of the following expressions must be true if you create a thread using Thread = new Thread(object)? Object instanceof Thread Object instanceof Iterable Object instanceof Synchronized Object instanceof Runnable

Object instanceof Runnable

13.3 What is an abstract method? Any method in an abstract class. A method which is inherited from a superclass One without a body that is declared with the reserved word abstract. A method in the child class that overrides a parent method.

One without a body that is declared with the reserved word abstract.

4.4 Given the following four patterns, Pattern A 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 2 3 4 5 6 Pattern B 1 2 3 4 5 6 1 2 3 4 5 1 2 3 4 1 2 3 1 2 1 Pattern C 1 2 1 3 2 1 4 3 2 1 5 4 3 2 1 6 5 4 3 2 1 Pattern D 1 2 3 4 5 6 2 3 4 5 6 3 4 5 6 4 5 6 5 6 6 Which pattern is produced by the following code? for(int i = 1; i <= 6; i++) for(int j = 6; j >= 1; j--) System.out.print(j <= i ? j + " " : " " + " ");

Pattern C

10.1 Which class do you use to write data into a text file? DataOutputStream, PrintWriter, Scanner, or System

PrintWriter.

10.2 Which class do you use to read data from a text file? DataInputStream, PrintWriter, Scanner or System

Scanner

Dunsmore 25. Which statement below would be used by a server to create a socket to which clients can connect to a specific port? A. Socket toomee = new Socket("ocean.cs.purdue.edu"); B. Socket toomee = new Socket("ocean.cs.purdue.edu", 6543); C. ServerSocket toomee = new ServerSocket(6543); D. ServerSocket toomee = new ServerSocket("ocean.cs.purdue.edu"); E. ServerSocket toomee = new ServerSocket("ocean.cs.purdue.edu", 6543);

ServerSocket toomee = new ServerSocket(6543);

Turkstra 24. Which of the following is not a valid thread state? New, Sleeping, Terminated, Runnable, Not Runnable

Sleeping

10.4 The client requests a connection to a server using the following statement. Socket s = new Socket(ServerName, port); Socket s = serverSocket.accept(); Socket s = serverSocket.getSocket(); Socket s = new Socket(ServerName);

Socket s = new Socket(ServerName, port);

6.4 Analyze the following code. Public class Test{ Public static void main(String[] args) { Int n = 2; inc(n); System.out.println("n is " + n); } Public static void inc(int n) { n++; } } The code has a compile error because inc does not return a value. The code has a compile error because inc is declared static. The code prints n is 2. The code prints n is 3.

The code prints n is 2.

8.2 What is the output of running class C? Class A { public A() { system.out.println("The default constructor of A is invoked");}} Class B extends A { public B() { System.out.println("The default constructor of B is invoked");}} Class C { public static void main(String[] args) { B b = new B(); }}

The default constructor of A is invoked.\nThe default constructor of B is invoked.

Dunsmore 4. What does it mean to say that the "+ operator is overloaded" in Java?

The meaning of the + operator is determined by what is to the left and right of it.

8.1 Analyze the following code. Class Square extends GeometricObject { Double length; Square(double length) { GeometricObject(length); } } The program compiles fine, but you cannot create an instance of square because the constructor does not specify the length of the Square. The program has a compile time error because the line GeometricObject(length); should be super(length); The program has a compile time error because the line GeometricObject(length); should be this(length);

The program has a compile time error because the line GeometricObject(length); should be super(length);

6.3 Analyze the following code. Public class Test { Int x; Public Test(String t) { System.out.println("Test");} Public static void main(String[] args) { Test test = null; System.out.println(test.x); } } The program has a compile error because test is not initialized. The program has a compile error because x has not been initialized. The program has a compile error because you cannot say "Test test = null;" The program has a runtime NullPointerException because test is null while executing test.x

The program has a runtime NullPointerException because test is null while executing test.x

5.3 Analyze the following code. Public class Test { Public static void main(String[] args) { Int[] x = new int[5]; Int i; for(i = 0; i < x.length; i++) X[i] = i; System.out.println(x[i]); The program displays 0 1 2 3 4. The program displays 4. The program has a runtime error because the last statement in the main method causes ArrayIndexOutOfBoundsException. The program has a compile error because i is not defined in the last statement of the main method.

The program has a runtime error because the last statement in the main method causes ArrayIndexOutOfBoundsException.

5.1 Analyze the following code. Public class Test { Publis static void main(String[] args) { Int[] x = new int[3]; System.out.println("x[0] is " + x[0]); The program has a compile error because the size of the array wasn't specified when declaring the array. The program has a runtime error because the array elements are not initialized. The program runs fine and displays x[0] is 0. The program has a runtime error because x[0] is not defined.

The program runs fine and displays x[0] is 0.

8.4 A Java exception is a subclass of _. RuntimeException Exception Error Throwable NumberFormatException

Throwable

12. A class, Tire, extends Wheel. Which of the following is true? Wheel cannot have subclasses other than Tire. Tire cannot have any subclasses. Tire cannot have superclasses other than Wheel. Wheel cannot have any superclasses. Java doesn't follow 'single inheritance'

Tire cannot have superclasses other than Wheel. Java does follow single inheritance. If Tire was marked as final, it could not have any subclasses. Classes always have a superclass.

Dunsmore 31. Which one of the statements about Java GUIs is true? A. The BorderLayout add method always requires two parameters (component, location). B. You can change the JFrame's layout manager to be GridLayout. C. Using the GridLayout manager always requires that you specify how many rows and columns to use. D. If a JFrame has a JPanel using the default FlowLayout manager that is showing 3 components per row and the user makes the JFrame much larger, the components will get larger and there will still be 3 components per row. E. Putting a JPanel inside a JPanel is not allowed.

You can change the JFrame's layout manager to be GridLayout.

Dunsmore 33. Which of the following is true about abstract class Account? A. You can create an object via Account a = new SavingsAccount(); B. You can create an object via Account a = new Account(); C. All methods in Account must be abstract. D. There can be no instance variables in Account. E. Any class that extends Account must have no abstract methods.

You can create an object via Account = new SavingsAccount();

8.3 Which of the statements regarding the super keyword is incorrect? You can use super to invoke a super class constructor. You can use super to invoke a super class method. You can use super.x to access a private instance variable x in the superclass. If you use super in a non-constructor method, it does not have to be used in the first line of that method.

You can use super.x to access a private instance variable x in the superclass.

10. The result from the following expression is "" + (int)(7.5 + 8) + 2 (a) "152" (b) "17" (c) 17.5 (d) 17 (e) "1782"

a

15. Given two interfaces Reliable and Unreliable, the following definition is syntactically correct. public interface ReliableUnreliable extends Reliable, Unreliable { } (a) True (b) False

a

16. What will the following code snippet print? double i = 3.7; float j = 7.0f; System.out.println((int)i + j); (a) 10.0 (b) 10 (c) 11 (d) 11.0 (e) 10.7

a

18. What does the main method print on execution? public static void main(String[] args) { int[] a = {3, 1, 2, 4, 0}; int[] b = a; for (int i = 0; i < a.length; i++) { a[i] = a[(a[i] + 3) % a.length]; } System.out.println(b[1]); } (a) 0 (b) 1 (c) ArrayIndexOutOfBoundsException (d) 2 (e) 3

a

21. The XOR operation when performed on two bits returns a 1 if the bits are different. (a) True (b) False

a

22. After evaluating the following statements boolean a = true && false; boolean b = true || false; (a) a will be false (b) b will be false (c) Both a and b will be true (d) a will be true (e) Both a and b will be false

a

26. A call to isEqual with 18 as argument will return a true. public boolean isEqual(int b) { return b == 2 * (b / 10 + b % 10); } (a) True (b) False

a

29. For the program in Question 28 Java determines which start() method to call at: (a) Run time (b) Compile time

a

13.2 What is an abstract class? One without any child classes. Any parent class with one or more child class. A class which cannot be instantiated. Another name for base class

a class which cannot be instantiated.

11.1 A server socket can connect to _ clients

an unlimited number.

19. Consider the following method that receives an ordered array of ints and a target. public static boolean task(int[] array, int target) { for (int i = 0; i < array.length; i++) { if (array[i] == target) { return true; } else if (array[i] > target) { return false; } } } How many iterations of the loop will run for the call task({2,3,6,7,9}, 4) ? (a) 5 (b) 3 (c) 2 (d) 4 (e) 1

b

20. In java an abstract class cannot extend another abstract class. (a) True (b) False

b

28. This question and the next one is based on the following three classes public class Vehicle { public void start() { System.out.println("Start method of Vehicle"); } } public class Car extends Vehicle { @Override public void start() { System.out.println("Start method of Car"); } } public class Test { public static void main(String[] args) { Vehicle vehicle = new Car(); vehicle.start(); } } When the Test class is executed, the statement vehicle.start() invokes the start() from the (a) Vehicle class (b) Car class

b

4. Code snippets 1 and 2 generate the same output // Code Snippet 1 int i = 5; while( i != 0) { System.out.println("Dreams"); i--; } // Code Snippet 2 for(int i = 0; i <= 5; i++) System.out.println("Dreams"); (a) True (b) False

b

9. In the MVC architectural pattern, which component generates an output representation for the user? (a) Model (b) View (c) Controller (d) Client (e) Server

b

13. What will the following code snippet print? String s = "ALICIA"; System.out.println(s.charAt(s.indexOf('I') + 3)); (a) 4 (b) 5 (c) A (d) L (e) Error: String index out of range

c

14. What value does the printIt method return in the following program? public static char printIt(String s1) { String s2 = s1.substring(1, 3); return s2.charAt(1); } public static void main(String[] args) { printIt("CS180!"); } (a) C (b) S (c) 1 (d) 8 (e) The code has compilation error, so it would not print anything

c

2. Which of the following is not a repetition statement? (a) for (b) while (c) switch (d) do-while (e) for-each

c

25. Every class in Java possesses the toString() method (even if it is not explicitly defined in the class) due to which of the following reasons? (a) Every class extends the Parent class (b) Every class extends the String class (c) Every class extends the Object class (d) All of the above (e) None of the above: every class in Java does NOT possess the toString() method

c

27. Which of the following is NOT a valid overloaded method for the method below? public static int max (int x, int y) { } (a) public static int max (int x) { } (b) public static int max (int x, int y, double z) { } (c) public static double max (int x, int y) { } (d) public static double max (double x, double y) { } (e) public static String max (String x, String y) { }

c

3. How many iterations will this loop have? int i = 0; do { i += 2; } while (i != 10); (a) 1 (b) 3 (c) 5 (d) 7 (e) This is an infinite loop

c

Dunsmore 24. In order to use a DataOutputStream object, it is usually.... A. chained to a File object B. chained to a FileOutputStream object which is chained to a File object C. chained to a FileOutputStream object which is chained to a FileInputStream object D. chained to a DataInputStream object which is chained to a File object E. chained to a DataInputStream object which is chained to a FileOutputStream object which is chained to a File object

chained to a FileOutputStream object which is chained to a File object.

1. When appropriately called the following method public int increment() { int a = 5; int i = (++a) + (++a) + (a++); System.out.println(a); return i; } (a) prints 8, returns 21 (b) prints 7, returns 21 (c) prints 8, returns 22 (d) prints 8, returns 20 (e) prints 7, returns 19

d

6. What does the following method print? public static void main(String[] args) { int[] a = new int[2]; int[] b = new int[2]; int[] c = new int[2]; a[0] = 3; b = a; a[1] = 4; b[0] = 2; c[1] = 1; System.out.println(a[0] + b[0] + c[0]); } (a) 2 (b) 5 (c) 6 (d) 4 (e) 7

d

7. Let x and y be two floating point numbers. In Java, to check if x and y are equal we compute Math.abs(x − y) and check if the result is less than some small number which refer to by the name epsilon. We learned that the choice of epsilon depends on the application. Let's consider an application where we want to conclude that x and y are equal if they have the same digits up to 4 decimal places. What should epsilon be for this application? (a) 10−8 (b) 10−6 (c) Any number smaller than 10−6 (d) 0.00009 (e) 0.0001

e

8. Which of the following constructs will always be executed at least once? (a) for (b) if (c) while (d) switch (e) do-while

e

7.1 What will be displayed by the second println statement in the main method? Public class Foo { Int i; Static int s; Public static void main(String[] args) { Foo f1 = new Foo(); System.out.println("f1.i is " + f1.i + " f1.s is " + f1.s); Foo f2 = new Foo(); System.out.println("f2.i is " + f2.i + " f2.s is " + f2.s); Foo f3 = new Foo(); System.out.println("f3.i is " + f3.i + " f3.s is " + f3.s); } Public Foo() { I++; S++; } }

f2.i is 1 f2.s is 2

1. A class can extend more than one class

false

4. What is the value of this expression? 1/10 == 0.1

false

Turkstra 1. Compiled Java programs execute directly on computer hardware

false

Turkstra 2. Static functions require a class to be instantiated before they can be invoked

false

Turkstra 26. Hostnames always resolve to a single IP address

false

Turkstra 30. Long-running event handlers do not impact a GUI's responsiveness because they run on the EDT

false

4. The following line would result in a compile-time error. Int[][][][] array = new int[0][3][-2][1];

false. Compile time errors are because of syntax. This is a Runtime error. That is when the object is created.

3. An object of a generic class can b created with any type, T.

false. Does not work with primitives. Generics work with only classes and interfaces.

3. What is the value of the boolean variable output? Boolean output - (4 > 5 && 5 - 6 < 0) || false;

false;

Turkstra 22. Writing and debugging concurrent programs is less difficult compared to non-concurrent programs

false;

Turkstra 23. Sleep() is guaranteed to cause your program to delay the precise number of milliseconds specified by its argument

false;

Turkstra 25. Instantiating a file object opens the file

false;

Turkstra 5. The following keyword creates a variable that stores an immutable value

final

9.4 What is the output of the following code? Public class Test { Public static void main(String[] args) { New Test(); } Public Test() { PrintChar printA = new PrintChar('a', 5); PrintChar printB = new PrintChar('b', 5); printA.start(); printB.start(); } Class PrintChar extends Thread { Private char charToPrint; Private int times; Public PrintChar(char c, int t) { charToPrint = c; times = t; } Public void run() { for(int i = 0; i < times; i++) System.out.print(charToPrint); }}}

five a's and five b's in some order.

Dunsmore 8. Suppose that s is an object pointing to the string "Indianapolis". What string does s.substring(3, 8) return?

ianap

Dunsmore 26. int tryAgain = JOptionPane.showConfirmDialog(null, "Do you want to try again?", "Alert", JOptionPane.YES_NO_OPTION); If you have the statement above in your program, which of the following is the best way to check if the user clicked the NO button? A. if (tryAgain == 0) B. if (tryAgain == -1) C. if (tryAgain == JOptionPane.YES_NO_OPTION) D. if (tryAgain == JOptionPane.NO_OPTION) E. if (JOptionPane.NO_OPTION == 0)

if (tryAgain == JOptionPane.NO_OPTION)

Dunsmore 27. fc is a JFileChooser object. Which statement below opens a frame in which the user can select a file and returns a value indicating whether the file is to be opened or not? A. fc.showOpenDialog(result); B. int result = fc.SetDialogTitle("open"); C. int result = fc.getSelectedFile(); D. int result = fc.showOpenDialog(null); E. String result = fc.showOpenDialog(null);

int result = fc.showOpenDialog(null);

11.5 in order to use JOptionPane, which package must you import? Javax.swing Java.io Java.util Java.applet

javax.swing

11.3 You can use the _ method to force one thread to wait for another thread to finish. sleep(long milliseconds) yield() join()

join()


Ensembles d'études connexes

FINAL REVIEW: Anxiety, OCD, and PTSD (50)

View Set

Throat, Thorax, and Abdominal Injuries

View Set

Financial Markets and Products 3

View Set

Macro: Ch 29- The Aggregate Expenditures Model

View Set

SOLVING ONE-VARIABLE INEQUALITIES

View Set

Одежда.EF Pre Unit 1C - Things you wear

View Set