COMP-202: Foundations of Programming. Lecture 5: More About Methods and Data Types Jackie Cheung, Winter 2016

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

COMP-202: Foundations of Programming. Lecture 6: Conditionals Jackie Cheung, Winter 2016

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

} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2.

COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015

Chapter 2: Data and Expressions

Information Science 1

COMP-202 Unit 2: Java Basics. CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables

Chapter 3: Operators, Expressions and Type Conversion

ENGINEERING 1020 Introduction to Computer Programming M A Y 2 6, R E Z A S H A H I D I

Chapter 2: Data and Expressions

Information Science 1

Zheng-Liang Lu Java Programming 45 / 79

Number Representation & Conversion

Chapter 2: Data and Expressions

Slide 1 Side Effects Duration: 00:00:53 Advance mode: Auto

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

Basics of Java Programming

CMPT 125: Lecture 3 Data and Expressions

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

COMP-202 Unit 2: Java Basics. CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables

CS1150 Principles of Computer Science Boolean, Selection Statements

CS313D: ADVANCED PROGRAMMING LANGUAGE

Two Types of Types. Primitive Types in Java. Using Primitive Variables. Class #07: Java Primitives. Integer types.

CIS 110: Introduction to Computer Programming

Basic Operations jgrasp debugger Writing Programs & Checkstyle

Visual C# Instructor s Manual Table of Contents

Values, Variables, Types & Arithmetic Expressions. Agenda

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Expressions and Casting. Data Manipulation. Simple Program 11/5/2013

Datatypes, Variables, and Operations

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

Primitive Data, Variables, and Expressions; Simple Conditional Execution

Expressions and Casting

1 class Lecture2 { 2 3 "Elementray Programming" / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch.

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Numerical Data. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

COMP-202: Foundations of Programming

COMP-202: Foundations of Programming. Lecture 8: for Loops, Nested Loops and Arrays Jackie Cheung, Winter 2016

Declaration and Memory

Operators. Java operators are classified into three categories:

More Programming Constructs -- Introduction

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

3. Java - Language Constructs I

Lecture Set 4: More About Methods and More About Operators

COMP-202 Unit 2: Java Basics. CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables

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

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #06 Loops: Operators

VARIABLES AND TYPES CITS1001

WEEK 4 OPERATORS, EXPRESSIONS AND STATEMENTS

COMP-202 Unit 2: Java Basics. CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables

Computer Architecture and System Software Lecture 02: Overview of Computer Systems & Start of Chapter 2

CS 251 Intermediate Programming Java Basics

Lesson 02 Data Types and Statements. MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

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

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

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators

SOFTWARE DEVELOPMENT 1. Operators 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

Lecture 3 Operators MIT AITI

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

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

Ex: If you use a program to record sales, you will want to remember data:

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

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

MODULE 02: BASIC COMPUTATION IN JAVA

Object-Oriented Programming

Lesson 02 Data Types and Statements. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

ECE 122 Engineering Problem Solving with Java

COMP-202: Foundations of Programming. Lecture 9: Arrays and Practice Jackie Cheung, Winter 2016

Unit 3. Operators. School of Science and Technology INTRODUCTION

Eng. Mohammed S. Abdualal

Values and Variables 1 / 30

LECTURE 3 C++ Basics Part 2

What we will do today Explain and look at examples of. Programs that examine data. Data types. Topic 4. variables. expressions. assignment statements

Chapter 6 Primitive types

CS Programming I: Primitives and Expressions

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

Operators. Java Primer Operators-1 Scott MacKenzie = 2. (b) (a)

Java Primer 1: Types, Classes and Operators

Chapter 4. Operations on Data

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

COMP-202: Foundations of Programming. Lecture 2: Java basics and our first Java program! Jackie Cheung, Winter 2015

Programming Lecture 3

Full file at

Types and Expressions. Chapter 3

Java enum, casts, and others (Select portions of Chapters 4 & 5)

COMP-202: Foundations of Programming. Lecture 4: Methods Jackie Cheung, Winter 2016

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. A Guide to this Instructor s Manual:

SECTION II: LANGUAGE BASICS

CS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation

EXPRESSIONS AND ASSIGNMENT CITS1001

Lecture Set 4: More About Methods and More About Operators

ISA 563 : Fundamentals of Systems Programming

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

Java Fall 2018 Margaret Reid-Miller

Lecture 3 Tao Wang 1

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

A complement number system is used to represent positive and negative integers. A complement number system is based on a fixed length representation

Operators. Lecture 3 COP 3014 Spring January 16, 2018

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

Transcription:

COMP-202: Foundations of Programming Lecture 5: More About Methods and Data Types Jackie Cheung, Winter 2016

More Tutoring Help The Engineering Peer Tutoring Services (EPTS) is hosting free tutoring sessions for COMP 202 every Tuesday and Thursday from 1:00 pm - 2:30pm in FDA 6. 2

Methods More about methods More about data types This Lecture 3

Review Questions What are the different parts of a method definition? When do we need a return statement? When are we not allowed to have a return statement? 4

How To Write A Method public static double log2ceil(double x) { // compute f(x) = ceil(log2(x)) double result = Math.log(x) / Math.log(2.0); return Math.ceil(result); } Keywords, return type of double Method signature, just like in the API Curly braces to define method body 5

Checking String Equality How do we check if two Strings are equal? Let s check the String library API: https://docs.oracle.com/javase/7/docs/api/java/ lang/string.html 6

No static! Unlike the methods we saw last class, the.equals() method is not static! This means that we have to call it on something of type String. 7

Examples of String Comparison "Abc".equals("Abc") "Abc".equals("A") "ABC".equals("Abc") Can also compare String variables String myname = "Jackie"; String yourname = "Bob"; System.out.println(myName.equals(myName)); System.out.println(myName.equals(yourName)); 8

Return Type Boolean Many of the methods dealing with Strings return a value of type boolean. equals(object anobject) startswith(string prefix) isempty() contains(charsequence s) compareto(string anotherstring) 9

True/False Expressions The year is 2015. There are 15 months in a year. true false September is the ninth month and it is two months before February. false COMP-202 is awesome.??? The Java data type boolean represents this type of data. 10

Boolean Expressions Boolean expressions evaluate to either true or false. mynumber > 0 // can be either true or false You can assign the result of a boolean expression to a variable of type boolean: boolean positive; positive = (mynumber > 0); 11

Boolean Expressions in Java A boolean expression is one of the following: Comparison of two values using a comparison operator like < true or false (Java's boolean literals these are keywords) A variable which has type boolean The result of a logical operator over other boolean variables 12

Comparison Operators The result of a comparison is always true or false. Used to compare numeric or character values (remember ASCII?) == : equal to!= : not equal to < : less than > : greater than <= : less than or equal to >= : greater than or equal to 13

Examples int x = 5; x < 6 x <= 5 x > 5 x >= 3 x == 5 x!= 5 true true false true true false 14

Careful! Terrible things might happen if you mistype == as = or vice versa. boolean halfway; // assignment operation halfway = (classnum >= 13); // evaluation of a boolean expression halfway == (classnum >= 13); 15

Logical Operators These take boolean expressions as input, and produce a result of type boolean.! Logical NOT Logical OR && Logical AND They can take either one input (unary), as in NOT, or two inputs (binary), as in OR and AND. 16

! Operator The NOT operator flips the truth value of the boolean expression that follows. For an input boolean expression X: X!X true false false true 17

! Operator Examples!(2 < 3)!(3 < 2)!true!false!(!(3>2))!(September comes after August)!(Earth is the 6 th planet from the sun) 18

&& Operator The AND operator is true if both of the input boolean expressions evaluate to true. For input boolean expressions X and Y: X Y X&&Y true true true true false false false true false false false false 19

&& Operator Examples (1 < 2) && (2 < 3) (1 < 1) && (2 < 3) (!(1 < 1)) && (2 < 3) (Television starts with a T) && (Java can also be coffee) (true && false) 20

Operator The OR operator is true if at least one of the input boolean expressions evaluate to true. For input boolean expressions X and Y: X Y X Y true true true true false true false true true false false false 21

Operator Examples (1 < 1) (2 < 3)!((3 < 4) (100 > 1000)) ((Vegetables are healthy) (Fruit is healthy)) (true false) 22

Short-Circuit Evaluation The evaluation of && and stops as soon as you know the end result: If the left operand of && is false, the whole thing is false, so the second is never looked at. (p1 && p2) if p1 is false, p2 is never looked at. If the left operand of is true, the whole thing is true, so the second is never looked at. (p1 p2) if p1 is true, p2 is never looked at. This seems like a minor detail, but is important. 23

How This Is Useful Use the first part to check to make sure the second part can actually be run ((x!= 0) && ((1 / x) < 5)) This ensures the we'll never get a runtime error due to trying to divide by zero. 24

Exercise Write a method that takes three Strings: word, prefix, and suffix. The method returns true if word starts with prefix and ends with suffix. Otherwise, it returns false. 25

Beware integer division MATHEMATICAL OPERATORS 26

Expressions Recall how to assign values to variables: <var_name> = <expression>; The expression on the RHS is evaluated, and the resulting value is what is assigned to the variable. int x; x = 3 + 4 * 5; // the expression is 3 + 4 * 5 // the value of x here is 23 27

Mathematical Operators Some operators: Addition (+) Subtraction (-) Multiplication (*) Division (/) Remainder (a.k.a., modulo) (%) How these operators actually function depends on the data type of the operands. 28

int + int 3 + 4 7 (int) + Operator int + double (or double + int) 3 + 4.0 7.0 (double) Also defined for: String + String "3" + "4" "34" (String) String + primitive data type (or p.d.t. + String) 3 + "4" "34" (String) 29

-, *, % Operators Subtraction (e.g., 3-4) and multiplication work as you would expect. Like for +, if you mix ints and doubles, you get a double. % is the remainder (or mod) operator 10 % 3 1 4.6 % 2 0.6 But not defined for as many data types String * String ERROR 30

Division Watch out for division! 31

Integer Division If both operands to the division operator are int, the result is also an int (with the fractional part discarded) 11 / 3 3-11 / 3-3 Division by 0 with integers causes a runtime error. Not detected at compile time! 1 / 0 CRASH 32

Tricky Question int x; x = (1 / 2) + (1 / 2); What is x at this point? Hint: Think like a machine. Don't think like you're in math class. How is this expression actually evaluated? 33

double x; x = 1 / 2; What is x? Tricky Question 2 Why is it like this? Work through it step by step. 34

Order of Operations Mostly as in math: 1. Parenthesis 2. *, /, % from left to right 3. +, -, from left to right Assignment happens after the evaluation of the expression. 35

Example What does this evaluate to? "5 plus 3 is " + 5 + 3 What about this? "5 plus 3 is " + (5 + 3) 36

Conversions Two different types Widening conversions convert to a type that is more expressive no information lost e.g., int to double, or byte to int Narrowing conversions convert to a type that is less expressive information loss possible e.g., double to int, or int to byte 37

Mixed Expressions As we have seen, Java will try to widen a narrower data type to make the operation work. 3 + 4.0 7.0 int double double But this still doesn't work: int x = 3.5 * 2; 38

Casting You can force a conversion to the type you want, even if you lose information! This is called type casting or just casting. Write (data_type) before the expression to convert. int x = (int) 7.5; int y = (int) -7.5; 39

Casting is Temporary Just as double x = 3.5; double y = -x; does not change x, neither does double x = 3.5; int y = (int) x; x is still a double. 40

Revised Order of Operations Note where casting happens 1. Parenthesis 2. Casting 3. *, /, % from left to right 4. +, -, from left to right Assignment happens after the evaluation of the expression. 41

Exercises What are the types and values of the following expressions? 1.0 / 2 4 / 3 + 4.0 / 3 (double) 1 / 2 (double) (1 / 2) (float) 3.5 Tricky/weird cases: (byte) 128 (byte) 129 42

Negative Integers in Binary (This slide and the next one are extra material; not examinable.) Java uses a method called two's complement 1111 1111-1 1111 1110-2 1111 1101-3 1000 0000-128 In general, flip all the bits, then add 1 to get the positive counterpart. Note: everything that starts with a 1 is negative 43

Why Does (byte) 128 Equal -128? 128 as an int 00000000 00000000 00000000 10000000 Casting it into a byte truncates the first 24 bits. 00000000 00000000 00000000 10000000 This represents -128 44

+=, ++ Programmers got lazy about writing x = x + 5; So, as a shortcut, you can write x += 5; Then they got even lazier about writing x += 1; So, as a short, you can write x++; 45

Similarly: -=, *=, /=, -- x -= 5; is the same as x = x - 5; And likewise for *=, /=. Also, x--; is the same as x -= 1; or x = x - 1; 46

++, -- You can put ++ or -- before or after a variable name, and even as part of a complex expression. After: happens after the statement is executed Before: happens before the statement is executed int x = 5, y = 5; System.out.println(x++); System.out.println(++y); 47

Recommendation Only use ++ or -- by themselves, and do not put them inside other expressions. int x = 5; int y = 2 * x++ + 4; // legal, but why? 48

Constants A constant is an identifier like a variable, except that it holds one value for its entire existence. In Java, use the final keyword to declare a constant. final double PI = 3.1415; final double E = 2.71828; If you try to modify a constant CRASH! 49

Exercise Write a method, isodd, that takes one int as input, and returns true if and only if that int is odd. Write a method, areallodd, that takes three ints as inputs, and returns true if and only if all of them are odd. 50

Challenge Question Using only type casting, multiplication and division, write some code that will take a double, and then truncate it to one decimal place. e.g., 32.756 32.7 5.0 5.0 Hint: What kind of type casting have we seen in this lecture that similarly truncates part of a double? How can we exploit this for our benefit? 51