Week 3 + Week 2 and 1 Review Flashcards
What is a generic type?
A generic class or interface that is parameterized over types.
Why use Generics?
Generics enable types (classes and interfaces) to be parameters when defining classes, interfaces, and methods.
Two types of generics? What does each do?
Generic method - introduce their own type parameters.
Generic class -
What is a generic method?
Exactly like a normal method but a generic method has type parameters that are cited by actual type.
Benefits of generic code over non-generic?
- Stronger type checks at compile time. A java compiler applies strong type checking to generic code and issues errors if the code violates type safety.
- Elimination of casts.
What are generics commonly used with?
Collections.
What is a generic called when declared on a class?
Generic type.
Why are generics useful?
Because it can help you to restrict a class to only accept objects of a given type and the compiler will prevent you from using any other type.
Why would the following code benefit from generics? How would you implement that code?
List names = new ArrayList();
names. add(“Alice”);
name. add(new Object());
In this code you would have to hope that other developers would know to use a certain data type. Generics would make it so the developer can only use objects of a given type.
List names = new ArrayList<>();
names. add(“Alice”);
names. add(new Object());
What is the Collections Framework?
A set of classes and interfaces that implement commonly used data structures.
What is a collection?
A single object which acts as a container for other objects.
Are collections iterable?
yes.
Main difference between Collection and Map?
Collection’s are iterable, maps are not.
Three interfaces derived from the Collection interface?
List.
Queue.
Set.
Classes derived from the List interface?
ArrayList.
Vector.
LinkedList.
Classes derived from the Queue interface?
LinkedList.
Priority Queue.
Classes derived from the Set interface?
Hash Set.
Linked Hash Set.
What is a List in Java?
A collection that is ordered and preserves the ordered in which elements are inserted into the list.
What is a Vector?
An older class which implements List.
A thread safe implementation of an ArrayList.
Vector.
What should you use for implementing a stack?
ArrayDeque.
ArrayList(class) implements _______ which extends _______.
List (interface)
Collection
Set Extends _______ which Extends ________ which Implements ________.
Sorted Set.
Navigable Set.
Treeset.
What is the Set interface?
an unordered collection of objects in which duplicate values cannot be stored.
How can I make the following code generic?
public class Printer { }
Add the type parameter after the class name.
public class Printer { }
How can I make the following code print an Integer generic type, assume Printer is generic.
Printer printer = new Printer (5);
printer.print();
You need to specify the type.
Printer printer = new Printer<>(5);
printer.print();
Generics work with primitive types and wrapper class objects.
False. Generics don’t work with primitive types.
Find the error in the following code.
Printer doublePrinter = new Printer<>(“Hello”);
doublePrinter.print();
The generic type is asking for a double (), but we attempted to print out a string ( (“Hello”) ).
Where is the error in the following code?
ArrayList cats = new ArrayList<>();
cats. add(new Cat());
cats. add(new Dog());
The ArrayList which is set to is trying to add Dog.
Which package is List found in?
java.util
Which interface does List inherit?
Collection
What are the four implementation classes of List interface?
ArrayList.
LinkedList.
Stack.
Vector.
Declare an array of the names of 4 friends. Call it friendsArray.
String[] friendsArray = new String[4];
Declare an array of your friends with the names… John, Steph, Sam, Amy. Call it friendsArray
String[] friendsArray = {“John”, “Steph”, “Sam”, “Amy”};
Declare an ArrayList with reference name friendsArrayList.
ArrayList friendsArrayList = new ArrayList<>();
What is the import for ArrayList?
java.util.ArrayList
Which have a fixed size, Array or ArrayList? or neither? or Both?
Array’s have a fixed size.
Declare an ArrayList called friendsArrayList that holds the values John, Chris, Eric, and Luke.
ArrayList friendsArrayList = new ArrayList<>(Arrays.asList(“John”, “Chris”, “Eric”, “Luke” ));
How can you print out “Steph” from the Array?
String[] friendsArray = {“John”, “Steph”, “Sam”, “Amy”};
System.out.println(friendsArray[1]);
How can you print out “Eric” from the following:
ArrayList friendsArrayList = new ArrayList<>(Arrays.asList(“John”, “Chris”, “Eric”, “Luke” ));
System.out.println(friendsArrayList.get(2));
How would I get the length of an Array called friendsArray? Show code.
System.out.println(friendsArray.length);
How would I get the length of an ArrayList called friendsArrayList? Show code.
System.out.println(friendsArrayList.size());
how would I add string “Mitch” to an ArrayList called friendsArrayList?
friendsArrayList.add(“Mitch”);
How would I change the first value in an Array called friendsArray to “Carl”?
friendsArray[0] = “Carl”;
How would I change the first value in an ArrayList called friendsArrayList to “Carl”?
friendsArrayList.set(0, “Carl”);
How would I remove “Chris” from an ArrayList called friendsArrayList?
friendsArrayList.remove(“Chris”);
implement a class called multiThreadThing, which extends thread, in your main method and run two threads. Threads will be called myThing and myThing2
public static void main(String[] args) {
multiThreadThing myThing = new multiThreadThing(); multiThreadThing myThing2 = new multiThreadThing();
myThing.start();
myThing2.start();
Explain the following code.
for(int i = 0; i < 5; i++)
This is a for loop that starts from count 0 (i =0) and iterates through the loop (i++) until i is no longer less than 5 (i<5)
Which package are Maps in ?
java.util package
What is a map?
An interface that represents a mapping between a key and a value.
how would a maps interface apply to managers and employees relationship?
You can map managers and employees with Managers (Key) with a list of Employees(Value) being managed.
Can you create objects in an interface? if so, how would you do it? If not, what do you need?
No.
You need a class that extends the interface.
Identify the problem and fix the code, show solution:
public class Dog {
private String name;
private int age;
public void setName (String name) {
name = name;
name = name is setting the passed in String name to itself. So we need to add this. keyword.
public void setName(String name) {
this.name = name;
This will set this.name to the private String name, and set that to the String parameter in setName.
Identify the problem and fix the code, show solution:
public class Dog {
private String name;
private int age;
public void setName (String name) {
name = name;
name = name is setting the passed in String name to itself. So we need to add this. keyword.
public void setName(String name) {
this.name = name;
This will set this.name to the private String name, and set that to the String parameter in setName.
A constructor requires a return type? T/F?
False. a constructur can NOT have a return type.
Code the following:
class Main
main method
Create method called myMethod, pass through String name.
print out name in method.
call names Tom and Jim through myMethod in main Method.
What would I use if i wanted to iterate over a data structure?
for loop
count from 1-5 using a for loop.
for (int i = 0; i <= 5; i++)
System.out.println(i);
count from 1-5 using a while loop.
i = 1;
while (i <=5) {
System.out.println(i);
i++;
import a Scanner.
import java.util.Scanner
create a Scanner object called scan.
Scanner scan = new Scanner(System.in);
What is java type casting? Two types.
When you assign a value of one primitive data type to another type.
Wide (automatically)
narrow (manually)
When do I need to use casting?
When passing a smaller size type into a larger type size.
Cast the following code: go from double to int. name int variable ‘y’
double x = 9.5;
int y = (int) x;
Write code that manually boxes the following code. Name variable y.
double x = 5;
double y = new Double(x);
What are the two types of constructors?
No args.
Parameterized.
take a class called myClass and create a no args constructor from int num. set equal to 100.
public class myClass { int num; myClass() { num = 100; } }
Add a paramterized constructor to the following code:
class myClass { int x = 5;
myClass(int i) {
x = i
What is an access modifier? List them, and state their access level.
keyword which define the ability of other code to access the given entity.
public - available anywhere
protected - within the same package. and within same class.
default - within same package.
private - only within same class.
If i use the private access modifier, what will use to retrieve and change information within a private modifier.
Getters and Setters.
What is method overloading?
a feature that allows a class to have more than one method having the same name, if their parameters are different.
What is method overriding?
feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes.
Write code to exemplify overriding with the following:
class Parent
method show
class Child which inherits Parent
override method show
main method to print show.
What is an abstract class?
A class that you can NOT instantiate.
How do you create an abstract class? show code in example of public class called Animal.
public abstract class Animal {
}
What is an abstract method?
A method within an abstract class.
What’s the difference betwen an abstract class and an interface?
You can implement as many interfaces as you want but you can only extend one class.
And every field declared inside an interface is static and final.
Name all non-access modifiers.
static.
final.
abstract.
synchornized.
transient.
volatile.
strictfp.
What is unit testing?
what are the benefits of unit testing?
- A unit test is a program that exercises a small piece of the codebase in complete isolation.
- fast. unit tests don’t interact with elements external to the code such as databases, filesystems, or the network.
- Deterministic. If a given test is failing, it will continue to fail until a change is made to the test or the code.
Why is unit testing useful?
Unit testing can reduce bugs. Even if your code is technically correct, it might not do what you intend. That’s where testing is useful.
What is TDD?
test driven development. This is when you use tests to drive the development of the application.
3 steps to Workflow of TDD?
- Start by writing a unit test related to the feature you want to implement.
- Make the test pass by writing the lease possible amount of code.
- Refactor in order to get rid of duplication or other problems (optional).
What does JUnit Annotations @Test do?
declares a method as a test method.
What does JUnit Anootation @BeforeClass do?
declares a setup method that runs once, before all other methods in the class.
What does JUnit Annotation @Before do?
decalres a setup method that runs before each test method.
What does JUnit annotations @After do?
declares a tear-down method that runs before each test method.
What does JUnit Annotations @AfterClass do?
Declares a tear-dpwn method that runs once, after all other methods in the class.
Difference between checked and unchecked exception?
- Checked Exceptions are required to be handled or declared by the programmer.
- Unchecked Exceptions is not required to be handled or declared.
What is an exception in java?
an unwanted or unexpected event.
When an exceptions occurrs within a method, it creates an ______. This is called an ________.
object.
exception object.
What does the exception object contain?
Information about the exception such as the name and description of the exception and the state of the program when the exception occurred.
Error vs Exception. What’s the difference?
- An error indicatesa a serious problem that a reasonable application should not try to catch.
- An exception indicates conditions that a reasonable application might try to catch.
What is a try/catch block used for?
to handle exceptions that could be thrown in our application.
explain the two functions of the try/catch block.
The try block enclose the code that may throw an exception .
The catch block defines an exception to catch and runs the code inside only if that type of exeption is thrown.
What is a HashMap?
A map which:
stores elements in key-value pairs.
Insertion/Retrieval of element by key is fat.
Does not maintain order of insertion.
How to access a value in the HashMap? show example if I wanted to get the String “England” from an object called capitalCities.
Use get() method.
capitalCities.get(“England”)
Declare a HashMap called capitalCities. Put two Strings, the first being the country then the capital. Do with the following then print.
England, London
Berling, Germany
Washington DC, USA
HashMap capitalCities = new HashMap();
capitalCities.put(“England”, “London);
capitalCities.put(“USA”, “Washington DC”);
capitalCities.put(“Germany”, “Berlin”);
System.out.println(capitalCities);
which package is LinkedList in?
java.util
Create a linked list with the following:
class Main
main method
Linked list animals
elements in list include Dog, Cat, Cow
print out Linked List.
import java.util.LinkedList;
class Main {
public static void main(String[] args) {
LinkedList animals = new LinkedList<>();
animals. add(“Dog”);
animals. add(“Cat”);
animals. add(“Cow”);
System.out.println(“LinkedList: “ + animals);
}
}
What is an ArrayDeque?
A special kind of growable array that allows us to add or remove an element from both sides.