CMPT 125: Lecture 3 Data and Expressions

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

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

ECE 122 Engineering Problem Solving with Java

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

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

Chapter 2: Data and Expressions

Chapter. Let's explore some other fundamental programming concepts

Chapter 2: Data and Expressions

Chapter 2: Data and Expressions

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

Basics of Java Programming

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Full file at

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

Program Fundamentals

Declaration and Memory

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

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

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

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

Primitive Data Types: Intro

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Data Conversion & Scanner Class

Chapter 2 Elementary Programming

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

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

Full file at

Getting started with Java

Visual C# Instructor s Manual Table of Contents

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

3. Java - Language Constructs I

Program Elements -- Introduction

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

A Java program contains at least one class definition.

2: Basics of Java Programming

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

Operators and Expressions

More Programming Constructs -- Introduction

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

Chapter 2 Primitive Data Types and Operations. Objectives

JAVA Programming Fundamentals

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

JAVA OPERATORS GENERAL

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

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

Zheng-Liang Lu Java Programming 45 / 79

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

4 Programming Fundamentals. Introduction to Programming 1 1

Basic Computation. Chapter 2

CMPT 125: Lecture 4 Conditionals and Loops

COMP 110 Introduction to Programming. What did we discuss?

Chapter 6 Primitive types

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

Information Science 1

Programming with Java

CS313D: ADVANCED PROGRAMMING LANGUAGE

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

Chapter 1 Introduction to java

Professor: Sana Odeh Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators

Lecture 3. More About C

Chapter 3: Operators, Expressions and Type Conversion

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: Using Data

Work relative to other classes

Operators. Java operators are classified into three categories:

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

Lecture 3: Variables and assignment

Chapter 2 ELEMENTARY PROGRAMMING

Operators. Lecture 3 COP 3014 Spring January 16, 2018

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Information Science 1

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language

LECTURE 3 C++ Basics Part 2

Prof. Navrati Saxena TA: Rochak Sachan

CHAPTER 3 Expressions, Functions, Output

Chapter 2 Working with Data Types and Operators

CSC 1214: Object-Oriented Programming

Chapter 2 Primitive Data Types and Operations

1.00 Lecture 4. Promotion

Types and Expressions. Chapter 3

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

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

Chapter 2: Using Data

Basic Operations jgrasp debugger Writing Programs & Checkstyle

Java Notes. 10th ICSE. Saravanan Ganesh

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

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

Chapter 2: Using Data

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

CIS 110: Introduction to Computer Programming

COMP6700/2140 Data and Types

Building Java Programs

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

MODULE 02: BASIC COMPUTATION IN JAVA

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

Values and Variables 1 / 30

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

A variable is a name that represents a value. For

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

Transcription:

CMPT 125: Lecture 3 Data and Expressions Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University January 3, 2009 1

Character Strings A character string is an object in Java, defined by the class String. Because they are used so frequently, Java allows the use of string literals, delimited by double quotes ("). We will return to the String class, for now let s look more closely at string literals. A string literal may include any valid character: "I like green @#($*& eggs and ham!" or no characters at all: "" CMPT 125: Data and Expressions, Lecture 3 2

The print and println Methods Recall from the program WiseWords, we invoked the println method as follows: System.out.println("No matter where you go..."); System.out.println("... there you are."); System.out represents an output device, or file, which by default is the monitor screen. The object s name is out and it is stored in the System class. The method println prints a character string to the screen. Each piece of data is sent to a method is called a parameter. The println takes a single parameter which is a character string. The print method is very similar to println but does not move to the beginning of a new line when completed. CMPT 125: Data and Expressions, Lecture 3 3

String Concatenation A string literal may not span multiple lines. //The following statement will not compile System.out.println("It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of disbelief, it was the epoch of incredulity,..."); Use + to append, or concatenate one string to another: If you use an integer literal in a string concatenation, it will automatically convert 100 to 100. System.out.println("This is probably one of the longest " + "sentences ever to open novel. " + "It uses over " + 100 + " words."); OUTPUT: This is probably one of the longest sentences ever to open a novel. It uses over 100 words. CMPT 125: Data and Expressions, Lecture 3 4

Concatenation vs. Arithmetic Addition Of course, the + operator is also used for arithmetic addition. The action performed by + depends on the data type of the parameter on which it operates. CODE: public class AdditionDemo { //The difference between concatenation and //arithmetic addition System.out.println("2 and 2 concatenated: " + 2 + 2); System.out.println("2 and 2 added: " + (2 + 2)); OUTPUT: 2 and 2 concatenated: 22 2 and 2 added: 4 First call to println: performs concatenation since operators are executed left to right. Second call to println: the parenthesis groups two numeric operands, (2+2), forcing this operation (addition) to happen first. This result, 4, is then concatenated with the preceding string. CMPT 125: Data and Expressions, Lecture 3 5

Escape Sequences An escape sequence can be used to represent a character that would otherwise cause compilation error. Eg: since Java uses the double quotation character (\") to represent a string, we must used an escape sequence if we wish to print this character type without confusing the compiler. System.out.println("This is a demonstration " + "of how \"Escape Sequences\" can be used \n" + "within a string literal to print on a diagonal: \n" + "one\n\t two\n\t\t three\n\t\t\t four\n\t\t\t\t five"); } }; OUTPUT: This is a demonstration of how Escape "Sequences" can be used within a string literal to print on a diagonal: one two three four five CMPT 125: Data and Expressions, Lecture 3 6

Java defines several Escape Sequences for printing special characters in string literals. Escape Sequence Meaning \b backspace \t tab \n newline \r carriage return \" double quote \ single quote \\ backlash CMPT 125: Data and Expressions, Lecture 3 7

Variables and Assignments A variable is a name for a location in memory used to hold a value of a particular data type. int x = 6; double cc1 = -2.1; 6 x 2.1 cc1 Figure 1: Variables that hold primitive values are like buckets A variable declaration instructs the compiler to reserve enough main memory space to hold that value type, and assigns a name by which we may refer to that location. CMPT 125: Data and Expressions, Lecture 3 8

Variable Declaration Each variable declaration consists of a type followed by a Variable Declarator. Type Variable Declarator int year = 2006; Identifier assignment operator value Figure 2: Variable Declaration. A variable declaration may consist of several variables of the same type, and may, or may not, include an initializing value: String yourname, myname = "Larry"; int count, minimum = 0, result; double rate; CMPT 125: Data and Expressions, Lecture 3 9

Assignment Statements It is an error to reference (or use) a variable before it is assigned a value (or initialized). A variable may be assigned a value using an assignment statement: rate = 0.5; When executed, the RHS of the assignment operator (=), is stored in the memory location indicated by the identifier. Identifier = Expression ; Figure 3: Basic Assignment. CMPT 125: Data and Expressions, Lecture 3 10

Changing a Variable Value A variable can store only one value of its declared type. A new assignment statement overwrites an old value. public class MySum { public static void main (String[] args) { int sum; sum = 7; sum = sum + 3; System.out.println( The sum is: + sum); } } OUTPUT: The sum is: 10 Java is strongly typed, meaning we cannot assign a value of one type to a variable of an incompatible type. CMPT 125: Data and Expressions, Lecture 3 11

Declaring Constants When values that do not change are used throughout a program, it is more meaningful to the programmer to give them names, rather than using a literal values. Constants are similar to variables, but they hold a particular value for the duration of their existence they cannot be changed. Constants are created by preceding the declaration with the final modifier. final double MAX_RATE = 0.07; It is conventional to use all uppercase letters for constant identifiers. CMPT 125: Data and Expressions, Lecture 3 12

Primitive Data Types Java distinguishes between two types of data 1. Primitive data: holds a value 2. Objects: holds a reference There are eight primitive data types in Java: four (4) subsets of integers two (2) subsets of floating point numbers a character data type a boolean data type Everything else is represented as objects. NOTE on Java 1.5 improvement: Primitive types are usually automatically converted to corresponding object types. Before Java 1.5, you had to convert between primitive types and Object types explicitly. CMPT 125: Data and Expressions, Lecture 3 13

Numeric Primitive Data Types Java has two basic types of numeric values: 1. integers (4 types) 2. floating points (with a fractional part) (2 types) Type # bits Min Value Max Value integer: byte 8-128 127 short 16-32,768 32,767 int 32-2,147,483,648 2,147,483,647 long 64-9,223,372,036,854,775,808 9,223,372,036,854,775,807 floating point: float 32-3.4E+38 (7 s.f.) 3.4E+38 (7 s.f.) double 64-1.7E+308 (15 s.f.) 1.7E+308 (15 s.f.) Table 1: Numeric Primitive Data Types All numeric types are signed, i.e., they may store both positive and negative values. Generally, for floating point values, always use double to avoid problems related to round-off errors. CMPT 125: Data and Expressions, Lecture 3 14

Numeric Literals A numeric literal is composed of a series of digits followed by an optional suffix to indicate its type. The number 34 may be represented as follows: literal type 34 int (default) 34L (or 34l) long 34F (or 34f) float 34D (or 34d) double 34.0 double (default) Table 2: Numeric Literals. An integer literal defaults to type int and a floating point literal defaults to type double. CMPT 125: Data and Expressions, Lecture 3 15

Characters A character literal represents a single character and is expressed using single quotes: a, A, 7, %. Recall, string are expressed using double-quotes ( ). char yes_c = Y ; \\ char String yes_s = yes ; \\ string CMPT 125: Data and Expressions, Lecture 3 16

Character Set A character set is a list of characters in a particular order. A particular value is assigned to each character according to its position in the set. The ASCII (American Standard Code for Information Interchange) consists of 128 different characters values, each using 7 bits: 1. non-printing (or control) characters (NULL, ESC, TAB etc) 2. special symbols: &,, etc. 3. digits: 0-9 4. punctuation:., ;,,, etc. 5. lowercase alphabetic characters a through z 6. uppercase alphabetic characters A through Z CMPT 125: Data and Expressions, Lecture 3 17

Unicode Character Set ASCII was extended from 7 to 8 bits doubling the number of possible characters. Still, this is not enough to support the world s alphabets. The Unicode character set, chosen by Java, uses 16 bits per character, supporting 65,536 unique characters. ASCII is a subset of Unicode. CMPT 125: Data and Expressions, Lecture 3 18

Booleans A boolean literal represents a logical value. The words true, false are reserved in Java. A boolean is defined in Java using the reserved word boolean. boolean opened = false; A boolean cannot be converted to any other type, nor can any other value be converted to a boolean. CMPT 125: Data and Expressions, Lecture 3 19

Expressions Expressions are combinations of operators and operands used to perform a calculation. Operands may be literals, constants, variables, or other sources of data. Operation Operator addition + subtraction - multiplication * division - modulus (remainder) % Table 3: Arithmetic Operations, defined for both integer and floating point. If either or both of the numeric operands are floating point values, the result will also be floating point. If both of the numeric operands are integers, the result will also be an integer. CMPT 125: Data and Expressions, Lecture 3 20

Integer Division CAUTION when using the division operator / : If both operands are integers, integer division will be performed, and the result will be an integer with any fractional part being discarded. public static void main(string arg[]) { System.out.println( Integer division: + 10/4); System.out.println( Floating point division: + 10.0/4); System.out.println( Floating point division: + 10/4.0); System.out.println( Floating point division: + 10.0/4.0); } OUTPUT: Integer division: 2 Floating point division: 2.5 Floating point division: 2.5 Floating point division: 2.5 CMPT 125: Data and Expressions, Lecture 3 21

Unary and Binary Operators A unary operator has only one operand, while a binary operator has two. The + and - can be either unary, representing positive and negative numbers) or binary, accomplishing addition and subtraction. CMPT 125: Data and Expressions, Lecture 3 22

Operator Precedence What is the result of the following expression? result = 14 + 8 / 2; Operator precedence in Java generally follow the rules of algebra: multiplication, division and the modulo operator have equal precedence. addition and subtraction have equal precedence, which is lower than those listed above. operators with the same level of precedence are performed left to right. CMPT 125: Data and Expressions, Lecture 3 23

Forcing precedence using parentheses Precedence can be forced using parentheses. result = (14 + 8) / 2; //result = 11 If parentheses are nested, innermost expressions are evaluated first. result = 3 * ((18-4) / 2); //result = 21 Ensure that the number of left parentheses match the number of right parentheses. CMPT 125: Data and Expressions, Lecture 3 24

Precedence Among Java Operators Since the computed result is stored in the variable to the LHS of the assignment operator (=), the assignment operator has a lowest precedence of all. Precedence Operator Operation Associates Level 1 + unary plus R to L unary minus 2 multiplication L to R / division % remainder 3 + addition L to R subtraction + string concatenation 4 = assignment R to L CMPT 125: Data and Expressions, Lecture 3 25

Increment and decrement operators Two other useful arithmetic operators (for either integer or floating point): 1. increment operator (++): adds 1 to any value 2. decrement operator (--): subtracts 1 from any value The following two statements are equivalent: count++; cound = count + 1; The increment or decrement operators can be applied after or before a variable (postfix form or prefix form respectively) yielding different results: count = 15; total = count++; //The value of count is assigned and then //incremented, yielding: total = 15 or count = 15; total = ++count; //The value is incremented and then //assigned, yielding: total = 16 CMPT 125: Data and Expressions, Lecture 3 26

Assignment Operators Some assignment and arithmetic operations are very common and may be combined for convenience: total += 5; total += (sum - 12) / count; product *= num1 + num2; product %= (highest - 40) / 2; is equivalent to: total = total + 5; total = total + (sum - 12) / count; product = product * (num1 + num2); product = product % ((highest - 40) / 2); CMPT 125: Data and Expressions, Lecture 3 27

Data Conversion There are two types of conversion from one primitive type to another: 1. widening conversions: converting from one data type to one requiring the same or more memory space. There is no loss of information except from integer to floating point (where least significant digits may be lost). 2. narrowing conversions: converting from one data type to one that is smaller. Information is more likely to be lost (magnitude and precision). Narrowing is harrowing and should be avoided! A short (16 bits) to a char (16 bits) is considered narrowing because the sign bit is incorporated into the new character value. Since the character is unsigned, a negative integer will not be converted correctly. CMPT 125: Data and Expressions, Lecture 3 28

Techniques for Data Conversion 1. assignment conversion: assigning a value of one type to a variable of a new, compatible, type. int dollars = 6; double money; money = dollars; converts the value of dollars from int to double. 2. promotion: when an operand needs be promoted in order to accomplish an operation. dividing a floating point by an integer: int count = 2; float mass = 18.342; mass = mass / count; passing an integer to an operator or method that expects a floating point concatenation of a number with a string (the number is promoted to a string). 3. casting: a Java operator specified by a type name in parentheses. double total = (double) count; CMPT 125: Data and Expressions, Lecture 3 29

Creating Objects Consider the two declarations: int num; String name; The first declaration creates a variable that holds an integer value and the second creates a variable that holds a reference to a String object. Neither of the two are are initializaed, and therefore are undefined, that is, they don t contain any data. num name Figure 4: A declaration creating empty variable holders. We may also create a reference that doesn t point to an object by using the null operator, a reserved word in Java. String name = null; CMPT 125: Data and Expressions, Lecture 3 30

Instantiation the new operator The new operator creates an instance of the class, and returns a reference to the newly created object. The new operator is followed by a call to the class constructor, a method with the same name as the class, allowing object initialization. Following these assignemnt statements num = 12; name = new String("Kurt Vonnegut"); the variables may be viewed as: num 20 name "Kurt Vonnegut" Figure 5: Instantiation. CMPT 125: Data and Expressions, Lecture 3 31

Shortcut notation Declaring an object reference and creating the object can be done in a single declaration statement: String name = new String("Kurt Vonnegut"); Because this kind of initialization is rather common, it can be done by shortcut notation to produce exactly the equivalent result: String name = "Kurt Vonnegut"; Once an object is instantiated, the dot operator may be used to access its methods or variables. len = name.length(); CMPT 125: Data and Expressions, Lecture 3 32

Aliases Multiple reference variables can refer to the same object. Consider two references str1 and str2 initially pointing to different objects. String str1 = string1 ; String str2 = string2 ; str1 = str2; The last assignemnt statement means there is now no longer any way of retrieving the object pointed to by ref1 creating a potential memory leak. Luckily Java has automatic garbage colloection, and can free this object from memory. If there are two references to an object, and one reference changes the object, this will also impact the other referenece. str2 = newstring ; Recall that str1 = str2, and this statement will change the contents of both! CMPT 125: Data and Expressions, Lecture 3 33