- Lecture
- Week 1
- 1.1 Java Fundamental
- 1.2 Type and Variable
- Primitive Types
- Casting
- Command Line Arguments
- Scanner - Standard Input
- Ternary Operator - Reduce long if-else statement
- Rounding to Nth decimal
- Compare String
- String is immutable
- Week 2
- 2.1 Control Flow
- do-while loop
- for-each loop
- call-stack
- increment difference
- 2.2 Arrays
- 1. Initilization
- 2. Reference Type Array
- 3. Multidimensional Array
- Week 3
- 3.1 Class
- Basic Knowledge
- Access Modifier - Controls the access level
- this keyword
- 3.2 UML (Unified Modelling Language)
- 3.3 Text-based I/O
- Reading from Files
- Writing to Files
- Week 4
- 4.1 Binary I/O
- 4.2 Stack & Heap
- Stack
- Heap
- Garbage Collector
- 4.3 ADT (Abstract Data Type)
- Collection
- ArrayList - Dynamic Array
- LinkedList
- Map & Set
- Week 5
- 5.1 Inheritance
- What does it offers
- Constructor
- Relationship
- Overloading Methods
- Constructor Overloading
- Overriding Methods
- **Definition:**
- **Runtime Polymorphism (Which method will be called?)**
- **Rules:**
- 5.2 Exception (Week 8 in detail)
- Week 6
- 6.1 Abstract Class
- 6.2 Interface
- Features
- Interface Type
- Default method
- 6.3 Package & Classpath
- Package
- Classpath
- Week 7
- 7.1 Generics
- Generic in Data Strcture
- Without Generic
- With Generic
- Generic Static Method
- Type Parameter Constraint
- Generic Arrays
- 7.2 Iterators
- Week 8
- 8.1 Exception
- Except Types
- Handling Exception
- 8.2 Enums
- 8.3 Test
- Assertion
- Testing
- JUnit - white box testing
- Setup
- Compile
- Execution
- Annotation
- Test Methods
- Week 9
- 9.1 Recursion
- 9.2 Memoization (Cache)
- 9.3 Javadoc
- Week 10
- 10.1 Anonymous Class
- 10.2 Lambdas (Anonymous Method)
- 10.3 Functional Interface (Where Lambdas Exist)
- What if the functional interface is generic?
- 10.4 Differences between Anonymous Class and Lambdas
- Week 11
- 11.1 Wildcards - Generics Helper
- 11.2 Debugging at Runtime
- Week 12-13
- True & False
- Variable Declaration
- Method Signature
- Tutorial & Challenge
- Week 2 notes
- 1. **char -> int**
- 2. **print out array nicely**
- Week 3 notes
- Modmad
- Week 5 notes
- Week 8 notes
- 1. get an array of enum types
- Week 9 notes
- 1. turn an array to a fixed-size list
- 2. calculate method running time
- Week 10 notes
- 1. array sort
- Week 12 notes
- 1. incrementing value in HashMap
- Quiz 1 notes
- 1. add an element in a list
- 2. overloading methods (same name and different signature)
- 3. sort customed linkedlist in ascending order
- Quiz 2 notes
- knowledge notes
- exception catch order
- Java is a compiled language and therefore there is an extra step to compile sourcecode to bytecode.
- After compilation has been successfully completed we are able to now execute our program using the java virtual machine (jvm).
- Hardware and Memory
- CPU: central procssing unit (follow programs’ instructions)
- Memory: main (volatile) / auxiliary (not volatile)
- RAM: random access memory -> main memory
- Hard drive -> auxiliary memory
- Address: the number of a byte
- Byte: smallest addressable unit of memory (a byte contains eight bits of memory)
————————————————
版权声明:本文为CSDN博主「误入CS的T酱」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_53212038/article/details/114673904
Unlike interpreted languages like python, Java has a separation of
primitive types and reference types.
- Widening Casting (automatically) - converting a smaller type to a larger type size (no value will be lost).
byte -> short -> char -> int -> long -> float -> double int myInt = 9; double myDouble = myInt; System.out.println(myDouble) -> 9.0
- Narrowing Casting (manually) - converting a larger type to a smaller size type (may lose some digits).
double -> float -> long -> int -> char -> short -> byte double myDouble = 9.8; int myInt = (int) myDouble; System.out.println(myInt) -> 9
if an arithmetric expression involves in larger type size, it will automatically convert the variable into large type size.
int numberOfItem = 1; double price = 1.0; System.out.println(numberOfItem/2); -> 0 // int/int floor division System.out.println(price/2); -> 0.5 //2 has been converted to 2.0 System.out.println(price/numberOfItem); -> 1.0 //1 has been converted to 1.0Command Line Arguments
- An array of String type, starting with index 0
- We often need to parse it into other datatype before use them
$java MyProgram firstArg secondArg .......Scanner - Standard Input
if we want to read from standard user input, we need to utilize scanner object with System.in as its parameter
Scanner myScanner = new Scanner(System.in);Ternary Operator - Reduce long if-else statement
variable = (condition) ? expressionTrue : expressionFalse
int marks = 60; String result = (marks >= 50) ? "Pass" : "Fail"; System.out.println(result); -> PassRounding to Nth decimal
//normal Math.round works by adding 0.5 then omit the decimal part Math.round(1023.149) -> 1023 Math.round(23.549) -> 24 //if we want to round a number to Nth decimal //e.g. rounding 1.61823 to 3rd decimal Math.round(1.61823 * 1000)/1000.0 -> 1.618 //e.g. rounding 1.61823 to 2nd decimal Math.round(1.61823 * 100)/100.0 -> 1.62Compare String
-
When comparing primitive types, we use == since it contains its
real value. However, if we use == to compare reference type, it
will test the equivalence of the memory reference, rather than
comparing its value. -
If a string literal is specified, it will be added to a string pool. This allow the compiler to optimise for memory usage. The compiler will use the same allocation and provide same reference to a string variable of refers to the same literal.
String cat1 = "Meow"; -> 0x1001
String cat11 = "Meow"; -> 0x1001
System.out.println(cat1 == cat11); -> true // since they have the same string literal
String cat2 = new String("Meow") -> 0x1002 //new allocation of memory
System.out.println(cat1 == cat2); -> false
System.out.println(cat1.equals(cat2)); -> true
String is immutable
Since String is an immutable data type, each time we use + to concatenate a String actually creates a new reference to the new String, which can be a costly of momery. --> Use StringBuilder will be an optimal solution
Week 2 2.1 Control Flowbesides normal while and for loop, java has provided two more loop structures.
do-while loopSyntax:
do {
doWork();
} while(condition)
Similar to the while loop but it will always execute the block at
least once and continue execution if condition is true
Syntax:
for(Type element : collection){
doSomething(element);
}
for-each loops involve the use of iterators (if we want to use for-each loop for a collection, it must be an iterator first)
call-stack- Java is a stack-based language so when a method is executed it is put onto a call stack.
- The method being executed at the top of the stack is the most recently called method.
- A method finishes executing once it has reached a return state or for void method, once it has reached the end of method scope.
i++ - post-increment: excute the line first, increment later
++i - pre-increment: increment before excution
int i = 0;
while(i < 5){
System.out.println(i++); // print 0 to 4
}
while(i < 5){
System.out.println(++i); // print 1 to 5
}
2.2 Arrays
An array is a contiguous block of memory containing multiple values of the same type.
1. Initilization • allocate memory and specify size: `int[] myArr = new int[10];`
• static initilization: `int[] numbers =={1, 2, 3, 4}; //Not often`
• more often initilization with pre-defined values: `int[] numbers = new int[]{1,2,3,4;}`
2. Reference Type Array
It stores the memory address of the reference type (8 byte), which means that reference type arrays do not contain a object but a reference to a object.
3. Multidimensional ArrayThere are two types, one adheres to a matrix like structure (rows == cols) and the other is commonly referred to as a jagged array(rows != cols).
//Matrix-like structure int[][] array = new int[3][3]; //Jagged structure int[][] jarray = new int[3][]; // in this situation, it takes each entry as the memory address reference to the inner array object jarray[0] = new int[5]; jarray[1] = new int[10];Week 3 3.1 Class Basic Knowledge
- reference types are classes;
- Objects are instance of a particular class, its type is the class;
- new keyword allocates memory and instantiates an object;
- Every class in Java has a Constructor even if it is not explicitly defined;
These modifiers refer to how the data is exposed to other objects and classes. (Encapsulation)
Class level
- public: The class is accessible by any other class
- default (no keyword): The class is only accessible by classes in the same package
Attribute level (methods, constructors…)
the accessibility reduces from top to bottom
- public: The code is accessible for all classes.
- protected: The code is accessible in the same package and subclasses.
- default(no keyword): The code is only accessible in the same package.
- private: The code is only accessible within the declared class
- The this keyword allows the programmer to refer to the object while within an instance method context. We cannot use the keyword within a static context.
- Reduces ambiguity.
- Refers to another constructor for code reusability.
- Represents current object.
UML is a visual language to assist with designing applications and systems.
Overal Structure:
| Class Name |
|---|
| attributes |
| instance methods |
Attributes Structure:
(access modifer) attribute name : type information
Methods Structure
(access modifer) method name : return type
-
“+” means public;
-
“-” means private;
-
“#” means protected;
-
“~” means package;
-
abstract class and polymorphic methods will be italicised;
-
<< interface >> means it is an interface;
-
A class with generics as a Template Class and it contains annotation of its type information and notable upper bound on top-right corner;
-
Inherited class is connected to the superclass by generalization link (is-a relationship);
- Implementer and interface is connected by realization link
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class FileHandle {
public static void main(String[] args)
File f = new File("README.txt");
Scanner scan;
try {
//we must check whether the file exists when reading
scan = new Scanner(f);
} catch (FileNotFoundException e){
System.err.println("File not found!");
}
}
- Should use try-catch block in case file does not exist. Notice we initialize scanner inside it but declare scanner outside of it (so that its scope is not limited to it, i.e. its contents will be
wiped from memory as soon as we leave the try-catch block!)
import java.io.PrintWriter;
import java.io.File;
import java.io.FileNotFoundException;
public class FileHandle {
public static void main(String[] args)
File f = new File("README.txt");
try {
//we must check whether the file exists when writing
PrintWriter writer = new PrintWriter(f);
writer.println("First line");
writer.println("Second line");
writer.close(); // we need to close the file after we write all the data into it.
} catch (FileNotFoundException e){
e.printStackTrace();
}
}
Week 4
4.1 Binary I/O
- .class files are not human readable, just like image formats and executables;
- We can use DataInputStream, DataOutputStream and use the available methods such as readChar, writeInt to read or write binary file.
Reading binary file
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException; // must catch IOException
public class BinaryReader {
public static void main(String[] args) {
try {
FileInputStream f = new FileInputStream("newfile.bin");
DataInputStream input = new DataInputStream(f);
int n = input.readInt();
System.out.println(n);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
}
}
Writing binary file - Same procedure, only changing the class to output
import java.io.DataOutputStream; import java.io.FileOutputStream; import java.io.FileNotFoundException; import java.io.IOException; // must catch IOException4.2 Stack & Heap Stack
- Everytime we invoke a method it will be placed on the top of the stack.
- A stack frame can be thought of as an instance of a method.
- Each method has a size which is the combination of its instructions, variables and argument data.
- Each stack frame has a return address.
- Stack based objects exist in lexicographical scope. (inside the {} braces)
-
The heap is separate memory space for which objects are dynamically allocated.
-
Whenever we use the new keyword, memory for the object is allocated and an address is returned. (However, primitive types will copy the value instead of the address)
-
While heap objects can be aliased and their lifetimes are dictated when all references are no longer in scope.
Java employs the use of a garbage collector to free memory. Any memory that is allocated using the new keyword will be kept on the heap. The garbage collector will subsequently free any allocation that no longer has a reference during execution.
4.3 ADT (Abstract Data Type)An abstract data type (ADT) is a type that is an aggregation of other types. - reference type
CollectionCollections or aggregate types allow us to store data in the
appropriate objects.
It will double its size when there is no enough space for another element
LinkedList- Each element contains a value and a link to the next element (Node).
class Node{
int value;
Node next;
}
Map & Set
A Map and Set provides a mapping of an object to location where that element is stored.
- Each key maps to a value
- Each key is unique, but values may be the same
- Keys and values should both be classes (reference types)
Iterating Keys from HashMap
HashMapm = new HashMap<>(); for (KEY_CLASS_TYPE key : m.keySet()) { System.out.println(m.get(key)); }
Incrementing values
- Traditional way
if (m.containsKey(KEY)) {
m.put(KEY, m.get(KEY) + 1);
} else {
m.put(KEY, 0);
}
- Using getOrDefault()
for(Key each : KeySet){
map.put(each,map.getOrDefault(each,0)+1);
}
- Using merge()
m.merge(KEY, 1, Integer::sum);Week 5 5.1 Inheritance What does it offers
- Attributes and methods reusability
- Defining sub-class methods
- Overriding inherited methods
- Type information provided
Syntax:
[public] class ClassName extends SuperClassName
It will inherit any protected or public methods or attributes from the superclass.
Constructor- Scenario 1: Assuming the default constructor is given to the
superclass, the subclass does not need to define one. (It will implicitly calls on super() which is the parent class default constructor.)
class Bottle{
protected String name;
protected double width;
protected double height;
public Bottle(){
this.name = "Basic Bottle";
this.width = 10.0;
this.height = 10.0;
}
}
class GlassBottle extends Bottle{
private boolean isBroken;
}
public class BottleTest{
public static void main(String[] args){
// this works even if the GlassBottle class doesn't have defined a constructor, it refers to the superclass default constructor
GlassBottle gb = new GlassBottle();
}
}
- Scenario 2: The superclass has only defined constructor with parameters, which makes it no longer has default constructor (condition), the subclass must invoke the super constructor. (Using the super keyword, we are able to refer to inherited constructors and methods).
class Bottle{
protected String name;
protected double width;
protected double height;
public Bottle(String name, double width, double height){
this.name = name;
this.width = width;
this.height = height;
}
}
class GlassBottle extends Bottle{
private boolean isBroken;
}
public class BottleTest{
public static void main(String[] args){
// this won't compile since it didn't invoke the only superclass constructor
GlassBottle gb = new GlassBottle();
}
}
It will raise compiler error, since the subclass didn’t invoke the only constructor of superclass
How to fix?
class GlassBottle extends Bottle{
private boolean isBroken;
public GlassBottle(String name, double width, double height){
// super() must be the first line of subclass constructor
super(name,width,height);
this.isBroken = false;
}
}
Constructor is responsible for object setup, if we don’t set up parent class properly first, then the child class won’t work well as it is extended from parent class.
That explains why each time we set up a child object, it will automatically calls on super() first even if we don’t put super() there. And that’s way we always need to put super keyword at the first line)
There are two types of relationships we will look at when it comes to inheritance.
- Is-a relationship (Extension, Inheritance)
- Has-a relationship (Composition)
Superclass vs Subclass
- Subclasses cannot be constructed using a superclass constructor, but you can bind superclass type information when creating a subclass object.
Subclass a = new Superclass(); //NOT WORKING Superclass a = new Subclass(); //WORKING
- Superclass does not know about its subclasses (You cannot use subclass properties through a superclass binding.)
- You can only inherit from 1 class, but one superclass can have multiple child classes.
Declaring an subclass object but binds to superclass type
By doing so it will treat our subclass object as the superclass type, hence it has access to all attributes in the superclass, but it will lose information about the original subclass
public class Vehicle {
private String colour; //notice we make the colour as private
public Vehicle(String colour) {
this.colour = colour;
}
public static void main(String[] args){
Vehicle t = new Toyota("red");
System.out.println(t.colour) // we can get access to colour even if we declare an Toyota object, because it binds to the Vehicle
}
}
class Toyota extends Vehicle{
public Toyota(String colour){
super(colour);
}
}
Overloading Methods
In regards to Java we are able to use the same method name but
with different method signature . (P.S. method signature is its parameters, not return type)
- We are able to define a method such as add and have a version that accepts two integers and another version that accepts three integers. (Java is able to link to different methods by looking at its signature)
public int add(int a, int b){}
public int add(int a, int b, int c){}
- However, since the method return type is not a part of its signature, we can’t apply overloading methods with the same parameter but different return type (it is invalid since the compiler doesn’t know which method it refers to)
public int[] crossProduct(float[] a, float[] b){}
public float[] crossProduct(float[] a, float[] b){}
- Ambiguous overloading scenario
What if we have two overloading methods look like this
int[] crossProduct(int[] a int[] b) int[] crossProduct(float[] a float[] b) //METHOD CALL int[] x = crossProduct(null, null); int[] y = crossProduct(null, null);
In above situation, the compiler would be unable to determine exactly
what method is trying to be called (cuz null belongs to both int[] and float[]) and will throw an error.
How to fix? - Mannual Type Casting
By casting the reference to a certain type, the compiler can deduce what method to call
int[] x = crossProduct((int[]) null, (int[]) null); int[] y = crossProduct((float[])null,(float[]) null);Constructor Overloading
Since one class can have multiple constructors with different unique signature, the this keyword allows us to refer to other constructors within the context of a class. (Reusing constructor helps reduce the amount of code)
Overriding MethodsRetrieved from: https://www.geeksforgeeks.org/overriding-in-java/
Definition:Runtime Polymorphism (Which method will be called?)When a method in a subclass has the same name, same parameters(aka signature), and same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class.
The version of a method that is executed will be determined by the object that is used to invoke it. In other words, it is the type of the object being referred to (not the type of the reference variable) that determines which version of an overridden method will be executed.
In following situation, DefaultObject is the type of the reference variable, while MyObject is the type of the object being referred to.
class MyObject extends DefaultObject; DefaultObject obj = new MyObject();
Example:
// A Simple Java program to demonstrate
// method overriding in java
// Base Class
class Parent {
void show(){
System.out.println("Parent's show()");
}
}
// Inherited class
class Child extends Parent {
// This method overrides show() of Parent
@Override
void show(){
System.out.println("Child's show()");
}
}
// Driver class
class Main {
public static void main(String[] args){
// If a Parent type reference refers
// to a Parent object, then Parent's
// show is called
Parent obj1 = new Parent();
obj1.show();
// If a Parent type reference refers
// to a Child object Child's show()
// is called. This is called RUN TIME
// POLYMORPHISM.
Parent obj2 = new Child();
obj2.show();
}
}
Output:
> Parent's show() > Child's show()Rules:
-
Access modifier in overriding methods only allows same or stronger modifiers, not weaker. (public > protected > default > private);
This example above will raise compiler-error since the ChildClass overriding method price() has weaker access modifier than ParentClass. -
Final methods can not be overridden;
-
The overriding method must have same return type (or subtype);
-
We can invoke overriden method in the subclass overriding method using super keyword;
// A Java program to demonstrate that overridden
// method can be called from sub-class
// Base Class
class Parent {
void show(){
System.out.println("Parent's show() is called");
}
}
// Inherited class
class Child extends Parent {
// This method overrides show() of Parent
@Override
void show(){
super.show(); // invoke superclass overriden method
System.out.println("Child's show() is called");
}
}
// Driver class
class Main {
public static void main(String[] args){
Parent obj = new Child();
obj.show();
}
}
Output:
> Parent's show() is called > Child's show() is called5.2 Exception (Week 8 in detail)
- Exception and any subclasses (with the exception of RuntimeException) is a checked exception, the programmer must handle it using a try-catch block.
- RuntimeException and any subclasses, is an unchecked exception. The programmer does not need to handle this case but can catch if they want to.
Notes:
- Generalization of many other types;
- Enforces methods implementation for subtypes;
- Works exactly like normal class (have constructor, attribute, can define static and non-static methods) but it cannot be instantiated as an object;
- An abstract class must have at least one abstract method(aka polymorphic method);
Example:
Shape is a generalisation of Triangle, Square, Circle but we don’t have a concrete instance of Shape.
Syntax: [modifier] abstract class ClassName
We can define abstract methods in only abstract classes, and we don’t define the method body when a method is abstract. The subtypes must implement all the abstract methods in the abstract superclass.
Abstract Class vs Interface:
Class heirarchy infers to a clear generalisation of a type while interfaces infers to an shared behaviour between types.
- Shares similarity with abstract classes in that it declares methods that a class must implement and it cannot be instantiated as well;
- However, a class can implement as many interfaces as they want, but can only inherit from one abstract class;
- Interface cannot specify any attributes (except static and final attributes), but only methods;
- Do not provide method definition, it will treat all methods like abstract methods (except default method);
Tips: Treat classes implements the same interface as the interface type will guarantee they are able to use the methods declared in the interface.
Since Dog and Dophin both implements Moveable interface, we can create an Moveable[] to store them, which means treating them as interface type.
Dog dog = new Dog("land");
Dophin dophin = new Dophin("water");
Moveable[] animals = {dog,dophin};
for(Moveable m : animals){
m.move(1.0);
}
public interface Moveable{
public void move(double hours);
}
public class Dog implements Moveable {
private String region; //Water or Land
private double landSpeed_kmh = 50.0;
private double waterSpeed_kmh = 8.0;
private double kmTravelled = 0.0;
public Dog(String region){
this.region = region;
}
public void move(double hours){
if(this.region.equals("water")){
this.kmTravelled += waterSpeed_kmh * hours;
} else if (this.region.equals("land")){
this.kmTravelled += landSpeed_kmh * hours;
}
}
public double getKMTravelled(){
return kmTravelled;
}
}
public class Dophin implements Moveable {
private String region; //Water or Land
private double landSpeed_kmh = 1.0;
private double waterSpeed_kmh = 60.0;
private double kmTravelled = 0.0;
public Dophin(String region){
this.region = region;
}
public void move(double hours){
if(this.region.equals("water")){
this.kmTravelled += waterSpeed_kmh * hours;
} else if (this.region.equals("land")){
this.kmTravelled += landSpeed_kmh * hours;
}
}
public double getKMTravelled(){
return kmTravelled;
}
}
Default method
Syntax: [modifier] default returntype MethodName(params)
When we define default method, subclass can directly utilise them, but they can also override default method if needed.
6.3 Package & Classpath PackageA package is a grouping of related types providing access protection and name space management. It gives the programmer control over the namespace and access of classes. To specify a package name for class, we use the package keyword and specify it at the top of the .java source file.
We are able to import files specified outside of the current directory by using the class path flag during compilation and execution.
Compilation:
javac -cp .:MyProgram.java
Execution:
java -cp .:Week 7 7.1 Generics Generic in Data Strcture Without GenericMyProgram
- We will need to duplicate the class(collection class) multiple times for storing different types.
- We need to store all different reference types as Object to reduce the amount of code.
- When we store them all as Object, we cannot guarrante the correct type for them when calling them, which will raise compiler error.
- Only make a class generic if one of the attributes and/or methods include a generic datatype.
- We can perform manual casting on them to be the correct type, but it is a runtime check and can lead to unsafe assumption.
- Generics gives us the ability to handle multiple different types without needing to rewrite the same code.
- Stronger type checks at compile time.
- Elimination of casts.
- Enabling programmers to implement generic algorithms.
Generics are specified as part of the class definition. We are able to show the parameter types that can be generalised by the class.
Syntax:
[public] class ClassName
Example:
We can define a generic static method within our class that can operate on a set of data (Usage).
Syntax:
[public] staticreturn_type methodName([,Param1..])
Example:
public staticType Parameter ConstraintT find(T needle, T[] haystack); //Actual method call Points. find(point, points);
We can specify an upper bound type when declaring our generic data structure to enforce we can utilise explicit functionality of superclass.
Syntax:
[public] class ClassName
Example:
With this specification, we are able to treat all the element stored in our ShoppingCart as an instance of Item, and utilise all methods in Item class.
public class ShoppingCart
However, If we put wrong type into a generic collection, the compiler will refuse to do this as the type safety is being violated.
Example:
class Liquid{}
class Water extends Liquid{}
class Oil extends Liquid{}
public class Barrel{
public static void main(String[] args){
Barrel waterBarrel = new Barrel();
waterBarrel.add(new Oil()); // it raises compiler error
}
}
Error Message:
Generics work not very well with array as we need to perform an unsafe operation to construct an generic type array.
Scenario:
We are not able to create an array with generic type T, and it raises compiler error.
Solution(unsafe operation):
Construct an Object[] first, and then cast it into Generic type T[].
public DynamicArray(){
@SuppressWarnings("unchecked") //As it is an unsafe operation, we need to put some annotation to get rid of warning message
array = (T[]) new Object[4];
}
If we don’t put annotation @SuppressWarnings("unchecked"), it will compile fine but with some warning message.
Note: JArray.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details.7.2 Iterators
Iterator is an object that allows reading through a collection (for-each loop).
By implementing Iterable
interface Iterable
Iterator
interface Iterator
Example(Customed LinkedList): This is just part of the code
import java.util.Iterator; public class GenericLinkedListWeek 8 8.1 Exceptionimplements Iterable { private int size; private Node head; public GenericLinkedList(){ this.head = null; this.size = 0; } public Iterator iterator(){ return new GenericIterator(this.head); } class GenericIterator implements Iterator { private Node cursor; public GenericIterator(Node head){ this.cursor = head; } public boolean hasNext(){ return this.cursor != null; } public T next(){ Node temp = this.cursor; this.cursor = this.cursor.next; return temp.data; } } class Node { private E data; private Node next; public Node(E data){ this.data = data; } public Node(E data, Node next){ this.data = data; this.next = next; } } }
Exceptions evolve from the state of the machine or program execution being considered invalid.
Except TypesDifferent types of except states and severity:
-
Checked Exception: This ensures you have handled the exception at compile time, it identifies a state that the programmer must handle.
-
Runtime Exception (Unchecked Exception): It is a state that
should occur during runtime and you cannot handle nicely prior. Unless you are expecting the code to raise an exception. -
Error (State that cannot be handled): Errors in Java can be handled by a try-catch block (but it is considered bad practice to catch them) and typically invoked when the state of the program is considered unrecoverable.
throw keyword will raise an exception, while throws keyword determines the method being called has ability to throw a checked exception, which must be handled (using try-catch block).
Checked Exception Example:
Unchecked Exception Example:
An enum is a data type which specifies predefined instances. An enumerated type can be a simple label that only has its label name and order number or can include its own fields, methods and constructor for the type.
- Not able to create new unique instance(cannot invoke new keyword);
- A finite set of instances;
- Managable sequence of instances that share similarity (a deck of playing cards, direction, days of a week…);
- Each instance has an ordinal number within the set. This also allows us to iterator through them.
enum construction:
- Enum values are always capitalized, e.g. SUNDAY rather than Sunday;
- To access values, simply use ENUM_NAME.ENUM_VAL, e.g. Weekdays.SUNDAY;
- To compare values between enum instances, use the equality operator ==;
Variant 1: Only use the instance itself
[public] enum EnumName{
FirstElement, // 0
SecondElement, // 1
ThirdElement; // 2
}
Variant 2: Adding attributes and methods to them
if we make our attributes private, we need to create getter methods to reach those attributes. Another way is to make them public final, hence we can directly reach them by calling the name and no need to worry about that it can be changed by users.
public enum Suit{
HEART(1,"Red"),
DIAMOND(2,"Red"),
SPADE(3,"Black"),
CLUB(4,"Black");
private int number; // public final int number;
private String color;
Suit(int number,String color){
this.number = number;
this.color = color;
}
}
What else can enum do?
- Implement interface;
- Overloading constructors/methods;
- Modify variables within a globally accessible instance.
- Abstract methods (every instance must implement it during declaration);
assert keyword allows checking for thetruthiness of an expression.
Syntax:
assert BooleanExpression assert myList.size() > 10;
assert evaluates an expression and will throw an AssertionError if the statement if false (causing our program to crash). Nothing happens when it passes assertion.
Testing-
Black Box Testing: User centric testing, without knowledge of the internals, input is given and compared to match the output of the program.
-
White Box Testing: This is typically where we employ some unit testing software, to help analyse the internals of the system and test them independently.
JUnit is a common testing framework in the Java ecosystem.
SetupTo set up JUnit you need to acquire junit.jar and hamcrest.jar files and place them in the folder in the same folder as your test class.
CompileCompile using classpath flag -cp and indicate the directory that junit.jar and hamcrest.jar are in.
javac -cp .:junit-4.12.jar:hamcrest-core-1.3.jar MyTestClass.javaExecution
Because we are utilising classes in a java archive file, we will need to
refer to that (org.junit.runner.JUnitCore) when executing our program.
java -cp .:junit-4.12.jar:hamcrest-core-1.3.jar org.junit.runner.JUnitCore MyTestClassAnnotation
Within JUnit we have access to variety of annotations that allow us to determine an order of execution for some of our methods.
Example (Testing for null):
import static org.junit.Assert.*;
import org.junit.Test;
public class TestMethods{
@Test
public void checkForNull() {
Container a = new Container(null);
assertNull(a.get());
}
}
Week 9
9.1 Recursion
Recursion is a technique within computer science that allows calling a function within itself. Difficult problems can often be represented easily with recursion.
A recursion function is made of:
- A base case(or many base cases), where the function terminates;
- Recursive case(or many recursive cases), which will converge to a base case.
Drawbacks:
- The java programming model does not allow for infinite recursion;
- Inefficient with memory;
- Potentially more computationally demanding due to the overhead caused by method calls.
Memoization is a technique for storing the results of a computation for later use. It can boost recursion function speed by reducing function calls on already-computed input.
9.3 Javadocjavadoc is speical comments that can generate html documentation for the java source files. The javadoc identifier starts with
Example:
Annotation:
Generation Command:
It requires us to specify a directory where the documents will be generated (
> javadoc -d
If the java source files contain subpackages, it require the use of the
-subpackages flag to recursively search all .java files and map each package in the document.
> javadoc -dWeek 10 10.1 Anonymous Class-subpackage packageName
An anonymous class is immediately constructed and an instance is returned to the caller.
Features:
- Only one instance of an anonymous class exists;
- It is typically declared within a method;
Syntax:
ClassType instanceName = new ClassType() {
// it constructs in the same way as normal classes
// can have multiple fields and methods (advantages against lambda expression, as lambda expression only works on functional interface)
[fields]
[methods]
};
Example:
interface SayHello{
public void hello();
}
SayHello hi = new SayHello() {
public void hello() {
System.out.println("Hello!");
}
}; // notice the semicolon here, it is the actual ending of line
In this example, we create an anonymous class that can utilise the methods in interface SayHello, which means the anonymous implicitly inherits from SayHello.
Why we do this?
We may want to hold a collection of commands and each command contains a unique implementation of the same method.
Creating different usage of the same method that shares pattern (a calculator that can apply different arithmetric expressions):
import java.util.HashMap;
interface IntegerBinaryOperation{
int apply(int x, int y);
}
public class Calculator{
public static void main(String[] args){
HashMap operations = new HashMap();
operations.put("ADD", new IntegerBinaryOperation() {
public int apply(int x, int y){
return x + y;
}
});
operations.put("SUB", new IntegerBinaryOperation() {
public int apply(int x, int y){
return x - y;
}
});
operations.put("MUL", new IntegerBinaryOperation() {
public int apply(int x, int y){
return x * y;
}
});
System.out.println(operations.get("ADD").apply(1,1)); // -> 2
System.out.println(operations.get("SUB").apply(3,5)); // -> -2
System.out.println(operations.get("MUL").apply(20,operations.get("SUB").apply(3,5))); // -> -40
}
}
10.2 Lambdas (Anonymous Method)
Lambda methods require an interface that declares only one method.
After an interface has been defined and only contains one abstract method (this kind of interface is called functional interface), it can adhere allow the usage of lambda methods.
Steps:
- Prior to defining a lambda, you will need to create a functional interface which your variables will use.
- When defining a variable, you can utilise the interface type and assign it to a lambda expression.
Syntax:
(arg1[, arg2…]) -> functionBody
// if we have multiple lines expressions, using curly braces as indication
(arg1[, arg2…]) -> { functionBody };
EXAMPLES: We define the function expression using "->"
SayHello hi = () -> System.out.println("Hello!");
IntegerBinaryOperation add = (int x, int y) -> x + y;
IntegerBinaryOperation add = (x, y) -> x + y;
Example:
import java.util.HashMap;
@FunctionalInterface
interface IntegerBinaryOperation{
int apply(int x, int y);
}
public class Calculator{
public static void main(String[] args){
HashMap operations = new HashMap();
// using lambda expressions
operations.put("ADD", (x, y) -> x + y);
operations.put("SUB", (x, y) -> x - y);
operations.put("MUL", (x, y) -> x * y);
System.out.println(operations.get("ADD").apply(1,1));
System.out.println(operations.get("SUB").apply(3,5));
System.out.println(operations.get("MUL").apply(20,operations.get("SUB").apply(3,5)));
}
}
10.3 Functional Interface (Where Lambdas Exist)
“A functional interface is an interface that has just one abstract method (aside from the methods of Object, such as equals(Object obj)), and thus represents a single function contract.”
It can have default methods and still be a functional interface. HOWEVER, we cannot use default methods in lambda expressions.
But we can use lambda expressions inside the default methods. In other words, we can utilise defined abstract method (which utilise lambda expression) in the default method call.
Example:
interface SayHello {
public default void howAreYou() {
hello();
System.out.println("How are you today?");
}
public void hello();
}
public class Hello {
public static void main(String[] args) {
SayHello hi = () -> {
System.out.println("Hello!");
};
hi.howAreYou();
}
}
Output:
> Hello!
> How are you today?
What if the functional interface is generic?
Sometimes we may wish our functional interface can operate on various type (generic). However, since lambda expression cannot be generic explicitly, as it requires type information to work with.
We need to declare the reference first with type information to let the lambda expression know.
Example:
interface IValue10.4 Differences between Anonymous Class and Lambdas Week 11 11.1 Wildcards - Generics Helper{ T getValue(); } public class Test{ public static void main(String[] args){ //Declare a reference to the IValue //functional interface with the type it works on; IValue ref; ref = () -> 3.1415f; float value = ref.getValue(); // value = 3.1415 //Another example IValue refInt = () -> 42; int valueInt = refInt.getValue(); // valueInt = 42 } }
Unlike arrays, where we are able to assign types to a variable of an inherited type, Generic types cannot be assigned to a type that specifies a lower bound.
Scenario:
Syntax:
Usually used when we pass parameters in a method or declare new variable.
Type> variable; Type super LowerBound> variable; Type extends UpperBound> variable
Rules:
- Using extends UpperBound when reading data;
- Using super LowerBound when writing data;
Examples:
-
READING: List extends Person> people; Given an upper bound, any type we retrieve from this collection can be treated as the upper bound. (cannot add variables to the list as we cannot assume what type the variable is bound to)
-
WRITING: List super Books> books; Given a collection which can contain its lower bound, we can only assume the types we read from this will be of Object but we can add type Book to it. (we cannot add a type Video that isn’t the lower bound.)
-
If we don’t specify any bounds, we can only read from and treat only as an Object. (Not often)
JDB (Java Debugger) provides functionality to:
- Inspect the current values of local variables;
- Stop execution and step through the code;
- Inspect object and class instances;
Commands:
Compilation:
> javac -g MyProgram.java
Execution:
> jdb MyProgramWeek 12-13 True & False
-
When we define a class, we have also created a datatype true
-
Primitive types can be assigned to null false
(Each primitive type has its own default value, only reference types have the default value null) -
Arrays are primitive types false
(Arrays are all reference types) -
ArrayLists are of fixed length false
-
LinkedLists keep elements in arbitrary positions of memory true
With above UML, specify whether the followings are valid:
Wolf w = new DomesticDog(); // invalid Animal a1 = new DomesticDog(); // valid a1.hunt(); // invalid a1.sits(); // invalid a1.bark(); // valid Animal a2 = new Wolf(); // valid a2.stalk(); // invalid a2.sleep(); // valid
Since we declare a1 and a2 as Animal type, we can only retrive the methods in the animal class, because they are not aware of subclasses.
Method Signaturepublic void deduce(int x, int y); // method 1 public void deduce(int x, double y); // method 2 public void deduce(double x, double y); // method 3 public void deduce(String x, int y); // method 4 public void deduce(String x, Integer y); // method 5
deduce(1, 2);
deduce(2, 2.0);
deduce((double) 2, 3); -> method 3 (it will automatically cast 3 to 3.0, as it is widen-casting, sees week 2)
deduce((int) 3.0, (int) 2.0); -> method 1
deduce("42", 123) -> method 4
Tutorial & Challenge
Week 2 notes
1. char -> int
Character.getNumericValue(char);
int[] occ = new int[10];
String target = "12791396482";
for(int i = 0; i < target.length(); i++){
for(int j = 0; j < occ.length; j++){
int value = Character.getNumericValue(a.charAt(i));
if( value == j){
result[j] += 1;
}
}
}
2. print out array nicely
Arrays.deepToString() or Arrays.toString()
import java.util.Arrays;
int[] oneDimension = new int[]{1,2,3,4,5,6};
System.out.println(oneDimension); -> [I@1b701da1
System.out.println(Arrays.toString(oneDimension));
-> [1, 2, 3, 4, 5, 6]
int[][] result = {{1,2,3,3},{3,2,1,6},{4,5,6,1}};
//if we use Arrays.toString(), it only works for one-dimension reference type array
System.out.println(Arrays.toString(result));
-> [[I@3f8f9dd6, [I@aec6354, [I@1c655221]
System.out.println(Arrays.deepToString(result));
-> [[1, 2, 3, 3], [3, 2, 1, 6], [4, 5, 6, 1]]
Week 3 notes
Modmad
The % computes the remainder in a division and should not be confused with the concept of modulo arithmetic.
-11 % 5 == -1 11 % -5 == 1 -11 % -5 == -1 // The sign of the first operand decides the sign of the result.
Generate a sequence of numbers using the modulus operation
Description:
- Each method returns an array of n numbers
- if n < 0 return null
- if n == 0 return array of size zero
Notes:
- Modulus number depends on when the first number’s abstract value occurs again (the number of repetition),
- and the modulus number also decides that the integer boundry (e.g. % 4 means the number abstract value can’t be equal or greater than 4)
- Java weird behavior: If we have negative numbers and use the % operator on them, we will get the result dependent on the left operand’s sign. If we have the left operand as positive, we will get the result as positive, and if the left operand is negative, we will get the result as negative. (e.g. -4 % 3 -> -1, while the correct modulus should be 2 )
Sequence: 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3...
result = new int[n];
for (int i = 0; i < n; i++){
result[i] = i % 4;
}
Sequence: 3, 2, 1, 0, 3, 2, 1, 0, 3, 2, 1, 0...
result = new int[n];
for (int i = 0; i < n; i++){
result[i] = 3 - (i % 4);
}
Sequence: 0, 3, 6, 0, 3, 6, 0, 3, 6...
result = new int[n];
for (int i = 0; i < n; i++){
result[i] = (i % 3) * 3;
}
Sequence: 0, 2, 4, 6, 0, 2, 4, 6, 0, 2, 4, 6...
result = new int[n];
for (int i = 0; i < n; i++){
result[i] = (i % 4) * 2;
}
Sequence: -3, -2, -1, 0, 1, 2, 3, -3, -2, -1, 0, 1, 2, 3...
result = new int[n];
for (int i = 0; i < n; i++){
result[i] = ( i % 7 - 3) % 4;
}
Sequence: 100, 105, 110, 115, 120, 100, 105, 110, 115, 120, 100...
result = new int[n];
for (int i = 0; i < n; i++){
result[i] = i % 5 * 5 + 100;
}
Sequence: -1, 1, 3, 5, -1, 1, 3, 5, -1, 1, 3, 5...
result = new int[n];
for (int i = 0; i < n; i++){
result[i] = 2 * ( i % 4 ) - 1;
}
Sequence: -0.5, 0, 0.5, 0, -0.5, 0, 0.5...
how it works:
0, 1, 2, 3, 4, 5, 6, 7...
----------- %4 -----------
0, 1, 2, 3, 0, 1, 2, 3...
----------- -1 -----------
-1, 0, 1, 2, -1, 0, 1, 2...
----------- %2 -----------
-1, 0, 1, 0, -1, 0, 1, 0...
----------- /2 -----------
-0.5, 0, 0.5, 0, -0.5, 0, 0.5...
result = new double[n];
for (int i = 0; i < n; i++){
result[i] = ((i % 4 - 1 ) % 2) / 2;
}
Sequence: 0, 1, 2, 3, 1, 2, 3, 4, 2, 3, 4, 5, 3, 4, 5, 6...
result = new int[n];
for (int i = 0; i < n; i++){
result[i] = (i % 4) + (i / 4);
Week 5 notes
Week 8 notes
1. get an array of enum types
EnumName.values() -> return an EnumName[]
public enum Weekdays{
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY;
}
Weekdays[] dayArray = Weekdays.values();
Week 9 notes
1. turn an array to a fixed-size list
Arrays.asList() -> Returns a fixed-size list backed by the specified array
List2. calculate method running timemyList = Arrays.asList(1); -> [1] String[] strArray = {"Alex", "Bob", "Cindy"}; List strList = Arrays.asList(strArray); -> ["Alex", "Bob", "Cindy"]
System.currentTimeMillis() -> returns long current time
long before = System.currentTimeMillis(); runningMethod(); long after = System.currentTimeMillis(); long timeConsumed = after - before;Week 10 notes 1. array sort
Arrays.sort(T[] array, Comparator super T> c)
We can create customed comparators (using anoynmous class or lambda expression) to sort an array with certain property.
Since Comparator<> is also a functional interface (methods that inherit from Object don’t count), we can adhere lambda expression on it, and what lambdas do can be replaced by anonymous class as well.
Example: Sorting Song[] with different properties
import java.util.*;
class Song {
private String title;
private String author;
private double duration;
public Song(String title, String author, double duration) {
this.title = title;
this.author = author;
this.duration = duration;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public double getDuration() {
return duration;
}
public String toString(){
return title + ", " + author + ", " + duration;
}
}
- Create an anonymous class
Song[] songs = new Song[]{s1,s2,s3,s4};
Comparator comp = new Comparator<>() {
public int compare(Song t1, Song t2){
if(t1.getDuration() > t2.getDuration()){
return 1;
} else if (t1.getDuration() < t2.getDuration()){
return -1;
} else {
return 0;
}
}
};
Arrays.sort(songs,comp);
- Utilise lambda expressions (type info can be omitted)
Song[] songs = new Song[]{s1,s2,s3,s4};
Arrays.sort(songs, (Song a,Song b) -> (a.getTitle().compareTo(b.getTitle())));
// omitting type information still works
Arrays.sort(songs, (a, b) -> (a.getArthor().compareTo(b.getAuthor())));
// we can also create a variable first, but this is redundant and not necessary
Comparator comp2 = (t1, t2) -> t1.getAuthor().compareTo(t2.getAuthor());
Arrays.sort(songs, comp2);
Week 12 notes
1. incrementing value in HashMap
map.getOrDefault(key, default value) if the key is not in the map, it will return default value.
Example:
HashMapQuiz 1 notes 1. add an element in a listmap = new HashMap (); String[] units = new String[]{"INFO1110","INFO1113","INFO1113","DECO2014","DATA1001"} for(String each : units){ map.put(each,map.getOrDefault(each,0)+1); }
list.add() besides normal add(T element) which will add the element at the end of the list, you can specify the index where you want the element to be added add(int index, T element).
Example:
import java.util.LinkedList;
public class ListTest{
public static void main(String[] args){
LinkedList uni = new LinkedList();
uni.add("USYD");
uni.add("UNSW");
uni.add("ANU");
uni.add(1, "UTS");
for(String each : uni){
System.out.println(each);
}
}
}
Output:
> USYD > UTS > UNSW > ANU2. overloading methods (same name and different signature)
Methods with same name but with different method signature (params type) are called overloading methods. We can create multiple overloading methods in a class. However, we can’t create two methods with same name and same signature, even if they have different return type
ReturnType is not a part of method signature!
- Valid: same ReturnType + same methodName + different Signature (Overloading) is allowed:
public static double calculateSalary(int hour, double rate){
System.out.println("A");
return hour * rate;
}
public static double calculateSalary(int hour, int rate){
System.out.println("B");
return hour * rate;
}
- Invalid: different ReturnType + same methodName + same Signature is not allowed:
public static double calculateSalary(int hour, double rate){
System.out.println("A");
return hour * rate;
}
public static int calculateSalary(int hour, double rate){
System.out.println("B");
return hour * rate;
}
3. sort customed linkedlist in ascending order
public void sort(){
Node cursor = head;
Node nextNode;
int temp;
if (cursor == null) System.exit(0);
// iterate through all the element
while(cursor.next != null){
nextNode = cursor.next;
while(nextNode != null){
// changes to "<" if in descending order
if(cursor.value > nextNode.value){
temp = cursor.value;
cursor.value = nextNode.value;
nextNode.value = temp;
}
nextNode = nextNode.next;
}
cursor = cursor.next;
}
}
Quiz 2 notes
knowledge notes
- Java uses stack type of memory to implement Recursion.
- Memoization helps to improve the time efficiency of recursive method.
- enums can implement interfaces.
- Junit cannot test private methods, as it doesn’t have access to them. (bad practice to make a method private)
when you try to catch an already-caught exception again, it will raise compile error.
All the exception will be caught in the first catch block if you catch class Exception rather than its child classes.
class InvalidValueException extends Exception{
public InvalidValueException(){
super("Invalid value exception");
}
}
class MyClass{
private double price;
public void setPrice(double price) throws InvalidValueException{
if(price < 0) throw new InvalidValueException();
this.price = price;
}
public double getPrice(){
return this.price;
}
}
public class Test{
public static void main(String[] args){
try{
MyClass m = new MyClass();
m.setPrice(-100);
m.getPrice();
} catch(Exception e){
System.out.println("1st catch");
} catch(InvalidValueException e){
System.out.println("2nd catch");
}
}
}
Error message:
Test.java:24: error: exception InvalidValueException has already been caught
} catch(InvalidValueException e){
^
1 error
How to fix? Catch child class exception first
public class Test{
public static void main(String[] args){
try{
MyClass m = new MyClass();
m.setPrice(-100);
m.getPrice();
} catch(InvalidValueException e){
System.out.println("1st catch");
} catch(InvalidValueException e){
System.out.println("2nd catch");
}
}
}
Output:
1st catch



