DM537 Object-Oriented Programming. Peter Schneider-Kamp.

Similar documents
DM550 Introduction to Programming part 2. Jan Baumbach.

DM503 Programming B. Peter Schneider-Kamp.

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

DM550 Introduction to Programming part 2. Jan Baumbach.

DM550 Introduction to Programming part 2. Jan Baumbach.

DM503 Programming B. Peter Schneider-Kamp.

DM537 Object-Oriented Programming. Peter Schneider-Kamp.

3. Java - Language Constructs I

Computer Components. Software{ User Programs. Operating System. Hardware

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

COMP 202 Java in one week

CSC 1214: Object-Oriented Programming

Computer Components. Software{ User Programs. Operating System. Hardware

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

3. Java - Language Constructs I

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

Chapter 2. Elementary Programming

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

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

CS 231 Data Structures and Algorithms, Fall 2016

Introduction to Computer Science Unit 2. Notes

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

DM502 Programming A. Peter Schneider-Kamp.

Java Programming. Atul Prakash

DM536 / DM550 Part 1 Introduction to Programming. Peter Schneider-Kamp.

Programming Lecture 3

CSCI 2101 Java Style Guide

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

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Lecture 2: Variables and Operators. AITI Nigeria Summer 2012 University of Lagos.

Important Java terminology

Accelerating Information Technology Innovation

Full file at

Simple Java Reference

JAVA OPERATORS GENERAL

Prof. Navrati Saxena TA: Rochak Sachan

AP CS Unit 3: Control Structures Notes

An overview of Java, Data types and variables

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Course Outline. Introduction to java

Java Basic Programming Constructs

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

Programming with Java

Program Fundamentals

COMP 202 Java in one week

c) And last but not least, there are javadoc comments. See Weiss.

DM536 Introduction to Programming. Peter Schneider-Kamp.

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

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Objectives. Problem Solving. Introduction. An overview of object-oriented concepts. Programming and programming languages An introduction to Java

Introduction to Java & Fundamental Data Types

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

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

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

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

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

Introduction to Programming Using Java (98-388)

Chapter 3: Operators, Expressions and Type Conversion

Elementary Programming

CS111: PROGRAMMING LANGUAGE II

Operators. Java operators are classified into three categories:

Chapter 3. Selections

DM550/DM857 Introduction to Programming. Peter Schneider-Kamp

Operators and Expressions

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

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

CS 61B Data Structures and Programming Methodology. June David Sun

DM536 Introduction to Programming. Peter Schneider-Kamp.

Software Practice 1 Basic Grammar

AP Computer Science A

: Primitive data types Variables Operators if, if-else do-while, while, for. // // First Java Program. public class Hello {

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

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

Introduction to Computer Science Unit 2. Notes

JAVA Ch. 4. Variables and Constants Lawrenceville Press

Java Identifiers. Java Language Essentials. Java Keywords. Java Applications have Class. Slide Set 2: Java Essentials. Copyright 2012 R.M.

2 rd class Department of Programming. OOP with Java Programming

Java Bytecode (binary file)

WEEK 4 OPERATORS, EXPRESSIONS AND STATEMENTS

Java Review. Java Program Structure // comments about the class public class MyProgram { Variables

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

Games Course, summer Introduction to Java. Frédéric Haziza

Index COPYRIGHTED MATERIAL

IEEE Floating-Point Representation 1

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

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

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

Language Fundamentals Summary

bitwise inclusive OR Logical logical AND && logical OR Ternary ternary? : Assignment assignment = += -= *= /= %= &= ^= = <<= >>= >>>=

Zheng-Liang Lu Java Programming 45 / 79

Chapter 4 Fundamental Data Types. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved.

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

CHAPTER 2 Java Fundamentals

boolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while

COMP 202. Java in one week

4 Programming Fundamentals. Introduction to Programming 1 1

Transcription:

DM537 Object-Oriented Programming Peter Schneider-Kamp petersk@imada.sdu.dk! http://imada.sdu.dk/~petersk/dm537/!

VARIABLES, EXPRESSIONS & STATEMENTS 2

Values and Types Values = basic data objects 42 23.0 "Hello!" Types = classes of values int double String Types need to be declared <type> <var>; int answer; Values can be printed: System.out.println(<value>); System.out.println(23.0); Values can be compared: <value> == <value> -3 == -3.0 3

Variables variable = name that refers to value of certain type program state = mapping from variables to values values are assigned to variables using = : <var> = <value>; answer = 42; the value referred to by a variable can be printed: System.out.println(<var>); System.out.println(answer); the type of a variable is given by its declaration 4

Primitive Types Type Bits Range boolean 1 {true, false byte 8 {-2 7 = -128,, 127 = 2 7-1 short 16 {-2 15 = -32768,, 32767 = 2 15-1 char 16 {'a',,'z', '%', int 32 {-2 31,, 2 31-1 float 32 1 sign, 23(+1) mantissa, 8 exponent bits long 64 {-2 63,, 2 63-1 double 64 1 sign, 52(+1) mantissa, 11 exponent bits 5

Reference Types references types = non-primitive types references types typically implemented by classes and objects Example 1: String Example 2: arrays (mutable, fixed-length lists) 6

Variable Names start with a letter (convention: a-z) or underscore _ contain letters a-z and A-Z, digits 0-9, and underscore _ can be any such name except for 50 reserved names: abstract continue for new switch assert default goto package synchronized boolean do if private this break double implements protected throw byte else import public throws case enum instanceof return transient catch extends int short try char final interface static void class finally long strictfp volatile const float native super while 7

Multiple Assignment variables can be assigned to different values of the same type: Example: int x = 23; x = 42; Instructions are executed top-to bottom => x refers to 42 variables cannot be assigned to values of different type: Example: int x = 23; x = 42.0; //!ERROR! only exception is if types are compatible : Example: double x = 23.0; x = 42; // :-) 8

Operators & Operands Operators represent computations: + * - / ++ -- Example: 23+19 day+month*30 2*2*2*2*2*2-22 Addition +, Multiplication *, Subtraction - as usual there is no exponentiation operator to compute x y need to use Math.pow(x, y) write your own function power static int power(int a, int b) { if (b == 0) return 1; else return a*power(a,b-1); Division / rounds down integers (differently from Python) Example Java: 3/-2 has value -1 Example Python: 3/-2 has value -2 9

Boolean Expressions expressions of type boolean with value either true or false logic operators for computing with Boolean values: x && y true if, and only if, x is true and y is true x y true if (x is true or y is true)!x true if, and only if, x is false Java does NOT treat numbers as Boolean expressions J 10

Expressions Expressions can be: Values: 42 23.0 "Hej med dig!" Variables: x y name1234 built from operators: 19+23.0 x*x+y*y grammar rule: <expr> => <value> <var> <expr> <operator> <expr> ( <expr> ) every expression has a value: replace variables by their values perform operations 11

Increment and Decrement abbreviation for incrementing / decrementing (like in Python) Example: counter = counter + 1; counter += 1; in special case of +1, we can use ++ operator Example: counter++; two variants: post- and pre-increment Example: int x = 42; int y = x++; // x == 43 && y == 42 int z = ++y; // y == 43 && z == 43 same for decrementing with -- operator 12

Relational Operators relational operators are operators, whose value is boolean important relational operators are: Example True Example False x < y 23 < 42 'W' < 'H' x <= y 42 <= 42.0 Math.PI <= 2 x == y 42 == 42.0 2 == 2.00001 x!= y 42!= 42.00001 2!= 2.0 x >= y 42 >= 42 'H' >= 'h' x > y 'W' > 'H' 42 > 42 remember to use == instead of = (assignment)! 13

Conditional Operator select one out of two expressions depending on condition as a grammar rule: <cond-op> => <cond>? <expr 1 > : <expr 2 > Example: int answer = (1 > 0)? 42 : 23; useful as abbreviation for many small if-then-else constructs 14

Operator Precedence expressions are evaluated left-to-right Example: 64-24 + 2 == 42 BUT: like in mathematics, * binds more strongly than + Example: 2 + 8 * 5 == 42 parentheses have highest precedence: 64 - (24 + 2) == 38 Parentheses ( <expr> ) Increment ++ and Decrement -- Multiplication * and Division / Addition + and Subtraction - Relational Operators, Boolean Operators, Conditonal, 15

String Operations Addition + works on strings; -, *, and / do NOT other operations implemented as methods of class String: String s1 = "Hello "; String s2 = "hello "; boolean b1 = s1.equals(s2); // b1 == false boolean b2 = s1.equalsignorecase(s2); // b2 == true int i1 = s1.length(); // i1 == 5 char c = s1.charat(1); // c == 'e String s3 = s1.substring(1,3); // s3.equals("el") int i2 = s1.indexof(s3); // i2 == 1 int i3 = s1.compareto(s2); // i3 == -1 String s4 = s1.tolowercase(); // s4.equals(s2) String s5 = s1.trim(); // s5.equals("hello") 16

Formatting Strings convert to string using format strings (like in Python) Example: System.out.println(String.format("%d", 42)); System.out.printf("%d\n", 42); String.format(String s, Object... args) more general format sequence %d for integer, %g for float, %s for string for multiple values, use multiple arguments Example: System.out.printf("The %s is %g!", "answer", 42.0); 17

Statements instructions in Java are called statements so far we know 3 different statements: expression statements: System.out.println("Ciao!"); assignments = : c = a*a+b*b; return statements: return c; as a grammar rule: <stmt> => <expr> <var> = <expr> return <expr> 18

Comments programs are not only written, they are also read document program to provide intuition: Example 1: c = Math.sqrt(a*a+b*b); // use Pythagoras Example 2: int tmp = x; x = y; y = tmp; // swap x and y all characters after the comment symbol // are ignored multiline comments using /* and */ Example: /* This comment is very long! */ Javadoc comments using /** and */ Example: /** This function rocks! */ 19

(Syntactic) Differences Java / Python every statement is ended by a semi-colon ; Example: import java.util.scanner; indentation is a convention, not a must L blocks of code are marked by curly braces { and Example: public class A {public static void main(string[] args) {Scanner sc = new Scanner(System.in); int a = sc.nextint(); System.out.println(a*a); objects are created using new Java variables require type declarations Example: Scanner sc = null; int a = 0; int b; b = 1; 20

CALLING & DEFINING FUNCTIONS 21

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()); 22

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); 23

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)); 24

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) 25

Stack Diagrams Pythagoras.main pyt è Pythagoras(3, 4) pyt.compute this Math.sqrt x è 25 26

SIMPLE ITERATION 27

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) { n == 3 2 1 0 while (n > 0) { System.out.println(n); n--; System.out.println("Ka-Boom!"); false true 28

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!"); 29

Approximating Square Roots Newton s method for finding root of a function f: 1. start with some value x 0 2. refine this value using x n+1 = x n f(x n ) / f (x n ) for square root of a: f(x) = x 2 a f (x) = 2x simplifying for this special case: x n+1 = (x n + a / x n ) / 2 Example: double xn = 1; while (true) { System.out.println(xn); double xnp1 = (xn + a / xn) / 2; if (xnp1 == xn) { break; xn = xnp1; 30

Approximating Square Roots Newton s method for finding root of a function f: 1. start with some value x 0 2. refine this value using x n+1 = x n f(x n ) / f (x n ) for square root of a: f(x) = x 2 a f (x) = 2x simplifying for this special case: x n+1 = (x n + a / x n ) / 2 Example: double xnp1 = 1; do { xn = xnp1; System.out.println(xn); double xnp1 = (xn + a / xn) / 2; while (xnp1!= xn); 31

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 32

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

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

Iterating with For Loops (standard) for loops very different from Python grammar rule: Example: int n = 10; <for-loop> => for (<init>; <cond>; <update>) { <instr 1 >; ; <instr k >; 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!"); 35

CONDITIONAL EXECUTION 36

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

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"); 38

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!"); 39

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

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"); 41

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" 42

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 >; 43

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

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"); 45

TYPE CASTS & EXCEPTION HANDLING 46

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; 47

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"; 48

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."); 49

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; 50

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]); 51

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]); 52

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()); 53

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]); 54

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(); 55

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; 56