DM550 Introduction to Programming part 2. Jan Baumbach.

Similar documents
DM503 Programming B. Peter Schneider-Kamp.

DM537 Object-Oriented Programming. Peter Schneider-Kamp.

DM550 Introduction to Programming part 2. Jan Baumbach.

DM537 Object-Oriented Programming. Peter Schneider-Kamp.

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

DM503 Programming B. Peter Schneider-Kamp.

DM550 Introduction to Programming part 2. Jan Baumbach.

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

DM503 Programming B. Peter Schneider-Kamp.

Introduction to Programming Using Java (98-388)

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

CS 231 Data Structures and Algorithms, Fall 2016

CSC Java Programming, Fall Java Data Types and Control Constructs

Numbers Implicit This Static Methods and Fields Packages Access Modifiers Main Overloading Exceptions Etc.

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

F1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept

Java for Non Majors Spring 2018

Loops. CSE 114, Computer Science 1 Stony Brook University

Array. Prepared By - Rifat Shahriyar

Java Bytecode (binary file)

Introduction to Computer Science Unit 2. Notes

The Scanner class reads data entered by the user. Methods: COSC Dr. Ramon Lawrence. Page 3. COSC Dr. Ramon Lawrence A) A = 6, B = 3

THE CONCEPT OF OBJECT

Programming II (CS300)

COSC 123 Computer Creativity. I/O Streams and Exceptions. Dr. Ramon Lawrence University of British Columbia Okanagan

CSC 1214: Object-Oriented Programming

Programming II (CS300)

Language Features. 1. The primitive types int, double, and boolean are part of the AP

COMPUTER APPLICATIONS

Loops. Eng. Mohammed Abdualal. Islamic University of Gaza. Faculty of Engineering. Computer Engineering Department

Introduction to Computer Science Unit 2. Notes

public class Test { static int age; public static void main (String args []) { age = age + 1; System.out.println("The age is " + age); }

Tutorial # 4. Q1. Evaluate the logical (Boolean) expression in the following exercise

3. Java - Language Constructs I

1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4'

AP CS Unit 3: Control Structures Notes

AP COMPUTER SCIENCE A

public static void main(string[] args) throws FileNotFoundException { ArrayList<Vehicle> arrayofvehicles = new ArrayList<Vehicle>();

Software Practice 1 Basic Grammar

Scanner Objects. Zheng-Liang Lu Java Programming 82 / 133

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Index COPYRIGHTED MATERIAL

Java for Python Programmers. Comparison of Python and Java Constructs Reading: L&C, App B

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 88 / 133

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Logic is the anatomy of thought. John Locke ( ) This sentence is false.

Simple Java Reference

CS212 Midterm. 1. Read the following code fragments and answer the questions.

IEEE Floating-Point Representation 1

This exam is open book. Each question is worth 3 points.

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

CS 101 Exam 2 Spring Id Name

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 89 / 137

COSC 123 Computer Creativity. Java Decisions and Loops. Dr. Ramon Lawrence University of British Columbia Okanagan

Software Practice 1 - Basic Grammar Basic Syntax Data Type Loop Control Making Decision

Data Types. 1 You cannot change the type of the variable after declaration. Zheng-Liang Lu Java Programming 52 / 87

CMP-326 Exam 2 Spring 2018 Total 120 Points Version 1

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Java Object Oriented Design. CSC207 Fall 2014

Birkbeck (University of London) Software and Programming 1 In-class Test Mar 2018

Java Programming. Atul Prakash

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Arithmetic Compound Assignment Operators

15CS45 : OBJECT ORIENTED CONCEPTS

Chapter 7 User-Defined Methods. Chapter Objectives

CSCI 136 Written Exam #0 Fundamentals of Computer Science II Spring 2015

2. [20] Suppose we start declaring a Rectangle class as follows:

CS 113 PRACTICE FINAL

if (i % 2 == 0) { return 4 + method(i + 5) } if (i % 2 == 1) { return 2 + method(i + 3) } public static int method( int i )

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

Loops and Expression Types

CONDITIONAL EXECUTION

Full file at

1 Shyam sir JAVA Notes

Full download all chapters instantly please go to Solutions Manual, Test Bank site: testbanklive.com

More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements

Polymorphism. return a.doublevalue() + b.doublevalue();

COMP 202 Java in one week

2. The object-oriented paradigm!

More on Java. Object-Oriented Programming

PROGRAMMING FUNDAMENTALS

Array. Array Declaration:

COP 3330 Final Exam Review

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

public class Foo { private int var; public int Method1() { // var accessible anywhere here } public int MethodN() {

CSC 1051 Algorithms and Data Structures I. Final Examination May 12, Name

Final Exam Practice Questions

Chapter 3. Selections

2. The object-oriented paradigm

Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A

I pledge by honor that I will not discuss this exam with anyone until my instructor reviews the exam in the class.

Fall CS 101: Test 2 Name UVA ID. Grading. Page 1 / 4. Page3 / 20. Page 4 / 13. Page 5 / 10. Page 6 / 26. Page 7 / 17.

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Key Points. COSC 123 Computer Creativity. Java Decisions and Loops. Making Decisions Performing Comparisons. Making Decisions

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

Character Stream : It provides a convenient means for handling input and output of characters.

Programming: Java. Chapter Objectives. Chapter Objectives (continued) Program Design Including Data Structures. Chapter 7: User-Defined Methods

CH. 2 OBJECT-ORIENTED PROGRAMMING

Transcription:

DM550 Introduction to Programming part 2 Jan Baumbach jan.baumbach@imada.sdu.dk http://www.baumbachlab.net

CALLING & DEFINING FUNCTIONS 2

Functions and Methods all functions in java are defined inside a class BUT static functions are not associated with one object a static function belongs to the class it is defined in functions of a class called by <class>.<function>(<args>) Example: Math.pow(2, 6) all other (i.e. non-static) functions belong to an object in other words, all non-static functions are methods! functions of an object called by <object>.<function>(<args>) Example: String s1 = "Hello!"; System.out.println(s1.toUpperCase()); 3

Calling Functions & Returning Values function calls are expressions exactly like in Python Example: int x = sc.nextint(); argument passing works exactly like in Python Example: System.out.println(Math.log(Math.E)) the return statement works exactly like in Python Example: return Math.sqrt(a*a+b*b); 4

Function Definitions functions are defined using the following grammar rule: <func.def> => static <type> <function>(, <type i > <arg i >, ) { <instr 1 >; ; <instr k >; Example (static function): public class Pythagoras { static double pythagoras(double a, double b) { return Math.sqrt(a*a+b*b); public static void main(string[] args) { System.out.println(pythagoras(3, 4)); 5

Method Definitions methods are defined using the following grammar rule: <meth.def> => <type> <function>(, <type i > <arg i >, ) { <instr 1 >; ; <instr k >; Example (method): public class Pythagoras { double a, b; Pythagoras(double a, double b) { this.a = a; this.b = b; double compute() { return Math.sqrt(this.a*this.a+this.b*this.b); public static void main(string[] args) { Pythagoras pyt = new Pythagoras(3, 4); System.out.println(pyt.compute()); constructor corresponds to init (self, a, b) 6

SIMPLE ITERATION 7

Iterating with While Loops iteration = repetition of code blocks while statement: <while-loop> => while (<cond>) { <instr 1 >; <instr 2 >; <instr 3 >; Example: static void countdown(int n) { while (n > 0) { false true n == 3 2 1 0 System.out.println(n); n--; System.out.println("Ka-Boom!"); 8

Breaking a Loop sometimes you want to force termination Example: while (true) { System.out.println("enter a number (or 'exit'):\n"); String num = sc.nextline(); if (num.equals("exit")) { break; int n = Integer.parseInt(num); System.out.println("Square of "+n+" is: "+n*n); System.out.println("Thanks a lot!"); 9

Fibonacci numbers: 1. Start with 0 and 1 Fibonacci code 2. The next one is the sum of the two previous ones. f(x n ) = x n-1 + x n-2 Example: int max = 1000; int x=0; int y=1; while (true) { f=x+y; System.out.println(f); x=y; y=f; if ((x+y) >= max) { break; 10

Fibonacci numbers: 1. Start with 0 and 1 Fibonacci code 2. The next one is the sum of the two previous ones. f(x n ) = x n-1 + x n-2 Example: int max = 1000; int x=0; int y=1; do { f=x+y; System.out.println(f); x=y; y=f; while ((x+y) <max); 11

Iterating with For Loops (standard) for loops very different from Python grammar rule: <for-loop> => for (<init>; <cond>; <update>) { <instr 1 >; ; <instr k >; Execution: 1. initialize counter variable using <init> 2. check whether condition <cond> holds 3. if not, END the for loop 4. if it holds, first execute <instr 1 > <instr k > 5. then execute <update> 6. jump to Step 2 12

Iterating with For Loops (standard) for loops very different from Python grammar rule: <for-loop> => for (<init>; <cond>; <update>) { <instr 1 >; ; <instr k >; Example: int n = 10; while (n > 0) { System.out.println(n); n--; System.out.println("Ka-Boom!"); 13

Iterating with For Loops (standard) for loops very different from Python grammar rule: <for-loop> => for (<init>; <cond>; <update>) { <instr 1 >; ; <instr k >; Example: int n = 10; while (n > 0) { for (int n = 10; n > 0; n--) { System.out.println(n); n--; System.out.println("Boo!"); 14

Iterating with For Loops (standard) for loops very different from Python grammar rule: <for-loop> => for (<init>; <cond>; <update>) { <instr 1 >; ; <instr k >; Example: int n = 10; while (n > 0) { for (int n = 10; n > 0; n--) { System.out.println(n); System.out.println(n); n--; System.out.println("Boo!"); System.out.println("Boo!"); 15

CONDITIONAL EXECUTION 16

Conditional Execution the if-then statement executes code only if a condition holds grammar rule: <if-then> => if (<cond>) { <instr 1 >; ; <instr k >; Example: if (x <= 42) { System.out.println("not more than the answer"); if (x > 42) { System.out.println("sorry - too much!"); 17

Control Flow Graph Example: if (x <= 42) { System.out.println("A"); if (x > 42) { System.out.println("B"); x <= 42 false x > 42 false true true System.out.println("A"); System.out.println("B"); 18

Alternative Execution the if-then-else statement executes one of two code blocks grammar rule: <if-then-else> => if (<cond>) { <instr 1 >; ; <instr k >; else { <instr 1 >; ; <instr k >; Example: if (x <= 42) { System.out.println("not more than the answer"); else { System.out.println("sorry - too much!"); 19

Control Flow Graph Example: if (x <= 42) { System.out.println("A"); else { System.out.println("B"); x <= 42 false true print "A" print "B" 20

Chained Conditionals alternative execution a special case of chained conditionals grammar rules: <if-chained> => if (<cond 1 >) { <instr 1,1 >; ; <instr k1,1 >; else if (<cond 2 >) { else { <instr 1,m >; ; <instr km,m >; Example: if (x > 0) { System.out.println("positive"); else if (x < 0) { System.out.println("negative"); else { System.out.println("zero"); 21

Control Flow Diagram Example: if (x > 0) { System.out.println("A"); else if (x < 0) { System.out.println("B"); else { System.out.println("C"); false x > 0 x < 0 true true false print "positive" print "negative" print "zero" 22

Switch Statement for int and char, special statement for multiple conditions grammar rules: <switch> => switch (<expr>) { case <const 1 >: <instr 1,1 >; ; <instr k1,1 >; break; case <const 2 >: default: <instr 1,m >; ; <instr km,m >; 23

Switch Statement Example: int n = sc.nextint(); switch (n) { case 0: System.out.println("zero"); break; case 1: case 2: System.out.println("smaller than three"); default: System.out.println("negative or larger than two"); 24

Nested Conditionals conditionals can be nested below conditionals: if (x > 0) { if (y > 0) { System.out.println("Quadrant 1"); else if (y < 0) { System.out.println("Quadrant 4"); else { System.out.println("positive x-axis"); else if (x < 0) { if (y > 0) { System.out.println("Quadrant 2"); else if (y < 0) { System.out.println("Quadrant 3"); else { System.out.println("negative x-axis"); else { System.out.println("y-Axis"); 25

TYPE CASTS & EXCEPTION HANDLING 26

Type Conversion Java uses type casts for converting values (int) x: converts x into an integer Example 1: ((int) 127) + 1 == 128 Example 2: (int) -3.999 == -3 (double) x: converts x into a float Example 1: (double) 42 == 42.0 Example 2: (double) "42" results in Compilation Error (String) x: views x as a string Example: Object o = "Hello World! ; String s = (String) o; 27

Catching Exceptions type conversion operations are error-prone Example: Object o = new Integer(23); Strings s = (String) o; good idea to avoid type casts sometimes necessary, e.g. when implementing equals method use try-catch statement to handle error situations Example 1: String s; try { s = (String) o; catch (ClassCastException e) { s = "ERROR"; 28

Catching Exceptions use try-catch statement to handle error situations Example 2: try { double x; x = Double.parseDouble(str); System.out.println("The number is " + x); catch (NumberFormatException e) { System.out.println("The number sucks."); 29

Arrays array = built-in, mutable list of fixed-length type declared by adding [] to base type Example: int[] speeddial; creation using same new as for objects size declared when creating array Example: speeddial = new int[20]; also possible to fill array using { while creating it then length determined by number of filled elements Example: speeddial = {65502327, 55555555; 30

Arrays array = built-in, mutable list of fixed-length access using [index] notation (both read and write, 0-based) size available as attribute.length Example: int[] speeddial = {65502327, 55555555; for (int i = 0; i < speeddial.length; i++) { System.out.println(speedDial[i]); speeddial[i] += 100000000; for (int i = 0; i < speeddial.length; i++) { System.out.println(speedDial[i]); 31

Command Line Arguments command line arguments given as array of strings Example: public class PrintCommandLine { public static void main(string[] args) { int len = args.length; System.out.println("got "+len+" arguments"); for (int i = 0; i < len; i++) { System.out.println("args["+i+"] = "+args[i]); 32

Reading from Files done the same way as reading from the user i.e., using the class java.util.scanner instead of System.in we use an object of type java.io.file Example (reading a file given as first argument): import java.util.scanner; import java.io.file; public class OpenFile { public static void main(string[] args) { File infile = new File(args[0]); Scanner sc = new Scanner(infile); while (sc.hasnext()) { System.out.println(sc.nextLine()); 33

Reading from Files Example (reading a file given as first argument): import java.util.scanner; import java.io.*; public class OpenFile { public static void main(string[] args) { File infile = new File(args[0]); try { Scanner sc = new Scanner(infile); while (sc.hasnext()) { System.out.println(sc.nextLine()); catch (FileNotFoundException e) { System.out.println("Did not find your strange "+args[0]); 34

Writing to Files done the same way as writing to the screen i.e., using the class java.io.printstream System.out is a predefined java.io.printstream object Example (copying a file line by line): import java.io.*; import java.util.scanner; public class CopyFile { public static void main(string[] args) throws new FileNotFoundException { Scanner sc = new Scanner(new File(args[0])); PrintStream target = new PrintStream(new File(args[1])); while (sc.hasnext()) { target.println(sc.nextline()); target.close(); 35

Throwing Exceptions Java uses throw (comparable to raise in Python) Example (method that receives unacceptabe input): static double power(double a, int b) { if (b < 0) { String msg = "natural number expected"; throw new IllegalArgumentException(msg); result = 1; for (; b > 0; b--) { result *= a; return result; 36

OBJECT ORIENTATION 37

Objects, Classes, and Instances class = description of a class of objects Example: a Car is defined by model, year, and colour object = concrete instance of a class Example: a silver Audi A4 from 2013 is an instance of Car Example (Car as Java class): public class Car { public String model, colour; public int year; public Car(String model, int year, String colour) { this.model = model; this.year = year; this.colour = colour; 38

Attributes attributes belonging to each object are member variables they are declared by giving their types inside the class Example: public class Car { public String model, colour; public int year; visibility can be public, protected, package or private for now only public or private: public = usable (read and write) for everyone private = usable (read and write) for the class 39

Getters and Setters getter = return value of a private attribute setter = change value of a private attribute Example: public class Car { private String model; public String getmodel() { return this.model; public void setmodel(string model) { this.model = model; 40

Getters and Setters very useful to abstract from internal representation Example: public class Car { // built after 1920 private byte year; public int getyear() { return this.year >= 20? this.year + 1900 : this.year + 2000; public void setyear(int year) { this.year = (byte) year % 100; 41

Static Attributes attributes belonging to the class are static attributes declaration by static and giving their types inside the class Example: public class Car { private static int number = 0; public Car(String model, int year, String colour) { this.model = model; this.year = year; this.colour = colour; Car.number++; public int getnumberofcars() { return number; 42

Initializing Global and Local Variables local variable = variable declared in a block global variable = member variable or static attribute all local and all global variables can be initialized Example: public class Car { private static int number = 0; public String model = "Skoda Fabia"; public Car(String model, int year, String colour) { boolean[] wheelok = new boolean[4]; 43

Constructors objects are created by using new Example: Car mine = new Car("VW Passat", 2003, "black"); Execution: Java Runtime Environment reserves memory for object constructor with matching parameter list is called constructor is a special method with no (given) return type Example: public class Car { public Car(String model, int year, String colour) { this.model = model; this.year = year; this.colour = colour; 44

Constructors more than one constructor possible (different parameter lists) constructors can use each other in first line using this( ); Example: public class Car { public Car(String model, int year, String colour) { this.model = model; this.year = year; this.colour = colour; public Car(String model, byte year, String colour) { this(model, year > 20? 1900+year : 2000+year, colour); 45

Overloading overloading = more than one function of the same name allowed as long as parameter lists are different different return types is not sufficient! Example: public class Car { public void setcolour(string colour) { this.colour = colour; public void setcolour(string colour, boolean dark) { if (dark) { colour = "dark"+colour; this.colour = colour; 46

Printing Objects printing objects does not give the desired result Example: System.out.println(new Car("Audi A1", 2011, "red")); method public String tostring() (like str in Python) Example: public class Car { public String tostring() { return this.colour+" "+this.model+" from "+this.year; 47

ADVANCED OBJECT-ORIENTATION 48

Object-Oriented Design classes often do not exist in isolation from each other a vehicle database might have classes for cars and trucks in such situation, having a common superclass useful Example: public class Vehicle { public String model; public int year; public Vehicle(String model, int year) { this.model = model; this.year = year; public String tostring() {return this.model+" from "+this.year; 49

Extending Classes Car and Truck then extend the Vehicle class Example: public class Car extends Vehicle { public String colour; public Car(string model, int year, String colour) { this.colour = colour; // this makes NO SENSE public String tostring() { return this.colour; public class Truck extends Vehicle { public double maxload; 50

Class Hierarchy class hierarchies are parts of class diagrams for our example we have: is-a Object is-a Vehicle is-a Car Truck 51

Abstract Classes often, superclasses should not have instances in our example, we want no objects of class Vehicle can be achieved by declaring the class to be abstract Example: public abstract class Vehicle { public String model; public int year; public Vehicle(string model, int year) { this.model = model; this.year = year; public String tostring() {return this.model+" from "+this.year; 52

Accessing Attributes attributes of superclasses can be accessed using this Example: public class Car extends Vehicle { public String colour; public Car(string model, int year, String colour) { this.model = model; this.year = year; this.colour = colour; public String tostring() { return this.colour+" "+this.model+" from "+this.year; 53

Accessing Superclass methods of superclasses can be accessed using super Example: public class Car extends Vehicle { public String colour; public Car(string model, int year, String colour) { this.model = model; this.year = year; this.colour = colour; public String tostring() { return this.colour+" "+super.tostring(); 54

Superclass Constructors constructors of superclasses can be accessed using super Example: public class Car extends Vehicle { public String colour; public Car(string model, int year, String colour) { super(model, year); this.colour = colour; public String tostring() { return this.colour+" "+super.tostring(); 55

Abstract Methods abstract method = method declared but not implemented useful in abstract classes (and later interfaces) Example: public abstract class Vehicle { public String model; public int year; public Vehicle(string model, int year) { this.model = model; this.year = year; public String tostring() {return this.model+" from "+this.year; public abstract computeresalevalue(); 56

Interfaces different superclasses could have different implementations to avoid conflicts, classes can only extend one (abstract) class interfaces = abstract classes without implementation only contain public abstract methods (abstract left out) no conflict possible with different interfaces Example: public interface HasValueAddedTax { public double getvalueaddedtax(double percentage); public class Car implements HasValueAddedTax { public double getvalueaddedtax(double p) { return 42000; 57

Interfaces Example: public interface HasValueAddedTax { public double getvalueaddedtax(double percentage); public interface Destructible { public void destroy(); public class Car implements HasValueAddedTax, Destructible { public double getvalueaddedtax(double p) { return 42000; public void destroy() { this.model = "BROKEN"; 58

Interface and Class Hierarchy interfaces outside normal class hierarchy HasValueAddedTax Destructible Vehicle Car Truck 59