Programming 2 Flashcards
Serialization
The flattening of an object structure to allow for storage in a file
Deserialization
The reading of an object stored in a file to allow for it to be used
Where does the relative path start from?
The project folder
Input and Output Streams
An abstract class that holds a stream of bytes. (Often representing a file, can be some other I/O)
How to add bytes to an OutputStream
write(int integer) or write(byte[] array)
Reader and Writer
An abstract class that holds a stream of characters
FileWriter/FileOutputStream constructor
Class(file, ifModifyingFile) (if not modifying will wipe existing data).
FileInputStream read
stream.read(array) reads all the bytes from the stream to a given array
FileReader read
reader.read() - reads one character, or -1 if end of stream
ByteArrayStream
Does reading and writing directly into memory, ususally used for generating temporary data
Pipeline Stream
Used for communication between two threads
Print Stream
Output only. Allows for outputting data in text form. Is a wrapper of an output stream
Tagging Interface
Has no methods
Serializing Requirement
The class must implement the Serializable tagging interface. All fields primitives/String/Serializable
What serializes/deserializes objects
ObjectStreams
Serializing/desializing steps
Create an output/input stream to place/recieve data. Pass this to a objectStream. Call write/readObject on the object stream passing the object to serialize if writing
Serial Version UID
serialisation
64 bit secure hash of the class saved with a serialized object. When deserializing can be compared to current class and if it does not match serialization fails. May still work with minor changes
Externalizable
Interface that allows for choosing of what to serialize. Contains writeExternal and readExternal. Requires an empty constructor
Default Deserialization
From the class type from the stream, go the the highest serializable superclass and call the no argument constructor of its superclass.This sets up initial variables and the object. Work down the heirarchy creating and assigning additional varibles from the stream, until the final class is reached
transient
Keyword for variables that prevents it from being serialized
Ways to make a String
- Direct assignment
- String constructor with array of bytes/chars
- String constructor with a String
compareTo
method in the String class that compares the unicode representation (character by character, so gives which is alphabetically first) of the String and the String parameter. output = First String - parameter string
Anonymous Object
Created object with no name, so will be deleted after used
Immutable
Contents of object cannot be changed. Property of a String.
String Creation Heap Usage
When using direct assignment all Strings with that same value will be stored in the same heap location. When using the String constructor it will create it’s own unique heap location
valueOf
static method converts primitives to new String objects
trim
String method that removes leading and trailing whitespaces
JVM
Abstract description of an architecture (virtual hardware, memory layout, registers, …) for implementing Java
Class Loader
JVM
Locates .class files. Verifies that they are well-formed classes. Loads them into Method Area, links and initialises class (static) variables
JVM Shared Memory
Contains 1 heap and 1 Method Area
JVM Non-shared Memory
Each thread has a Java Stack and Program Counter (no registers)
Java Stack
JVM
Holds state information for thread (e.g. called methods, storing local variables, parameters and doing calculations)
Execution Engine
JVM
Describes how bytecode is executed, and what should happen, in terms of the JVM instruction set. Separate instances for each thread
Method Area
JVM
Stores class information (e.g. name, modifier(public…), field information), method definitions and class (static) variables. Stores a constant pool for each type of Class.
Method Area Structure
JVM
Often use method tables, each class has a table of pointers to methods that can be called on it, including from superclasses
Constant Pool
JVM
Contains ordered list of constants used by the class, i.e. literals (strings, integers) and symbolic references (to methods(ones called by the class methods), classes). If the symbolic reference refers to another loaded class then the reference will be replaced with a pointer to it (constant pool resolution)
Heap
JVM
Stores object, along with their (non-static) variables, including inherited ones. Each object has a pointer to it’s class in the method area
Non-Shared Memory
JVM
Contains a program counter and a stack for each thread
JVM Program Counter
Points to instruction being executed in Method Area.
JVM Stack
Allows for only push/pop frame. When a thread calls a method, frame (containing state information on thread execution) is pushed onto stack. All local variables, parameters and calculations done on frame. Can call other method, which puts the other method on top on stack
Stack Frame local Variable (and parameters) Storage
JVM
Stored as array of words. These variables are referenced by index. Will store primitives directly and references to objects in heap. The zero index always references the object that the method is called on (when non-static method)
Operand Stack
JVM Stack Frame
Storing arguments for any instructions. e.g. in a = 1, 1 would first be stored in the operand stack, then put into the variables array
Stack Frame Pointers
JVM
- To its constant pool
- To the code to go back to after it is done
- To the exception table
Exception Table
JVM
Holds a method’s catch clauses. Matching catch clause searched for when exception happens. If found, PC updated to catching code. Else, method terminated and exception rethrown to previous frame
Tail Recursion
JVM
If the last line of code is the recursive call then the same stack frame could be used. Java does NOT do this
Checked Exceptions
Exceptions that the compiler forces you to catch or defer
Unchecked Exceptions
Don’t need to catch/defer exception as unchecked exceptions should not happen if the code is written properly. Includes runtime exceptions
Error
subclass of throwable indicating serious problem, unchecked
Finally
In try catch block
Final clause, always run
Static Variables
The variable is now for the class, all objects of that class share the same value. Can be changed with Class.variable or object.variable.
Static Methods
Invoked in the class, not the object. Can only use static variables and methods
Final Variables
Can only be changed once when initialised if non-static, or only when declared if static
Extending Thread Class
to do threading
Overwrite the run method and call object.start.
Implementing Runnable Interface
to do threading
Write run method and then objects can be used in thread constructor. The thread can the be started.
Benefits of Runnable
for threading
Allows for a different class to be extended. Data is shared more easily as can call start on same thread multiple times
sleep
thread method
Thread sleeps for given milliseconds
thread priorities
Can use getter and setters to set priority, from 1-10
yield
thread method
Skips next slot of execution
interrupt
thread method
Wakes up sleeping thread, causing interruption
Java Thread States
Exists in exactly 1 states
1. New - not yet started
2. Runnable - executing
3. Blocked - waiting for a lock
4. Waiting - waiting indefinitely for notification
5. Timed Waiting - waiting for notification/time out whichever happen first
6. Terminated
isAlive
threads
Checks if thread is in the runnable state
join
thread
Waits for a specific thread to die before continuing
daemon thread
low-priority threads. JVM terminates if only daemon threads left. Can only produce other daemon threads
User Thread
High-priority, will be allowed to fully execute
@deprecated methods
threads
These methods are not recommended as can cause deadlock
suspend
resume
stop - ends thread execution (better if you change a flag to tell method to stop)
deadlock
Situation where multiple threads are stuck forever
Race Condition
threads
When mutliple threads race to access a shared resource, can lead to unintended ordering of data access
Synchronization
threads
To use a sychronised section of code the lock is needed, meaning only 1 thread can access it at a time. defined by synchronized block or keyword
Mutual Exclusion
Threads
The idea that only 1 thread can access a bit of code at a time
Mutex Lock
The lock needed in order to access synchronized code
atomic execution
threads
The order of threads does not affect the execution of instructions
monitor
Any object that manages the states of threads. Contains:
special room - the only thread that can run sychronized code
wait room - Threads that have chosen to wait and must be notified to leave
Entry Set - threads that are ready to go into the special room
Build Tool
Programs that automate the process of creating an executable application from code. Maven is a Java build tool
Archetype
Maven
Template of a project used to make initial structure. Specifies the structure, dependencies and configuration of the project.
POM
Project Object Model - XML file that contains the details about the project and configurations, dependencies and build settings
POM plugins
set up plugin with version in < pluginManagmement> and configure settings in < plugins>. Represent add-ons to software tool, used in creation of software
POM dependencies
Done in < dependencies> tags. External libraries used when compiling or running the software
Uber jar
Maven
contains dependencies and source code, in 1 jar file. Uses Shade plugin
JavaFX
Software platform for creating desktop application
Stage
JavaFX
Top level container. Primary Stage automatically produced. Visually a window. Contains 1 active scene at a time
Scene
JavaFX
Holds contents of a window. Contains 1 root node.
Scene Graph
JavaFX
A tree made up of a scene and all of its contents
Root Node
JavaFX
Parent of all other nodes in a scene
Container
JavaFX
A non leaf node
Widget/control
JavaFX
Leaf node
#
JavaFX CSS file
Used when referring to ID of component, only used for 1 instance. ID of component set with component.setID(“ID”)
.
JavaFX CSS file
Used when referring to class of component, which is applied to any instances of the class.
FXML files
Contain visual representation of what is wanted on the screen. Special language for designing the GUI
Lambda Expression
Java
object.condition((parameters) -> {
code
});
Method Reference
Java
A Lambda expression which only calls another function. object.condition(class::method); where class is the class that the method is in
var
Java
Used to simplify defining variables. Use var as the object type and it will still have the same type if it is implicit. This is only used in local variables
Event Handler
java
an interface that specifies how an event is handled. node.setOnEvent(EventHandler) where the event handler is implemented as an anonymous class
Observer Pattern
Java
An object that can choose to get updates from other objects
Listener
Java
An implementation of an observer pattern (gains updates from other objects). An interface with one method
Properties
Listeners
Allows for attaching listeners to variables. Property wraps the variable so when getter or setter called events can be triggered, and binders can be used
Binding
Properties
Can link together some properties so when one is changed the other reflects the change
Scheduler
Runs given code every so many milliseconds on a seperate thread
Event
JavaFX
Something happening in the GUI, e.g. button press
Animations
JavaFX
Can be done with transitions which are pre-made classes that extend the Transition class. ParralelTransition and SequentialTransition play a given list of animations. Can also make transition with a TimeLine
Timeline
JavaFX
A type of animation for allowing customisation. Defined by giving it a set a keyframes which define the values of certain nodes at certains times. timeline.getKeyFrames().add(new KeyFrame(Duration.millis(number), new KeyValue (node.doSomething, byValue));
timeline.play
Animation Timer
JavaFX
Abstract class with 1 method so can implement with lambda expression. The method is called every frame. Can be started and stopped
Verification
Testing
Ensuring software implements a function correctly (is the thing done right)
Validation
Testing
Ensuring software satisfies customer requirements (Is the right thing being done)
White-Box Testing
Used to determine if methods/data structures work. The tester needs to know the internal structure.
Black-Box Testing
Testing done without knowledge of internal structure. Tests outputs for given inputs.
Unit Testing
White-box testing done on small isolated pieces. Done by developers
Integration Testing
White/Black-Box testing done on a combination of larger and larger sections of code. Done by testers
System Testing
Black-box testing for the entirety of the system. Done by all
Unit Testing benefits
- Early bug detection
- Allows better decision making
- Faster and safer
seam
testing
Boundry between what is being tested and other classes being interacted with
Stub
testing
A fake object with bare minimum methods. Used for state verification. Passes hard-coded values to a higher up in the program structure class
Mock
testing
A fake object attempting to mimic the bahaviour of the real object. Used for verifying expected behavior
Stub/Mock benefits
testing
- Errors in the external class don’t cause issues
- The external class doesn’t need to be implmented
- The test is faster if the external class uses many resources
Dependancy Injection
testing
The passing of an external fake object to a class being tested. The fake object and the real one implement the same interface
Dependancy Injection Types
- Passing the fake object in the constructor
- Using an extension class to store the current object which can be settered and gettered
- Create a factory class that returns the fake object
JUnit
testing
Testing framework for Java
Exception testing
JUnit
assetThrows(expectedException.class, () -> testedMethod) where the tested method is the method being tested
Driver
Testing
A fake class that simulates behaviour of upper level modules.
Using mock objects steps
Testing
- Set the method calls in the expected order for the mock object
- Set the mock to replay mode to allow execution of test
- Set to verify mode to check if the expected methods were called
Top Down Integration
Integration Testing
Starts with testing high-level classes with stubs for the needed classes. The adds in these called classes and tests them together.
Top Down Integration pros/cons
Integration Testing
Pros:
* Drivers easy to write as just user simulation
* Encourages early prototypes
Cons:
* Needs many stubs/mocks early
* Modules at bottom of hierarchy not tested in isolation
Bottom Up Integration
Integration Testing
Tests lowest level modules in isolation. Add in modules that call the previous modules and test them together
Bottom Up Integration Pros/Cons
Integration Testing
Pros:
* No/few stubs
* reusable low-level modules thoroughly tested
* Testing in parralel with development
Cons:
* Needs drivers, can be difficult to find where to start testing from
* Overall logic tested late
Sandwich Integration
Integration Testing
Hybrid of bottom up and top down. Tests the top and bottom three layers of the program. More complicated but can mitigate problems of both individual solutions
Big Bang Integration
Integration Testing
No incremental testing. Tests done in isolation and for the whole system. Good for smaller systems to save time. Issues found late and hard to pinpoint.
scanf
C
scanf(“%type”, &variable). Stores the input of the given type in the given address
Numbers viewed as boolean
C
Statements viewed as true if the value is non-zero
sizeof
C
sizeof(variable) gives the number of bytes the variable takes up
&
C
&variable gives the memory address of the variable
Pointer
C
A variable that holds a memory address. When declared started with an * and the type determines what type the memory address is of.
Pointer Value
C
Value stores at address in pointer is gotten with *pointer.
*
C
Dereference Operator
Moving Pointers
C
Changing a pointer increases its memory address by a factor of the number of bytes of the type it is storing.
*pointer++
C
returns *pointer then increments *pointer by 1
++*pointer
C
Increments the value of *pointer then returns the value
malloc
C
malloc(bytes) - Returns a pointer at the beginning of some allocated memory of the given size
failed allocation
malloc
May have NULL returned if memory is unable to be allocated
free
malloc
free(pointer) - Frees up memory at the given pointer, otherwise will be locked, even after program finishes
calloc
C
calloc(numberOfBlocks, sizeOfBlock) - Same as malloc but sets all bytes to 0
Passing arrays to functions
C
Arrays are passed by reference.
Ordering Functions
C
If a function is called before it’s defined and the value returned by the function hasn’t been declared than it is assumed to return an int. Functions can be written in reverse order of execution or declared before they are called. i.e. returnType name (parameters);
Passing by reference for variables
C
Using a pointer to the variable can effectively accomplish this.
Structure
C
Works like defining a new type that can store a collection of different data types. Can then be used to declare variables of the type i.e. struct structName varName;
Structure Definition
C
struct name {
type member1;
type member2;
.
.
}
Initialise members
C Structure
varName.member = value;
typedef
C
Assigns an alternative name to a data type i.e. typedef oldTypeName newName. Written by replacing name of a declared variable with the new type name. If used on pointers removes the need to use the dereference operator (*) in decleration.
typedef for structures
C
Additional alternative definition:
typedef struct {
type member1;
.
.
} newName