Week 2 Flashcards

1
Q

Method - Describe boolean equals(Object o)

A

indicates whether some other object is “equal to” this one

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

Method - Describe Object clone()

A

creates and returns a copy of the object

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

Method - Describe void finalize()

A

called by the garbage collector on an object when garbage collection determines that there are no more references to the object

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

Method - Describe Class< ? > getClass()

A

returns the runtime class of the object

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

Method - Describe int hashCode()

A

returns a hash code value for the object

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

Method - Describe void notify()

A

wakes up a single thread that is waiting on the object’s monitor

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

Method - Describe void notifyAll()

A

wakes up all threads that are waiting on the object’s monitor

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

Method - Describe String toString()

A

returns a string representation of the object

automatically called if you print an Object. Usually, this is overridden to provide human-readable output

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

Method - Describe void wait()

A

causes the current thread to wait until another thread invokes the notify() or the notifyAll() method for the object

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

Method - Describe void wait(long timeout)

A

causes the current thread to wait until either another thread invokes the notify() or the notifyAll() method for the object, or a specified amount of time has elapsed

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

Method - Describe void wait(long timeout, int nanos)

A

causes the current thread to wait until another thread invokes the notify() or the notifyAll() method for the object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed

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

What is an Error?

Some examples?

A

An Error represents something that went so wrong with your application that you shouldn’t attempt to recover from it

EX - ExceptionInInitializerError, OutOfMemoryError, StackOverflowError

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

Define hash code

A

a number that puts instances of a class into a finite number of categories

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

try/catch/finally block rules (5)

A
  1. multiple catch blocks are allowed
  2. multi-catch blocks (catching more than one exception in a given block)are allowed; exception types are separated by |
  3. a finally block is optional
  4. a try/finally block only IS allowed, but a try block by itself is not
  5. a finally block will always execute, unless System.exit() is called
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What are unchecked exceptions?

Examples?

A

an exception that is not required to be handled or declared

EX: RuntimeException;

  • ArithmeticException (for illegal math problems);
  • IndexOutOfBoundsException (if you reference an index that’s > the length of an array);
  • NullPointerException (if you attempt to perform an operation on a reference variable that points to a null value)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Define annotations

A

special constructs that use the @ symbol. provide metadata about the source code to the compiler and JVM

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

Explain Test Driven Development (TDD)

A
  • process of writing unit tests you want your code to pass

Steps

  1. write a unit test
  2. run the test ==> test will fail
  3. fix the test by writting application code
  4. retest until the test passes
  5. repeat
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Define Unit Testing

A

testing of individual software components in isolation from the rest of the system; writing unit tests which execute the code we want to inspect

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

JUnit Annotations

A

Java framework for unit testing

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

static Assert methods (5)

A
  1. assertTrue()
  2. assertFalse()
  3. assertEquals()
  4. assertNotEquals()
  5. assertThat()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

JUnit Assertions

A

verifies that the state of the application meets what is expected

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

What annotation would you use to prevent a test from running?

A

@Ignore (use sparingly!)

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

Testing Best Practices (7)

A
  1. dependency injection - design pattern in which an object receives other objects that it depends on
  2. write testable code
  3. use mocking libraries for dependencies
  4. measure your code coverage
  5. externalize test data when possible (read test datat from external file)
  6. try to use only 1 assert statement per test (helps pinpoint defects when debugging)
  7. write deterministic tests (“flkay tests”)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

4 types of variable scopes in Java?

A
  1. instance/object scope - variable is attached to individual objects created from the class; when modified, it has no effect on other, distinct objects of the same class
  2. class/static scope -variables reside on the class definition itself. This means that when objects update a class-scoped variable, the change is reflected across all instances of the class
  3. method scope - scope of a variable declared within a method block, whether static or instance; do not exist after method finishes execution
  4. block scope - only exist within the specific control flow block (for/while/do-while loops/if/else-if/else blocks, switch cases, regular blocks declared by {}; no longer available after block ends
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

return statements

A

used for returning a value when the execution of the block is completed. The return statement inside a loop will cause the loop to break and further statements will be ignored by the compiler

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

Explain stack vs heap?

A

Heap is where objects are stored in memory. Stack is where local variable references are kept - a new stack FRAME is created for each method invocation

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

Non-accessmodifiers (6)?

A
  1. static
  2. final
  3. abstract
  4. default
  5. synchronized
  6. transient

obscure keywords :volatile, native, strictfp

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

What makes a class immutable (6)?

A
  1. Declare the class as final so it can’t be extended.
  2. Make all fields private so that direct access is not allowed.
  3. Don’t provide setter methods for variables.
  4. Make all mutable fields final so that it’s value can be assigned only once.
  5. Initialize all the fields via a constructor performing deep copy.
  6. Perform cloning of objects in the getter methods to return a copy rather than returning the actual object reference.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

How to pass multiple values with a single parameter into a method?

A

Use varargs (aka variable arguments)

30
Q

Where are Strings stored?

A

In the String pool in the heap

31
Q

Why are Strings immutable in Java?

A

Identical String literals are collected in the “String pool” in an effort to conserve memory. Reference variables will then point to the same String object instance. Changing the object’s state in the String pool will make changes to all references to that String object. Instead, when a change to a String is made, the JVM makes a new String object, and the reference variable points to the new String in the String pool.

32
Q

What makes a class immutable?

A
  • Declare the class as final so it can’t be extended.
  • Make all fields private so that direct access is not allowed.
  • Don’t provide setter methods for variables.
  • Make all mutable fields final so that it’s value can be assigned only once.
  • Initialize all the fields via a constructor performing deep copy.
  • Perform cloning of objects in the getter methods to return a copy rather than returning the actual object reference.
33
Q

What is the difference between String, StringBuilder, and StringBuffer?

A

Strings are immutable.

StringBuilder and StringBuffer are mutable.

Furthermore, StringBuffer is synchronized while StringBuilder is not.

34
Q

Explain stack vs heap?

A

heap is where objects are stored in memory.

stack is where local variable references are kept - a new stack FRAME is created for each method invocation

35
Q

what are annotations?

A

a type of syntax metadata added to the code, read by the compiler (use @ syntax)

36
Q

What is POJO?

What is bean?

A

plain old Java object - any Java object that you create

bean - a POJO that has private data members, public getters/setters, and overrides .hashcode(), .equals(), and .toString() methods

37
Q

How can you force garbage collection in Java?

A

Garbage collection cannot be forced but only requested using System.gc()

38
Q

What are the access modifiers in Java (4)? Explain them.

A
  1. public - can be accessed from any package.
  2. private - only members of the same class can access.
  3. protected - can be accessed by classes inside the package and subclasses anywhere.
  4. default - no access by classes or subclasses outside the package
39
Q

What are the non-access modifiers in Java?

A

static, final, abstract, default, synchronized, transient

obscure keywords: volatile, native, strictfp

40
Q

What is the difference between static and final variables?

A

static variables are shared by all the instances of objects and it has only single copy. A final variable is a constant and it cannot be changed. However, if the variable holds a reference to an object, the state of the object may still be changed and manipulated.

41
Q

What are the default values for all data types in Java?

A
  • Objects - null
  • int, short, byte, long, float, double - 0
  • boolean - false
  • char - ‘u0000’ (null character)
42
Q

If two objects are equal, do they have the same hashcode? If not equal?

A

If two objects have the same hashcode then they are NOT necessarily equal. But if objects are equal, then they MUST have same hashcode.

43
Q

What methods are available in Object class?

A

.clone, .hashcode, .equals, .toString

44
Q

How would you clone an object?

A

First, tag the class with the Cloneable marker interface. Next, invoke clone(). The clone method is declared in java.lang.Object and does a shallow copy.

45
Q

What is the difference between == and .equals()?

A

== - tests to see if two reference variables refer to the exact same instance of an object.

.equals() - tests to see if the two objects being compared to each other are equivalent, but they need not be the exact same instance of the same object.

46
Q

What is an enhanced for loop and what is a forEach loop?

A

Enhanced for loop allows easier traversal of Collections (actually any arrays or Iterables) - syntax: for (Object o : collection) {…}

47
Q

What are the implicit modifiers for interface variables?

A

public
static
final

48
Q

What are collections in Java?

A

A general data structure that contains Objects. Also the name of the API

49
Q

What are the interfaces in the Collections API?

A

Iterable, Collection, List, Queue, Set, Map, SortedSet, SortedMap

50
Q

What is the difference between a Set and a List?

A

Set does not allow duplicates (its members are unique)

51
Q

What is the difference between a Array and an ArrayList?

A

An array is static and its size cannot be changed, but an ArrayList can grow/shrink

52
Q

What is the difference between ArrayList and Vector?

A

Vector is synchronized whereas ArrayList is not.

53
Q

What is the difference between TreeSet and HashSet?

A

The two general purpose Set implementations are HashSet and TreeSet. HashSet is much faster (constant time versus log time for most operations) but offers no ordering guarantees.

54
Q

What is the difference between HashTable and HashMap?

A

Hashtable is synchronized whereas Hashmap is not.

Hashmap permits null values and the null key.

55
Q

Are Maps in the Collections API?

A

Yes, but they do not implement Collection or Iterable interfaces

56
Q

What are generics? What is the diamond operator (<>)?

A

A way of specifying a type within a data structure - they enforce type safety. <> operator lets you infer generic types from the LHS of assignment operation

57
Q

What is the difference between final, .finalize(), and finally?

A

final: final keyword can be used for class, method and variables. A final class cannot be subclassed and it prevents other programmers from subclassing a secure class to invoke insecure methods. A final method can’t be overridden. A final variable can’t change from its initialized value.

finalize(): finalize method is used just before an object is destroyed and called just prior to garbage collection.

finally: finally, a key word used in exception handling, creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block. The finally block will execute whether or not an exception is thrown. For example, if a method opens a file upon exit, then you will not want the code that closes the file to be bypassed by the exception-handling mechanism. This finally keyword is designed to address this contingency.

58
Q

throw vs throws vs Throwable?

A

Throwable - the root (super) class of exceptions, allow a class to be “thrown”

throws - keyword in method signature after params that declare which exception the method might throw

throw - the keyword that will actually “throw” an exception in code

59
Q

What is try-with-resources? What interface must the resource implement to use this feature?

A

Try-with-resources allows for automatically closing resources in a try/catch block using try(resource) {…} syntax. Must implement the AutoCloseable interface

60
Q

Do you need a catch block? Can have more than 1? Order of them?

A

Catch block is not necessary - try/finally will compile. You can have more than one catch block, but the order must be from most narrow exception to most broad/general.

61
Q

What is base class of all exceptions?

A

The base class is Exception, which extends the Throwable class.

62
Q

List some checked and unchecked exceptions?

A

Checked - IOException, ClassNotFoundException, InterruptedException

Unchecked - ArithmeticException, ClassCastException, IndexOutOfBoundsException, NullPointerException

63
Q

Multi-catch block - can you catch more than one exception in a single catch block?

A

Yes, use the || and && operators

64
Q

Is this an example of a checked or unchecked exception?

A

public class MyException extends RuntimeException {}

65
Q

What is JUnit?

A

A Java unit testing framework for testing code - use it for TDD

66
Q

What is TDD?

A

Test-driven development - write unit tests before application code, then write code to make tests pass. Repeat this process until functionality is complete.

67
Q

What are the annotations in JUnit? Order of execution?

A

BeforeClass, AfterClass, Before, After, Test, Ignore

68
Q

Give an example of a test case?

A

Adding two numbers, check that the method returns the sum

69
Q

How do you serialize / deserialize an object in Java?

A

Step 1: An object is marked serializable by implementing the java.io.Serializable interface, which signifies to the underlying API that the object can be flattened into bytes and subsequently inflated in the future.

Step 2: The next step is to actually persist the object. That is done with the java.io.ObjectOutputStream class. That class is a filter stream–it is wrapped around a lower-level byte stream (called a node stream) to handle the serialization protocol for us. Node streams can be used to write to file systems or even across sockets. That means we could easily transfer a flattened object across a network wire and have it be rebuilt on the other side!

70
Q

How do you restore the object back after serialize / deserialize?

A

To restore the object back, you use ObjectInputStream.readObject() method call. The method call reads in the raw bytes that we previously persisted and creates a live object that is an exact replica of the original. Because readObject() can read any serializable object, a cast to the correct type is required. With that in mind, the class file must be accessible from the system in which the restoration occurs. In other words, the object’s class file and methods are not saved; only the object’s state is saved.