Please enable JavaScript.
Coggle requires JavaScript to display documents.
COMP16412: Introduction to Programming II - Coggle Diagram
COMP16412: Introduction to Programming II
Crash course on Java I
Comparing Programming Languages
Python vs Java: Differences
Java has a large corporate sponsor, python support is more distributed
Python compiles at runtime, Java compilation is a separate step
It is possible to write a Python application without defining a new class. Java applications always need to define a new class (Jshell allows you to test one or two lines of code)
In Python, whitespace is syntactically significant, while in Java ; and {} are used to end and group statements
Java is statically typed, Python is dynamically typed
Python vs Java: Similarities
Widely used, open source, platform independent languages
Compiled down to bytes that run on virtual machines
Share an "almost everything is an object" philosophy
ALGOL-like langauages
code blocks with a defined begin and end, implement assignment by evaluating the right, then left and assigning the right to the left
Both provide extensive libraries including tools for GUIs, databases, multimedia, processing text and images
Assignment and Types
Assigning a variable in Java(Types)
int i = 10;
String s = "hello world";
boolean b = true;
Python
Duck Typing
If it looks like a duck its a duck
Strongly Typed
Typing errors are prevented at runtime
Little implicit type conversion
Dynamically Typed
Types are checked during execution
Java
Strongly Typed
boolean a = 4; would produce an error
Statically Typed
Strong typing: Type errors are prevented at compile time
Automatic type conversion provided in some cases
Java Types
integers from very small to very big: byte, short, int, long
float, real numbers
double, very big real numbers
char
boolean
String
Array
Static vs Dynamic typing != Compiled vs interpreted language
Weakly typed languages don't produce errors when presented with operators that require a value to have characteristics associated with another type
Control Structures
Selection
if
else if
else
switch
Switch
switch(dayOfWeek){case "Monday": System.out,println("It's the start of a new week!"};break; ... default: System.out.println("It's the weekend!");}
This allows you to execute different statements based on the value of a variable. Each case label must be unique.
Iteration
for
while
do...while
break
continue
do ... while
do {string age = System.console().readline();}while (!age.equals("");
Crash course on Java II
Introduction and classes
A class
A programmer-defined type
The state of class: attributes or properties
Behaviour of a class: methods
Representation of a UML class as a name, attributes and methods
Objects and instances
What is an object?
Defining objects in Java
OO is about defining classes that interact with each other
Objects are obtained by creating instances of a class
Using the new operator to create a new Object
You can declare a variable that refers to a Triangle object using Triangle t = new Triangle();
the constructor is a method that has the same name as the class and does not return anything.
Implementing classes in java
You can have multiple constructor methods
This is known as constructor overloading and is possible as long as the number and type of the parameters is not the same
Encapsulation
Controlling access
Access level modifiers determine if other classes can use a particular attribute and invoke a particular method
Top level (i.e. class): public or none
Member level: public, protected, private or none
You usually make data private and behaviours public
Encapsulation
Makes attributes accessible only to the methods of the class
allows us to protect the data
no program can assign values tot he attributes directly
easy to maintain
"getters" and "setters"
public get methods to retrieve the data in an attribute
public set methods to update an attribute
Getters and setters
each private attribute has a setter and getter
To use a class, we need to know the names of the methods and what they are expected to do, input and output
Attributes
We initialise attributes at declaration or not at all
Java always initialises attributes
int and double = 0
boolean = false
objects = null
It's good practice to initialise yourself
Accessing objects
An object's attributes and methods can be accessed though the dot operator via the object's reference variable
The static operator and the scope of variables
The static operatior
private static int total score = 0; (underlined in the UML)
An attribute declared as static is a class attribute
Updates to a static attribute apply to all instances of a class
They can be accessed without instantiation
Uses of static
to define resources shared/used by different classes
to define resources shared/used by different object of the same class
Methods can be static and have the same properties as static attributes
A static method cannot access instance properties and methods can only call other static methods and access static attributes
An instance method can invoke\access instance and static methods and properties.
A static method can invoke\access static methods and properties but not instance ones
The scope of variables
Attributes of a class are instance variables
The scope is the whole class
They can be defines anywhere in the class
You declare it once
A variable defined inside a method is a local variable
The scope is the method
Order matters
If it has the same name as an instance variable, the local variable takes precedence
Working with I/O and String handling
An intro to types in Python and Java
Strings and chars
Python types (primitives)
int, float, boolean, strings
Java Types
Primitives
byte, short, int, long, float, double, char, boolean
Objects
String
A Java char is always exactly one character. If no value is explicitly declared then the value is '\0'
Python has no distinct character type
A Java string can be zero, one or more than one character in length. It's initial value is null.
Python also allows strings with length 0 or more characters
In Java, char is primitive, String is a reference type (an object)
In Python, strings are one of the four primitive types
Primitive, reference and null types
boolean initial is false
numerical initial = 0
floating point initial is 0.0
reference type initial = null
Primitive types are created on the stack
Reference types are creates in heap space
Null types require one stack reference, and need no heap space
Getting keyboard input from users
Buffered reader
Reads input from many streams
Uses System.out.print() to write prompts to the user
Reads char, char arrays and lines
Throws checked exceptions
Thread safe
8KB buffer, best performance
Needs to be closed to avoid memory leak, .close()
Console
Only reads console input
Provides methods to write prompts to the output stream/user
Doesn't throw checked excpetions
Thread safe
No read buffer
Doesn't need to be closed after use
Supports reading of secure data with echoing disabled
Not available in IDEs
New Lines
\n represents a newline character and is known as an escape character
Other escape characters include, \r(carriage return), \f (form feed), \t (tab), \', \", \0, \b (backspace), \\
Scanner
Reads input from many streams
Uses System.out.print() to write prompts to the user
Reads and parses a variety of types, including regex parsing
Doesn't throw checked exceptions
Not thread safe
1KB buffer
Needs to be closed to avoid memory leak, .close()
Syntax
valueOf, repeat, and indexOf are provided by the Java String API
To check if two strings are equal, we use .equals()
Strings are a specific type of Object - both will have their values in heap space and and a handle on the stack
Uninstantiated objects will have an entry on the stack but nothing in heap space.
Advanced OOP
Introduction and inheritance
Motivation
The OO paradigm enables and promotes reusability
Reusability is about using what is already available
reduces cost
code is less prone to bugs
increases maintainability
increases quality
OO languages include features not to reinvent the wheel
Inheritance
Java allows to extend existing classes by adding methods and attributes to them
This inherits all attributes and methods
The constructors are not inherited by the subclass
Implementing the constructor of the subclass
if in the superclass x and y are private and if there are no setters to inherit then use super to call the constructor of the superclass
Note that super must be classed on the first line of the constructor of the subclass
If super is not invoked explicitly, the compiler puts super()
If a class is going to be extended, provide a non-arg constructor to avoid errors as it is called implicitly.
Inheritance: super and this
keyword super refers to the superclass and can be used to invoke the superclass's methods and constructors
the constructors are not inherited by the a subclass
the subclasses below are equivalent
calls the inherited method, invokes the superclass's constructor, calls the method of the superclass
keyword this is a reference variable the refers to the current object
It can be used inside a constructor to call another constructor of the same class
Polymorphism
Overloading
Polymorphism means something takes multiple forms
It is encoded by using overloading and overriding
Overloading: define multiple methods with the same name but different signatures
Overloaded methods must have different parameter lists. You cannot overload based on return types or modifiers.
Overriding
Used when the subclass needs to modify the method defines in the superclass
To override a method, the method must be defines in the subclass using the same signature as in its superclass
Use the
Override
annotation
Preventing extending and overriding
Use the final modifier
The final attribute is a constant, it can be inherited but not modified
Abstraction
Abstract classes
Declare the class as abstract to prevent people from creating instances of it
Abstract classes act as the basis to create other classes, you cannot create instances
Abstract methods
Methods can be declared as abstarct as well
A class containing an abstract method does not have to be abstract
Abstract classes don't have to contain abstract methods
Subclasses must override abstract methods or declare themselves abstract
define header but not the body of the abstract class
the implementation is left to the subclass
Interfaces
Motivation
A class is not allowed to inherit from more than one superclass
It leads to ambiguity and errors
A class can implement many interfaces
An interface is a class containing abstract methods: the subclass is obliged to override them
We remove ambiguity as methods are abstract and mist be implemented in the subclass
An interface is like making a contract with the user of the class as it guarantees that the class will have certain methods
Interfaces use the keyword implements
Error and file handling
Error handling philosophies
Motivation
Bad error handling == Bad user experience
Coding philosophies
Look Before You Leap
Easer to Ask Forgiveness than Permission
Time Of Check, Time Of Use
Look Before You Leap
Checking our variables
Only proceed if you know it will work
Exceptions are exceptional
Typically accepted as the norm for Java
EAFP
Do what you expect to work
Generally accepted as the norm for Python
TOCTOU
Between time of check and time of use the variable (or more often file) permissions changed
Java's Exception Classes (Checked and unchecked exceptions)
Exceptions are objects
Error
A subclass of Throwable that indicates serious problems that a reasonable application should not try to catch
Error and all of its subclasses are regarded as unchecked exceptions
Exception
Another subclass of Throwable
All exceptions that don't extend error extend exception
RuntimeException
deals with errors that arise from the logic of a program
unchecked excpetion
can occur anywhere in the code
not flagged by the compiler
left to the programmer to avoid
IOException
deals with errors that could affect the program during input and output
checked exception
arises in predictable circumstances
java compiler knows ahead of time and forces the developer to take action
Checked and Unchecked Exception
important to understand in Java
Claiming and Catching Exceptions
Must be caught or declared to be thrown
Claim the exception by telling the compiler that it could throw an exception, passing responsibility for dealing with the error to the call stack
Catch the exception using try
There are many code examples in the notes
try...catch Three Execution Paths
The instructions within the try block are all executed successfully
An exception occurs in the try block, the try block is exited and a catch block is found for this exception
An exception occurs in the try block, the try block is exited and no catch block is found, the exception is thrown from the method
with
The nearest Java equivalent to Python with is try-with-resources
File I/O
Methods of encoding data in files
text
binary
object serialisation
IO Streams
Java views each file as a sequential stream of bytes, getting data from source to destination
Input streams provide input to a program from an external source
Output streams accept output from a program and delivers is to an external source
Streams and files
Every file that you're reading or writing will have two identifiers/names:
the name used by the OS
the name of the stream object
Basic Text File IO
Basic Binary File IO
Basic Object File IO
The Serializable Interface
Any class that you intend to write out to a file using object encoding must implement the serializable interface, which contains no methods, but tells Java that instances can be serialized
If a serializable class has instance variables of Object types then those classes must also be serializable
To exclude part of a serializable object, we can use the transient keyword
Object Serialization
Java assigns a serial number to each object
If the same object is re-written, after the first write only the serial number will be written
When an object is read more than once then there will be more that one reference to the same object.
Where aren't classes serializable by default?
Security: serialization allows access to data irrespective of modifiers
Complexity
Flexibility: it becomes difficult to change classes
Access patterns
Series (in order)
Random (out of order)
Security (Quiz details)
Security vulnerabilities identified were
Using insecure cryptographic hash functions
Bypassing certificate validation
Disabling default protection against CSRF attacks
There has been a growth ins reliance on the Spring Security framework since 2012
Authentication
defines how a client and server prove their identities
Authorisation
ensures that users have permissions to complete a specified operation
Programmatic security
is embedded in an application and used to make security decisions
Declarative security
expresses an application component's security requirements as a description or annotation
The API which the majority of security relates code snippets taken from questions relate to is java.security
On an analysis of 200, 672 Android apps from the google Play Store, 15% contained an insecure code snippet
The findings reported by Fischer et al:
Snippets containing comments giving security warnings are copied more into applications that those without.
Insecure code snippets are (roughly) equally common in applications with 500 downloads as those with 100, 000 downloads
Questions that contain secure code snippets are more likely to be upvoted.
Data structures I
Arrays and Array Lists
The Problem with Arrays
We cannot increase capacity
We can cause ArrayOutOfBounds errors when adding elements
ArrayLists don't have a fixed capacity, but dynamically adjust
ArrayLists - Instantiating
import java.util.ArrayList;
ArrayList <String> shoppingList = new ArrayList<String>();
ArrayLists - Common Operations
get
size
set
remove
clear
isEmpty
ArrayLists - Limitations
Copying the new array each time it reaches capacity has some performance implications
Adding/removing from the beginning or middle is problematic
No support for primitive types
Stack
Stack
The stack operator points to the top of the stack
LIFO data structure
Stack - Populating
import java.util.Stack;
Stack <String> readingPile = new Stack<String>();
readingPile.push("Java");
Stack - Common Operations
pop
size
peek
clear
isEmpty
List Interface
Both stack and Array List implement the List interface
It is possible to declare there types using List<String>
Queue and set
Queue
import join.util.Queue;
import join.util.PriorityQueue;
Queue<String> trafficJam = new PriorityQueue<String>();
FIFO data structure
add
remove
peek
Set
import join.util.Set;
Set<String> directoryListing = new HashSet<String>();
add
remove
Contains no duplicate elements
Revisiting iteration
Standard
for (int i = 0; i < shoppingList.size(); i++)
Enhanced for
for (String item: shoppingList)
for each
shoppingList,forEach(item -> {});
The Java collections Framework includes the following interfaces: Iterable, Collection, List, Queue, Set, Deque, SortedSet
Java Generics
Motivation
We often develop similar classes, so we can create a template and increase reusability
We cannot verify how the class is going to be used
Results in runtime errors
Generic classes
Java Generics
A generic type is a generic class or interface that is parameterized over types
Algorithms can work on collections of different types, can be customised, and are type safe and easier to read
A generic class is defined with the following statement
class name <T, T2, ..., Tn> {}
The angled brackets specify the type parameters
Naming Conventions
Type parameters are single uppercase letters
E: Elements used by Java Collections framework
K: Key represents parameter type of a key of a map
V: Value represents parameter type of value of a map
N: Number is used to represent numbers
T: Type issued to represent first generic type parameter
SUV: Types as well, and one used to represent the second, third and fourth type parameter
Instantiating a generic type
Similar to an ordinary method invocation, but passing a type arguments
Template <Square> squareTemplate = new Template<Square>();
A type variable can be any non-primitive type you specify. Use wrappers for the primitives.
Generic methods
Wrapper classes
For every primitive type, Java provides a corresponding class
The name of the class is similar to the basic type, but begins with a capital letter
They are called wrappers because they wrap a class around a basic type
boolean - Boolean, char - Character, int - Integer, double - Double
Autoboxing/unboxing
Unboxing converts objects into primitives. int a = i.get().intValue(); or Integer a = i.get(); or int a = i,get()
Autoboxing converts primitives into objects, i.set(new Integer (10));
Generic methods
A generic method declaration that van be called with arguments of different types
include a list of the parameters, inside angle brackets, which appears before the method's return type
a generic method's body is declared like that of any other method. Type parameters cannot represent primitive types
public static <T, U> int sum (Template <T> t, Template<U> u){}
Bounded type parameters
The compiler does not know the type of T and U so operands between classes are not allowed except from those of the object class
Using bounded type parameters we set constraints on how generic types are
We lose the quality of being extremely generic
We gain the certainty about the operands we can use
Use the extend operator to establish such bounfs
By extending you are declaring to be a subtype of a certain class, in addition to being generic
When defining a generic class
public class Generic <T extends Vehicles>
When defining a generic method
public <U extends Integer> int sum (Large Number <U> u)
Multiple bounds can be set: <T extends B1 &B2 & B3>
Building GUIs with Java: Introduction to JavaFX
Introduction
Motivation
The command line may be useful in certain situations, but most modern applications have a GUI
UI elements are called controls in Java
Applications are interactive so Java includes graphics packages and multiple functionalities to build interactive applications
The JavaFX Model
The stage is the container of the application
The stage is the top level window, contents go into the scene
Elements are nested in a hierarchical fashion
Elements can contain containers and controls
Use the parent-children notation when referring to containers' contents
JavaFX classes extend the Application class so import javafx.application.Application must be included
When a JavaFX application begins there are three methods that are called:
void init(): for routines that need to be carried out before the application itself starts
void stop(): for code that we want to be executed after the application finishes
abstract void start (Stage stage): which must be overridden and you place the code of the application.
Debugging JavaFX
The main problems that are encountered while developing JavaFX applications:
not extending application
not making the class public for getting imports
issues with other shapes or containers into other containers
Containers and layouts
The JavaFX Model
The minimal template for a JavaFX application needs
no constructor
at least one scene
If there are Panes, the main container must be included in the constructor of the scene
The stage must be shown explicitly
Shapes must be included in panes
The scene is contained in the stage
Stages, scenes, controls and shapes
There is no constructor
There is at least one scene
If there are Panes, the main container must be included in the constructor of the scene
Shapes must be included in Panes
The Scene is contained in the stage
the stage must be shown explicitly
Takeaway messages
shapes must be in containers. A scene can contain a Control or Pane, but not a shape
A Pane can contain only subtypes of nodes
Check the imports for layouts, controls etc
Extend the application
Override the start method
Note that launching the app is done differently
Containers and Layouts
Adding controls in specific coordinates
is time consuming
assumes certain UI sizes
Results in non-responsive applications
Java has containers and layouts to make this happen in addition to HBox and VBox
Event Handling
Event Handling in JavaFX
Graphical applications typically require interaction with the users through peripherals
Events are triggered constantly, the program can choose to respond or ignore an event
Interactions on controls trigger Event objects
EventHandler receives the event and executes instructions
The requirements for an object to handle an event are:
It must be an instance of the EventHandler<T extends Event>
The EventHandler object handler must be registered with the event source object
JavaFX uses lambda expressions where code is used as a method argument. The requirements for this are:
setOnAction registers an event handler with the event source object
The compiler recognises that the lambda expression is an object of the EventHandler<ActionEvent>
The compiler recognises that e is a parameter of the ActionEvent type
To use variables outside of an event handler, it has to be a private variable of the class
Legacy Java Event Handling
Inner classes
A class written inside another class (nested inner class)
A class written inside a method (method local inner class)
Used when a class is only needed once
You cannot have static methods in the inner lass, and can refer to the attributes of the outer class
In method inner classes, you can refer to variables of the outer class only if they are final
Anonymous inner classes
Anonymous inner classes are declared without any name
They are created in two ways
As a subclass of a specified type
As an implementer of the specified interface
Event Handling in JavaFX
Lambda expression
Can be used to greatly simplify coding for event handling
Before JavaFX - Mode I: as an inner class
Before JavaFX - Mode II: the event handler as an anonymous inner class
Further JavaFX and Concurrency
Further JavaFX: mouse handling and event handling
Motivation
JavaFX provides many UI controls for developments
Applications are interactive
UI controls are common to all applications
Event-handling: review
Events are triggered constantly, programs choose to respond or ignore them
EventHandler receives the event and executes instructions
Event-handling: beyond onAction
ActionEvent has setOnAction(EventHandler<ActionEvent>)
MouseEvent has setOnMouseClicked/Entered/Moved/Dragged(EventHandler<MouseEvent>)
KeyEvent has setOnKeyPressed/Released(EventHandler<KeyEvent>)
Event-handling: Mouse Events
A MouseEvent is fired whenever a mouse button is pressed, release, clicked, moved or dragged on a node or scene
You can get Button, ClickCount, X and Y and check which button is down
Event-handling: Key Events
A KeyEvent is fired whenever a key is pressed, released, or typed on a node or a scene
You can get character, code and text and check id the alt and control buttons are down.
Programming JavaFX controls
The JavaFX Model
Stages, scenes, controls and shapes
Label: is a non-editable text control
TextArea: text input component that allows a user to enter multiple lines of plain text
Combo/ChoiceBox: a drop down list provides users with a choice to be selected
CheckBox: a box with a checkmark or tick mark when checked
RadioButton: create a series of items where only one can be selected
And more under javafx.scene.control.Control
Case Studies
Case Study I: Absolute positioning in containers
HBox, VBox and most classes extending Pane arrange the elements within
Coordinates are override for shapes and controls
Controls must be added to Pane containers to enable positioning of elements
setLayoutX/Y(int) are available for all Node elements including shapes
Case Study II: Using multiple screens and scenes
Alternate scenes in event handlers using the setScene(Scene s)
Define the scenes as instance attributes
Concurrency: motivation and introduction
Motivation
Computers used to perform one task at a time
This is typically handled by the OS, but there are dependencies that need to be managed
Programming languages are quipped with functionalities to manage how a number of programs should run at the same time
Defintions
Multi-tasking is the feature that Java programs have to perform more than one task at once
Process is a running program using the operative system jargon
Time-slicing is the technique by when the processor time is distributed across the processor
Concurrency is the technique by which processes are run at the same time. We can talk of concurrent processes
Java Threads
Lightweight process
fewer resources from the system
Threads share code and memory
Java's job is to manage this following the time-slicing principle
The Thread class implements the Runnable interface
A class extends Thread or implements Runnable
It has one method: run()
You run a thread by creating an instance (Thread t = new Thread(new Feed()); and invoking the start() method
Once started the thread is executed via time-slicing
Concurrency: synchronisation and thread states
Java Threads
Time-slicing is the responsibility of the OS and JVM so it c=goes beyond out control
We don't know the amount of time allocated to each process
Synchronising Java Threads
Multiple thread behaviour may seem random
Most of the rune we want different threads to be coordinated, especially with the producer-consumer problem
Buffers are used to enable the communication of several threads/processes
They require exclusive access in mutual exclusion mechanisms
A thread accesses these critical sections one at a time
The synchronised keyword on a method declaration makes this method a critical section of exclusive access
wait() vs sleep(time)
wait is called from a critical section or synchronised method
it belongs to an object Object, while sleep is a static method of the thread class
wait() should occur in a loop that checks whether a condition is met
use wait and notify for interthread communication
use sleep for introducing a small pause during thread execution
Case-study: the producer-consumer problem
Both producer and consumer wait if the shared resource is in use
If threads are waiting for a condition to become true, use notify() and notifyAll() to signal that the condition has changed and they can wakeup
If multiple threads are waiting then notify will only inform one of the threads
Java Thread States
Much of threads life cycle is under the control of the OS and JVM
The programmer has some control over start(), sleep(time), wait(), notify() and notifyAll()
Data Structures II
Maps, Hashing, HashMap and HashSet
Hashing 101
A hash function allows you to deterministically get from one value to another, usually from string to int
They can be really useful to help us store and retrieve data
Use the hash function to decide where to store the data
Use the hash function to determine where to look for the data
HashSet
HashSet is a specific implementation of Set that uses a HashMap to hold the underlying data
HashSet has no duplicate values
HashMap has no duplicate keys
using the keys of a HashMap to hold the data of a HashSet means it won't be possible to add duplicate values
Sorting
Sorting
Java provides in-built sorting for ordered collections and Arrays
Relies on two interfaces
Comparable
Comparator
Comparable
Used when you have exactly one natural sort order
Make sure your class implements comparable
provide a compareTo method
Use java.util.Collections to do the actual sorting
Comparator
Used when you have more than one natural sort order
Create a class that implements Comparaot for each different sort order
Provide a compare method in each of your implementation
Use java.util.Collections to do the actual sorting
Trees and Binary Search Trees
An unbalanced binary search tree has everything to one side
Remember Breadth-first and Depth-first(pre-, in- and post-order)
When removing from a binary tree, replace the removed the the closest in the in-order traversal order