Branching and Boolean Expressions

Similar documents
Branching and Boolean Expressions

Loops and Expression Types

Introduction Basic elements of Java

Chapter Goals. 3.1 The if Statement. Contents 1/30/2013 DECISIONS

Arrays and Basic Algorithms

Software and Programming 1

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

Software and Programming 1

Java Coding 2. Decisions, decisions!

CS 11 java track: lecture 1

Getting started with Java

Object-Oriented Programming in Java

Java Bytecode (binary file)

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Computer Programming. Basic Control Flow - Decisions. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Full file at

CS 177 Recitation. Week 1 Intro to Java

ANSWERS. Birkbeck (University of London) Software and Programming 1 In-class Test Feb Student Name Student Number. Answer all questions

Data Structure and Programming Languages

Introduction to Programming Using Java (98-388)

DM550 Introduction to Programming part 2. Jan Baumbach.

Lecture Set 2: Starting Java

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

Flow of Control. Chapter 3

3. Java - Language Constructs I

Lecture Set 2: Starting Java

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

! Widely available. ! Widely used. ! Variety of automatic checks for mistakes in programs. ! Embraces full set of modern abstractions. Caveat.

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

Flow of Control. Chapter 3

Programming Language Concepts: Lecture 1

Object-oriented programming in...

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

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

Chapter 5 Decisions. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved.

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

An overview of Java, Data types and variables

Programming Language Basics

Program Fundamentals

1 Introduction Java, the beginning Java Virtual Machine A First Program BlueJ Raspberry Pi...

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Datatypes, Variables, and Operations

Programming Language Concepts: Lecture 2

Introduction to Software Development (ISD) David Weston and Igor Razgon

Lecture 2: Intro to Java

Chapter 4: Control Structures I

MODULE 02: BASIC COMPUTATION IN JAVA

Lec 3. Compilers, Debugging, Hello World, and Variables

Chapter 2 Elementary Programming

CEN 414 Java Programming

Inf1-OOP. Textbooks. Who and What. Organizational Issues. Why Java? Course Overview. Hello, World! in Java. Ewan Klein, Perdita Stevens

CSC 1214: Object-Oriented Programming

Define a method vs. calling a method. Chapter Goals. Contents 1/21/13

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

DM503 Programming B. Peter Schneider-Kamp.

4 Programming Fundamentals. Introduction to Programming 1 1

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

The if/else Statement

Programming with Java

CSI33 Data Structures

COMP Primitive and Class Types. Yi Hong May 14, 2015

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false.

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

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language

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

Java Programming. Atul Prakash

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

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

CS 106 Introduction to Computer Science I

Elementary Programming

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

More on Objects and Classes

Java+- Language Reference Manual

Software and Programming I. Classes and Arrays. Roman Kontchakov / Carsten Fuhs. Birkbeck, University of London

PROGRAMMING STYLE. Fundamentals of Computer Science I

MATVEC: MATRIX-VECTOR COMPUTATION LANGUAGE REFERENCE MANUAL. John C. Murphy jcm2105 Programming Languages and Translators Professor Stephen Edwards

Input-Output and Exception Handling

Chapter 3: Operators, Expressions and Type Conversion

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Introduction to Software Development (ISD) Week 3

Introduction to Programming (Java) 2/12

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

Programming: Java. Chapter Objectives. Control Structures. Chapter 4: Control Structures I. Program Design Including Data Structures

Inf1-OOP. Textbooks. Who and What. Organisational issues. Why Java? Course Overview. Hello, World! in Java

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

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

Flow Control. CSC215 Lecture

Variables and data types

Java is an objet-oriented programming language providing features that support

Data Structure and Programming Languages

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

17 Hello world 18 Type: String: literal 19 Standard API: System: out.println() 20 Hello world 21 Statement 22 Statement: simple statements are ended w

Object-Oriented Programming

More types, Methods, Conditionals. ARCS Lab.

Key Differences Between Python and Java

AP CS Unit 3: Control Structures Notes

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

EXPRESSIONS AND ASSIGNMENT CITS1001

Transcription:

Software and Programming I Branching and Boolean Expressions Roman Kontchakov / Carsten Fuhs Birkbeck, University of London

Outline The if statement Comparing numbers and strings Nested branches Boolean variables and expressions Sections 3.1 3.4, 3.7 SP1 2018-02 1

Java Compilation and JRE source HelloWorld.java compiler javac bytecode HelloWorld.class java public static void main(string[] args) {... } running program Virtual Machine (VM) SP1 2018-02 2

My First Program 1 /* HelloWorld.java 2 Purpose: printing a hello message on the screen 3 */ 4 public class HelloWorld { 5 // each program is a class (week 6) 6 // almost everything in Java is an object 7 public static void main(string[] args) { 8 System.out.println("Hello, " + args[0] + "!"); 9 } 10 } NB. watch out for semicolons they are compulsory NB. names and reserved words are case-sensitive SP1 2018-02 3

Methods A method is a named sequence of instructions method name public static int sq(int x) { java code (sequence of instructions) } parameter (type and name) type of return value Parameter values are supplied when a method is called The return value is the result that the method computes Method algorithm function (in Python) NB: until week 6, all methods will be public static SP1 2018-02 4

Example 2: y = x 2 as a Method 1 public class PrintSquares { 2 public static void main(string[] args) { 3 printsquare(7); 4 printsquare(9); 5 } 6 public static int sq(int x) { // x is a parameter 7 int y = x * x; // compute xˆ2 8 return y; // return the value 9 } 10 public static void printsquare(int n) { 11 System.out.println(n + "ˆ2=" + sq(n)); 12 } 13 } the output: 7ˆ2=49 9ˆ2=81 NB: void means that the method does not return any value SP1 2018-02 5

Method Call Stack args main printsquare(7); n printsquare 7 public static void printsquare(int n) { System.out.println(n + "ˆ2=" + sq(n)); x y 7 49 0 sq public static int sq(int x) { int y = x * x; return y; } SP1 2018-02 6

Method Call Stack args main printsquare(7); printsquare(9); 7ˆ2=49 9ˆ2=81 n printsquare x y 7 9 9 81 0 sq public static void printsquare(int n) { System.out.println(n + "ˆ2=" + sq(n)); } public static int sq(int x) { evaluated to 49 81 int y = x * x; return y; } SP1 2018-02 7

Method Call Stack args main printsquare(7); printsquare(9); 7ˆ2=49 9ˆ2=81 SP1 2018-02 8

Swapping Values suppose there are two variables 1 int a, b; // the same as int a; int b; how do you swap the contents of a and b? a 4 b 5 2 int t = a; a 4 b 5 t 4 3 a = b; a 5 b 5 t 4 4 b = t; a 5 b 4 t 4 SP1 2018-02 9

The if Statement The if statement allows a program to carry out different actions depending on the nature of the data to be processed 1 Scanner s = new Scanner(System.in); 2 int floor = s.nextint(); 3 int actualfloor; 4 if (floor > 13) { 5 actualfloor = floor - 1; 6 } 7 else { 8 actualfloor = floor; 9 } 10 System.out.println("Actual floor: " + 11 actualfloor); floor actual floor 14 15 14 13 11 12 12 9 10 11 7 8 10 5 6 9 3 4 8 7 1 2 6 5 4 3 2 SP1 2018-02 1 10

Statement Blocks A block is a group of 0 or more statements between balanced { and } (in Python: a group of statements indented at the same level) A block can be used anywhere a single statement is allowed the following is equivalent to the code on p. 10, lines 3-9 1 int actualfloor; 2 if (floor > 13) 3 actualfloor = floor - 1; 4 else 5 actualfloor = floor; SP1 2018-02 11

The Else Branch is Optional The else branch is optional 1 int discountedprice = originalprice; 2 if (originalprice > 100) 3 discountedprice = originalprice - 10; is equivalent to 1 int discountedprice; 2 if (originalprice > 100) 3 discountedprice = originalprice - 10; 4 else 5 discountedprice = originalprice; SP1 2018-02 12

If: Common Mistakes NB: do not put the semicolon after if(...) 1 int discountedprice = originalprice; 2 if (originalprice > 100); { // empty statement in if 3 // LOGICAL ERROR: this block is executed anyway 4 discountedprice = originalprice - 10; 5 } // it is, however, NOT a syntax (compile) error SP1 2018-02 13

Constants the reserved word final ensures that the value of the variable never changes: final double BOTTLE VOLUME = 2; use names for constants and avoid magic numbers all uppercase with words separated by is a coding convention Java does not check it! SP1 2018-02 14

Comparing Numbers relational operators >, >=, <, <=, ==,!= are applicable to int, double and other numerical datatypes NB: NOT but why not, e.g., => instead of >=? (assignment operators, week 3) relational operators return boolean values (either true or false), which, for example, can be stored in boolean variables 1 int floor = 2; 2 int top = 12; 3 boolean over = floor > top; SP1 2018-02 15

IEEE Floating Point Numbers float: ±1.18 10 38 to ±3.4 10 38 with approx. 7 decimal digits sign exponent (8 bit) fraction (23 bit) NB: float should never be used for precise values, e.g., currency; use java.math.bigdecimal class instead double: ±2.23 10 308 to ±1.80 10 308 with approx. 15 decimal digits sign exponent (11 bit) fraction (52 bit) NB: in Java, 1e-14 means 10 14 or 0. 0000000000000 }{{} 13 zeros SP1 2018-02 16 1

Comparing Floating-Point Numbers arithmetic operations on floating-point numbers cannot be precise use small ε = 10 14 to compare floating numbers: 1 final double EPSILON = 1e-14; // constant (see p. 14) 2 double r = Math.sqrt(2.0); 3 // r*r is 2.0000000000000004 rather than 2.0 4 if (Math.abs(r * r - 2.0) < EPSILON) { 5 System.out.println("Math.sqrt(2.0) squared " + 6 "is approx 2.0"); 7 } SP1 2018-02 17

Strings strings are sequences of characters: String name = "Harry"; }{{} literal the length method yields the number of characters in the string: int n = name.length(); the empty string "" is of length 0 string positions are counted starting with 0 H a r r y position 0 1 2 3 4 SP1 2018-02 18

Comparing Strings "Tomato".substring(0,3).equals("Tom") is true NB: == is not useful for strings in Java: (in contrast to Python) "Tomato".substring(0,3) == ("Tom") is false why? Strings are objects (week 6) s1.compareto(s2) compares strings lexicographically: < 0 if s1 comes before s2 in the dictionary == 0 if s1 equals s2 > 0 if s1 comes after s2 in the dictionary in Python, use s1 < s2, s1 == s2 and s1 > s2, respectively SP1 2018-02 19

Characters char is a numerical datatype literals H, A, etc. NB. do not confuse characters ( H ) and strings containing a single character ("H") NB. Python has no special datatype for characters, there H and "H" are both strings Class Character provides the following methods: Character.isDigit(ch): 0, 1,..., 9,... Character.isLetter(ch): A, B,..., Z, a, b,..., z,... Character.isUpperCase(ch): A, B,..., Z,... Character.isLowerCase(ch): a, b,..., z,... Character.isWhiteSpace(ch):, \n,... SP1 2018-02 20

Nested Branches and the Dangling else What is wrong in the following example? 1 double shippingcharge = 5.00; 2 if (country.equals("usa")) 3 if (state.equals("hi")) 4 shippingcharge = 10.00; // Hawaii is 5 // more expensive 6 else 7 shippingcharge = 20.00; // as are foreign 8 // shipments NB: the Java compiler does not care about indentation (in contrast to Python) SP1 2018-02 21

Nested Branches and the Dangling else 1 double shippingcharge = 5.00; 2 if (country.equals("usa")) { 3 if (state.equals("hi")) 4 shippingcharge = 10.00; // Hawaii is 5 // more expensive 6 } 7 else 8 shippingcharge = 20.00; // as are foreign 9 // shipments NB: use curly brackets {} to avoid the dangling else problem SP1 2018-02 22

Boolean Variables and Operators The Boolean type boolean has two values, false and true three Boolean operators that combine conditions: && (and), (or),! (not) A B A && B false false false false true false true false false true true true A B A B false false false false true true true false true true true true A!A false true true false SP1 2018-02 23

Lazy Evaluation && and are computed using lazy evaluation: stops as soon as the result is known price/quantity < 10 && quantity > 0 can result in a run-time error (division by 0) if quantity is 0 quantity > 0 && price/quantity < 10 never divides by 0 SP1 2018-02 24

Boolean Operators De Morgan s Laws:!(A && B) is equivalent to!a!b!(a B) is equivalent to!a &&!B NB: Java does not use mathematical notation: if (0 <= temp <= 100) // ERROR - not an expression instead, use if (0 <= temp && temp <= 100) NB: and is NOT a Java operation SP1 2018-02 25

Conditional Operator conditional operator? : lets us write simple conditional statements as expressions 1 int actualfloor = (floor > 13)? floor - 1 : floor; is equivalent to 1 int actualfloor; 2 if (floor > 13) 3 actualfloor = floor - 1; 4 else 5 actualfloor = floor; an expression SP1 2018-02 26

Operation Precedence! unary highest *, /, % multiplicative +, - additive <, <=, >=, > relational ==,!= equality && logical AND logical OR?: conditional lowest boolean f = 13 < floor - 1; is the same as boolean f = 13 < (floor - 1); SP1 2018-02 27

Return Values The return statement (1) terminates a method call and (2) yields the method result 1 public static double cubevolume(double sidelength) { 2 if (sidelength < 0) 3 return 0; 4 // more code 5 return sidelength * sidelength * sidelength; 6 } NB: if a method has no return value (void), then it can contain return; only (without any value) SP1 2018-02 28

Take Home Messages The if statement allows a program to carry out different actions depending on the data to be processed Relational operators are used to compare numbers Use equals and compareto to compare strings else is matched with the preceding if && and are computed lazily The return statement terminates a method call and yields the method result SP1 2018-02 29