0% found this document useful (0 votes)
42 views

COMP161 Lecture Notes

This document provides summaries for 11 lectures on Java programming topics including data types, program structure, objects, graphics, selection, and structured programming. Key concepts covered include primitive vs reference types, classes and objects, inheritance, methods, interfaces, exceptions, I/O streams, and testing.

Uploaded by

benmcmorran05
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views

COMP161 Lecture Notes

This document provides summaries for 11 lectures on Java programming topics including data types, program structure, objects, graphics, selection, and structured programming. Key concepts covered include primitive vs reference types, classes and objects, inheritance, methods, interfaces, exceptions, I/O streams, and testing.

Uploaded by

benmcmorran05
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

🤖

COMP161
Lecture summaries for final exam study.

Lecture 1: Intro to Java


The Java language was developed for embedded processors.
The Java Platform is a set of tools and resources that support the language.
The Java Developer Kit is one form of the platform which includes the compiler
(needed for creating programs) and the interpreter / Java virtual machine (JVM)
which runs programs.

Three kinds of error:

Syntax (compile time) errors

Code is not legal, picked up when program is compiled.


Run time errors

Code is legal and compiles but specifies impossible operations, picked up


when program is ran.

Semantic (logic) errors

Code compiles and runs, but doesn’t perform as intended.

Algorithm: clear sequence of basic steps.

Lecture 2: Data types


Primitive data types hold primitive values.
Reference data types hold references to objects.

double, float Uses 64 bits

int, byte, short, long Uses 32 bits

char Uses 16 bits

boolean Uses 1 bit

COMP161 1
💾 Unicode & ASCII ordering:
' ' < digits < symbols / punctuation < A < Z < a < z

Lecture 3: Program structure


Data stored in either variables or data fields.
Libraries are part of the Java Developer Kit, which include Java Foundation
Classes.

Lecture 4: Expressions
The remainder operator (%) used on integers is sometimes called ‘mod’ or
‘modulo’.

Casting can be either a widening conversion or a narrowing conversion.

int i = (int) 15.32 //narrows double 15.32 to int 15

Lecture 5: Objects I
Instance objects are created with the keyword new. This is the followed by a
constructor method of that object.

JFrame obj1 = new JFrame();

Constructors have the same name as the class they belong to, and may be
overloaded. They do not have a return type. They let us create objects that are
instances of the same class, but in different states.
Accessors return the value in a data field.

Mutators change the value in a data field.

Lecture 6: Graphics I
Windows are a visible representation of an instance object constructed from the
library class JFrame. GUI elements are usually created within panels, instances
of the library class JPanel.
To add drawing content to a JPanel, it must have a paintComponent method.
JPanel is a library class, so we must extend it to give it a paintComponent
method.

COMP161 2
💾 Extending a (parent) class makes a new (child) class. The child has
all of the (non private) members (data fields & methods) of the
parent, and can also include its own members.

java.awt.Graphics contains various drawing methods.


Lecture 7: Selection I
If statements require a condition, which is always a boolean expression.

if (condition == true) {
//block of statements;
} else {
//block of statements;
}

< Less than > Greater than

<= Less than || Equal to >= Greater than || Equal to

= Equal to != Not Equal to

Only == and != can be used with reference data types.

Relational and logical


operators have various
levels of precedence.
Equal precedence
operators are treated as left
associative.

Lecture 8: Selection II
Switch lets us choose from a finite number of possible cases depending on the
value of a selector variable. Case labels must be the same type as the selector.

int n;
switch (n) {
case 1:
System.out.println("n is 1");

COMP161 3
break;
case 2:
case 3:
System.out.println("n is 2 or 3");
break;
case 4:
System.out.println("n is 4");
break;
default:
System.out.println("n is another value");
}

If a case is missing a break; statement at the end, execution will carry on into the
next case.

💾 A variables scope is the block it is declared in and any blocks inside


the declaring block.

Expression evaluation can be viewed as an expression tree. The left side is


evaluated first, and in some cases there is no need to evaluate the right side. For
example, false && ____ is always false, and true || ____ is always true. This
short circut evaluation speeds up the program, but can have occasional
consequences.
Lecture 9: Objects II
A methods signature is its name and the type, number, and order of its
parameters. When methods have the same name this is called overloading.

Data fields and methods are members of a class. If a member is declared with
static it is a class member, part of the class object. If it is declared without static it
is an instance member, part of the instance object.
Class members are created and usable before the program starts to run;
members of the application class are usually class members, support classes are
usually not.

You can use You can’t You can use Using a class member in an
class members use instance instance object works, but
in class instance members in you are really using the
objects. members instance member in the underlying
in class objects. class object.
objects.

COMP161 4
(don’t
exist!)

An object is distinct and seperate from a reference to the object. References are
integer values referring to an address in memory. If an instance object is
referenced by multiple variables they are called aliases. If it is referenced by no
variables it cannot be accessed and will get eaten by the garbage collector.
Lecture 10: Structured programming
Service methods are called on an object. This means that they must be public
and called from elsewhere in the program. Support methods are intended to be
called within the class and thus should be private.

Strings in java are immutable. This means they can’t be changed, however
you can build a new String and assign it to a String variable and thus
overwrite the original value. The variable is now storing the address of the
new String.

//Writing to file:
import java.io.*; import java.nio.file.*;
public static void writeToFile (String newContent, String fileName) {
try {
FileWriter fw = new FileWriter(fileName);
fw.write(newContent);
fw.close();
catch (Exception e) { }
}

//Generating a random number


import java.util.Random;
public static int randomIntRange (int low, int high){
Random random = new Random(); //Random cannot be referenced from a static context
return (random.nextInt(high-low+1)+low); //Returns a random number
}

//Uses decimal format


import java.text.DecimalFormat
DecimalFormat df1 = new DecimalFormat(); //Creates instance object
df1.setMaximumFractionDigits(2);
System.out.println( f1.format(Math.PI) ); //Applies format method, printin 3.14

Lecture 11: Design & Testing I

COMP161 5
Development process: Typical tools programmers use include
Unified Modelling language (UML),
1. Establish requirements
flowchats, and pseudocode.
2. Design program

3. Implement design

4. Test program

Pre 1950’s

Programs were “machine codes” based very closely on the binary hardware
of the computers. Programmers used machine codes, console buttons and
switches, physical re-wiring (ENIAC)!

1950’s

Assembly languages introduced but still tied to a specific machine.


Development of “autocodes” and FORTRAN.

1960’s
Growth of machine independent “high level” languages such as BASIC, Lisp,
Algol 60, Cobol. Most “serious programming” still done in assembly language
(slow to write, fast to run).

1970’s
“Structured programming” methods increase program correctness. There is a
further development of high level structured languages such as Pascal, C,
and Algol 68.

1980’s
Large projects with more focus on reducing the complexity of the task.
Program management systems introduced such as Make, APSE, and Project
Builder.

New “paradigms” (styles) of programming are object-oriented and


functional.
New languages created such as Ada, Modula-2, and C++.

1990’s

4000+ programming languages...

Impact of the internet and the Web popularise HTML, XML, network portable
applications and “applets”, Java. Database integration streamlined.

COMP161 6
2000+
Languages created for distributed and parallel / concurrent computing.
Significant impact of Artificial Intelligence / Neural Networks. Quantum
computing?

There are two ways of classifying languages, by generation and by style. Java is
an object-orientated 3rd generation language.

1GL - Machine languages Imperative: describes operations to

2GL - Assembly languages perform on data.

3GL - “high level” languages Object-orientated: combines


operations and data to create objects.
4GL - application languages
Functional: specifies result via
5GL - AI techniques, interface functions.
languages
Logic: specifies properties of
6GL - neural networks, machine problem, solved by system.
learning

Lecture 12: Repitition I

while (condition) { do {
//block of statements; //block of statements;
} } while (condition);

do..while loops are used when we want to execute the body at least once, and
then continue executing it while the condition remains true.

//For-each loops process Arrays or Collections that implement the iterable interface
Datatype[] listOfData = {obj1, obj2, obj3};
for (Datatype data: listOfData) {
//block of statements;
{

💾 break; is used to jump out of the execution of a block of statements.


continue; returns to the beginning of the loop and increments by 1.

Lecture 13: Repitition II

COMP161 7
for (initialisation; condition; update) {
//block of statements;
{

Loops can be identified as counter controlled, state controlled, sentinel controlled,


and menu controlled.
Where a loop body is a block, variables are not visible outside it.
Lecture 14: Arrays I
Arrays are named collections of data composed of elements/cells, which each
function as a normal variable. They are also called indexed variables.

int [] intArr = new int[5] //Creates an array of int with a fixed size of 5
int [] initialisedIntArr = {3, 7, 9, 23, 2}; //Creates and initialises an int Array

Lecture 15: Arrays II


Arrays can also hold references to objects. They behave the same was as arrays
of primitive data types.

For-each loops are very useful for iterating through an array, however they are
“read only”. It can’t be used to write values back into the array.

The relational operator compares references, so


given the following 3 arrays a==b is true and a==c is
false. However, Arrays.equals(a, b) &&
Arrays.equals(a, c) is true as this relational method
compares the contents of arrays.

//Splitting a string to elements of an array


String[] myArray = myString.split("[-,.! \n]");
//delimiters go in [ ]

Lecture 16: Arrays III

//Creates and initialises a 2D array


double[][] multidimensionalArray = { {1.0, 2.2, 3.4}, {5.6, 2.1, 7.7} };

COMP161 8
Java can also hold ragged arrays, arrays that are not perfectly rectangular.
Because of this, processing of elements should be based upon the length of that
row.

for (row = 0; row < array.length; row++){


for (col = 0; col < array[row].length; col++){
//block of statements;
}
}

try {
//code that might cause an
} catch (ExceptionClass variable) {
//try to handle exception or warn user
}

Some common exceptions include FileNotFoundException,


InputMismatchException, and NoSuchElementException.

//copying a file to array


Object[] myArray = new Object[100];
int count = 0;
try {
Scanner fileScan = new Scanner(new File("fileName.txt"));
while (fileScan.hasNextLine() && count < myArray.length) {
String line = fileScan.nextLine();
Scanner lineScan = new Scanner(line);
try {
double var1 = lineScan.nextDouble();
int var2 = lineScan.nextInt();
String var3 = lineScan.next();
myArray[count] = new Object(var1, var2, var3);
count++;
} catch (InputMismatchException e) {
System.out.println(line + "contains an invalid data type!");
} catch (NoSuchElementException e) {
System.out.println(line + "does not contain enough tokens!");
}
}
} catch (FileNotFoundException e) { }

Lecture 17: Objects III


Actual parameters are sent in the method call and are also known as arguments.

Formal parameters are declared and expected in the argument list.

COMP161 9
Always refer to class (static) data fields with ClassName.name, not
variableName.name (if you’ve created an instance object).

Packages are a related group of classes. You can use any class without
importing it by using its fully qualified name (e.g. java.util.Random). You can use
a class’s simply name (e.g. Random) if we import the class, the class is in
java.lang, or the classes are in the same package as each other. To put a class in
a named package (override the default), the name is stated at the top of the file:
package java.lang;

Visibility Applied to members of a class

private accessible only within this class

default accessible only to classes in this package

accessible to classes in this package and any class extending this


protected
one

public accessible to all other classes (provided class is public)

Lecture 18: Objects IV


The keyword this always refers to the current instance object. When resolving a
name, the compiler looks first for a local variable and then for a data field.

Lecture 19: ArrayList

ArrayList<Object> arrList1 = new ArrayList<Object>();

Collection classes include ArrayList, Vector, Hashtable, List, HashMap, Map, Set,
and more. Collections have useful methods such as copy, fill, min, max, reverse,
shuffle, sort, contains, etc. Collection classes often implement library interfaces
such as Iterator and Iterable.

ArrayLists can collect groups of objects of related types, if objects have the same
parent type somewhere in the hierarchy.
For example, JButton extends AbstractButton extends JComponent extends
Container extends Component extends Object. An ArrayList declared as
<JComponent> would be able to store both JButton and JPanel.

If a class is abstract you can’t make instances of it, but it can be extended and
you can make instances of its children. An abstract class can have abstract
methods that child classes must implement. This is a way of ensuring that all
children must have their specialised versions of the same functionality.

COMP161 10
//Removing elements from an ArrayList
ArrayList<String> myArrayList = new ArrayList<String>();
ArrayList<String> toBeRemoved = new ArrayList<String>();
for(String word: myArrayList){
if(word.length() > 10){ //arbitrary condition
toBeRemoved.add(word);//if condition true for that element, add to new ArrayList
}
}
for(String word: toBeRemoved){
myArrayList.remove(word);//then iterate through toBeRemoved list
}

Lecture 20: Design & Testing II


The values stored in data fields are the state of the object, its methods are its
behaviours.
An abstract data type (ADT) refers to a data type that is defined solely through
operations for creating and manipulating values of that type so all internal
structure is hidden from the user. Common examples include stack, queue, table,
vector, and more.

Testing concepts:
• code reviews: a group looks at the code together
• walkthroughs: step through code line by line
• defect testing (test case, test suite): actively look for possible errors
• black-box testing: check that inputs = correct outputs (not looking at code)
• white/glass-box testing: check code in detail (follow all paths)
• unit testing: test individual “units” of code (e.g. methods) in isolation
• integration testing: test how units interact with each other
• regression testing: if you fix one bug, run your other tests again
• system testing: test the entire finished program / product (alpha, beta)
• test-driven development: testing is central to coding, not an afterthought!

COMP161 11

You might also like