1/47
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced |
---|
No study sessions yet.
What are enums and when should you use them?
An enumerated type is a special sort of class with fields consisting of a fixed set of constants.
You should use enum types any time you need to represent a fixed set of constants ie you know all possible values at compile time.
To make code more readable and less error-prone than using plain strings or integers.
When you want to leverage features like switch statements, methods, or fields associated with constant values.
What are the benefits of enums?
Enums improve type safety.
Can be easily used in a switch statement.
Can be traversed.
Enums are more readable than integers and provide a way to group related constants, improving maintainability and clarity in code.
Enums can have fields, constructors and methods.
Note: cannot extend any other class as it internally extends the enum class but can implement interfaces.
How to define a basic enum?
public enum Direction {
NORTH, EAST, SOUTH, WEST;
}
Use an enum in a switch statement?
public void move(Direction d) {
switch (d) {
case UP : y += 1; break;
case DOWN : y -= 1; break;
case LEFT : x -= 1; break;
case RIGHT : x += 1; break;
}
}
Define a direction enum with methods and fields.
public enum Direction {
UP(0, 1), DOWN(0, -1), LEFT(-1, 0), RIGHT(1, 0);
private final int x, y;
private Direction(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
When does the enum constructor get called?
During runtime for each constant of the enum.
What is an iterator?
An iterator enables you to cycle through any collection to obtain or remove elements without exposing the underlying structure of the collection. It provides a standard way to traverse a collection sequentially, allowing the user to access each element while providing the option to modify the collection during iteration.
What are the iterator methods?
hasNext() returns true if the iterator has more elements.
next() returns the element and moves the cursor pointer to the next.
remove() returns the last elements returned by the iterator.
Use a for each loop to traverse through a list.
public void moveList(List<Direction> ds) {
for (Direction d : ds) {
move(d);
}
}
Use an iterator to traverse through a list.
public void moveList(List<Direction> ds) {
Iterator<Direction> it = ds.iterator();
while (it.hasNext()) {
Direction d = it.next();
move(d);
}
}
Create a JUnit Test for the moveList() method.
@Test
publicvoid testMoveList() {
List directions = Arrays.asList(Direction.UP, Direction.UP, Direction. LEFT);
Point p = new Point(0, 0);
p.moveList(directions);
assertEquals(2, p.getY());
assertEquals(-1, p.getX());
}
What edge cases should be tested in JUnit tests?
Edge cases such as an empty list, a list with null values, or a list containing only one element should be tested in JUnit tests. These scenarios help ensure that the method can handle unexpected or extreme input. Or if the method handles values between a certain range, then values close and on the range should be tested - ie testing boundary cases.
What is unit testing?
Unit testing is the testing of an individual unit or group of related units. Unit testing is usually at the function or method level. It is often used to test that the unit implementing is producing expected output against given input. It allows developers to catch bugs early in the development process and ensures that changes do not introduce new errors.
What is a set data structure?
A set data structure is a collection that contains no duplicate elements.
What is the differences between a HashSet and TreeSet?
A HashSet and TreeSet are both implementations of the Java Set interface. A HashSet is backed by a HashMap so uses a HashCode to store each element. However it does not maintain insertion order or ascending value order. Whereas a TreeSet implements a Red-Black tree (self-balancing binary search tree) so the values are stored in ascending order. A HashSet has O(1) for inserting, removing, and retrieval whereas a TreeSet has O(logn) tree complexity. But a TreeSet is beneficial when the elements are required to be sorted.
How does the respective iterators differ for a TreeSet and a HashSet?
The iterators for a TreeSet return elements in ascending order due to its sorted nature, while the iterators for a HashSet return elements in an arbitrary order, as it does not maintain any specific order.
Can a HashSet be converted to a TreeSet and a TreeSet to a HashSet?
A TreeSet can be easily converted into a HashSet as all that is required is for the elements to be hashtable. Whereas a TreeSet requires the elements to be comparable so if the HashSet does not have comparable elements then it will not be able to be converted into a TreeSet unless a suitable comparator is provided.
What is the Waterfall software process?
The Waterfall software process is a linear and sequential approach to software development where each phase must be completed before the next begins. It typically includes stages such as requirements analysis, system design, implementation, testing, deployment, and maintenance. Each phase is distinct and must be thoroughly finished before the next starts, emphasizing documentation and planning.
What is the Spiral software process?
Demonstrates incremental development and delivery, iteration, evaluation and feedback.
Focuses on prototyping and formalises and evolutionary approach to software development.
Includes risk analysis during each cycle, and user involvement throughout the development process. Requirements are continually validated and prioritised.
Project manager can terminate project at any point, and still ensure the customer gets some benefit from each increment.
Advantages of waterfall method
The advantages of the waterfall method include clear project milestones, thorough documentation, and straightforward project management due to its linear structure. It is also beneficial for projects with well-defined requirements, allowing for easier progress tracking and accountability.
Disadvantages of the waterfall method.
The waterfall lifecycle means that some high-risk and difficult elements occur towards the end.
It’s usually late in the project before a working version is available for user to test and criticise.
The earlier an issue is identified, the smaller the cost.
Difficult to respond to changing customer needs.
What is Test-Driven Development (TDD)?
Works by building tests first. Aims for bug free code at all times.
Read, understand, and process the feature or bug request.
Translate requirements to a unit test. The unit test will run and fail as no code is implemented yet.
Write and implement the code that fulfils the requirement. Run all tests and they should pass, if not repeat this step
Clean up your code by refactoring.
Rinse, lather, and repeat.
What is unit testing?
Unit testing is the testing of an individual unit or group of related units. Unit testing is usually at the function or method level.
It is often used by the programmer to test that the unit he/she has implemented is producing expected output against given input.
What are unit testing frameworks?
Unit testing frameworks are tools that help developers write, organize, and run automated tests for individual units (usually methods or classes) of code. JUnit is an example of a unit testing framework. JUnit provides method annotations like @Test and assertions (assertEquals) to define expected behaviour. This separates test from production code and allows individual or groups of tests to be run at once.
What is a checked Exception? And provide examples.
A checked exception also known as compile-time exception is named as such as the compiler checks to see if any of these exceptions occur. If so, the program will not compile unless the programmer has handled the exception. All subclasses of Exception (except RuntimeException and their subclasses) are checked exceptions. Such as FileNotFoundException and IOException.
What is an unchecked Exception? And provide examples.
Also known as runtime Exceptions, these are only known at run time. They are not checked at compile time. If these exceptions are not handled properly this will cause the program to crash if the exception is thrown. Most runtime exceptions come from a problem in your code therefore, they should not usually be caught. Any exceptions that are a subclass of RuntimeException is an unchecked exception, such as ArrayIndexOutOfBoundsException or NullPointerException.
How can exceptions ben handled?
There are two ways to handle exceptions:
Surround the code with try, catch, finally statements to handle the exception.
Throw the exception from the method this method up the stack but will need to be handled at a higher level.
What is the finally keyword and when should it be used?
Defines a block of code used after a try-catch block. This is optional but if used will run after completion of the try-block, irrespective whether and exception was thrown or not. Each try-block can only have 1 finally block and is typically used for code cleanup, closing files or releasing resources.
Give an example of using the finally keyword.
FileReader r;
try {
r = new FileReader(“data.txt”);
}
catch (IOException e) {
System.out.println(e.getMessage());
}
finally {
if (r ≠null) {
try {
r.close();
}
catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
ArrayLists and Uses
Ordered based on insertion order. List stored in dynamic array. Provides very fast access by index. ArrayLists are more efficient for read only operations with fixed length sequences and is not so efficient if a lot of alteration is required.
LinkedLists and Uses
Elements in the structure is linked with pointers. Good for frequency modification to the data structure such as removing and adding. Poor at finding the nth index or quick lookup.
What is a design pattern?
A general repeatable solution to a commonly occurring problem in software design.
It is not a finished design which can be transformed directly into code.
It is a description or template for how to solve a problem that can be used in many different situations.
What are the advantages of design patterns?
Avoid re-inventing the wheel.
Maximise code reuse.
Increase cohesion.
Reduce coupling.
Provide a common vocabulary of solutions for coders and architects familiar with them.
They promote best practices in software engineering and facilitate easier communication between developers.
What issues did Agile development solve?
Problem:
Rigid requirements
Late product delivery
Poor stakeholder / customer involvement
Heavy documentation
Siloed teams
Solutions:
Flexible and adaptive
Early and continuous delivery
Frequent feedback and collaboration
Focus on working software
Cross-functional and communicate teams
What is the thread life cycle? And how does the thread go between states?
How do I start a thread using the Thread superclass?
To start a thread using the Thread superclass, create a subclass of Thread, override its run() method with the code to be executed, and then instantiate the subclass and call its start() method to initiate the thread execution. The class with the overridden run() method must extend the Thread class.
How do I start a thread from an object that already extends a different class?
To start a thread from an object that already extends a different class, implement the Runnable interface, override the run() method, then instantiate a Thread object with the Runnable instance and call its start() method.
MyThread t = new MyThread();
Thread thread = new Thread(t);
thread.start();
How to prevent interference in shared resources by threads?
Make the method header synchronized. It is generally impossible to predict when a particular thread will execute a statement. This means that two or more threads can interfere with each other. The synchronized keyword can be used on methods or code sections to prevent interference from occurring. Only one thread may enter an object’s synchronized regions at any one time.
Why is the MVC pattern used in GUI based applications?
The MVC (Model-View-Controller) pattern is typically used in GUI applications as it splits the code up into three components; the Model (Data and Logic), View (UI), Controller (User interaction).
The design pattern provides:
Clarity in design as different components are separated
Low coupling between different components - different developers can work easily on different sections
Extensibility - controllers and views can be added/removed without affecting the model
Modularity - allows for different components to be swapped out or different view acting on the same model.
What are the main components of the MVC pattern and how are they coupled together?
MVC consists of three modules: Model, View, and Controller. It uses two other design patterns to aid communication between the modules so is sometimes referred as a compound design pattern.
The observer pattern is the glue between model and view.
The strategy pattern is the glue between view and controller.
What are different JUnit test annotations?
@Test, @RepeatedTest, @ParameterizedTest - to declare tests.
@BeforeEach, @BeforeAll, @AfterEach, @AfterAll - test life cycle annotations.
Different JUnit Assertions?
assertEquals(expected, actual, message)
assertThrows()
assertTrue()
assertFalse()
What is defensive programming?
Defensive programming is a methodology aimed at ensuring software remains functional under unforeseen circumstances. It involves writing code that anticipates potential errors or misuse and includes safeguards to prevent or minimize issues.
External causes: errors by interactions with users, network, file system etc…
Internal causes: programmer errors, JVM errors, etc…
Create a custom exception.
public class InvalidFractionException extends Exception {
public InvalidFractionException(String msg) {
super(msg);
}
}
Throw a checked exception in a constructor.
public Fraction(int n, int d) throws InvalidFractionException {
if (d==0) {
throw new InvalidFractionException(“Denominator cannot equal 0”);
}
…
}
What keywords are used for exceptions?
throw keyword is used to throw an exception.
throws keyword declare the exceptions that may be thrown by a method.
try keyword defines block that contains statement that might throw an exception.
catch keyword defines block that handles the exception thrown by the try vlock.
finally keyword (optional) is always executed, used for clean-up code.
List vs Set vs Map
List is an ordered collection (ArrayList or LinkedList)
Set is a collection that contains no duplicate elements (HashSet, LinkedHashSet, TreeSet)
Map is a collection of unique key/value pairs (HashMap, LinkedHashMap, TreeMap)