Test 2 Flashcards
What happens if I declare a specific type for a list interface
declare a specific type → need to define
many List interfaces, one for each specific type
creates a lot of duplicate code
what happens if I declare a list with elements are simply Object
lose the safety of compile-time type checking (need to cast) cant do anything with the list because it needs to be casted to type
type parameter
a variable that takes a type as its value and
is used to make a generic class or interface more specific
what type is List<E></E>
generic type
List<String></String>
parameterized type
List
raw type
what can you do with Parametrized types
Can declare variables of parameterized types
Can construct objects of parameterized types
Can invoke methods on objects of parameterized types
Can define methods that take or return parameterized types
what can’t raw types do
never declare or instantiate!
what can generics extend
Generic types can extend/implement other generic types
We could not define…
public class MyList<T> implements List<E>
Generic types can extend non-generic types</E></T>
what can non generics extend
Non-generic types can also extend/implement generic types
Invariance
must use the exact type specified
Contravariance
can use a less specific type than declared
Covariance
can use a more specific type than declared
Pros of covariance
more flexible
invariance
more safe (less prone to failing at runtime)
boolean add(E elem) (.add)
adds elem to the end of the List and returns true, if its an element it return false
add(int idx, E elem)
adds elem to the List at index idx
E set(int idx, E elem) (.set)
places the element at index idx in the
List, replacing what was there previously
E get(int idx)
returns the element at index idx in the List
int indexOf(E elem)
returns the index of elem in the List
boolean contains(Object obj)
returns true if obj is in the
List; false otherwise
E remove(int idx)
removes element at index idx from the List
boolean remove(Object obj)
removes obj from the List
if remove could be boolean remove or normal remove what does java go with
removes number at that idx
what do u do when u want to remove a certain value from a list but that number is also a valid index
.remove(Integer.valueOf());
If we define a generic type (class or interface) by declaring one or more type
parameters, what is the scope of those type parameter(s)?
The scope would be the entire class or a single method.
There are only two circumstances under which it may be a good design to use a
raw type. What are those circumstances?
a. When you want to access a static field or method of generic class
because it enables you to quickly create non empty lists
b. When you want to use instanceOf to perform type checking
what are javas 3 primary ways of creating a constructor
- Default constructors (zero args) – create an empty container: List<Integer> myList = new ArrayList<Integer>(); 2.Copy constructors – create a shallow copy of a given container 3.Static “factory” methods – quick means of building a new
non-empty container
List<Integer> myList = List.
of(1, 3, 5, 7, 9)</Integer></Integer></Integer>
difference between generic methods and types
Generic methods offer greater flexibility. Generic types offer better consistency & type safety generic types are a good fit for when
you want a consistent type across
multiple methods that share state
If we define a generic method by declaring one or more type parameters, what is
the scope of those type parameter(s)?
The scope of the type parameter is simply the single method for which it is
defined
describe one situation in which a generic method would be the better design
An example would be if we had a generic copier
method this way we could use one copier object once to copy lists of different
type inputs. If we used a generic class we would have to instantiate a different
copier for each type of list we wanted to copy
Describe one situation in which a generic class would be the better design
Generic classes are better for consistency and type safety. An example would be
a Map class when the values for K and V are type parameters for the entire
class, having Java’s static type checking guarantees the argument type will
match the parameter type and the return value is assigned to the right type.
pros and cons of LVT
Pros of explicit declaration:
● Code is more “self-documenting”
● Can be used in all cases
● Have full control over the choice of
numeric type (e.g. int vs. short)
Cons of LVTI:
● Code is less self-documenting
● Can only be used in select cases
● Can’t indicate that you want a byte or
short (will always get an int)*
pros and cons of explicit declaration
Pros of explicit declaration:
● Code is more “self-documenting”
● Can be used in all cases
● Have full control over the choice of
numeric type (e.g. int vs. short)
Cons of explicit declaration:
● Code might take slightly longer to write
● Less adaptable to interface changes
Two kinds of type inference in modern Java:
- Local variable type inference (LVTI), introduced in Java 10
- Generic type inference (diamond operator), introduced in Java 7
generic type inference
● Pros:
○ Code is faster to write
○ Code is more adaptable to changes, in interfaces and locally
○ Code is arguably more readable (shorter, but without any loss of
information) if declaration & construction are in the same line
● Cons:
○ Code is less readable if declaration & construction statements are
not located near each other Verdict: use whenever declaration
& construction are near each other!
what happens when LVTI and generic type is combined
var myList = new ArrayList<>();
● Problem:
○ var infers the type from the righthand side; finds ArrayList,
but no type parameter
○ <> infers the type from the lefthand side; no type is found
● Result: type is ArrayList<object></object>
constraints on wildcards
New constraints, in order to preserve type safety:
1. Can’t put anything besides null into a Collection<?>
2. Can’t assume anything about the types of the objects you
take out of a Collection<?>
3. Can’t directly instantiate an object with a wildcard
generic methods vs wildcards
generic methods offer
greater consistency
Wildcards offer
greater flexibility
PECS principle:
“producer
extends, consumer super” A ○ producer = a collection that we’re taking elements out of
○ A consumer = a collection that we’re putting elements into
○ Use upper bounds (extends) when you want a producer
○ Use lower bounds (super) when you want a consumer
○ If you want both, need to use a specific (non-wildcard) type
what is the point of type erasure
java uses type erasure to make raw types and parameterized
types work together seamlessly
Limitations on defining generic types & methods:
- Cannot use a type parameter T to construct an object of type T
- Cannot use a type parameter T to construct an array of type T[]
Limitations
public static <T> T constructObject() {
return new T();
}
public static <T> T[] constructArray() {
return new T[10];
}</T></T>
Limitations on using parameterized types
Cannot use instanceof to check parameterized types
List<Integer> myList = new ArrayList<Integer>();
boolean isIntList = myList instanceof List<Integer>;
List<T> myList = new ArrayList<T>();
boolean isList = myList instanceof List<T>;</T></T></T></Integer></Integer></Integer>
Compile-time errors
errors that are detected by the compiler (syntax & type safety)
Logical errors
not detected by the compiler or the JVM, but
cause the program to do the wrong thing
Runtime errors
errors that are detected by the JVM ■ Error only occurs for certain inputs to the program
■ Program reads file; error only occurs if the file is missing or
malformed
Checked
must be handled
Unchecked
do not need to be handled
Java’s compiler requires that every checked exception is
handled in one of two ways:
- A function can catch an exception and handle it appropriately
- A function can throw an exception to its caller
Checked Exceptions
what are errors
Errors are typically
non-recoverable issues;
typically originate in the JVM
what are exceptions
Exceptions are issues that
are potentially recoverable;
can originate in code or JVM
runtime exceptions
RuntimeExceptions are unchecked (no handling
required); often the result of programmer error
what are types of unchecked exceptions
IOException, TimeoutExpection all other Exceptions are
checked (must be handled);
typically not the result of
programmer error
there are 3 types of Throwable objects in Java:
errors: typical point of origin? JVM Typically caused by programmer error? No
Typically recoverable? No
Need to be handled? No
Runtime
Exceptions:Typical point of origin? JVM
Typically caused by programmer error? Yes
Typically recoverable? No
Need to be handled? No
All Other
Exceptions
Typical point of origin?: Code
Typically caused by programmer error?: No
Typically recoverable?: Maybe
Need to be handled?: Yes
pros and cons of exceptional control flow
● Pros of using exceptional control flow:
○ Forces you to think about what errors may occur
○ Forces you to handle errors in a structured way
○ Seamless integration with the JVM
● Cons of using exceptional control flow:
○ Code is slightly bulkier, but no worse than checking return values
○ Slight time overhead
○ Can be abused out of laziness
When not to use exceptional control flow?
Don’t use to handle unchecked exceptions!
These are generally caused by poor programming.
role of device drivers
The OS uses device drivers to
communicate with I/O devices
memory vs storage
Memory = short-term; contents are lost when power is lost
■ Contains data used by running programs
Stroage = long-term; contents persist when power is lost
■ Contains data that appears to be organized as files
hard disk
a circular disk + a fixed arm that reads from the disk;
disk spins to the correct location for the arm to read
has no notion of files
solid state drive
non-volatile memory: sequence of fixed-size storage
cells like “normal” memory (DRAM), but persistent
what is a file system
an abstraction, which
imposes structure on the data in storage by:
○ Dividing the space on the HDD/SSD into blocks
○ Maintaining an indexing system for organizing files
what are the options to read a file
Read the entire contents into a single String:
String contents = Files.readString(Paths.get(path));
○ Use a Reader to perform more granular operations
buffered vs unbuffered
In unbuffered I/O, each
read/write goes to the OS,
triggering a potentially
slow hardware access. In buffered I/O, a buffer
serves as an intermediary
between the OS and the
Reader/Writer, allowing
multiple read/writes to be
combined into one
hardware access
call stack
the in-progress function calls that have led to the
current point
frame
One frame per function = an abstraction encapsulating the value
of each of the function’s local variables
breakpoint
a custom stopping point that you can place in the
program to pause execution when running in debug mode. Set a breakpoint by clicking in the lefthand margin next to the line
you’d like to stop at
why Modern operating systems typically provide a graphical user
interface (GUI)
so that you can run programs with a single click
● This GUI is an abstraction; when you click on an icon to run a
program, a command is sent to the OS telling it:
1. The path (location) of the program to be run
2. Which arguments to use as inputs to that program
Running Your Program from the Command Line
public class Main {
public static void main (String[] args) {
System.
out.println(args[0]);
}
}java Main hello
compiles Main.java, generating Main.classjavac Main.java
runs Main.main() with args = [“hello”], printing “hello”
Two types of RNGs:
- Pseudo random number generators (PRNGs), AKA deterministic
random number generators (DRNGs)
○ Numbers only appear to be random - Hardware random number generators (HRNGs), AKA true
random number generators (TRNGs)
○ Numbers are genuinely random
PRNGs
pros and cons
● Pro:
○ Fast!
● Con:
○ Not truly random; a poorly-designed PRNG
may exhibit:
■ A short period
■ Correlation of successive values
■ Lack of uniformity of distribution
…
Because of this lack of true randomness,
PRNGs are less secure: if the seed is known,
the entire sequence can be reproduced
when are PRNGs cryptically secure
A PRNG is a CSPRNG iff it’s been proven that:
○ If an attacker knows all of the generated bits up to a point
○ But the attacker does not know the seed
○ Then the attacker cannot guess the next bit with probability
significantly higher than 50%
pros and cons of HRNGs
● Pro: non-deterministic!
● Con: slow!
○ The rate at which entropy can be harvested from a natural source
depends on the underlying physical phenomena
○ Some algorithms may request random numbers faster than they
can be generated; this causes the HRNG to block
hybrids of PRNG and HRNG
Hybrid approaches can be used to strike a balance of between
non-determinism and efficiency, e.g.:
1. Use an HRNG by default, but fall back on a PRNG when the
desired rate of generation exceeds the HRNG’s capabilities
2. Use a PRNG, but periodically re-seed it with a number generated
by an HRNG
create a variable that will get a random number between 2 values
randNum = (Math.random() * (upper - lower)) + lower;
Randomness in Java
process
A process encapsulates an instance of a running program However, each process believes that:
1. It’s the only process
2. It has exclusive access to resources such as memory and CPU
3. All of its operations get executed back-to-back
how do process protect against malicious attacks
The OS runs in kernel mode; has complete power
○ Processes run in user mode; the hardware bans certain
operations from being performed in user mode
■ Processes need to ask the OS for help with these operations,
at which point it can safeguard against malicious behavor The OS gives each process a private virtual address space
○ Physical address = real (hardware) memory address
○ Virtual address = fake address used within a process
advantages of virtual address
Security: OS is involved in the “address translation” process →
process can’t access memory that doesn’t belong in it
○ Convenience: OS can present the process with a contiguous
virtual address space, even if the physical pages are scattered