Lecture Set 4: More About Methods and More About Operators

Similar documents
Lecture Set 4: More About Methods and More About Operators

Lecture 3 Operators MIT AITI

Prof. Navrati Saxena TA: Rochak Sachan

Object-Oriented Programming

Outline. Performing Computations. Outline (cont) Expressions in C. Some Expression Formats. Types for Operands

Programming with Java

Lecture 2: Variables and Operators. AITI Nigeria Summer 2012 University of Lagos.

Operators and Expressions

Java Primer 1: Types, Classes and Operators

Chapter 3: Operators, Expressions and Type Conversion

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

Basics of Java Programming

Program Fundamentals

Accelerating Information Technology Innovation

Chapter 7. Expressions and Assignment Statements ISBN

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

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

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

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

Expressions & Assignment Statements

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

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

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

Building Java Programs

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

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

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

COMP 110 Introduction to Programming. What did we discuss?

Chapter 7. Expressions and Assignment Statements

Chapter 7. Expressions and Assignment Statements (updated edition 11) ISBN

Exercises Software Development I. 05 Conversions and Promotions; Lifetime, Scope, Shadowing. November 5th, 2014

INDEX. A SIMPLE JAVA PROGRAM Class Declaration The Main Line. The Line Contains Three Keywords The Output Line

3. Java - Language Constructs I

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

The Arithmetic Operators

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

CS111: PROGRAMMING LANGUAGE II

Object-Oriented Programming. Topic 2: Fundamental Programming Structures in Java

9/21/17. Outline. Expression Evaluation and Control Flow. Arithmetic Expressions. Operators. Operators. Notation & Placement

AYBUKE BUYUKCAYLI KORAY OZUYAR MUSTAFA SOYLU. Week 21/02/ /02/2007 Lecture Notes: ASCII

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

JAVA OPERATORS GENERAL

Operators in java Operator operands.

Zheng-Liang Lu Java Programming 45 / 79

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

ECE 122 Engineering Problem Solving with Java

CIS133J. Working with Numbers in Java

Selenium Class 9 - Java Operators

Expressions and Assignment Statements

CS313D: ADVANCED PROGRAMMING LANGUAGE

Operators. Lecture 3 COP 3014 Spring January 16, 2018

Chapter 2: Using Data

Arithmetic Operators. Portability: Printing Numbers

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

LECTURE 3 C++ Basics Part 2

Operators and Expressions:

Unit 2: Java in the small. Prepared by: Dr. Abdallah Mohamed, AOU-KW

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

The Order of Operations. Unit 1 Lesson 3

Full file at

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

More Programming Constructs -- Introduction

Lesson 5: Introduction to the Java Basics: Java Arithmetic THEORY. Arithmetic Operators

Type Conversion. and. Statements

Research Group. 2: More types, Methods, Conditionals

CSC 1214: Object-Oriented Programming

Informatics Ingeniería en Electrónica y Automática Industrial

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands

1.00 Lecture 4. Promotion

4 Programming Fundamentals. Introduction to Programming 1 1

Unit 2: Java in the small

Chapter 2 Primitive Data Types and Operations. Objectives

Building Java Programs

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.

Software II: Principles of Programming Languages. Why Expressions?

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

Lesson 3: Basic Programming Concepts

Declaration and Memory

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

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

DATA TYPES AND EXPRESSIONS

CS 112 Introduction to Programming

Building Java Programs

Chapter 2: Data and Expressions

Values and Variables 1 / 30

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

Chapter 2 Elementary Programming

Example: Tax year 2000

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

Object Oriented Software Design

CMPT 125: Lecture 3 Data and Expressions

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

PROGRAMMING FUNDAMENTALS

Chapter 2. Elementary Programming

Expression Evaluation and Control Flow. Outline

Data Conversion & Scanner Class

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

Visual C# Instructor s Manual Table of Contents

Variables, Types, Operations on Numbers

Chapter 7. Expressions and Assignment Statements ISBN

Transcription:

Lecture Set 4: More About Methods and More About Operators Methods Definitions Invocations More arithmetic operators Operator Side effects Operator Precedence Short-circuiting main method public static void main(string args[]){ // statements here All projects and examples have defined this method No explicit call needed Parts of the line Name = main Parameter List = String args[] Return type = void Access = public -- more on this later Modifier = static Other public static methods A static method is associated with a class not an individual instance (object) Must have all of the same parts as the main public static returntype name(arglist){ body MethodStars.java For example defining a method to print a number of stars public static void printstars(int count){ for (int curr = 0; curr < count; curr=count+1){ System.out.print( * ); For example defining a method to print a number of stars printstars(3); System.out.println(); printstars(77); 1

method information: parameters and arguments parameter list type name for each item in the list e.g. (MyGrid grid, char where) argument list expression for each item in the list e.g. (grid, t ) Matched between the arguments and the parameters based on position in the list PrimesMethods.java Non-main static public methods: defining, invoking and commenting Defined based on a name and a list of parameters public static void name(parameterlist){ body Invoked by stating its name and giving an argument for each element of the parameter list name(argumentlist); Each method must have a well defined purpose That information goes into a comment before the method definition Each parameter s purpose should be explained Return value s purpose should be explained Expressions Java expressions that yield values e.g. x x + 1 - y x == y && z == 0 foo.equals ( cat ) Expressions have values of a specific type (int, boolean, etc.) Expressions can be assigned to variables, appear inside other expressions, etc. 2

Expressions and Side Effects Some expressions can also alter the values of variables e.g. x=1 x=1 is an expression? Yes! Value is result of evaluation right-hand side of = It also alters the value of x Such alterations are called side effects E1OpExpr.java Are the Following Legal? int x, y; x = y = 1; Yes. Result assigns 1 to x and to y int x = 0, y = 1; boolean b = false; if (b = (x <= y)){ x = y; Yes. Result assigns true to b and 1 to x Other Expressions with Side Effects Java includes abbreviations for common forms of assignment Example: increment operations (Basically equivalent to x = x + 1 ++x Pre-increment Increments x, returns the new value of x ( increment x, then return it ) x++ Post-increment Increments x, returns the old value of x ( return x, then increment it ) Same or Different x == x++ x == ++x Compare x++ * y++ ++x * ++y ++x * y++ x++ * ++y always true never true 3

E2PrePostCompare.java Other Assignment Operators Example: decrement operations (Basically equivalent to x = x - 1 --x Pre-decrement Decrements x, returns the new value of x x-- Post-decrement Decrements x, returns the old value of x return x, then decrement it General modification by constant General form: <var> <op with=> <constant> Examples x += 2 equivalent to x = x+2 x -= 2 equivalent to x = x-2 x *= 2 equivalent to x = x*2 x /= 2 equivalent to x = x/2 Precedence Explains how to evaluate expressions What is value of 1 2 + 3 * 4? Precedence rules answer this question Higher-precedence operators evaluated first Example from math: Please, Excuse my Dear Aunt Sally or PEMDAS Multiple and divide (higher precedence) before you add and subtract (lower precedence) Java follows Aunt Sally s Rules but what about other operators? Java Precedence Rules parentheses: ( ) unary ops: +x -x ++x -x x++ x--!x multiply/divide: * / % add/subtract: + - comparisons: < > <= >= equality: ==!= logical and: && logical or: assignments: = += *= /= %= (these are right to left associative) Higher precedence on top 4

Examples x * y + -z Same as (x*y) + (-z) (x <= y && y <= z w > z) Same as ((x <= y) && (y <= z)) (w > z) What is value of 1 2 + 3 * 4? = 1-2 + 3 * 4 = 1-2 + (3 * 4) = (1-2) + 12 = -1 + 12 = 11 Should You Rely on Precedence? No! The only ones people can remember are Please Excuse My Dear Aunt Sally (PEMDAS) And maybe unary and increment/decrement operators Bad: if (2 * x++ < 5 * z + 3 && -w!= x / 2) Better: if ((2 * x++ < 5 * z + 3)) && (-w!= x / 2)) Best: if (((2 * x++) < (5 * z + 3)) && (-w!= (x / 2))) Short-circuiting Example As soon as Java knows an answer it quits evaluating the expression. int x = 0, y = 1; if ((y > 1) && (++x == 0)){ --y; System.out.println (x); => 0 Why? y > 1 is false The result of && will be false, regardless of second expression Java therefore does not evaluate second expression of && This treatment of &&, is called short-circuiting Subexpressions evaluated from left to right Evaluation stops when value of over-all expression is determined 5

Examples int x = 0, y = 1; if ((y >= 1) && (++x == 0)) { --y; System.out.println(x); => 1 int x = 0, y = 1; if ( ((y > 1) && (++x == 0)) ((y == 1) && (x++ == 0)) ) { --y; System.out.println(x); System.out.println(y); 1 0 Examples (cont.) int x = 0, y = 0; while (x++ <= 4){ y += x; System.out.println (y); => 15 Programming with Side-Effects Generally: Side effects in conditions are hard to understand Good programming practice Conditions should be side-effect-free Side effects should be in stand-alone statements Major Goal: Strive to create the most readable and maintainable code. 6

Primitive Types and their Hierarchy double float long int short byte int x = 7.2; double y = 6; Changing to something else Further Up this list is acceptable called Widening Conversion Changing to Something else Further Down this list is not acceptable called Narrowing Conversion Explicit casting needed for when you want to go lower in the list Type Casting - implicit Which of the following are legal? int x = 3.5; Illegal: 3.5 is not an int float x = 3; Legal: 3 is an int, which is also a float long i = 3; Legal: 3 is an int, which is also a long byte x = 155; Illlegal: 155 is to big to be a byte (> 127) double d = 3.14159F; Legal: 3.14159F is a float, which is also a double Mixed Expressions with Explicit Type Casting What is result of float x = 3 / 4; x assigned value 0.0F Why? 3, 4 are ints So integer / operation is used, yielding 0, before upcasting is performed To get floating point result, use explicit casting float x = (float) 3 / (float) 4; Assigns x the value 0.75F Can also do following float x = (float) 3 / 4; Why? (float) 3 returns a value type float (3.0F) 4 is an int In this case, Java compiler uses widening conversion on lower type (here, int) to obtain values in same type before computing operation Or: float x = 3.0f / 4; 7