Branching and Boolean Expressions

Similar documents
Branching and Boolean Expressions

Introduction Basic elements of Java

Loops and Expression Types

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

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

Software and Programming 1

Arrays and Basic Algorithms

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)

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

CS 177 Recitation. Week 1 Intro to Java

Flow of Control. Chapter 3

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

Flow of Control. Chapter 3

Data Structure and Programming Languages

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

Object-oriented programming in...

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

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

An overview of Java, Data types and variables

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

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

Programming Language Concepts: Lecture 1

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

Introduction to Programming Using Java (98-388)

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

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

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

DM550 Introduction to Programming part 2. Jan Baumbach.

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

Lecture Set 2: Starting Java

Program Fundamentals

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

Lecture Set 2: Starting Java

Programming Language Concepts: Lecture 2

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

MODULE 02: BASIC COMPUTATION IN JAVA

Programming Language Basics

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

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

More on Objects and Classes

PROGRAMMING STYLE. Fundamentals of Computer Science I

The if/else Statement

Introduction to Software Development (ISD) Week 3

Full file at

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

Language Reference Manual

3. Java - Language Constructs I

Variables and data types

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

CSE 114 Computer Science I

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

Key Differences Between Python and Java

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

List of Slides 1 Title 2 Chapter 2: Sequential execution and program errors 3 Chapter aims 4 Section 2: Example:Hello world 5 Aim 6 Class: programs ar

COMP 202 Java in one week

Getting Started with Java. Atul Prakash

Chapter 2 Elementary Programming

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Tutorial 1 CSC 201. Java Programming Concepts عؾادئماظربجمةمبادؿكدامماجلاصا

BASICS.

CSE 201 JAVA PROGRAMMING I. Copyright 2016 by Smart Coding School

What did we talk about last time? Examples switch statements

CS 106 Introduction to Computer Science I

COMP 202 Java in one week

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

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

CONDITIONAL EXECUTION

Condensed Java. 12-Oct-15

1.1 Your First Program

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

Computational Expression

Lecture 2: Intro to Java

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

PROGRAMMING FUNDAMENTALS

Datatypes, Variables, and Operations

Object-Oriented Programming

1.1 Your First Program

Elementary Programming

CEN 414 Java Programming

Programming with Java

Conditional Programming

Data Structure and Programming Languages

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

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

A PROGRAM IS A SEQUENCE of instructions that a computer can execute to

DM503 Programming B. Peter Schneider-Kamp.

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

Java+- Language Reference Manual

CS 61C: Great Ideas in Computer Architecture Introduction to C

CS 231 Data Structures and Algorithms, Fall 2016

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

Java Programming. Atul Prakash

AP CS Unit 3: Control Structures Notes

More types, Methods, Conditionals. ARCS Lab.

Goals. Java - An Introduction. Java is Compiled and Interpreted. Architecture Neutral & Portable. Compiled Languages. Introduction to Java

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 Return Statement Section 5.4 SP1 2019-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 2019-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 2019-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 2019-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 2019-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 2019-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 2019-02 7

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

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 2019-02 1 9

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. 9, lines 3 9 1 int actualfloor; 2 if (floor > 13) 3 actualfloor = floor - 1; 4 else 5 actualfloor = floor; SP1 2019-02 10

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 2019-02 11

If: Common Mistakes ; is a valid Java statement it does nothing 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 2019-02 12

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 2019-02 13

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 2019-02 14

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 2019-02 15 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. 13) 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 } 2.0000000000000004 the interval contains all x 2.0 ε 2.0 2.0 + ε with ε < x 2 < ε or, equivalently, x 2 < ε SP1 2019-02 16

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 2019-02 17

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 2019-02 18

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 2019-02 19

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 2019-02 20

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 2019-02 21

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 2019-02 22

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 2019-02 23

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 2019-02 24

Return Statement The return statement (1) terminates a method call (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 2019-02 25

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 2019-02 26