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

Similar documents
Control Structures. Code can be purely arithmetic assignments. At some point we will need some kind of control or decision making process to occur

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Introduction to Programming Using Java (98-388)

PROGRAMMING FUNDAMENTALS

Following is the general form of a typical decision making structure found in most of the programming languages:

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

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Decisions: Logic Java Programming 2 Lesson 7

Control Structures in Java if-else and switch

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

Programming with Java

Lecture Set 4: More About Methods and More About Operators

Java Coding 2. Decisions, decisions!

5. Control Statements

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

CS313D: ADVANCED PROGRAMMING LANGUAGE

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

Control Structures in Java if-else and switch

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.

Conditional Programming

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

Lecture Set 4: More About Methods and More About Operators

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Chapter 3. Selections

Flow of Control. Flow of control The order in which statements are executed. Transfer of control

V2 2/4/ Ch Programming in C. Flow of Control. Flow of Control. Flow of control The order in which statements are executed

Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Advance mode: Auto

Flow of Control. Chapter 3

Flow of Control. Chapter 3 Part 3 The Switch Statement

Chapter 4: Control Structures I

Primitive Types. Four integer types: Two floating-point types: One character type: One boolean type: byte short int (most common) long

What did we talk about last time? Examples switch statements

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

CS 106 Introduction to Computer Science I

Important Java terminology

Administration. Conditional Statements. Agenda. Syntax. Flow of control. Lab 2 due now on floppy Lab 3 due tomorrow via FTP

Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1

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

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

Software Design & Programming I

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Loops. CSE 114, Computer Science 1 Stony Brook University

Lesson 7 Part 2 Flags

1 Shyam sir JAVA Notes

Flow Control. CSC215 Lecture

Flow of Control. Chapter 3

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

Controls Structure for Repetition

Boolean Algebra Boolean Algebra

CSEN 202 Introduction to Computer Programming

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

Array. Prepared By - Rifat Shahriyar

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

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

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

CSC 1214: Object-Oriented Programming

CS2141 Software Development using C/C++ C++ Basics

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

Basics of Java Programming

Java I/O and Control Structures

CSE 142 Su 04 Computer Programming 1 - Java. Objects

CSE 1223: Introduction to Computer Programming in Java Chapter 3 Branching

Object Oriented Programming Lecture (2.1) Supervisor Ebtsam AbdelHakam Department of Computer Science Najran University

Fundamentals of Programming Data Types & Methods

Selection Statements and operators

Language Reference Manual

Java Basic Programming Constructs

H212 Introduction to Software Systems Honors

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

SELECTION. (Chapter 2)

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

CS 106 Introduction to Computer Science I

Operators. Java operators are classified into three categories:

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

Java+- Language Reference Manual

Branching. Chapter 5 11/14/16 & 11/15/16

Selection Statements and operators

Java Bytecode (binary file)

Basic Operations jgrasp debugger Writing Programs & Checkstyle

COMP 110 Project 1 Programming Project Warm-Up Exercise

Intro. Scheme Basics. scm> 5 5. scm>

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Introduction to Java & Fundamental Data Types

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

Computer Science 202 Introduction to Programming The College of Saint Rose Fall Topic Notes: Conditional Execution

In this chapter, you will:

Variables and literals

3. Java - Language Constructs I

The for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming

IEEE Floating-Point Representation 1

Expressions and Casting

Java I/O and Control Structures Algorithms in everyday life

BM214E Object Oriented Programming Lecture 4

Chapter 1. Introduction to Computers and Programming. M hiwa ahmad aziz

Values and Variables 1 / 30

Conditionals and Loops

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

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

Lecture Set 2: Starting Java

Transcription:

Table of Contents 1 INTRODUCTION... 1 2 IF... 1 2.1 BOOLEAN EXPRESSIONS... 3 2.2 BLOCKS... 3 2.3 IF-ELSE... 4 2.4 NESTING... 5 3 SWITCH (SOMETIMES KNOWN AS CASE )... 6 3.1 A BIT ABOUT BREAK... 7 4 CONDITIONAL OPERATOR... 8 1 Introduction If nothing interferes, a Java program begins executing at the first line of code in the main() method and stops when the last line is executed. While this is useful it can be cumbersome without the ability to do things like change what will be done next based on conditions that are encountered while the program is running. This is an easy sell for most people. Imagine being on the 10m board of a diving pool and you discover that there is no water below. If you couldn t change your course of action you would probably have what old programmers called an ABEND or ABnormal ENDing. Most programming languages provide the ability to change the course of execution through a series of constructs commonly called selection constructs allowing you to select what will be executed next. This document discusses Java features supporting selection. 2 if The if statement is the first and simplest ways of changing what will be done next based on testing a condition. Definition: An if statement allows a program to choose whether or not to execute an associated statement. Syntax: The syntax for an if statement is; if(<condition>) <statement1>; [ 1 of 9

<statement2>;] Rules: <condition> must be a boolean expression that evaluates to true or false. If the condition is true then <statement1> is executed. If the condition is false then <statement1> is skipped and <statement2> is executed if is present. If there is no, execution continuing after <statement1>. Only a single statement can follow the <condition> and the (we will fix this shortly). Here is an example program illustrating how if works. /* Program demoing if. A decision is made about an input temperature. If the temperature is below 20 a message is output. */ import java.util.scanner; class Temperature final static int COLD = 20; public static void main(string[] args) Scanner In = new Scanner(System.in); ("Enter the temperature outside."); int temperature = In.nextInt(); if(temperature <= COLD) ("It s cold out there!"); ("Bye!"); As output the program could produce several results; or Enter the temperature outside. 21 Bye! Enter the temperature outside. 19 It s cold out there! Bye! Note that only a single statement can be associated with the condition. 2 of 9

2.1 Boolean Expressions Definition: Anything that evaluates to true or false is a boolean expression. For example; true total == val 4 > 3 will all evaluate to one or the other. It is also possible to assign the results of a boolean expression to a boolean variable as in, boolean ans = (total == val); Java provides a set of relational operators each with its own precedence. The operators are shown in the table below. Operator Meaning == equal to (note: not assignment)!= not equal to < less than <= less than or equal to > greater than >= greater than or equal to 2.2 Blocks Recall that an if statement allows only one statement after the condition. You can avoid this problem by making a block of statements. Definition: A block is a list of statements enclosed in curly brackets We have already seen blocks in the main method and a class definition. We revisit the above example below. // Program demoing if. A decision is made // about an input temperature. If // the temperature is below 20 a message is output. import java.util.scanner; class Temperature1 3 of 9

final static int COLD = 20; public static void main(string[] args) Scanner In = new Scanner(System.in); ("Enter the temperature outside."); int temperature = In.nextInt(); if(temperature <= COLD) ("It s cold out there!"); ("But this is Canada!"); ("Bye!"); 2.3 if- The following program illustrates the use of the if- combination as well as blocks. /* Program demoing if-. A decision is made about input. */ import java.util.scanner; class Decision public static void main(string[] args) Scanner In = new Scanner(System.in); ( Enter 1 or 2. ); int answer = In.nextInt(); if(answer == 1) ( You entered 1! ); ( Ha, I knew you would ); ( You entered 2! ); ( I thought you would enter 1! ); ( Bye! ); Notes: The Bye! always gets printed 4 of 9

There is a problem what if they don t enter 1 or 2? 2.4 Nesting Now, an if statement is, in particular, a statement. This means that either statement-1 or statement-2 inside an if statement can itself be an if statement. (Note: If statement-1 is an if statement, then it has to have an part; if it does not, the computer will mistake the "" of the first if statement for the missing "" of statement-1. This is called the dangling problem. You can avoid this problem by enclosing statement-1 between and, making it into a block.) An if statement in which the part is itself an if statement would look like this (perhaps without the final part): if (<boolean-expression-1>) <statement-1> if (<boolean-expression-2>) <statement-2> <statement-3> You should think of this as a single statement representing a three-way branch. When the computer executes this, one and only one, of the three statements, statement-1, statement-2, and statement-3, will be executed. The computer starts by evaluating boolean-expression-1. If it is true, the computer executes statement-1 and then jumps all the way to the end of the big if statement, skipping the other two statement's. If boolean-expression-1 is false, the computer skips statement-1 and executes the second, nested if statement. That is, it tests the value of boolean-expression-2 and uses it to decide between statement-2 and statement-3. Here is an example that will print out one of three different messages, depending on the value of a variable named temperature: if (temperature < 50) ("It's cold."); if (temperature < 80) ("It's nice."); ("It's hot."); If temperature is, the computer prints out the message "It's cold", and skips the rest -- without even evaluating the second condition. 5 of 9

You can go on stringing together "-if's" to make multiway branches with any number of cases: if (boolean-expression-1) statement-1 if (boolean-expression-2) statement-2 if (boolean-expression-3) statement-3 // (more cases) if (boolean-expression-n) statement-n statement-(n+1) You should just remember that only one of the statements will be executed and that the computer will stop evaluating boolean-expressions as soon as it finds one that is true. Also, remember that the final part can be omitted and that any of the statements can be blocks, consisting of a number of statements enclosed between and. (Admittedly, there is lot of syntax here; as you study and practice, you'll become comfortable with it.) 3 Switch (sometimes known as case ) Java also provides a control structure that is specifically designed to make multiway branches of a certain type: the switch statement. A switch statement allows you to test the value of an expression and, depending on that value, to jump to some location within the switch statement. The positions you can jump to are marked with "case labels" that take the form: "case constant:". This marks the position the computer jumps to when the expression evaluates to the given constant. As the final case in a switch statement you can, optionally, use the label "default:", which provides a default jump point that is used when the value of the expression is not listed in any case label. A switch statement has the form: switch (integer-expression) case integer-constant-1: statements-1 case integer-constant-2: statements-2. 6 of 9

. // (more cases). case integer-constant-n: statements-n default: // optional default case statements-(n+1) // end of switch statement 3.1 A bit about break The break statements are technically optional. The effect of a break is to make the computer jump to the end of the switch statement. If you leave out the break statement, the computer will just forge ahead after completing one case and will execute the statements associated with the next case label. This is rarely what you want, but it is legal. Note that you can leave out one of the groups of statements entirely (including the break). You then have two case labels in a row, containing two different constants. This just means that the computer will jump to the same place and perform the same action for each of the two constants. Here is an example of a switch statement. This is not a useful example, but it should be easy for you to follow. Note, by the way, that the constants in the case labels don't have to be in any particular order, as long as they are all different: switch (N) // assume N is an integer variable case 1: ("The number is 1."); case 2: case 4: case 8: ("The number is 2, 4, or 8."); ("(That's a power of 2.)"); case 3: case 6: case 9: ("The number is 3, 6, or 9."); ("(That's a multiple of 3.)"); case 5: ("The number is 5."); default: ("The number is 7,"); (" or not in the range 1-9."); 7 of 9

The switch statement is pretty primitive as control structures go, and it's easy to make mistakes when you use it. Java takes all its control structures directly from the older programming languages C and C++. The switch statement is certainly one place where the designers of Java should have introduced some improvements. 4 Conditional Operator The conditional operator (? :) is a ternary operator. The operator selects one of two expressions for evaluation, based on the value of its first operand. In this way, the conditional operator is similar to an if statement. The conditional operator produces a pure value. Conditional expressions group from right to left. Consider the following expression: g?f:e?d:c?b:a It is equivalent to g?f:(e?d:(c?b:a)) The first operand of the conditional operator must be of type boolean, or a compile-time error occurs. If the first operand evaluates to true, the operator evaluates the second operand (i.e., the one following the?) and produces the pure value of that expression. Otherwise, if the first operand evaluates to false, the operator evaluates the third operand (i.e., the one following the :) and produces the pure value of that expression. Note that the conditional operator evaluates either its second operand or its third operand, but not both. The second and third operands of the conditional operator may be of any type, but they must both be of the same kind of type or a compile-time error occurs. If one operand is of an arithmetic type, the other must also be of an arithmetic type. If one operand is of type boolean, the other must also be of type boolean. If one operand is a reference type, the other must also be a reference type. Note that neither the second nor the third operand can be an expression that invokes a void method. The types of the second and third operands determine the type of pure value that the conditional operator produces. If the second and third operands are of different types, the operator may perform a type conversion on the operand that it evaluates. The operator does this to ensure that it always produces the same type of result for a given expression, regardless of the value of its first operand. 8 of 9

If the second and third operands are both of arithmetic types, the conditional operator determines the type of value it produces as follows: If both operands are of the same type, the conditional operator produces a pure value of that type. If one operand is of type short and the other operand is of type byte, the conditional operator produces a short value. If one operand is of type short, char, or byte and the other operand is a constant expression that can be represented as a value of that type, the conditional operator produces a pure value of that type. Otherwise, if either operand is of type double, the operator produces a double value. Otherwise, if either operand is of type float, the operator produces a float value. Otherwise, if either operand is of type long, the operator produces a long value. Otherwise, if either operand is of type int, the operator produces an int value. If the second and third operands are both of type boolean, the conditional operator produces a pure boolean value. If the second and third operands are both reference types, the conditional operator determines the type of value it produces as follows: If both operands are null, the conditional operator produces the pure value null. Otherwise, if exactly one of the operands is null, the conditional operator produces a value of the type of the other operand. Otherwise, it must be possible to cast the value of one of the operands to the type of the other operand, or a compile-time error occurs. The conditional operator produces a value of the type that would be the target of the cast. 9 of 9