cs Flashcards

1
Q

Output?

public static void main(String [] args){
int number = 6;
int secondNumber = changeNumber (number);
System.out.print(number + “ “ + secondNumber);
}

      public static int changeNumber(int number){
        number = 12;
        return number;
      }
A

6 12

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Which Line will Line A produce?

public class Unknown{
private int x;

            public Unknown(){
                x = 17;
                method1();
                method2(5);
                method3();
                System.out.println(x);      // Line D
            }
        
            public void method1(){
                --x;
                int x = this.x;
                x++;
                System.out.println(this.x); // Line A
            }
        
            public void method2(int x){
                x++;
                System.out.println(x);      // Line B
            }
        
            public void method3(){
                --x;
                int x = 2;
                x++;
                System.out.println(x);      // Line C
            }
        }
A

16

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Output?

public void foo () {
int x = 42;
int y = 24;
mystery (x, y);
System.out.println (x + “ “ + y);
}

        public void mystery (int var1, int var2) {
          int temp = var1;
          var1 = var2;
          var2 = temp;
        }
A

42 24

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What should be done to correct the following code?

public class exam {
float mark;
public static void main(String[]arg){
float aCopyofMark;
exam e = new exam();
System.out.println( e.mark + aCopyofMark);
}
}

A

Initalize aCopyofMark

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How many objects are created in the following declaration?

String name;

A

0

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Output?

int income = 30;
boolean condition1 = true, condition2 = true;
if(income < 100)
if(income > 10)
if(condition1){
System.out.print(“A”);
if(income < 20)
System.out.print(“B”);
}
else
System.out.print(“C”);
if(!condition2){
if(income > 50)
System.out.print(“D”);
}
else{
System.out.print(“E”);
}

A

AE

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

The scope of a variable in Java is:

A

The part of the program in which it can be used

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Which of the following JUnit tests will fail?

A

assertNull(50-25-25);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Imagine a class named Club, to be a member a person must be aged 15 or older, but less than 50. What values would you use to boundary test a method designed to check if a person was a suitable age to join?

A

14 15 49 50

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Which set of values is just enough to provide code coverage for the following code: if (cost > 10 && tip > 4)

cost: 20 and tip: 2, cost: 20 and tip: 6, cost: 9 and tip: 1, cost: 9 and tip: 6

cost: 20 and tip: 4, cost: 5 and tip: 1

cost: 20 and tip: 2, cost: 9 and tip: 5, cost: 15 and tip: 6

A

cost: 20 and tip: 2, cost: 9 and tip: 5, cost: 15 and tip: 6

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Which set of values is just enough to provide code coverage for the following code: if (cost < 10 || cost >20)

cost: 5, 10, 15, 20

cost: 5, 25

cost: 5, 25, 15

A

cost: 5, 25, 15

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Which line of code is needed at the beginning of the follow block of code used to test whether remove throws the correct exception:

          try
          {
            collection.remove(item);
          }
          catch (Exception exception)
          {
            thrown = exception;
          }

          assertNotNull(thrown);

          assertTrue(thrown instanceof NoSuchElementException);

          assertEquals(thrown.getMessage(), "That item is not in the collection.");

Exception thrown;

Exception thrown = null;

Exception thrown = NoSuchElementException;

Exception thrown = That item is not in the collection.”;

A

Exception thrown = null;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Which of the following lines of code would properly test the equality of two arrays. For example:

        Object[] expectedArray = {"H","I","J","K"};
        Object[] actualArray = {"A","B","C","D"};            

assertEquals(expectedArray, actualArray);

assertEquals(actualArray, expectedArray);

      if (actualArray.length == expectedArray.length) {
        for (int i =0; i < expectedArray.length; i++)
        {
          assertEquals(expectedArray[i],actualArray[i]);
        }  
      }

      for (int i =0; i < expectedArray.length; i++)
      {
        assertEquals(expectedArray[i],actualArray[i]);
      }  

      for (int i =0; i < actualArray.length; i++)
       {
        assertEquals(expectedArray[i],actualArray[i]);
      }  

assertTrue( expectedArray.equals( actualArray) );

A

if (actualArray.length == expectedArray.length) {
for (int i =0; i < expectedArray.length; i++)
{
assertEquals(expectedArray[i],actualArray[i]);
}
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Suppose you are writing a method in a new class. You are also writing unit test cases to demonstrate that this method works correctly. You know you have written enough test cases to demonstrate the method works as desired when?

You have written at least one test case for every input value that can be given to the method.

You have written at least one test case for every output value that can be produced by the method.

You have written at least one test case that uses the method.

You have written at least one test case for every input/output value combination that can be given to/produced by the method.

You have written separate test cases for each identifiable “group” of input values and/or output values where the behavior is expected to be similar.

A

You have written separate test cases for each identifiable “group” of input values and/or output values where the behavior is expected to be similar.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Which method is run before each test method?

All of these answers are correct

public void setUp(){}

public void SetUp(){}

public Hokie(){}

public void setup(){}

public void SetUp(){}, public void setup(){}, and public Hokie(){} are all correct

A

public void setUp(){}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Which of the following is false according to the course style guidelines?

constants use a reverse camel case convention

package names should be all lowercase

methods and variable follow the same naming convention

classes and interfaces both follow the same naming convention

A

constants use a reverse camel case convention

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Reasons for following style and documentation guidelines are:

code is easier to debug

code is more readable and easier to understand

all of these

code is easier to maintain

A

all of these

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Which of the following is not a commonly used javadoc tag?

@return

@version

@param

@args

@author

A

@args

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Which of the following do not need to be avoided to adhere to the course style guidelines

unused fields/variables

sufficient javadocs

lines that are too long

debug statements left within the code

hardcoded values

A

sufficient javadocs

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

When an exception occurs within a method, the method creates an Exception object then hands it off to the Java runtime system to take further action, this is referred to as…

instantiating a semaphore

exception passing

runtime passing

throwing an exception

A

throwing an exception

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Which of the following could NOT result in code throwing a null pointer exception?

Using an object that became null

Attempting to use an object that was declared but never instantiated

Attempting to invoke a method from a null object

Attempting to use an object that was instantiated but never declared

A

Attempting to use an object that was instantiated but never declared

22
Q

True or False:
The following is a valid combination of try and finally blocks:

try {
// statements
}
finally {
// statements
}

A

True

23
Q

Which of the following statements are false?

A try block can have multiple catch blocks

A catch block must have an associated try block

Code in a finally block will always execute whether or not an exception occurs in the try block

A try block can have only one catch block

A

A try block can have only one catch block

24
Q

Which pair of code blocks are used to enclose exception-prone code, and to check for and handle exceptional events?

try and catch

catch and while

try and finally

if and then

A

try and catch

25
Q

We implement the following code and receive an error message on the riskyCodeThatWantsToDefer() method call indicating “Unhandled exception type IOException”.

public void riskyCodeThatWantsToDefer ( ) throws IOException {
// some code
}

public void callingMethod() {
riskyCodeThatWantsToDefer();
}
We realize that the riskyCodeThatWantsToDefer() method has passed exception handling responsibility to callingMethod().
To resolve this error we must modify callingMethod().
Which of the modifications listed below would resolve this error?

public static void callingMethod() {
try {
riskyCodeThatWantsToDefer();
}
catch (IOException e) {
e.printStackTrace();
}
}

public static void callingMethod() throws IOException {

riskyCodeThatWantsToDefer();
}

Both of these answers are correct

A

Both of these answers are correct

26
Q

Consider the following: When foo is executed, what is printed out?

        public void foo () {
          int x = 42;
          int y = 24;
          mystery (x, y);
          System.out.println (x + "  " + y);
        }

        public void mystery (int var1, int var2) {
          int temp = var1;
          var1 = var2;
          var2 = temp;
        }

42 24

24 42

A

42 24

27
Q

What kind of variable is label?

        public class Labeller extends JFrame {
          public Labeller () {
            JLabel label = new JLabel("Field or Variable");
          }
         
          public static void main (String[] args) {
           new Labeller();
          }
        }

Instance variable, Object Reference

Instance variable, primitive

local variable, primitive

local variable, Object Reference

A

local variable, Object Reference

28
Q

Using the information in the UML diagram above, suppose an Oak prepares for winter like a Tree, but it drops its leaves first. What code should replace ??? in the following code?

public class Oak extends Tree {

public void prepareForWinter(){
this.dropLeaves();
???
}
}

this.absorb(new Water());

super(this);

super.this();

Tree.prepareForWinter();

super.prepareForWinter();

A

super.prepareForWinter();

29
Q

The simplified UML diagram above shows the relationships among Java classes Bird, Crow, and Duck. Suppose Bird has a fly(Location place) method, but we want Crows to makeNoise() just before they take off and then behave like other Birds. Assuming Crows have a makeNoise() method, we should

Define a fly method in Crow by copying the fly code from Bird then adding in makeNoise() at the start, i.e.

      public void fly(Location place) {
        this.makeNoise();
        //[paste the body of Bird's fly method here]
      }

Define a fly method in Crow that just consists of makeNoise() and this.fly(place), i.e.

      public void fly(Location place) {
        this.makeNoise();
        this.fly(place);
      }

Define a fly method in Crow that just consists of makeNoise() and super.fly(place)
public void fly(Location place) {
this.makeNoise();
super.fly(place);
}

Define a fly method in Crow that just consists of makeNoise() and Bird.fly(place); i.e.

      public void fly(Location place) {
        this.makeNoise();
        Bird.fly(place);
      }

Define a fly method in Crow that just consists of makeNoise(), i.e.

      public void fly(Location place) {
        this.makeNoise();
      }
A

Define a fly method in Crow that just consists of makeNoise() and super.fly(place)
public void fly(Location place) {
this.makeNoise();
super.fly(place);
}

30
Q

Given an array of doubles named values, what does the following code do?

        double total = 0;
        for(double element :  values)
        {
            total = total + element;
        }
        double average = 0;
        if (values.length > 0)
        {
            average = total/values.length;
        }
A

Calculates the sum and average of the values

31
Q

Given an array of ints named values, what does the following code do?

        for (int i = 0; i < values.length; i++)
        {
            values[i] = i * i;
        }

Calculates the sum and average of the values

Prints all the values

Finds the maximum of the values

Fills the array with squares (0, 1, 4, 9, 16, …)

A

Fills the array with squares (0, 1, 4, 9, 16, …)

32
Q

Given the following code:

          for (int i=0; i < values.length; i++) {
            if (values[i] == searchedValue){
              found = true; 
            } else {
              found = false;
            }
          } 
          if (found) { 
            System.out.println("found " + searchedValue); 
          } else { 
            System.out.println ("not found"); 
          }      

If the initital values are:

        int[] values = { 3, 6, 10, 12, 100, 200, 250, 500 };
        int searchedValue = 10;
        boolean found = false;

What is output?

found 10

not found

A

not found

33
Q

Given the following code:

        for (int i=0; i < values.length; i++) {
          if (values[i] == searchedValue){
            found = true; 
          } else {
            found = false;
          }
        } 
        if (found) { 
          System.out.println("found " + searchedValue); 
        } else { 
          System.out.println ("not found"); 
        }      

If the initial values are:

      int[] values = { 3, 6, 10, 12, 100, 200, 250, 500 };
      int searchedValue = 250;
      boolean found = false;

What is output?

found 250

not found

A

not found

34
Q

If currentSize is 8, trace

        int[] values = { 35, 16, 100, 12, 100, 200, 250, 500, 0, 0};
        int newElement = 11;
        if (currentSize < values.length) {
            currentSize++;
            values[currentSize - 1] = newElement;
        }

What is the array after the code executes?

{ 35, 16, 100, 12, 100, 200, 250, 500, 11, 0};

{ 35, 16, 100, 12, 100å, 200, 250, 11, 500, 0};

{ 35, 16, 100, 12, 100, 200, 250, 500, 0, 11};

{ 11, 35, 16, 100, 12, 100, 200, 250, 500, 0 };

{ 35, 11, 16, 100, 12, 100, 200, 250, 500, 0 };

{ 35, 11, 100, 12, 100, 200, 250, 500, 0, 0 };

A

{ 35, 16, 100, 12, 100, 200, 250, 500, 11, 0};

35
Q

If pos is 4 and currentSize is 7, trace this code that removes an item:

        int[] values = {10, 20, 30, 40, 50, 60, 70};
        for (int i = pos + 1; i < currentSize; i++) {
             values[i - 1] = values[i];
        }    

What is the array after the code executes?

{10, 20, 30, 40, 50, 60, 70}

{10, 20, 30, 40, 60, 70, 70}

{10, 20, 30, 50, 60, 70, 70}

{10, 20, 30, 40, 70, 60, 50}

A

{10, 20, 30, 40, 60, 70, 70}

36
Q

Given the following code:

        public class MoveData {

            public static  void shiftUpArray(T[] dataset)
            {
                for (int i =1; i < dataset.length; i++) {
                    dataset[i] = dataset[i-1];
                }
            }
        
          public static void main(String args[]) {
          
          }
        
        
        ...
        }

Which of the following would not be possible correct code inside the main method of MoveData?

        Integer[] bits = {32, 64, 256, 512};
        shiftUpArray(bits);
      

        WritingInstrument[] box = new WritingInstrument[20];
        box[0] = new Marker();
        box[1] = new Marker();
        box[2] = new Pencil();
        shiftUpArray(box);
      

        int[] scores = {92, 18, 76, 76};
        shiftUpArray(scores);
      

        String[] oceans = {"Pacific", "Indian", "Atlantic", "Arctic"}; 
        shiftUpArray(oceans);
A

int[] scores = {92, 18, 76, 76};
shiftUpArray(scores);

37
Q

The use of a generic data type is preferred over using Object as a general class in a collection because…

It ensures that all the members of the collection are objects related by inheritance.

It allows the data type to be determined later by the client of the class.

It can contain objects of type OrderedPair.

A

It ensures that all the members of the collection are objects related by inheritance.

38
Q

What does the add method return?

True if the addition is successful, or false if not.

True if the bag contains anEntry, or false if not.

The values array filled with the entries in the bag.

The object that was added.

A

True if the addition is successful, or false if not.

39
Q

A set is an abstract data type that is similar to a bag. It is also unordered, but it does not allow duplicates. Examples of sets would be even integers or a collection of the movies you have previously seen. Which bag behavior would need to be modified for a set?

contains

clear

toArray

add

A

add

40
Q

Junit testing…

Provides ability to test specific methods

All of these answers are correct

Has a setUp method useful for initializing variables

Should be used throughout development

Uses assert statements instead of print statements

A

All of these answers are correct

41
Q

In the Fixed Size Array implementation of a Bag, depicted below as ArrayBag1, what happens when a client tries to add an element to the ArrayBag1 but the underlying array is full?

UML Diagram of Bags

The add method throws an exception

The element does not get added

The add method doubles its size and adds the new element

The add method replaces the last element with the new element

A

The element does not get added

42
Q

Which of the following 5 implementations could not be used for contains?

public boolean contains(T anEntry)
{
return getFrequencyOf(anEntry) > 0;
}

public boolean contains(T anEntry)
{
boolean found = false;
int i = 0;
while ( !found && (i < numberOfEntries))
{
if (anEntry.equals(contents[i]))
{
found = true;
}
i++;
}
return found;
}

public boolean contains(T anEntry)
{
return !isEmpty();
}

public boolean contains(T anEntry)
{
return getIndexOf(anEntry) > -1;
}

public boolean contains(T anEntry)
{
int i = 0;
while (i < numberOfEntries)
{
if (anEntry.equals(contents[i]))
{
return true;
}
i++;
}
return false;
}

A

public boolean contains(T anEntry)
{
return !isEmpty();
}

43
Q

Which of the following 5 implementations could not be used for getFrequency?

public int getFrequencyOf(T anEntry)
{
int i = 0;
int count = 0;
while(anEntry.equals(contents[i]))
{
i++;
count++;
}
return numberOfEntries - count;
}

public int getFrequencyOf(T anEntry)
{
int count = 0;
for(int i = numberOfEntries - 1; i > -1; i–)
{
if(anEntry.equals(contents[i]))
{
count++;
}
}
return count;
}

public int getFrequencyOf(T anEntry)
{
int i = 0;
int count = 0;
while( i < numberOfEntries)
{
if(anEntry.equals(contents[i]))
{
count++;
}
i++;
}
return count;
}

public int getFrequencyOf(T anEntry)
{
int count = 0;
for(int i = 0; i < numberOfEntries; i++)
{
if(anEntry.equals(contents[i]))
{
count++;
}
}
return count;
}

public int getFrequencyOf(T anEntry)
{
int count = 0;
for(int i = numberOfEntries - 1; i >= 0; i–)
{
if(anEntry.equals(contents[i]))
{
count++;
}
}
return count;
}

A

public int getFrequencyOf(T anEntry)
{
int i = 0;
int count = 0;
while(anEntry.equals(contents[i]))
{
i++;
count++;
}
return numberOfEntries - count;
}

44
Q

package linkedchain;

public class LinkedChain {

private Node head; // Reference to first node
private int numberOfEntries;

public static void main(String[] args) {

  LinkedChain chain = new LinkedChain();
  chain.add(10);
  chain.add(-2);
  chain.add(57);    }

public LinkedChain() {
head = null;
numberOfEntries = 0;
} // end default constructor

public void add(int newEntry) {
// Add to beginning of chain:
Node newNode = new Node(newEntry);
newNode.next = head; // Make new node reference rest of chain
head = newNode; // New node is at beginning of chain
numberOfEntries++;
} // end add

private class Node {
private int data;
private Node next; // Link to next node

  private Node(int dataPortion) {
     this(dataPortion, null);
  } // end constructor

  private Node(int dataPortion, Node nextNode) {
     data = dataPortion;
     next = nextNode;
  } // end constructor    } // end Node }

For this question, refer back to the code in LinkedChain class in the course material What if the line statement

chain.add(40);
was added before the line

chain.add(10);
what would the the order of the integers be starting at the front of the chain?

57, -2, 10, 40

10, -2, 57, 40

40, 10, -2, 57

40, 57, -2, 10

A

57, -2, 10, 40

45
Q

package linkedchain;

public class LinkedChain {

private Node head; // Reference to first node
private int numberOfEntries;

public static void main(String[] args) {

  LinkedChain chain = new LinkedChain();
  chain.add(10);
  chain.add(-2);
  chain.add(57);    }

public LinkedChain() {
head = null;
numberOfEntries = 0;
} // end default constructor

public void add(int newEntry) {
// Add to beginning of chain:
Node newNode = new Node(newEntry);
newNode.next = head; // Make new node reference rest of chain
head = newNode; // New node is at beginning of chain
numberOfEntries++;
} // end add

private class Node {
private int data;
private Node next; // Link to next node

  private Node(int dataPortion) {
     this(dataPortion, null);
  } // end constructor

  private Node(int dataPortion, Node nextNode) {
     data = dataPortion;
     next = nextNode;
  } // end constructor    } // end Node }

For this question, refer back to the code in the LinkedChain class in the course material What if the line statement

chain.add(16);
was added after the line

chain.add(57);
what would the order of the integers be starting at the front of the chain?

16, 10, -2, 57

10, -2, 57, 16

16, 57, -2, 10

57, -2, 10, 16

A

16, 57, -2, 10

46
Q

This is a still image of the concept map for the term “pointers”. You can check the actual concept map on the glossary page.

Which among the following is true?

A pointer is a variable whose value is a default data type

A pointer is not a variable

A pointer is a variable whose value is the address of another variable

None of the above

A

A pointer is a variable whose value is the address of another variable

47
Q

Where does new data get added to this linked implementation of a bag?

Beginning

End

Middle

A

Beginning

48
Q

What are the two fields of a Node?

data and node

data and next

data and null

A

data and next

49
Q

Which of the following is a correct implementation of getFrequencyOf

public int getFrequencyOf(T anEntry)
{
int frequency = 0;

while ((currentNode != null)) {
Node currentNode = firstNode;
if (anEntry.equals(currentNode.getData())) {
frequency++;
} // end if

currentNode = currentNode.getNext();   } // end while

return frequency;
} // end getFrequencyOf

public int getFrequencyOf(T anEntry)
{
int frequency = 0;
Node currentNode = firstNode;
while ((currentNode != null)) {
if (anEntry.equals(currentNode.getData())) {
frequency++;
} // end if

currentNode = currentNode.getNext();   } // end while

return frequency;
} // end getFrequencyOf

public int getFrequencyOf(T anEntry)
{

Node currentNode = firstNode;
while ((currentNode != null)) {
if (anEntry.equals(currentNode.getData())) {
frequency++;
} // end if

currentNode = currentNode.getNext();   } // end while

return frequency;
} // end getFrequencyOf

public int getFrequencyOf(T anEntry)
{
int frequency = 0;
Node currentNode = firstNode;
while ((currentNode != null)) {
if (anEntry.equals(currentNode.getData())) {
frequency++;
} // end if

currentNode++;   } // end while

return frequency;
} // end getFrequencyOf

A

public int getFrequencyOf(T anEntry)
{
int frequency = 0;
Node currentNode = firstNode;
while ((currentNode != null)) {
if (anEntry.equals(currentNode.getData())) {
frequency++;
} // end if

currentNode = currentNode.getNext();   } // end while

return frequency;
} // end getFrequencyOf

50
Q

Which of the following implementations could not be used for contains?

public boolean contains(T anEntry)
{
return getIndexOf(anEntry) > -1;
}

public boolean contains(T anEntry) {

Node currentNode = firstNode;

while (!anEntry.equals(currentNode.getData())) {
currentNode = currentNode.getNext();
} // end while

return true;
} // end contains

public boolean contains(T anEntry)
{
return getFrequencyOf(anEntry) > 0;
}

public boolean contains(T anEntry)
{
boolean found = false;
Node currentNode = firstNode;

while (!found && (currentNode != null)) {
if (anEntry.equals(currentNode.getData()))
found = true;
else
currentNode = currentNode.getNext();
} // end while

return found;
} // end contains

A

public boolean contains(T anEntry) {

Node currentNode = firstNode;

while (!anEntry.equals(currentNode.getData())) {
currentNode = currentNode.getNext();
} // end while

return true;
} // end contains

51
Q

The method remove that has no parameter in the linked implementation

removes the first element in the chain

removes the last element in the chain

none of these answers are correct

A

removes the first element in the chain