Please enable JavaScript.
Coggle requires JavaScript to display documents.
M250 - Coggle Diagram
M250
Random Ideas
A class should have:
constructor
setter methods
getter methods
To
declare a field,
its when you first say that such a variable actually exists and is usually done first, at the start of a class.
To
initialise a /fieldvariable
mean to assign a value to it and is usually done in the constructor part of a class.
To go
one directory up
, use "../[filename]"
ERRORS
cost = item.discount() - "
void cannot be converted to double
" - The discount method was found to not return anything, it was a setter method and therefore had void return. Hence, setting a variable to have such a method results in a variable that has void.
ConcurrentModificationException
- This happens if we try to remove an item from a collection while using a for-each loop
Use 'is' in front of getter methods that return a boolean value. Its easier to read.
NULL
means "no object"
method calls cannot be made on variables that do not reference objects. Hence, on variables which reference null.
ANNONYMOUS OBJECT
An object without a name because if a variable name were given, it would not be used for much. The usage of the variable would be short lived.
E.g. Bid bid = lot.getHighestBid();
Person bidder = bid.getBidder();
String name = bidder.getName();
System.out.println(name);
Here you can see that the variable 'bid' is almost immediately used. And in this example, it won't be used again. So, to save time,
chain method calls
is better.
E.g. System.out.println(lot.getHighestBid().getBidder().getName());
CONVENTIONS
Boolean variables are usually named to reflect their true state. E.g. the variable 'isComplete' would be initialised to have a value of 'true' if the thing really is complete. The variable name and the value should make sense.
SOME TERMS
Immutable: a String is immutable. This means that it cannot be modified. Unlike an int.
So, simply adding a method to a String variable will not do anything since the String variable cannot actually be changed. To solve this, any modification attempt of a String should assigned to a variable. Often the variable can be the same as before.
SOME SYNTAX
'
boolean add(E o)
' is used in documentation to indicate what elements can be added to an ArrayList. In this case, elements of type 'E' can be added. Real example: boolean add(String o) means elements of type String can be added.
E get(int index) is used in documentation to indicate which type of elements can be returned from an ArrayList. In this case 'E' elements can be returned. REal example: String get(int index) means that String will be returned.
Import Statements:
'import package-name.class-name' Real example: java.util.Random. In this example, java.util is the package name. Putting a '*' instead of a class-name will import all classes from that package.
CH6
:
More Sophisticated Behaviour:
How to work with library classes
A good Java programmer should know some of the most important class, and be able to find out/look up other classes.
The Java documentation show the
interface
of all the classes. I.e. how each class works. It doesn't show the code for each class since, if the interface is well written, knowing the code doesn't matter.
The source code underpinning each class is know as the
implementation
, as opposed to the
interface
.
Random Class
Java cant actually produce real random numbers because algorithms are needed to and since they're human made, they just can't do it. So we say that the Random class produce pseudo-random numbers.
Conditional Operator
Can be used instead of an 'if' statement. Works like this:
somevariable = otherVariable == 10 ? "Child" : "Adult";
There are 2 characters '?' and ':' and 3 operands. The last 2 operands must be expressions, they cannot contain methods.
HashMap
A map is a set of key/value pairings. Each key and value is an object. There is no index with a map, instead the key object acts in this way.
A
hashmap
is a form of a map. It has important 'get' and 'put' methods.
Creating a new hashmap includes stating what data type each key and value is.
E.g. HashMap <String, String> contacts = new HashMap<>().
its easy to look up the keys, but its difficult to look up from the value side.
Lists vs Sets
A set does not allow duplicates, does not keep insertion order.
A list allows duplicates and keeps insertion order.
They are quite similar.
keySet
A method that is used on a map that returns a set. E.g. executing this on a hashmap will return a set containing all the keys.
Autoboxing
primitive types need to be converted to objects before they can be inserted into list. So this process is called
boxing
, and the reverse is called
unboxing
. Java does this automatically, hence 'autoboxing.
This is achieved with the
Wrapper
class.
Note: dont say for example ArrayList<Int>, rather say ArraList<Integer>. Each primitive type has its own wrapper class.
Public vs Private
These keyword are modifiers and control the visibility of fields, constructors, methods, or classes.
fields are usually private because they only need to apply to what is near them, like a method.
Methods are usually public, because they provide a way for a class to perform some action, so they need to be accessible from outside the class it belongs to.
Helper methods
are different. They are usually private because they are only needed to perform actions within the class they belong to.
The
interface of a class
shows a programmer what they need to know in order to use the class effectively. Hence, private fields or methods are private and not shown on the interface because a programmer does not need to know about them.
The
implementation
part of a class is the part of a class that shows the details of the methods, constructors, fields, etc that run the class. This part of a class is aka the private part of a class.
Static
Keyword
This keyword defines class variables. As opposed to instance variables.
These are variables that are stored in the class itself. not in an object. Hence, they are not declared in the constructor.
All object instances share class variables.
Constants
These are variables that remain the same for all instances and cannot be changed.
These include the keyword,
final
, before the type name.
And they must be initialised with a value at the point of declaration.
private final int SIZE = 10;
note: var name is capitalised to differentiate it from other variables.
Note: there is no 'static' keyword here.
Variable SUMMARY
:
with static -> class variable, instances do not get a copy of the var and can only use the var assigned on declaration within the instance.
with static and final -> instances do not get a copy of the var and must use the value declared initially.
Static can be used for methods too.
These methods can be invoked without there being an instance.
These methods can only access class variables. Not variables of instances.
They also may not call an instance method from the class.
Sorted Collections
There is
TreeSet
and
TreeMap
which are classes that sort collections according to their values.
These classes automatically sort the items that they contain. So if you want a list of things that are sorted, its better to use these over the normal HashSet or HashMap.
CH3
: Object Interaction
ABSTRACTION
: the ability to focus on general broad ideas instead of the details.
Used to deal with the
complexity
that some programs will generate.
Divide and Conquer
: divide problem into sub-problems, then again and again until a single problem is easy to deal with.
Once one problem is solved, then we don't need to think about it anymore. It becomes a building block of the whole program.
This is
MODULARIZATION
OBJECT DIAGRAMS
static
view: shows classes (aka class diagram)
dynamic
view: shows objects at runtime.
TYPES
PRIMITIVE
predefined by java, include int, boolean, etc
stored in a variable
OBJECT
defined by classes
not stored in variable, instead reference to object is stored.
OPERATOR
De Morgan's Laws
In Java we can say that the following conditions are equivalent
! (A || B) is the same as ! A && ! B
! (A && B) is the same as ! A || ! B
+
- concatenation
Using this with a string then a number will convert the number to a string.
Using with 2 numbers will result in the numbers being added.
INCREMENT
new
This is used when creating an object
new ClassName (parameter-list)
This creates an object of the named class.
Executes the constructor of that class.
Assigning this to a variable creates a reference to that object from a different class.
E.g. if a class has in its constructor this statement: hours = new NumberDisplay(24);
This creates an object, and a reference to that object so that when we want to deal with that object, we can use 'hours' to do so.
Its possible for a class to have more than one constructor. This is called
overloading
.
A
zero-argument
constructor is one without parameters.
METHOD CALLS
Internal method call
When method call and method code are in same class.
Hence, no 'variable.method()' syntax. Just 'method()'.
You can use "self.methodName" where self means this object. Or you can just name the method directly without "self"
External method call
A method call to a method of another object
'object.methodname()'
this
parameters and variables can have the same name.
public MailItem(String from, String to, String message)
{
this.from = from;
this.to = to;
this.message = message;
}
Why can't I write from = from?
If I do, then the parameter 'from' will be used because it is the closest enclosing block to where it is being used.
Writing 'this' signifies that the 'from' field from the object that is using it will be used. So it negates the use of the parameter 'from'. So we can use 'this' to use the field instead of the parameter.
So:
field named
from =
parameter named
from;
We do this for readability reasons. We could just use different parameter names. But that would make reading the code more difficult.
Some names are just perfect.
CH2
: Understanding Class Definitions
Classes contain:
definitions of fields
constructors
methods
CLASSES
A class has 2 main parts:
Outer wrapping - 'class header'
Inner part - 'body'
Body
CLASSES
contain fields, constructors and methods
FILEDS
store data
another name for field = instance variable
usually start with 'private'
include a data type
include a user chosen name
end with semicolon
Fields are defined outside of methods.
They persist through the life of the whole object.
Are accessible to all of the object's methods.
If a field's value cannot be changed once initialized, we say it is
immutable
.
CONSTRUCTORS
construct the object. Otherwise known as initialisation.
after an object is constructed, it is no longer used.
The constructor initialises the fields, hence the fields and constructor have a close relationship.
Constructor's name always matches the name of its class.
A constructor never contains a return statement.
METHODS
implement behaviour of the object
Contain header and body
Method
HEADER
:
method headers have return type. constructors do not have return types
method wrapper includes the header + the part with the round brackets.
method header must have a return type or indicate 'void' to show nothing will be returned.
Method
BODY
contain declarations and statements that define what an object does
4 more items...
ACCESSOR
methods
return information to the caller about the state of the object.
usually contain a return statement.
aka
GETTER
these methods often prefixed with 'get'
MUTATOR
methods
methods that change the state of the object via certain operations.
aka
SETTER
these methods often prefixed with 'set'
Common method is println(). Which is a method of the 'System.out object that is built into Java.
Class header
Often contain the words 'public' and 'class'. These are called key words or reserved words. There are 50 of these in Java.
Java key words never contain capital letters.
provides the name for the class. Usually starting with an uppercase letter.
PARAMETERS
defined in the header of a constructor or method.
makes data from outside the constructor or method available inside.
formal parameters
= the name given to a parameter
if multiple parameters, then separate with a comma.
actual parameters
= the actual value assigned to the formal parameter.
Is only available within the body of a constructor or method. The scope is restricted.
the scope of a field, however, covers the whole class.
The
lifetime
of a parameter is limited to a single call of a constructor or method.
ASSIGNMENT
: copying a short-lived value stored in a parameter into a more permanent variable.
assignment is usually done in the body near the beginning with an assignment statement.
the data type of the parameter must match the data type of the variable it is assigned to.
CONDITIONAL STATEMENT
aka = if statements
if (test) {
do something
}
else {
do something else
}
the 'test' part is a boolean expression which usually has an '
operator
'
the context can affect an operand. E.g. in concatenation, the '+' symbol might convert an int variable to a string. Operands that are altered by their context are called '
overloaded
' operators.
unary
operators have only one operand. E.g. '++'
binary
operators have 2 operands.
the 'else' part is not necessary to compile the code.
3 kinds of
VARIABLES
Fields
fields defined outside constructors and methods
store data that persists throughout the life of an object.
have class scope
means that methods can change the values of these.
if defined with 'private', fields cannot be accessed outside the class in which they are defined.
structure:
public/private type name
parameters
persist only for the period that a constructor or method executes.
defined in the header of a constructor or method
local variables
persist only for the period that a constructor or method executes.
defined inside the body of a constructor or method
must be initialised before they are used in an expression.
not accessible from anywhere outside the block in which they are defined.
Ch5
: Functional processing of Collections
Processing data starts with a data source and ends with a method that collects the results.
Java was at first an
imperative
language. but then was modified to have
functional
qualities as well.
Lambdas
and
streams
(closures) were added.
LAMBDAS
A segment of code that can be stored and used later.
The segment of code could be a parameter, and could be passed to a method.
Structure when lambdas are applied to collections:
collection.doThisForEachElement(some code);
Syntax
Similar to a method, but does not belong to a class.
(parameter) ->
{
Something to do;
}
Note that no private/public keyword, nor is a return type required. These are inferred from the context.
Basically, it works like...parameter...do something to the parameter
Used for once-off tasks.
Know as
anonymous
functions
The predicate: takes at least 1 argument and returns a boolean.
STREAMS
Similar to collections, but...
Elements accessed sequentially, not by index.
Content and ordering cant be changed.
Could be infinite.
functions
filter function
filters out an existing stream by some conditions and produces a new filtered stream.
intermediate operation and outputs a new stream.
This filter operation is a method that takes a lambda as a parameter (called a predicate).
The lambda returns a boolean result. One that represents whether the list item matches or not the filter condition.
E.g. 1
aList.stream().filter(s -> "aCondition".equals(s.aMethod()))
E.g. 2
{
sightings.stream()
.filter(s –> animal.equals(s.getAnimal()))
.forEach(s –> System.out.println(s.getDetails()));
}
First creates a stream, filters it based on the given parameter which results in a new stream. The new stream is then run through a forEach loop that gets the details of each item in the loop.
map function
maps each element of a stream to new, different elements. A new stream of the new, mapped elements is created.
reduce function
collapses all elements in a stream into a single result.
It is a terminal operation.
Takes 2 parameters
The first one is called an identity, and it is like a counter of a running total.
The second parameter is a lambda. with 2 parameters. One for the running total and one for the current element of the stream.
E.g
sightings.stream()
.reduce(0, (total, count) -> return total + count);
Pipelines
chaining of 2 or more functions.
Always start with a source stream, followed by sequence of operations.
2 kinds of operations - (1)
intermediate
(all operations before the terminal one) and (2)
terminal
(last operation).
intermediate operations always produce a new stream.
terminal operations always produce a result, or are void.
Chapter 7: Fixed-size Collections
-UNFINISHED MATERIAL
This chapter is about
arrays
, with a small 'a'. These are different to ArrayLists, which are a specific java class. Main different I think is that arrays must have a fixed size.
Main advantages:
Fetching info form an array is quite efficient.
Arrays can store either primitive data-types or Objects. ArrayLists for example can only store objects. Note: that an int needs to be autoboxed in order to go into an ArrayList.
array variables
Declaring an array variable.
private int[] hourCounts;
The square brackets is the main feature that create a variable of type integer array.
int is called the
base type
of this array.
After declaration, you need to create an array object.
hourCounts = new int[24];
General form:
new type[integer-expression]
type is about the type of items to store.
integer-expression specifies size of array.
Using arrays
Get value by index: hourCounts[3] refers to the forth item in the array.
Set value in array by simply:
hourCounts[3] = 45;
This set the value of the forth item in the array to the int 45.
for loop
useful for when:
we want to execute some statements a fixed number of times.
we need a variable whose value changes a fixed number of times by a fixed amount.
Its good for situations that require
definite iteration
.
Its actually close to a while loop than a for each loop.
Which loop to use?
You know how many iterations
for loop
You dont know how many iterations
while loop
you're dealing with a collection
for each
You need to remove items from a collection
for loop + iterator.
Two-dimensional Arrays (NOT ASSESSED)
Basically, an array where each element is itself a one dimensional array.
Declare:
int[][] myArray = new int[3][5];
convention: first array[3] are the rows, the second array[5] are the columns.
Initialise:
int[][] myArray = {{4, 3, 1, 5, 3}, {9, 5, 3, 8, 2}, {4, 2, 9, 4, 3}};
each curly '{' is a row.
To access, do like this:
myArray[2][3]. This will access row index 2, col index 3.
If you go myArray[0], then you will access the entire first row.
.length will give the number of rows.
myArray.length
to get the col length, you go:
myArray[0].length. The number of cols in first row.
To loop over either the rows or the cols, you need to fix one of them, then loop over the other.
Like this:
for (int i = 0; i < myArray[0].length; i++){System.out.print(myArray[2][i]);}
This will iterate over each col in row index 2.
A neater way is like this:
for (int aRowElement : myArray[2]){System.out.print(aRowElement);}
To print each element in a col, we can do like this
for(int i =0; i < myArray.length; i++){System.out.print(myArray[i][4]);}
PREQUEL
Fundamental Hardware and Software
Source code is translated to machine code
Programming code is high level
Machine code is low level
Compiler translates source code to machine code.
COMPILE
Interpreter also does this, but a line of source code at a time when it is required.
Compiler first checks if source code conforms to syntax rules of the language. If check is successful, then it is turned into machine code.
Different computers use different compilers, so sometimes its not simple to run software on different computers.
So virtual machines (VMs) help with this. It resides on top of an OS.
Here, the source code is translated into intermediate code which is the code of the VM instead of into hardware dependent machine code.
This code is called bytecode, not machine code.
It allows code to be used on different hardware.
3 Options from bytecode
Include an interpreter in the VM which translate source code into machine code specific to the hardware being used.
Static compilation: VM translates all intermediate code into machine code in one go. Traditional approach.
Just in time compilation (JIT): Used by Java VM. It both compiles and interprets. The VM translates intermediate code into machine code, which is then stored. Subsequent source code is then interpreted.
Computer is a layered device.
Bottom to top:
Hardware.
OS
Software and JVM + Java Programs
Object Technology
Procedural programming: step-by-step.
Has a main program that contains further, smaller programs like functions.
Problem can be that this method relies on data structures, which if changed, could result in a need to change all the functions of the entire program.
Object-oriented programming (OOP)
Instead of procedural approach, do OOP. Maps the real world by creating objects that interact with each other. (How these cant be considered as functions is not clear to me).
It seems that in answer to my question in brackets in previous bubble, software components, which are reusable pieces of software, include data in their make-up. And if they are termed as objects, then having the data paired with the object would make it seem quite different from the procedural approach.
JAVA
Java Development Kit (JDK), Private. Will be used in this module.
Java Runtime Environment (JRE). Public
Chapter 9: Debugging
Compile-time errors
: errors that cause compilation to fail.
Aka
static errors
. These errors can only be identified without the program running.
Unreachable error
: when a statement lies beyond a return statement
Runtime errors
: errors that occur after the program is compiled and is running.
logical errors
fall in this category. The program is not logical for some reasons and when running, leads to an error.
aka bugs
Do
testing
to deal with logical errors.
Design by contract
means that the coder is at fault if the code is used incorrectly. If you obey the 'code' then it will perform as expected.
Defensive code
: write code in such a way that it shows you if errors in logic are around.
Some ways to test:
Document when code is not expected to work.
2.
Positive testing
: test will known, correct outputs.
Test with values that should not work, aka
negative testing
.
Boundary testing
: test with values near the boundaries of what might lead to correct or incorrect output. Linked to '
off-by-one
' error, where the code logic calculates the output by one 'thing' being off. x < 0, or x <= 0.
Regression errors.
These could occur when new feature is added to already existing code, which generates outputs that have not been tested for. Hence, the new outputs dont 'gel' with the older code and causes errors.
Exceptions
: errors that occur at runtime.
Exceptions are objects that are created by an exception class.
Common exceptions:
ArrayIndexOutOfBoundsException
- program tries to access an array with an index outside the array's limits.
ArithmeticException
: like dividing by zero. Math error.
NullPointerException
: try to call method when reference var is null.
NumberFormatException
: when stong to int converter method gets an arg with wrong format.
StringIndexOutOfBounds
: when try to access the part of a string that is out of its bounds.
StackOverFlowError
: when so many methods are called that the stack space has become full.
These are classes.
Debugging Principles
Check documentation
Wrint one thing, fix one thing.
Use skeleton code and wrappers.I.e. Test with dummy variables first. Progress step by step.
Read every character of your code.
Be persistent, take breaks.
Explain your code to yourself.
Draw a picture/sketch diagrams.
Use tools.
Keep backups.
Ask in forums.
Ch4
: Grouping Objects
COLLECTIONS
A collection is a bunch of objects grouped together. OR
A data structure that allows us to store references to multiple objects and perform operations with them.
Like a group of students, the course one student is taking, etc.
Operations can be done to the collection, like sorting in some way, reducing it, etc.
Its kind of like a class itself.
Which can have instances, and those can have objects.
And there are libraries of these in java.
In java these are called packages
Packages contain a number of classes that are useful to programmer, like the
ArrayList
class from the
java.util
package.
1 more item...
LOOPS
Aka:
iterative control structures
.
for-each loop
for (
ElementType element : collection
) {
loop body
}
pseudo-code
:
for each
element
in
collection
do: {
loop body
}
E.g.
for (String filename : files) {
System.out.println(filename);
}
You can see that the "String filename" part is a declaration of a new variable that is then used in the loop body. Its the counter.
This counter is called the
loop variable
.
The variable can be named anything we want, but its type should match the type that is in the collection.
Used to process whole collections.
Could be called a
definite iteration
(it has a start and end point).
while loop
Aka:
indefinite iteration
while(
boolean condition
) {
loop body
}
pseudo-code
:
while (whatever is true) do: {
loop body
}
More complex to code than a for each loop because you have to make your own counter, and each element in a list needs to be extracted.
possible to write an infinite loop.
Benefits: (1) does not need to run on a collection. (2) does not need to process every item in a collection.
Used to
search
for things in collections and elsewhere.
What if you do not find what you want? Then you need a way to end the loop or it will become an infinite loop.
the boolean condition part of the loop and using an index can limit the number of iterations and bring the loop to an end.
Two ways to end a search. (1) finding the thing you are looking for. (2) The thing you are looking for is not there. There needs to be a way to alter the while boolean condition if either of those results are encountered.
Iterator
There is the Iterator class/interface, and there is the iterator (small 'i') method that belongs to the ArrayList class.
Using the iterator method on ArrayList will produce an Iterator object that has 4 methods, 2 of which are hasNext() and next(), both of which have non-void return types.
pseudo-code
:
[FIRST, create the Iterator object]
Iterator<
ElementType
> it = myCollection.iterator();
[THEN, use a while loop to use it]
while(it.hasNext()) {
call
it.next()
to get the next element
do something with that element
}
indefinite
method of iteration
Possible to remove items in the collection with this method. Only the last item retrieved from the Iterator's next method can be removed.
It is a
generic type
.
All collections provide the iterator method
CH1
: Objects and Classes
CLASSES
: the blueprints of objects
OBJECTS
: an example of a particular class
have data fields, the value of the data tells us the objects
state
.
Otherwise known as
PARAMETERS
.
can have their own unique characteristics
Instance is used interchangeably with objects sometimes.
An object has
fields
, that are determined by the class of an object. These give the object characteristics. Every field has a certain value.
Each object has a copy of the characteristics of the class, but may vary in terms of what each characteristic is. E.g. characteristic = colour, specific = 'red'.
The values that each field has sets the state of an object. To change the state, we can't just change the object. Instead, we should 'ask' the object to change so and so characteristic by invoking a method.
Objects do 'operations' which are 'actions' that an object can do.
Operations are implemented using '
METHODS
'
The nomenclature is to say 'invoke a method' or 'call a method'
Some methods require additional values called
PARAMETERS
.
There can be many parameters.
All the values of all the parameters set an object's '
STATE
'.
Another way to say is "objects have
ATTRIBUTES
that are stored in fields which set an objects state."
Objects of the same class have the same set of attributes, but the values of each might be different. These are defined by the class.
Other objects can be used as parameters for methods of other objects.
Method Structure:
header eg: void moveHorizontal (int distance)
ínt distance' is a parameter
ínt' is the
data type
of parameter. 'distance' is the name of the parameter.
'void' means that nothing is returned. If something like 'String' is there in place of 'void' then it means that a value of string data type will be returned by the method.
Objects of the same class have the same set of methods.
Methods can change an objects state, or return values that represent its current state.
Each object made from a class are independent after being made.
Objects can create other objects
labelled by capitalising the first letter.
A class should represent a distinct kind of object.
This means that one program could have multiple classes, and therefore multiple objects.
Chapter 8: Code Conventions and Design
Use as a reference