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

Similar documents
Chapter. Let's explore some other fundamental programming concepts

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

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

ECE 122 Engineering Problem Solving with Java

2: Basics of Java Programming

A variable is a name for a location in memory A variable must be declared

Chapter 2: Data and Expressions

Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections

Chapter 2: Data and Expressions

CMPT 125: Lecture 3 Data and Expressions

Chapter 2: Data and Expressions

Data Conversion & Scanner Class

COMP 202 Java in one week

More Programming Constructs -- Introduction

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

COMP 202. Java in one week

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

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

CS313D: ADVANCED PROGRAMMING LANGUAGE

Declaration and Memory

For the course, we will be using JCreator as the IDE (Integrated Development Environment).

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

CS111: PROGRAMMING LANGUAGE II

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

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Lecture 3: Variables and assignment

Learning objectives: Objects and Primitive Data. Introduction to Objects. A Predefined Object. The print versus the println Methods

Program Elements -- Introduction

Chapter 2. Elementary Programming

Program Fundamentals

Chapter 2 Elementary Programming

Programming with Java

Full file at

Basics of Java Programming

Programming for Engineers Iteration

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

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

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

Chapter 2 ELEMENTARY PROGRAMMING

Lecture Set 2: Starting Java

COMP-202 Unit 2: Programming Basics. CONTENTS: The Java Programming Language Variables and Types Basic Input / Output Expressions Conversions

Lecture Set 2: Starting Java

Operators in java Operator operands.

CEN 414 Java Programming

Programming Language 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

objectives chapter Define the difference between primitive data and objects. Declare and use variables. Perform mathematical computations.

3. Java - Language Constructs I

Primitive Data Types: Intro

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

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

Basic Operations jgrasp debugger Writing Programs & Checkstyle

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

AP Computer Science A

COMP 110 Introduction to Programming. What did we discuss?

B.V. Patel Institute of BMC & IT, UTU 2014

Chapter 3: Operators, Expressions and Type Conversion

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

JAVA OPERATORS GENERAL

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

Chapter 3. Selections

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

CS 112 Introduction to Programming

Zheng-Liang Lu Java Programming 45 / 79

Mr. Monroe s Guide to Mastering Java Syntax

Chapter 6 Primitive types

Chapter 2 Primitive Data Types and Operations. Objectives

Introduction to Java (All the Basic Stuff)

Lecture Set 4: More About Methods and More About Operators

Lecture Set 4: More About Methods and More About Operators

Java Notes. 10th ICSE. Saravanan Ganesh

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Getting started with Java

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

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

Conditional Programming

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

Sir Muhammad Naveed. Arslan Ahmed Shaad ( ) Muhammad Bilal ( )

Course Outline. Introduction to java

CMSC131. Introduction to your Introduction to Java. Why Java?

CMPT 125: Lecture 4 Conditionals and Loops

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

Visual C# Instructor s Manual Table of Contents

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

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

Lecture 3. More About C

Variables, Constants, and Data Types

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Computational Expression

What did we talk about last time? Examples switch statements

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

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

Operators and Expressions

SECTION II: LANGUAGE BASICS

A variable is a name that represents a value. For

Chapter 1 Introduction to java

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

Primitive Data, Variables, and Expressions; Simple Conditional Execution

Object-Oriented Programming

1007 Imperative Programming Part II

Transcription:

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

Programming Language Levels There are many programming language levels: machine language assembly language high-level language Java, C, C++, Fortran 011001011 110111100 Add r1,5 Mov r1,r2 Each type of CPU (Sparc processor, Intel processor, ) has its own specific machine language. These are the simple built-in instructions the CPU comes pre-designed with. The other levels were created to make it easier for a human to write programs 202 Data and Expressions 2

Programming Languages A program must be translated into machine language before it can be executed on a particular type of CPU This can be accomplished in several ways A compiler is a software tool which translates source code into a specific target language. Often, that target language is the machine language for a particular CPU type. Input: files written in a high-level programming language Output: executable binary file that can be processed by CPU need compilers for each CPU type Interpreter: no output executable file Instead the source code is translated and executed on-the-fly. The Java approach is somewhat different 202 Data and Expressions 3

Java Translation and Execution The Java compiler translates Java source code into a special representation called bytecode Java bytecode is not the machine language for any traditional CPU Another software tool, called an interpreter, translates bytecode into machine language and executes it Therefore the Java compiler is not tied to any particular machine Java is considered to be architecture-neutral 202 Data and Expressions 4

Java Translation and Execution Java source code Java compiler.java Java interpreter Java bytecode Bytecode compiler Machine code.class 202 Data and Expressions 5

More on System.out Two built-in commands to print on the screen: System.out.println(.stuff to print out.); A line-break is printed after.stuff to print out System.out.print(.stuff to print out.); Only.stuff to print out. is printed Syntax: System.out.println(EXPRESSION); Where: EXPRESSION = anything between quotes EXPRESSION = variable EXPRESSION = anything + variable EXPRESSION = anything + variable + something more Example: System.out.print( x = + x); 202 Data and Expressions 6

Countdown.java class Countdown { public static void main(string args[]) { System.out.print( Three ); System.out.print( Two ); System.out.print( One ); System.out.print( Zero ); } } System.out.println( Liftoff! ); System.out.println( Houston, we have a problem! ); What does this output? 202 Data and Expressions 7

Countdown Result Three Two One Zero Liftoff! Houston, we have a problem! Cursor ends up here 202 Data and Expressions 8

Variables MODIFIER TYPE IDENTIFIER = VALUE; Where: MODIFIER final, static (optional) TYPE int, char, double, (mandatory) IDENTIFIER a single word as defined previously (mandatory) = VALUE a constant matching the TYPE (optional) ; (mandatory) This is a partial definition 202 Data and Expressions 9

Primitive Data There are exactly 8 primitive data types in Java Four of them represent integers: byte, short, int, long Two of them represent floating point numbers: float, double One of them represents characters: char And one of them represents boolean values: boolean 202 Data and Expressions 10

Numeric Primitive Data The difference between the various numeric primitive types is their size and type, and therefore the values they can store: Type byte short int long float double Storage 8 bits 16 bits 32 bits 64 bits 32 bits 64 bits Min Value -128-32,768-2,147,483,648 < -9 x 10 18 Max Value 127 32,767 2,147,483,647 > 9 x 10 18 +/- 3.4 x 10 38 with 7 significant digits +/- 1.7 x 10 308 with 15 significant digits 202 Data and Expressions 11

Characters A char variable stores a single character from the Unicode character set char gender; gender = F ; A character set is an ordered list of characters, and each character corresponds to a unique number The Unicode character set uses 16 bits (2 Bytes) per character, allowing for 65,536 unique characters It is an international character set, containing symbols and characters from many world languages Character literals are delimited by single quotes: 'a' 'X' '7' '$' ',' '\n' 202 Data and Expressions 12

Characters The ASCII character set is older and smaller than Unicode, but is still quite popular The ASCII characters are a subset of the Unicode character set, including: uppercase letters lowercase letters punctuation digits special symbols control characters A, B, C, a, b, c, period, semi-colon, 0, 1, 2, &,, \, carriage return, tab,... 202 Data and Expressions 13

Boolean A boolean value represents a true or false condition A boolean can also be used to represent any two states, such as a light bulb being on or off The reserved words true and false are the only valid values for a boolean type boolean done = false; done = true; 202 Data and Expressions 14

More on Boolean Expression evaluates to either true or false if (denominator == 0) System.out.println(.. Boolean variable can be used where a boolean expression is expected if (done) System.out.println( you are done ); if (!done) System.out.println( not yet done ); The! negates the value of a boolean expression if a boolean expression e is true, then!e is false if a boolean expression e is false, then!e is true 202 Data and Expressions 15

Adding an arbitrary amount of numbers import java.util.scanner; public class AddArbitraryAlternative { public static void main (String [] args) { double input; double output = 0; boolean done = false; } } Scanner scan = new Scanner(System.in); // read in the values in a loop and incrementally perform calculation while (!done) { System.out.println("Enter number (0 indicates you want to exit):"); input = scan.nextdouble(); if (input == 0) done = true; else output = output + input; } System.out.println("The sum is: " + output); 202 Data and Expressions 16

Arithmetic Expressions An expression is a combination of operators and operands Arithmetic expressions compute numeric results and make use of the arithmetic operators: Addition + Subtraction - Multiplication * Division / Remainder % If either or both operands to an arithmetic operator are floating point, the result is floating point 202 Data and Expressions 17

Operator Precedence Operators can be combined into complex expressions result = total + count / max - offset; Operators have a well-defined precedence which determines the order in which they are evaluated Multiplication, division, and remainder are evaluated prior to addition, subtraction, and string concatenation Arithmetic operators with the same precedence are evaluated from left to right Parentheses can always be used to force the evaluation order 202 Data and Expressions 18

Operator Precedence What is the order of evaluation in the following expressions? a + b + c + d + e a + b * c - d / e 1 2 3 4 a / (b + c) - d % e 2 1 4 3 a / (b * (c + (d - e))) 4 3 2 1 3 1 4 2 202 Data and Expressions 19

Assignment Revisited The assignment operator has a lower precedence than the arithmetic operators First the expression on the right hand side of the = operator is evaluated answer = sum / 4 + MAX * lowest; 4 1 3 2 Then the result is stored in the variable on the left hand side 202 Data and Expressions 20

Assignment Revisited The right and left hand sides of an assignment statement can contain the same variable First, one is added to the original value of count count = count + 1; Then the result is stored back into count (overwriting the original value) 202 Data and Expressions 21

TempConvert.java class TempConvert { public static void main (String args[]) { final int BASE = 32; final double CONVERSION_FACTOR = 9.0 / 5.0; double fahrenheittemp; int celsiustemp; } } Scanner scan = new Scanner(System.in); celsiustemp = scan.nextint(); farenheittemp = celsiustemp * CONVERSION_FACTOR + BASE; System.out.println(Celsius Temp = + celsiustemp); System.out.println(Farenheit Temp = + FarenheitTemp); 202 Data and Expressions 22

Syntactic Sugar: Increment/Decrement increment operator unary operator: adds one to its only operand counter++; ++counter; prefix and postfix forms differ when used in larger expression equivalent to counter = counter + 1; total = counter++; assign value of counter to total and then increment value of counter total = ++counter; increment value of counter and then assign the new value of counter to total decrement operator subtracts one from operand counter--; 202 Data and Expressions 23

Example import java.util.scanner; public class AddArbitrary { public static void main (String [] args) { double input; int iterations; double output = 0; int counter; } } Scanner scan = new Scanner(System.in); System.out.println( Indicate the amount of number:"); iterations = scan.nextint(); // read in the values in a loop and incrementally perform calculation counter = 1; while (counter++ <= iterations) { // counter = counter + 1; // counter++; System.out.println("Enter number:"); input = scan.nextdouble(); output = output + input; } System.out.println("The sum is: " + output); What are the advantages/disadvantages of the different choices? 202 Data and Expressions 24

Syntactic Sugar: Assignment Operators Assignment and arithmetic operations Example 1: total = total + 5; total += 5; Example 2 result = result * (count1 + count2); result *= count1 + count2 Evaluate the entire expression on the right-hand side first, then use the result as the right operand of the other operation 202 Data and Expressions 25

Assignment Operators There are many assignment operators, including the following: Operator += -= *= /= %= Example x += y x -= y x *= y x /= y x %= y Equivalent To x = x + y x = x - y x = x * y x = x / y x = x % y 202 Data and Expressions 26

Example import java.util.scanner; public class AddArbitrary { public static void main (String [] args) { double input; int iterations; double output = 0; int counter; } } Scanner scan = new Scanner(System.in); System.out.println( Indicate the amount of number:"); iterations = scan.nextint(); // read in the values in a loop and incrementally perform calculation counter = 1; while (counter <= iterations) { System.out.println("Enter number:"); input = scan.nextdouble(); output += input; counter++; } System.out.println("The sum is: " + output); 202 Data and Expressions 27

Data Conversion Sometimes it is convenient to convert data from one type to another For example, we may want to treat an integer as a floating point value during a computation Conversions must be handled carefully to avoid losing information Widening conversions usually go from a data type with X Bytes to a data type with X or Y>X Bytes usually no information lost Narrowing conversions usually go from a data type with X Bytes to a data type with Y < X Bytes can lose information (e.g. when converting from int to a short) 202 Data and Expressions 28

Assignment Conversion In Java, data conversions can occur in three ways: assignment conversion arithmetic promotion casting Assignment conversion occurs when a value of one type is assigned to a variable of another Only widening conversions can happen via assignment Recall: the value of a variable of type int can be assigned to a variable of type double //money is double, dollars is int money = dollars; If dollars has value 25, then money has value 25.0 after assignment If we attempt a narrowing conversion (assign the value of a variable of type double to a variable of type int), the compiler issues an error message 202 Data and Expressions 29

Arithmetic Promotion Arithmetic promotion happens automatically when operators in expressions convert their operands //mpg is a double, gallons is a float, miles is an int mpg = miles / gallons; 4) assign result to mpg 3) auto convert to double 1) auto convert to float 2) divide 202 Data and Expressions 30

Casting Most general, but trusts that you to understand the effect Both widening and narrowing conversions can be accomplished by explicitly casting a value To cast, the type is put in parentheses in front of the value being converted floating point to integer cast truncates fractional part //money is double, dollars is int dollars = (int) money; If money has value 25.8, then dollars has value 25 after assignment cast does not change the value of the casted variable money still has 25.8 after the assignment 202 Data and Expressions 31

Casting total and count are integers, result is a float result = total / count; Integer division and assignment conversion e.g., if total is 10 and count is 4, then result is assigned 2.0 result = (float) total / count; cast returns floating point version of value of total arithmetic conversion now treats count as floating point division is floating point division e.g., if total is 10 and count is 4, then result is assigned 2.5 note 1: cast has higher precedence than /, thus cast operates on value of total, not on the result of division note 2: cast does not change the value in total for the rest of the program. 202 Data and Expressions 32

Conversion Examples EXPRESSION double x = 5.9; int y = (int) x; int a = 5; float b = 7.3; double c = 10.03; c = b + a; int a = 2, b = 5; double c = 22; c = a / b; RESULT y has 5 c has 12.3 c has 0 202 Data and Expressions 33