You are on page 1of 5

LECTURE NOTES

COSC120 Object Oriented Programming (Java)

Week 1:

Language: means of exchanging information to communicate


Java been around for a long time, develop once run everywhere
All browsers have java virtual machine embedded so that browser can run java applets.
Standard programs require java runtime installed on OS.
What is a programming language? A set of rules that provides a way of telling a computer
what operations to perform, for communicating an algorithm and to provide a linguistic
framework for describing computations. Has keywords, symbols (mix & match to create
variable identifiers) and grammar rules (syntax).
Why are there so many programming languages? Each language is better at doing specific
things eg. Matlab better at matricies. Evolved over time as better ways developed to design
them.
What are the TYPES of programming languages? High level (class Triangle, return b*h/2),
assembly (Load r1, b | load r2, h | mul r1, r2| div r1, #2|RET) and executable machine code.
Compiler (eg visual studio) broadly works but may not be optimised for a device, so may
require assembly-level optimisation.
Traditional languages sequence of instructions. Write functions to execute sequence.
Object-oriented objects are created rather than sequences. E.g. Classes. Class is like a
blueprint eg a cars blueprint that determines how to build a car. Object of a class is an
instance. When instantiated, it runs.
Does the world need new languages?

Java coding:

Java source code file contains classes, these are compiled in realtime
If more than one class, only one may be made public. This must match the name of the source
code file. (eg. A class named Simple must be in a file named Simple.java)
Each java class may be separated into parts
Main Class will have method called Main. This is where the java virtual machine/runtime
starts compiling. Usually contains statements that compile the objects required.
println = print statement.
// Double slash to comment.
/* To create a multiline comment */
Can also add comment on line after semicolon which ends statement; //eg. Comment here
To Compile: javac Simple.java //this will create the simple.class file in the working directory
To Run: java Simple //no c and no extension the .class is assumed
(String [] args) allows you to pass an array of strings to the program through the console
Applications Programming Interface (API) library of standard class objects that can be called
All classes descend from Object eg. (Object).System.out.println
\n generates a newline character in java the backslash is an escape sequence, what
follows is printed or operated.
A variable is a named storage location; a literal is a value written into the code
Start variables with lowercase, then caps e.g. int taxRate
Start class with caps e.g. public static class TaxCalculator
Floats/doubles can be written as exponents +n, eg 10+30 = 10 x 10^30
Exponentials shown as E eg. X10^25 = E25
You can cast values by appending. float number = 23.5F
ASCII has 8 bits/1 byte. Max 256letters. Java uses Unicode double byte. Can represent 65536
chars (2^16)
Constants = name used to represent unchanging value that can be referred to by name. Must
use keyword final. E.g. final int HOUR; HOUR = 24; once value is assigned it cannot be changed.

Likely exam points:

Integer division will truncate any decimal remainder (rounds automatically) e.g. 1 / 2 = 0
Order precedence does * / % first, then does furthest statement to nearest statement (reads
left to right)
LECTURE NOTES

COSC120 Object Oriented Programming (Java)

Week 2:

If statement may be written on one line, ends at semicolon;


Can use bool as flag: set bool as true or false, then check as if(boolValue) doMethod();
Strings are objects of the string class (rather than values). The string variable (e.g. string S)
refers to the memory location of the start of the string object, rather than the basic value
itself.
Therefore even two strings with the same content are not equal as they are different objects

Week 3: Loops and Files

The While loop while (condition) {statements;} while the condition is true the statements
execute repeatedly.
While look is a pretest loop tests the loop before executing the loop. Happens zero or more
times.
Use for testing conditions e.g. number = keyboard.nextInt() while number < 1)
{system.out.println(That number is invalid.) number = keyboard.nextInt();
nextInt() will interpret next input as a number if string is entered it will interpret characters
as Unicode numbers
The do-while loop is post test. do {something } while (condition); Will run at least once!
The for loop: Initialisation section allows loop to specify control variable. Usually initialises a
counter variable. Can initialise multiple variabels.
E.g. for(x; y;) {do something} - if this is run with only semicolons it will run forever!
In logic, null implies true. No condition = null = true.
For(variable; limit; updater ++)
Nested loops a nested loop will run all its iterations in a single iteration of the outer
the break statement can be used to force exit of loop. Considered bad form
File input/output Open file, write data to file, close prior to program termination
Java file input/output focuses on binary/text files
PrintWriter outputFile = new PrintWriter(Names.txt
outputFIle.println(Chris)
outputFile.println(Katheryn);
outputFile.close(); //considered good practice to close the file once finished using it
To use, import java.io
Exceptions the method handling the file must abort or pas it up the line (e.g. if file name
doesnt exist, isnt found etc).
Can use try-catch or add throws IOException etc after makes this exception illegal. Throws
to Java virtual machine and prints stack trace.
To append text to existing file create as FileWriter fw = new FileWriter(names.txt, true);
then create a PrintWriter object as PrintWriter pw = new PrintWriter(fw); Otherwise
PrintWriter will overwrite the existing file.
To read: File myFile = new File(Customers.txt); Scanner inputFile = new Scanner(myFile)
Can make more robust by asking for filename if file cant be found using try/catch
Reading data from a file
File file = new File(names.txt);
Scanner inputFile = new Scanner(file);
String str = inputFile.nextLine();
inputFile.close();
Scanner class can be used to detect end of the file using hasNext() method:
File file = new File(filename);
Scanner inputFile = new Scanner(file);
While (inputFile.hasNext()) {String str = inputFile.nextLine(); System.out.println(str);}
Generating random numbers import java.util.Random; Random r = new Random();
Then double val = r.nextDouble(); or int, float, etc. Will generate within range of float/int
method etc unless limits are specified. Only next int can overload nextInt(int n) where n is
the upperlimit.
THIS IS ENOUGH FOR ASSIGNMENT 1
Week 5:

Week 6:

Arrays can declare on one line: int[] temps, numbers, scores;


Can add brackets after but required for each: int temps[], numbers[], scores; (scores will be a
regular int variable in this instance)
IN A FOR LOOP, can iterate through entire array in format:
for(datatype elementVariable: arrayName){//statement;}
for example:
int[] numbers = {3, 6, 9}
for(int val: numbers)
{System.out.println(The next value is + val);}
Bounding: use length to loop within bounds of array. Eg:
for(int i = 0; i < numbers.length; i++) {//statement;}
To COPY array you cannot assign one variable to another. Must individually assign elements
using a loop. Eg. For(int i=0; i<firstArray.length;i++) {secondArray[i] = firstArray[i];}
Passing Array to Method pass object as any other variable give array as argument type
Comparing Arrays you cannot use == as this checks for the same variable. First check if
they are the same size, if so check data:
while(arraysEqual && i<firstArray.length) {
if (firstArray[i] != secondArray[i]) arraysEqual = false;
i++;}

You might also like