Exam Flashcards

1
Q

Is it legal to assign an object to a variable declared to be of the type of one of its superclasses?

A

Yes

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

Is it legal to assign an object to a variable declared to be of the type of one of its subclasses?

A

No

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

Are all methods abstract in an abstract class?

A

No

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

Can an abstract class include a constructor?

A

Yes

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

Can an abstract class be instanstiated?

A

No

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

Can an interface be instanstiated?

A

No

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

Can an interface include a constructor?

A

No

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

Are all methods in an interface abstract?

A

Yes

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

Is it legal to assign an object to a variable declared as the type of its superclass if the superclass is abstract?

A

Yes

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

Is it legal to suppy as a method’s actual argument an object which is a direct or indirect subclass of the type specified by the formal argument?

A

Yes

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

Is it legal to supply as a method’s actual argument an object whose class is a superclass of the formal argument?

A

No

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

Explain the concept of substitutability

A

Where a Java program expects an instance of a particular class, it is legal to substitute an instance of any of its direct or indirect subclasses.

sameColourAs(Amphibion)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q
Frog kermit = new HoverFrog();
((HoverFrog) kermit).up();

What is the result?

A

The HoverFrog referenced by kermit will move up, and will NOT be cast to a HoverFrog reference variable.

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

Frog kermit = new HoverFrog();
HoverFrog h = (HoverFrog) kermit;
h.up();

What is the result?

A

The HoverFrog referenced by kermit will be cast and assigned to the HoverFrog reference variable h.

The HoverFrog now referenced by kermit and h will move up.

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

What is an interface?

A

An interface specifies a list of public abstract methods that a group of unrelated classes must implement so that their instances can receive a common set of messages.

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

Does a subclass of a class that implements an interface inherit the implementation?

A

Yes

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

Can interface methods return values?

A

Yes

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

If varA and varB are two variables, what needs to be true about their types if the statement

varA = varB;

is to compile?

A

If they are of the same type, or the variable on the right is a subtype of the one on the left, the assignment will work without a cast.

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

If varA and varB are two variables, under what circumstances can you cast a reference variable of one type to another type in an assignment?

A

The variable to which the cast is applied (the one on the right) must be of the same type as, or a supertype of, the variable on the left.

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

Explain the concept of polymorphism

A

A polymorphic message is a message understood by more than one class. Each class of object can behave in its own way in response to such a message. This occurs via overriding/interfaces.

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

Give an example of direct interaction between objects

A

frog1.sameColourAs(frog2)

frog1 sends a message to frog2 within the body of the method, which is then used to alter the state of frog1.

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

Give an example of indirect interaction

A

frog1.setPosition(frog2.getPosition());

A third party (e.g. OUWorkspace, coordinating object) is sending a message to frog2 and using the result to alter the state of frog1.

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

Can you use the keyword this in a class method?

A

No

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

Can you use the keyword super in a class method?

A

No

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

Give an example of static binding

A

The class method Collections.sort() can be resolved at compile time because it is not a message and therefore does not have a receiver.

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

Give an example of dynamic binding

A

The instance method anAmphibian.right() cannot be resolved at compile time because it could refer to one of several different right() methods depending on the class of the receiver

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

Are class methods and variables inherited?

A

Yes

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

Can an instance method override an inherited class method?

A

No - compilation error

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

Can an instance method override an inherited instance method?

A

Yes

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

Can a class method override an inherited instance method?

A

No - compilation error

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

Can a class method override an inherited class method?

A

No - it hides the inherited class method, which can still be accessed by qualifiying the method with the superclass name.

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

Is super(); always implied in a constructor?

A

Yes, if there is no explicit super() statement.

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

Is a zero-argument constructor always included by the compiler?

A

No - only when no other constructor is included.

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

Where should static variables be initialised?

A

Upon declaration

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

Where should final variables be initialised?

A

Upon declaration or in the constructor

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

Where should static final variables be initialised?

A

Upon declaration

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

What are the implications for declaring primitive data type variables and reference type variables as final?

A

For primitive data, the value assigned cannot be altered.

For references variables, the reference cannot be altered but the object it references can.

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

Are local variables given default values?

A

No

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

Are instance variables given default values?

A

Yes

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

Are static variables given default values?

A

Yes

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

True or false:

Methods that may throw a checked exception must either handle the exception or declare that it throws an exception

A

True

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

True or false:

Methods that may throw a unchecked exception must either handle the exception or declare that it throws an exception

A

False

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

Which classes of exception are checked?

A

Exception and its subclasses, excluding RuntimeException and its subclasses.

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

Which classes of exception are unchecked?

A

Error and its subclasses

RuntimeException and its subclasses

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

Explain the Design by Contract approach

A

Preconditions and postconditions are established before writing a method. The method is then written to guarantee that if the precondition is met, the postcondition will be guaranteed.

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

What does the Design by Contract approach require to happen if a method’s precondition is not met?

A

Throw an exception

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

How do you throw an exception?

A

throw new IllegalArgumentException(“debit “
+ anAmount + is inappropriate. Balance “
+ this.balance);

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

Write an assert statement that will cause an AssertionError with the argument “oops” if the boolean variable b is not true

A

assert b : “oops”;

49
Q

Assert statements are usually found in what kind of methods?

A

Private helper methods

50
Q

What is the main difference between using an assert statement and throwing an AssertionError or Exception?

A

assert statements are ignored at during the normal running of the program. They are used for testing and documenting assumptions about the program.

51
Q

Do or Don’t?

Use assertions in public methods to check the validity of any arguments received

A

Don’t - instead throw IllegalArgumentsException

52
Q

Do or Don’t?

Use assertions to write code that changes the state of the object

e.g. assert condition : doSomething();

A

Don’t - the behaviour will change when assertions are disabled

53
Q

Do or Don’t?

Use assertions in private helper methods to check the validity of any arguments received

A

Do

54
Q

Do or Don’t?

Use assertions in private methods to test your assumptions about the state of the object receiving the message (this)

A

Do

55
Q

Do or Don’t?

Throw an IllegalArgumentsException in a private method

A

Don’t - we should be in control of any arguments passed to a private method so we should be confident that it will not receive any illegal arguments

56
Q

True or false?

An assert statement must be placed within a try-catch block because it can throw an AssertionError

A

False - AssertionError is unchecked. In fact, such errors should not be caught.

57
Q

How do you declare an array variable?

A

String[ ] names;

Frog[ ] frogPond;

58
Q

How do you create an empty array object?

A

(String[ ] names;)

names = new String[7];

59
Q

How do you find the size of an array?

A

anArray.length

60
Q

Are array components given default values?

A

Yes

61
Q

How do you declare and initialise an array in one line?

A
String[ ] names = {"Jay", "John", "Ali", "Alan"};
Frog[ ] frogPond = {new Frog(), new Frog()};
62
Q

How do you declare and initialise an array on separate lines?

A

Frog[ ] frogPond;

frogPond = new Frog[ ] {new Frog(), new Frog()};

63
Q

How do you access an array element?

A

anArray[5]

64
Q

How do you change the colour of a Frog object stored in an array of Frog objects?

A

frogPond[5].setColour(OUColour.RED);

65
Q

How do you use a for loop to iterate through an array?

A

for (int i = 0; i

66
Q

Can you iterate through an array using a for-each loop?

A

Yes

67
Q

What is the main limitation of for-each loops?

A

It cannot be used to assign values to components.

68
Q

How do you search for a value in an array using a loop?

A

String searchTerm = “term”;
int i = 0; boolean found = false;
while ((i

69
Q

Can arrays be sorted?

A

Yes, provided they are of a type with a natural ordering, by using the Arrays class method: Arrays.sort()

70
Q

How do you search for a value in an array using a Class method?

A

Arrays.sort(myArray);

Arrays.binarySearch(myArray, 9);
Arrays.binarySearch(myArray, “Matthew”);

71
Q

How do you get the size of a String?

A

aString.length()

72
Q

What is string interning?

A

Each time a string literal is created the Java compiler looks to see if it already exists. If it does, it simply creates a new reference to the existing String object rather than creating a new one.

73
Q

What is the difference between the size() and capacity() of a StringBuilder object?

A

The size() is the number of characters it currently holds. The capacity() is the total number of characters it has space to hold.

74
Q

How do you find the size of a Set/Map/List?

A

myCollection.size()

75
Q
What are the wrapper classes for:
int
long
float
double
short
byte
char
boolean
A
Integer
Long
Float
Double
Short
Byte
Character
Boolean
76
Q

What is auto-boxing and auto-unboxing?

A

Java uses auto-boxing and auto-unboxing to automate the process of wrapping primitive data into a wrapper class (e.g. int into Integer) and unwrapping it back to primitive data. This allows us to perform arithmetic operations on objects stored in collections and add primitive data to a collection without having to handle the wrapping and unwrapping manually.

77
Q

What is the effect of this code?

Map m = new Map();

m. put(1, “A”);
m. put(1, “B”);

A

m has one entry: (1, “B”).

78
Q

How do you iterate through the key-value pairs in a Map?

e.g. Map cities

A
for (String eachCity : cities.keySet())
{
  System.out.println(eachCity 
    \+ this.cities.get(eachCity));
}
79
Q

How do you iterate through the keys in a Map?

e.g. Map cities

A

for (String eachCity : cities.keySet())
{
System.out.println(eachCity);
}

80
Q

How do you iterate through the values in a Map?

e.g. Map cities

A

int total = 0;

for (Integer eachPopulation : cities.values())
{
total = total + eachPopulation;
}

81
Q

What happens if you remove an entry from the set returned by keySet() or values()?

A

The key-value pair will be removed from the Map

82
Q

How do you obtain the union of two sets?

A

Set Union = new HashSet(set1);

union.addAll(set2);

83
Q

How do you obtain the intersection of two sets?

A

Set intersection = new HashSet(set1);

intersection.retainAll(set2);

84
Q

How do you obtain the difference between two sets?

A

Set differenceA = new HashSet(set1);

differenceA.removeAll(set2);

Set differenceB = new HashSet(set2);

differenceB.removeAll(set1);

85
Q

What are the features of a List?

Fixed-size/Dynamic
Primitive/Reference values
Ordering
Indexing
Duplicates
A
Dynamic size
Stores reference values
Ordered by index (can be sorted)
Indexable
Duplicates allowed
86
Q

Arrays consist of several ______, each of which holds an ______.

A

Arrays consist of several COMPONENTS, each of which holds an ELEMENT.

88
Q

What are the features of a Map?

Fixed-size/Dynamic
Primitive/Reference values
Ordering
Indexing
Duplicates
A
Dynamic size
Stores reference values
Not ordered (SortedMap is)
Keys-values
No duplicate keys allowed
Duplicate values allowed
89
Q

How do you insert an element to a certain position in a List?

A

myList.add(5, “Element Six”);

90
Q

How do you access an element in a List?

A

myList.get(5)

91
Q

How do you search for an element in a list?

A

myList.indexOf(“Matthew”);

92
Q

How do you replace an element of a List?

A

myList.set(5, “Matthew”);

93
Q

How do you convert an array to a List?

A

String[ ] sArray = {“The”, “cat”, “sat”};

List stringList = Arrays.asList(sArray);

94
Q

How do you swap two elements in a List?

A

Collections.swap(herbList, 2, 4);

95
Q

How do you find a sublist in a List?

A

Collections.indexOfSublist(myList, subList)

96
Q

How do you find the minimum and maximum values in a List?

A

String maxScore = Collections.max(scoreList);

String minScore = Collections.min(scoreList);

97
Q

How do you implement Comparable?

A

public class Test implements Comparable

public int compareTo(Test obj)
{
return this.getAttribute() - obj.getAttribute();
}

98
Q

How do you override the equals() method?

A
public boolean equals(Object obj)
{
  RowOfStars row = (RowOfStars) obj;
  return this.getLength() == row.getLength();
}
99
Q

How do you write a hashCode method?

A

public int hashCode()
{
return this.getLength()
}

To match equals()

109
Q

How do you read from a file using BufferedReader?

A

String pathname = OUFileChooser.getFilename();

File aFile = new File(pathname);

BufferedReader bufferedFileReader = null;

try
{
  String currentLine;
  bufferedFileReader = new BufferedReader(new FileReader(aFile));

currentLine = bufferedFileReader.readLine();

  while (currentLine != null)
  {
    System.out.println(currentLine);
    currentLine = bufferedFileReader.readLine();
  }
}
catch (Exception anException)
{
  System.out.println("Error: " + anException);
}
finally
{
  try
  {
    bufferedFileReader.close();
  }
  catch (Exception anException)
  {
    System.out.println("Error: " + anException);
  }
}
110
Q

How do you create an object from a text file using a Scanner?

e.g. an Account object

A

String pathname = OUFileChooser.getFilename();

File aFile = new File(pathname);

Scanner bufferedScanner = null;
Set accountSet = new HashSet();
try
{
  String accountHolder;
  String accountNumber;
  double accountBalance;
  Scanner lineScanner;
  String currentLine;
  bufferedScanner = new Scanner(new BufferedReader(new FileReader(aFile)));
  while (bufferedScanner.hasNextLine())
  {
    currentLine = bufferedScanner.nextLine();
    lineScanner = new Scanner(currentLine);
    lineScanner.useDelimiter(",");
    accountHolder = lineScanner.next();
    accountNumber = lineScanner.next();
    accountBalance = lineScanner.nextDouble();
    accountSet.add(new Account(accountHolder, accountNumber, accountBalance));
  }
}
catch (Exception anException)
{
  System.out.println("Error: " + anException);
}
finally
{
  try
  {
    bufferedScanner.close();
  }
  catch (Exception anException)
  {
    System.out.println("Error: " + anException);
  }
}

return accountSet

111
Q

What are the features of a Set?

Fixed-size/Dynamic
Primitive/Reference values
Ordering
Indexing
Duplicates
A
Dynamic size
Stores reference values
Not ordered (SortedSet is)
Not indexed
No duplicates
129
Q

What are the features of an array?

Fixed-size/Dynamic
Primitive/Reference values
Ordering
Indexing
Duplicates
A
Fixed-size
Stores primitive or reference values
Ordered by index
Indexable
Duplicates allowed
130
Q

What is a stream?

A

A stream is the object we use to link a data source to a date sink, enabling data to be transferred from the source to the sink.

131
Q

What do objects of the File class represent?

A

File objects represent the name of a particular file or folder in a platform-independent way

132
Q

How do you write a platform-dependent line break?

A

System.getProperty(“line.separator”)

133
Q

How do write to a file using FileWriter?

A

OUFileChooser.setPath(“C:/Users/Kyuzo/Documents”);

String pathname = OUFileChooser.getFilename();

File aFile = new File(pathname);
File aFileWriter = null:
try
{
  aFileWriter = new FileWriter(aFile);
  aFileWriter.write("To be or not to be");
}
catch (Exception anException)
{
  System.out.println("Error: " + anException);
}
finally
{
  try
  {
    aFileWriter.close();
  }
  catch (Exception anException)
  {
    System.out.println("Error: " + anException);
  }
}
134
Q

How do you append a file using FileWriter?

A

FileWriter aFileWriter = new FileWriter(aFile, true);

135
Q

How do you read from a file using FileReader?

A

String pathname = OUFileChooser.getFilename();

File aFile = new File(pathname);
FileReader aFileReader = null;
try
{
  aFileReader = new FileReader(aFile);

int ch = aFileReader.read();

  while (ch != -1)
  {
    System.out.print((char) ch);
    ch = aFileReader.read();
   }
}
catch (Exception anException)
{
  System.out.println("Error: " + anException);
}
finally
{
  try
  {
    aFileWriter.close();
  }
  catch (Exception anException)
  {
    System.out.println("Error: " + anException);
  }
}
136
Q

How do you write to a file using BufferedWriter?

A

String pathname = OUFileChooser.getFilename();

File aFile = new File(pathname);

BufferedWriter bufferedFileWriter = null;

try
{
  bufferedFileWriter = new BufferedWriter(new FileWriter(aFile));
  bufferedFileWriter.write("Writing to a file");
  bufferedFileWriter.newLine();
  bufferedFileWriter.write("More text");
}
catch (Exception anException)
{
  System.out.println("Error: " + anException);
}
finally
{
  try
  {
    bufferedFileWriter.close();
  }
  catch (Exception anException)
  {
    System.out.println("Error: " + anException);
  }
}
137
Q

Why should a BufferedWriter variable be declared and assigned null before the try block in which it is assigned a BufferedWriter object?

A

So that it is accessible from the scope of the finally block, where it must be closed.

138
Q

What is a variable?

A

A variable is a named block of the computer’s memory that can hold either a value of some primitive type or the address of an object.

139
Q

What is the difference between a reference type variable and a value type variable?

A

A reference type variable holds the address of an object, whereas a value type variable holds a value of some primitive data type.

140
Q

What does the pseudo-variable ‘this’ represent?

A

‘this’ is used within a method to reference the receiver of the message that activated the method.

141
Q

What is a class?

A

A class is a template that serves to describe all instances of that class. It defines the attributes and protocol for objects belonging to it.

142
Q

What is a subclass?

A

A subclass is a class defined in terms of an existing class (its superclass). A subclass is used to create a more specialised version of its superclass, and might include extra variables or methods.

143
Q

Explain the concept of inheritance

A

In a class hierarchy, classes that are lower in the hierarchy (subclasses) inherit all of the methods and variables from classes higher in the hierarchy (their direct and indirect superclasses).

144
Q

Explain the concept of data hiding

A

Java classes can use access modifiers to restrict access to its members (methods and variables), thereby hiding its inner workings and forcing objects of other classes to interact via a limited set of methods.

145
Q

Explain the concept of encapsulation

A

Encapsulation is the bundling together of state and behaviour. Classes achieve this by defining the variables (state) and methods (behaviour) that each of its objects will consist of.