INFO1113 Lecture Notes with Code Snippets PDF

Title INFO1113 Lecture Notes with Code Snippets
Course Object-Oriented Programming
Institution University of Sydney
Pages 50
File Size 2.1 MB
File Type PDF
Total Downloads 43
Total Views 147

Summary

Object Oriented Programming Lecture Notes done with notion and including code snippets. Premium resource made with Notion....


Description

INFO1113 2.2

INFO1113

Java

Study Areas StringBuilder ArrayList HashMap Reading/Writing to Files Scanner LinkedList

1 1.1 Introduction and guidelines ed stem: online discussion assignment submission challenges course materials canvas: marks for assessments quizzes online recordings OOP: a programming paradigm, in the same way that procedural and functional are programming paradigms the idea is that objects communicate to each other reusing and portability encapsulation

1.2 Java fundamentals, compilation, syntax, types and ifs the classic "Hello, World!" program:

// in java, every program begins with a class definition public class HelloWorld { // every program must have the main method:

// public static void main(String[] args) { ... } public static void main(String[] args) { System.out.println("Hello World!"); } }

name of class and file name have to be the same in Java (if public class) main method must be inside the class definition compiler executes code starting from main method compilation java is a compiled language and therefore there is an extra step in terminal this compilation step transforms the source code to bytecode to be understood by the computer > javac MyProgram.java > java MyProgram Hello everyone! This is a java program

these are the steps:

after this process has been completed we are able to execute our program using the java virtual machine > java MyProgram

anatomy of a source file:

// imports the Scanner class so that it can be used within your class import java.util.Scanner; /* class body: contains attributes and methods within it, access modifier: allows the following definition to be accessible by others then class keyword and then class name (if public then class name has to equal the fil name) */ public class Anatomy { // method body: scope is defined with curly braces and methods must be contained within a class // static modifier allows it to be accessed without the need of an object // main method: this is the first function invoked in your java program // command line arguments: it is of type string and [] defines it as an array public static void main(String[] args){ // outputting to the screen, string literals are defined using double quotes System.out.println("Hello! This will output to the screen"); // primitive type int followed by a variable name and initalised to 1 int integerVar = 1; // double type double d1 = 1.5; // creates a scanner object which allows you to read input from standard input Scanner keyboard = new Scanner(System.in); // reference type string variable set to string literal String s = "This is a string!"; // assign s to the next line of input that user has given s = keyboard.nextLine(); // output the string using println System.out.println(s); } }

opening brace: creates a scope which variables and instructions are executed closing brace: shows where the scope ends scoping a block is a collection of statements that is delimited by a pair of curly braces unlike interpreted languages like Python, Java has a separation of primitive types and reference types

primitive types: int float double char short byte long boolean string is a reference as it is an aggregation of the char type any class you create is a reference type why is it called a reference type? we are actually working with a binding to a memory address, not the object itself types and range

why do types exist? we are able to confirm the type that is being assigned. The compiler can check the assignment of variables ( in the event we are attempting to assign float to an int or some other nasty assignment). Also, clear allocation of memory, with type of information the compiler knows how much memory should be allocated for that variable type conversions and casting

public static void main(String[] args) { int i = 1; double f = 1.0; int j = (int) f; // two integers are involved and this is where integer division occurs. Since i

// is assigned to 1, the divsion will be 0, not 0.5 as 0.5 cannot be represented // as an integer System.out.println(i/2); // since a double number is involved during the calculation it will promote the // integer (2) to a double System.out.println(f/2); System.out.println(f/i); }

there are specific operations that occur depending on the type and operation command line arguments

public class CommandLineArgs { public static void main(String args[]){ String arg1 = args[0]; System.out.println(arg1+"!"); } }

output:

> java CommandLineArgs Hi Hi!

scanner is an abstracted object that provides an interface for reading data

import java.util.Scanner; public class UsingScanner { public static void main(String[] args){ // scanner object declared and initialised and we read the next line inputted // by the user using the nextLine() method Scanner keyboard = new Scanner(System.in); String s = keyboard.nextLine(); } }

boolean

public static void main(String[] args){ boolean t = True; boolean f = False; boolean exampleAnd = t && t; boolean exampleOr = f || t; boolean exampleNot = !t; }

if statements

public class IfProgram{ public static void main(String[] args){ boolean t = true; boolean f = false; if(t){ System.out.println("This will be executed"); } // not executed as the logic is false if(f){ System.out.println("This will not be executed"); } } }

similar to other languages, Java also has if statements. However, t has a strict requirement that statement is of type boolean in other languages, 1 and 0 are defined as true and false, however the code below would read an error

public class IfProgram{ public static void main(String[] args){ int t = 1; int f = 0; if(t){ System.out.println("This will be executed"); } // not executed as the logic is false if(f){ System.out.println("This will not be executed"); } } }

parsing a String to any other type

int x = Integer.parseInt(String "10"); // except with Double.parseDouble etc

L1 L1

2 2.1 Control flow, while/do-while/for loop, for-each loop, static methods four types of loops we can write within Java while

do-while for for-each while loop as with if statements, for this branch to start and continue execution the condition must be true

initialization; // a boolean expression is evaluated here and is checked on every iteration while(condition){ // the body of the loop, it will execute the following body until the condition is no longer met doWork() increment/decrement; }

do-while loop similar to the while loop but it will always execute the block at least once and continue execution if condition is true

initialization; // the do keyword must be followed by the while keyword after the block definition do(condition){ doWork() increment/decrement; }while(condition)

for loop broken up into three separate sections:

for(initialization; condition; update)

initialization; // the variables initialized here are local to the scope of the loop for(initialization; condition; update){ doWork() }

you can always write a for loop as a while loop, and vice versa for-each loop for-each loops involve the use of iterators // a binding in this case is just some variable that will represent an element of the collection // a collection is an object that aggregates other objects for(binding:collection){ doWork(binding); }

an example

for(String str:strings){ // can't iterate through a String but strings actually represents an iterable object here System.out.println(str); }

for-each loops don't have an index static methods a method is a stored set of instructions bound to an object in the case of a static method, the object is the class which it is defined in

// static keyword binds the method to the class, without it the method would be an instance method // int specifies what is being returned from the method // addThree is the method identifier // arguments of the method public static int addThree(int a, int b, int c){ return a+b+c; }

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 methods, once it has reached the end of method scope each method executed gets a frame allocated and a frame will hold data, partial results, return values and dynamic linking a frame is created when a method is invoked at runtime by the JVM

2.2 Arrays, array layout, multidimensional arrays, strings, StringBuilder an array is a contiguous block of memory containing multiple values of the same type array initialisation most common way of initialising an array is to allocate and specify size

int[] numbers = new int[16];

we can also initialise using static initialisation

int[] numbers = { 1, 2, 3, 4 };

general rules primitive integer types are initialised to 0 by default default value of elements of a boolean array are false

floating point numbers are initialised to 0.0f and 0.0d (float and double) elements of a char array are initialised to \u0000 (null character) any reference type is initialised to null array layout assuming the array we have received is allocated at 0x1000 (address 4096), since an integer is 4 bytes, what is the address of element at index 1? the address of the element at index 1 is 0x1000 + 4 = 0x1004 (as we are moving 4 bytes from the starting address) reference type arrays consider this

String[] strings = new String[4];

since it is a reference type it is initialising 4 references, where a reference in this instance is a memory address this infers that reference type arrays do not contain a string but a reference to a string multi-dimensional arrays as with the name

int[][] array = new int[3][3];

there are two types: matrix-like structure and jagged array

int[][] jarray = new int[3][] jarray[0] = new int[5]; jarray[1] = new int[10];

traversals int[][] numbers = new int[5][5]; for(int i = 0; i < array.length; i++){ for(int j = 0; j < array[i].length; j++){ System.out.println(array[i][j] + ""); } System.out.println(); }

strings string is a reference type that aggregates characters and java treats strings as immutable when initialising a string type, the JVM will allocate memory to contain the string comparing strings

String cat1 = "Meow"; String cat2 = "Meow"; // this will output true, as each have the same memory location System.out.println(cat1 == cat2);

this will output false

String cat1 = "Meow"; String cat2 = new String("Meow"); // the memory location is different, as the new String syntax creates a new memory reference System.out.println(cat1 == cat2); // this will yield true though, as it compares the contents of the memory location and not the location its System.out.println(cat1.equals(cat2));

string pool when writing our first program we have been able to define a string literal however, java employs an intelligent but often mistaken optimisation for strings if a string literal is specified, it will be added to a string pool this allows the compiler to optimise for memory usage, the compiler will use the same allocation and provide the same reference to a string variable mutable string (welcome

StringBuilder

)

recreating a new string and deallocating the old one can be a costly for the JVM we are able to mitigate this by using a class called

StringBuilder

the StringBuilder class contains an internal array of characters and is mutable but does not have the same kind of affordances as String

StringBuilder b = new StringBuilder(); b.append("Hello"); b.append(" World!");

allows us to assemble a string and resize the internal character array when the number of characters exceeds the capacity of the array remember, every time we use

+=

with the String type we are creating a new string

L2 L2

3 3.1 Classes, object attributes, instance methods, UML class diagram there is a clear distinction between a primitive type and a reference type but how is that distinction made? references types are classes

what is a class? a blueprint/template of an object the type of an object variable is its class objects are instances of particular classes use

new

keyword to instantiate a class

public class Cupcake{ // define attributes of an object within this space public boolean delicious; public String name; /* looks like a method but has no return type, the constructors role is to construct an object of the type Cupcake. We can expand on this to provide default values and parameters for our constructor, we can then invoke the parameter with arguments that relate to the object */ public Cupcake(boolean isTasty){ delicious = isTasty; name = "Chocolate Cupcake"; } } // to instantiate, declare the Cupcake object Cupcake mine = new Cupcake(True); Cupcake toShare = new Cupcake(False); // we can access the attributes of classes System.out.println(mine.delicious); System.out.println(toShare.delicious);

constructors every class in java has a constructor even if it is not explicitly defined called when an instance of the class is created instance methods an instance method operates on attributes associated with the instance, these methods can only be used with an object

public class Cupcake{ public boolean delicious; /* private modifier limits how and where the attribute can be accessed, public allows access outsie of the class while private limits itself to the scope of the class to access these non-static variables need to instantiate Cupcake in the main method (except private) */ private String name; public boolean eaten; // constructor does not need a return type (constructor name must be same as class name) public Cupcake(boolean isTasty, String cupcakeName){ delicious = isTasty; name = cupcakeName; } /* a setter method specified, this allows us to modify the name attribute, setter and getter required for private variables to change or to get */ // no static for instance methods (cannot call on class name) public void setName(String n){name = n;} /* a getter method specified, this method merely returns the attribute name */ public String getName(){return name;}

public void eat() { if(!eaten){ System.out.println("Keen to eat this cupcake!"); eaten = True; } } } Cupcake mine = new Cupcake(true, "My Cupcake!"); Cupcake toShare = new Cupcake(false, "Everyone's Cupcake!"); mine.setName("My Cupcake, don't touch!"); // if classes in same directory than no need to import them into each program

example of static method

UML unified modelling language, a visual language to assist with designing applications and systems class diagrams allow us to design classes prior to implementing them, giving the ability to model the system without implementing it first

3.2 this keyword and non-static context, mixing static and non-static context, text I/O 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 also used for referring to another constructor to allow for code reusability say we have this issue public class Postcard{ String sender; String receiver; String address; String contents; public Postcard(String sender, String receiver, String address, String contents){ this.sender = sender; this.receiver = receiver; this.address = address; this.contents = contents; } }

instance methods the

this

keyword within the context of an instance method refers to the current calling object

it cannot be used within a static method as it is unable to refer to the calling object instance method reinterpreted

public class Postcard{

String sender; String receiver; String address; String contents; public Postcard(String sender, String receiver, String address, String contents){ this.sender = sender; this.receiver = receiver; this.address = address; this.contents = contents; } public void setSender(String sender){ this.sender = sender; } /* this static method is attempting to utilise an instance variable, why is this a problem? Trying to access a non-static attribute from a static context */ public static boolean inTransit(){ return !received; } /* it is a problem because it isn't referring to an object. Instance methods are not allowed in this context */ /* this static method is attempting to utilise an instance method attached to an object, is there an issue? Nope! Simply, there is an object instantiated and we are able to utilise method */ public static boolean hasArrived(Postcard p){ if(!p.inTransit()){ return True; } else {return False;} } /* we have an instance method invoking a static method while also using the this keyword, is this correct? Yes! We are just passing the instance to a static function */ public boolean alreadyArrived(){ return hasArrived(this); } }

input and output files I/O classes within the java api we have access to a large range of I/O classes have already been using the Scanner class for reading content from the standard input, however we are able to interact with a variety of sources using Scanner

import java.io.File; import java.util.Scanner; import java.io.FileNotFoundException; public class Filehandle { public static void main(String[] args){ // file object that will represent the file stored at a Path File f = new File("README.txt"); // if the file does not exist we can have two branches, catching the error try { Scanner scan = new Scanner(f); scan.close(); } catch(FileNotFoundException e){ System.err.println("File not found!");

} } }

how is reading performed reading any kind of file is analogous to working with contiguous memory lets say we have the following file called contents

README.txt

which contains the following

Today is great!

the text is represented in an array Scanner itself doesn't support reading character by character, reasoning behind this is because the idea of a character depends on how it is encoded

File f = new File("README.txt"); try { Scanner scan = new Scanner(f); scan.next(); //Today scan.next(); //is scan.next(); //great! scan.close(); // always needs to be closed } catch (FileNotFoundException e) { e.printStackTrace(); }

writing text data Scanner performs reading an object, so how about writing? note Scanner always needs to be wrapped around a PrintWriter

allows for printing formatted representations of objects to a text-output

stream import java.io.File; import java.util.Scanner; import java.io.FileNotFoundException; public class Filehandle { public static void main(String[] args){ File f = new File("README.txt"); // for writing to a file try { PrintWriter writer = new PrintWriter(f); writer.println(1.0); writer.println(120); writer.println("My String!"); writer.close(); } catch(FileNotFoundException e){ e.printStackTrace(); } } }

can also use

FileNotFoundException

nextLine()

L3 L3

4 4.1 Binary input/output, stack, heap, garbage collector binary I/O for writing import java.io.FileOutputStream; import java.io.FileNotFoundException; import java.io.DataOutputStream; import java.io.IOException; public class BinaryWriter{ public static void main(String[] args){ try{ FileOutputStream f = new FileOutputStream("some_file.bin"); DataOutputStream output = new DataOutputStream(f); output.writeInt(50); output.close(); }catch(FileNotFoundException e){ e.printStackTrace(); }catch(IOExcep...


Similar Free PDFs