Exam Flashcards
Is it legal to assign an object to a variable declared to be of the type of one of its superclasses?
Yes
Is it legal to assign an object to a variable declared to be of the type of one of its subclasses?
No
Are all methods abstract in an abstract class?
No
Can an abstract class include a constructor?
Yes
Can an abstract class be instanstiated?
No
Can an interface be instanstiated?
No
Can an interface include a constructor?
No
Are all methods in an interface abstract?
Yes
Is it legal to assign an object to a variable declared as the type of its superclass if the superclass is abstract?
Yes
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?
Yes
Is it legal to supply as a method’s actual argument an object whose class is a superclass of the formal argument?
No
Explain the concept of substitutability
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)
Frog kermit = new HoverFrog(); ((HoverFrog) kermit).up();
What is the result?
The HoverFrog referenced by kermit will move up, and will NOT be cast to a HoverFrog reference variable.
Frog kermit = new HoverFrog();
HoverFrog h = (HoverFrog) kermit;
h.up();
What is the result?
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.
What is an interface?
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.
Does a subclass of a class that implements an interface inherit the implementation?
Yes
Can interface methods return values?
Yes
If varA and varB are two variables, what needs to be true about their types if the statement
varA = varB;
is to compile?
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.
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?
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.
Explain the concept of polymorphism
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.
Give an example of direct interaction between objects
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.
Give an example of indirect interaction
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.
Can you use the keyword this in a class method?
No
Can you use the keyword super in a class method?
No
Give an example of static binding
The class method Collections.sort() can be resolved at compile time because it is not a message and therefore does not have a receiver.
Give an example of dynamic binding
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
Are class methods and variables inherited?
Yes
Can an instance method override an inherited class method?
No - compilation error
Can an instance method override an inherited instance method?
Yes
Can a class method override an inherited instance method?
No - compilation error
Can a class method override an inherited class method?
No - it hides the inherited class method, which can still be accessed by qualifiying the method with the superclass name.
Is super(); always implied in a constructor?
Yes, if there is no explicit super() statement.
Is a zero-argument constructor always included by the compiler?
No - only when no other constructor is included.
Where should static variables be initialised?
Upon declaration
Where should final variables be initialised?
Upon declaration or in the constructor
Where should static final variables be initialised?
Upon declaration
What are the implications for declaring primitive data type variables and reference type variables as final?
For primitive data, the value assigned cannot be altered.
For references variables, the reference cannot be altered but the object it references can.
Are local variables given default values?
No
Are instance variables given default values?
Yes
Are static variables given default values?
Yes
True or false:
Methods that may throw a checked exception must either handle the exception or declare that it throws an exception
True
True or false:
Methods that may throw a unchecked exception must either handle the exception or declare that it throws an exception
False
Which classes of exception are checked?
Exception and its subclasses, excluding RuntimeException and its subclasses.
Which classes of exception are unchecked?
Error and its subclasses
RuntimeException and its subclasses
Explain the Design by Contract approach
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.
What does the Design by Contract approach require to happen if a method’s precondition is not met?
Throw an exception
How do you throw an exception?
throw new IllegalArgumentException(“debit “
+ anAmount + is inappropriate. Balance “
+ this.balance);
Write an assert statement that will cause an AssertionError with the argument “oops” if the boolean variable b is not true
assert b : “oops”;
Assert statements are usually found in what kind of methods?
Private helper methods
What is the main difference between using an assert statement and throwing an AssertionError or Exception?
assert statements are ignored at during the normal running of the program. They are used for testing and documenting assumptions about the program.
Do or Don’t?
Use assertions in public methods to check the validity of any arguments received
Don’t - instead throw IllegalArgumentsException
Do or Don’t?
Use assertions to write code that changes the state of the object
e.g. assert condition : doSomething();
Don’t - the behaviour will change when assertions are disabled
Do or Don’t?
Use assertions in private helper methods to check the validity of any arguments received
Do
Do or Don’t?
Use assertions in private methods to test your assumptions about the state of the object receiving the message (this)
Do
Do or Don’t?
Throw an IllegalArgumentsException in a private method
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
True or false?
An assert statement must be placed within a try-catch block because it can throw an AssertionError
False - AssertionError is unchecked. In fact, such errors should not be caught.
How do you declare an array variable?
String[ ] names;
Frog[ ] frogPond;
How do you create an empty array object?
(String[ ] names;)
names = new String[7];
How do you find the size of an array?
anArray.length
Are array components given default values?
Yes
How do you declare and initialise an array in one line?
String[ ] names = {"Jay", "John", "Ali", "Alan"}; Frog[ ] frogPond = {new Frog(), new Frog()};
How do you declare and initialise an array on separate lines?
Frog[ ] frogPond;
…
frogPond = new Frog[ ] {new Frog(), new Frog()};
How do you access an array element?
anArray[5]
How do you change the colour of a Frog object stored in an array of Frog objects?
frogPond[5].setColour(OUColour.RED);
How do you use a for loop to iterate through an array?
for (int i = 0; i
Can you iterate through an array using a for-each loop?
Yes
What is the main limitation of for-each loops?
It cannot be used to assign values to components.
How do you search for a value in an array using a loop?
String searchTerm = “term”;
int i = 0; boolean found = false;
while ((i
Can arrays be sorted?
Yes, provided they are of a type with a natural ordering, by using the Arrays class method: Arrays.sort()
How do you search for a value in an array using a Class method?
Arrays.sort(myArray);
Arrays.binarySearch(myArray, 9);
Arrays.binarySearch(myArray, “Matthew”);
How do you get the size of a String?
aString.length()
What is string interning?
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.
What is the difference between the size() and capacity() of a StringBuilder object?
The size() is the number of characters it currently holds. The capacity() is the total number of characters it has space to hold.
How do you find the size of a Set/Map/List?
myCollection.size()
What are the wrapper classes for: int long float double short byte char boolean
Integer Long Float Double Short Byte Character Boolean
What is auto-boxing and auto-unboxing?
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.
What is the effect of this code?
Map m = new Map();
m. put(1, “A”);
m. put(1, “B”);
m has one entry: (1, “B”).
How do you iterate through the key-value pairs in a Map?
e.g. Map cities
for (String eachCity : cities.keySet()) { System.out.println(eachCity \+ this.cities.get(eachCity)); }
How do you iterate through the keys in a Map?
e.g. Map cities
for (String eachCity : cities.keySet())
{
System.out.println(eachCity);
}
How do you iterate through the values in a Map?
e.g. Map cities
int total = 0;
for (Integer eachPopulation : cities.values())
{
total = total + eachPopulation;
}
What happens if you remove an entry from the set returned by keySet() or values()?
The key-value pair will be removed from the Map
How do you obtain the union of two sets?
Set Union = new HashSet(set1);
union.addAll(set2);
How do you obtain the intersection of two sets?
Set intersection = new HashSet(set1);
intersection.retainAll(set2);
How do you obtain the difference between two sets?
Set differenceA = new HashSet(set1);
differenceA.removeAll(set2);
Set differenceB = new HashSet(set2);
differenceB.removeAll(set1);
What are the features of a List?
Fixed-size/Dynamic Primitive/Reference values Ordering Indexing Duplicates
Dynamic size Stores reference values Ordered by index (can be sorted) Indexable Duplicates allowed
Arrays consist of several ______, each of which holds an ______.
Arrays consist of several COMPONENTS, each of which holds an ELEMENT.
What are the features of a Map?
Fixed-size/Dynamic Primitive/Reference values Ordering Indexing Duplicates
Dynamic size Stores reference values Not ordered (SortedMap is) Keys-values No duplicate keys allowed Duplicate values allowed
How do you insert an element to a certain position in a List?
myList.add(5, “Element Six”);
How do you access an element in a List?
myList.get(5)
How do you search for an element in a list?
myList.indexOf(“Matthew”);
How do you replace an element of a List?
myList.set(5, “Matthew”);
How do you convert an array to a List?
String[ ] sArray = {“The”, “cat”, “sat”};
List stringList = Arrays.asList(sArray);
How do you swap two elements in a List?
Collections.swap(herbList, 2, 4);
How do you find a sublist in a List?
Collections.indexOfSublist(myList, subList)
How do you find the minimum and maximum values in a List?
String maxScore = Collections.max(scoreList);
String minScore = Collections.min(scoreList);
How do you implement Comparable?
public class Test implements Comparable
…
public int compareTo(Test obj)
{
return this.getAttribute() - obj.getAttribute();
}
How do you override the equals() method?
public boolean equals(Object obj) { RowOfStars row = (RowOfStars) obj; return this.getLength() == row.getLength(); }
How do you write a hashCode method?
public int hashCode()
{
return this.getLength()
}
To match equals()
How do you read from a file using BufferedReader?
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); } }
How do you create an object from a text file using a Scanner?
e.g. an Account object
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
What are the features of a Set?
Fixed-size/Dynamic Primitive/Reference values Ordering Indexing Duplicates
Dynamic size Stores reference values Not ordered (SortedSet is) Not indexed No duplicates
What are the features of an array?
Fixed-size/Dynamic Primitive/Reference values Ordering Indexing Duplicates
Fixed-size Stores primitive or reference values Ordered by index Indexable Duplicates allowed
What is a stream?
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.
What do objects of the File class represent?
File objects represent the name of a particular file or folder in a platform-independent way
How do you write a platform-dependent line break?
System.getProperty(“line.separator”)
How do write to a file using FileWriter?
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); } }
How do you append a file using FileWriter?
FileWriter aFileWriter = new FileWriter(aFile, true);
How do you read from a file using FileReader?
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); } }
How do you write to a file using BufferedWriter?
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); } }
Why should a BufferedWriter variable be declared and assigned null before the try block in which it is assigned a BufferedWriter object?
So that it is accessible from the scope of the finally block, where it must be closed.
What is a variable?
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.
What is the difference between a reference type variable and a value type variable?
A reference type variable holds the address of an object, whereas a value type variable holds a value of some primitive data type.
What does the pseudo-variable ‘this’ represent?
‘this’ is used within a method to reference the receiver of the message that activated the method.
What is a class?
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.
What is a subclass?
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.
Explain the concept of inheritance
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).
Explain the concept of data hiding
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.
Explain the concept of encapsulation
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.