Logical Operators and switch

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

Mr. Monroe s Guide to Mastering Java Syntax

Flow Control. CSC215 Lecture

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

STUDENT LESSON A12 Iterations

Flow of Control. Branching Loops exit(n) method Boolean data type and expressions

CS1004: Intro to CS in Java, Spring 2005

Operators. Java operators are classified into three categories:

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

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

2.2 Order of Operations

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Chapter 3. Flow of Control. Branching Loops exit(n) method Boolean data type and expressions

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

In Delphi script, when values are assigned to variables, the colon-equal operator is used; :=

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

Topics. Chapter 5. Equality Operators

Introduction to Java & Fundamental Data Types

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

More Programming Constructs -- Introduction

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

CS 106 Introduction to Computer Science I

Program Development. Java Program Statements. Design. Requirements. Testing. Implementation

ECE 122 Engineering Problem Solving with Java

Conditionals and Loops

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

CS313D: ADVANCED PROGRAMMING LANGUAGE

Lecture Set 4: More About Methods and More About Operators

ARG! Language Reference Manual

1 Lexical Considerations

Comparing Data. Comparing Floating Point Values. Comparing Float Values. CS257 Computer Science I Kevin Sahr, PhD

Case by Case. Chapter 3

CIS 110: Introduction to Computer Programming

CMPT 125: Lecture 3 Data and Expressions

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

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

Maltepe University Computer Engineering Department. Algorithms and Programming. Chapter 4: Conditionals - If statement - Switch statement

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Chapter 4: Control structures. Repetition

The following expression causes a divide by zero error:

Lecture 3 Tao Wang 1

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

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

Contents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual

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

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

Decision Structures. Lecture 3 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

Simple Java Programming Constructs 4

WEEK 4 OPERATORS, EXPRESSIONS AND STATEMENTS

SAMPLE QUESTIONS FOR DIPLOMA IN INFORMATION TECHNOLOGY; YEAR 1

Chapter 4: Control structures

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

Lexical Considerations

Program Elements -- Introduction

Chapter 2.4: Common facilities of procedural languages

Programming with Java

Lecture Set 4: More About Methods and More About Operators

Program Fundamentals

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

Object Oriented Programming with Java

Chapter 3: Operators, Expressions and Type Conversion

Java Coding 2. Decisions, decisions!

Midterms Save the Dates!

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Logic & program control part 2: Simple selection structures

Introduction to C Programming

Darrell Bethea May 25, 2011

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

Lesson 3: Basic Programming Concepts

Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent

Chapter 3. Selections

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

CS112 Lecture: Working with Numbers

Chapter 4: Expressions. Chapter 4. Expressions. Copyright 2008 W. W. Norton & Company. All rights reserved.

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

CT 229 Java Syntax Continued

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

Conditional Programming

Introduction to Programming using C++

Add Subtract Multiply Divide

Introduction to Programming Using Java (98-388)

Full file at C How to Program, 6/e Multiple Choice Test Bank

1.00 Lecture 4. Promotion

5. Selection: If and Switch Controls

CS61B Lecture #2. Public Service Announcements:

Lexical Considerations

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

Variables and literals

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.

CSC 1214: Object-Oriented Programming

Learning the Language - V

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

CSCI 131, Midterm Exam 1 Review Questions This sheet is intended to help you prepare for the first exam in this course. The following topics have

Full file at

Course Outline. Introduction to java

CS 106 Introduction to Computer Science I

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

Decision Structures. Lesson 03 MIT 11053, Fundamentals of Programming

Transcription:

Lecture 5 Relational and Equivalence Operators SYS-1S22 / MTH-1A66 Logical Operators and switch Stuart Gibson sg@sys.uea.ac.uk S01.09A 1 Relational Operator Meaning < Less than > Greater than <= Less than or equal to >= Greater than or equal to Equivalence Operator Meaning == equal to!= not equal to A variable may be tested against a constant or another variable. 2 Examples of Simple Logical Expressions final int b=21; final char no = n ; int a = 20; int c = 20; char choice = y ; Expression Value a < b a == c c > b choice == no c!= a (Incorrect in Lecture 4 ) In the last lecture we saw how these logical expressions are evaluated at run time as either or. 3 Evaluation of logical expressions int a=10, b=20, c=5; if( a < b ) 10 < 20 if ( a > c ) 10 > 5 System.out.println( Second if ); System.out.println( End of first if ); else System.out.println( In else ); System.out.println( After ); Second if End of first if After Flow of program execution. 4

Evaluation of logical expressions int a=10, b=20, c=25; if( a < b ) 10 < 20 if ( a > c ) 10 > 25 System.out.println( Second if ); System.out.println( End of first if ); else System.out.println( In else ); System.out.println( After ); Evaluation of logical expressions int a=25, b=20, c=25; if( a < b ) if ( a > c ) System.out.println( Second if ); System.out.println( End of first if ); else System.out.println( In else ); System.out.println( After ); 25 < 20 Does NOT get evaluated as the first if statement. End of first if After Flow of program execution. 5 In else After Flow of program execution. 6 Logical Operators The AND Operator ( && ) The logical operators AND, OR and NOT can be used in Java to form more complex logical expressions by combining simple logical expressions. Example: if ( x >= 0 && x <= 10) System.out.print( x in range 0 to 10 ); && AND Two Arguments An AND expression evaluates as only if BOTH arguments are.! OR NOT Two Arguments One Argument 7 Truth Table: Argument 1 Argument 2 Argument 1 && Argument 2 8

The AND Operator ( && ) - Examples The OR Operator ( ) int x = 10, y = 11, z = -3; if (x > z && x > y) (10 > -3 && 10 > 11) ( && ) if (z < x && y > x) (-3 < 10 && 11 > 10) ( && ) if (z > x && x > y) (-3 > 10 && 10 > 11) ( && ) 9 Example: if ( x < 0 x > 100) System.out.print( x is invalid ); An OR expression evaluates as if EITHER arguments are evaluated as. Truth Table: Argument 1 Argument 2 Argument 1 Argument 2 10 The OR Operator ( ) - Examples int x = 10, y = 11, z = -3; if( x > z x > y ) (10 > -3 10 > 11) ( ) if( z < x y > x ) (-3 < 10 11 > 10) ( ) if( z > x x > y ) (-3 > 10 10 > 11) ( ) 11 Evaluation of && and Operator The computer is quite clever, so when evaluating && and operators in some cases it only evaluates the first argument. For example: int a = 0; if (a > 0 && b / a > 1) In an AND (&&) statement, if the first argument is, then whatever the second argument is, doesn t matter! This is because according to the truth table, any combination starting with. In an OR ( ) statement, if the first argument, then whatever the second argument is, doesn t matter! This is because and combination starting with, evaluates to. 12

Example: The NOT Operator (! ) if (! ( x == y ) ) System.out.print( x is not equal to y ); System.out.print( easier to use x!=y in ); System.out.print( this case. ); The NOT Operator (! ) - Examples int x = 10, y = 11, z = -3; if(!( x > z ))!(10 > -3)!() A NOT expression is when its argument is. if(!( z > y )) Truth Table: Argument! Argument!(-3 > 11)!() 13 14 Compound Logical Expressions Compound Logical Expressions We can build more complex expressions containing more than one logical operator. int x = 1, y = 2, z =3; ( x == 1 y == 2 ) && z == 4 int x = 1, y = 2, z =3; x == 1 y == 2 && z == 4 Now the expression in the parentheses is evaluated first: Unless parentheses (brackets) are used AND is always evaluated before OR so: x == 1 y == 2 && z == 4 x == 1 && x == 1 ( x == 1 y == 2 ) && z == 4 ( ) && z == 4 && z == 4 && However the expression to evaluate can be even more complicated such as: if (!( x > y && y < z) && z > 0 (y>=12)) But we could rewrite it using parentheses as: 15 16

Compound Logical Expressions if (!( x > y && y < z) && z > 0 (y>=12)) Q: How does the computer know what to evaluate first? A: Precedence! Brackets have the highest precedence. Always solve the deepest nested set first (L:N where N is the level of nesting): if ((x >5 && (y < z y > 3)) && (a > 3)) L:1 L:2 L:3 L:3 L:2 L:2 L:2 L:1 So, solve level 3 (deepest nested) first, then level2, note ties Operator! + - * / % + - < <= >= > ==!= && = Precedence Table Description Logical not, unary plus and minus Multiplication, division and mod Addition and subtraction Relational operators Equivalence operators Logical AND Logical OR Assignment on the same level are solved left to right and finally level 1. 17 18 Highest Lowest More Logical Expressions Logical expression can involve arithmetic operators: if ((x = y + 5) > 10 && (z = z + y) == 4)) System.out.print( Some condition met ); But it is much better to write: x = y + 5; z = z + y; if (x > 10 && z == 4) System.out.print( Some condition met ) Character Comparisons You can compare characters as well: Expression Value A < B A < a? > @ Q: Where does those values come from? A: The computer converts the characters to numbers and then compares those numbers. The numbers come from the ASCII / UNICODE values: A = 65, B = 66, a = 97,? = 63, @ = 64. 19 20

Control Structures In the last lecture we saw that there were three main types of Control Structures: Selection Sequence Selection Repetition So far we have seen the following Java control sequences: One Alternative: Two Alternatives: More than two Alternatives: if statement if else statement nested if else statements Selection: switch switch statements can be used to chose between one of several alternatives. The alternatives are dependant on the value of a selector The selector must be an expression that an integer (int), character (char), or boolean. Note that with boolean selector you can only have two choices, or, like a two alternative, if else statement. 21 22 switch( selector ) case label 1 : statements 1 ; case label 2 : statements 2 ;.. case label n : statements n ; switch statement switch statement switch statements provide an alternative syntax to multiple if statements. Consider the following nested if: char stafftype; if( stafftype == A ) System.out.print( Academic Staff ); else if( stafftype == U ) System.out.print( Undergraduate Student ); else if( stafftype == P ) System.out.print( Postgraduate Student ); else if( stafftype == T ) System.out.print( Technical Staff ); else System.out.print( Unknown Staff Type ); default: statements d ; 23 24

switch statement Execution of a switch statement char stafftype; The selector expression is evaluated and compared to each switch (stafftype) case label in turn, for example: case A : stafftype = P ; System.out.print( Academic Staff ); case A : stafftype == A P == A stafftype == U P == U System.out.print( Undergraduate Student ); case P : stafftype == P P == P case P : System.out.print( Postgraduate Student ); If the selector is equal to the condition of one of the case labels, then the statements associated to this case are case T : System.out.print( Technical Staff ); executed, so in our example the output would be: Postgraduate Student System.out.print( Unknown Staff Type ); 25 26 switch the use of break All statements after the matched case label are executed until a break statement is reached. The purpose of the break statement is to break out of the current control structure, in this case the switch statement. In our example where stafftype = P ; the program executes the one line of code associated with the case P : and then breaks out of the switch. Program execution continues at the next statement after the last curly brace of the switch statement. 27 char stafftype; stafftype = P ; switch (stafftype) case A : switch with break System.out.print( Academic Staff ); System.out.print( Undergraduate Student ); case P : System.out.print( Postgraduate Student ); case T : System.out.print( Technical Staff ); System.out.print( Unknown Staff Type ); System.out.println( After Switch ); At the break execution jumps to after the switch Postgraduate Student After Switch Flow of execution 28

Without break statements execution continues through the switch switch missing break char stafftype; stafftype = P ; switch (stafftype) case A : Postgraduate Student Technical Staff Unknown Staff Type After Switch System.out.print( Academic Staff ); System.out.print( Undergraduate Student ); case P : System.out.print( Postgraduate Student ); case T : System.out.print( Technical Staff ); System.out.print( Unknown Staff Type ); System.out.println( After Switch ); switch default case In our example what would happen if stafftype was Z? stafftype = Z ; case A : stafftype == A P == A stafftype == U P == U case P : stafftype == P P == P case T : stafftype == P P == P Unknown Staff Type If none of the case labels are matched, the statements associated with the default case are executed. Flow of execution 29 A default case is optional in a switch statement. 30 switch definition errors switch with integers (int) Each case label is a single, constant value and each label must be different. System.out.print( Undergraduate Student ); System.out.print( Postgraduate Student ); Gives the following error: HelloWorld.java:15: duplicate case label case 'U': ^ 1 error 31 int numwheels; switch (numwheels) case 1: System.out.print( Unicycle ); case 2: System.out.print( Bike ); case 3: System.out.print( Trike ); case 4: System.out.print( Stabilisers ); System.out.print( Weird Bike! ); 32

Multiple cases You can have multiple cases associated with a single set of statements: int employeecode = 3; switch (employeecode) case 0: case 1: salary = salarylevel_1; case 2: case 3: case 4: salary = salarylevel_2; case 5: salary = managerlevel; System.out.print( Unknown Employee Code ); Multiple cases NO range! For example trying to specify a range would give you an error: int employeecode = 3; switch (employeecode) case employeecode <=1: HelloWorld.java:9: incompatible types found : boolean required: int case employeecode <=1: ^ 1 error However each case has to be specified individually in a list as you can not specify a range of values. 33 34 switch case sensitive Remember Java is case sensitive! If your switch selector is a character, you need to deal with both upper and lower case letters, for example: case u : System.out.print( Undergraduate Student ); A more advanced solution would be to convert the selector to uppercase or lowercase before entering the switch statement, more later 35