Accelerating Information Technology Innovation

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

Lecture 3 Operators MIT AITI

3. Java - Language Constructs I

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Program Fundamentals

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

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

Programming Lecture 3

3. Java - Language Constructs I

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

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

The Arithmetic Operators

Programming with Java

CSC 1214: Object-Oriented Programming

Chapter 2. Elementary Programming

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

Object-Oriented Programming

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

BASIC ELEMENTS OF A COMPUTER PROGRAM

Lecture Set 4: More About Methods and More About Operators

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

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

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

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Full file at

Language Fundamentals Summary

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Java Language Basics: Introduction To Java, Basic Features, Java Virtual Machine Concepts, Primitive Data Type And Variables, Java Operators,

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Visual C# Instructor s Manual Table of Contents

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

COMP 202 Java in one week

Chapter 3: Operators, Expressions and Type Conversion

Elementary Programming

DM550 Introduction to Programming part 2. Jan Baumbach.

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Declaration and Memory

Unit 3. Operators. School of Science and Technology INTRODUCTION

DEPARTMENT OF MATHS, MJ COLLEGE

Operators. Java operators are classified into three categories:

Basics of Java Programming

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

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

Chapter 2: Using Data

Java Programming. Atul Prakash

Zheng-Liang Lu Java Programming 45 / 79

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Java Notes. 10th ICSE. Saravanan Ganesh

An overview of Java, Data types and variables

JAVA Programming Fundamentals

Lecture Set 4: More About Methods and More About Operators

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

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.

Introduction to C# Applications

UNIT- 3 Introduction to C++

Java Identifiers. Java Language Essentials. Java Keywords. Java Applications have Class. Slide Set 2: Java Essentials. Copyright 2012 R.M.

CS313D: ADVANCED PROGRAMMING LANGUAGE

JAVA Ch. 4. Variables and Constants Lawrenceville Press

More Programming Constructs -- Introduction

Entry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes

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

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

Programming in C++ 5. Integral data types

Creating a C++ Program

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

A Java program contains at least one class definition.

CSCI 123 Introduction to Programming Concepts in C++

Welcome to CSE 142! Zorah Fung University of Washington, Spring Building Java Programs Chapter 1 Lecture 1: Introduction; Basic Java Programs

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

Software Practice 1 Basic Grammar

Fundamental of Programming (C)

Variables. Data Types.

SECTION II: LANGUAGE BASICS

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

C++ Programming: From Problem Analysis to Program Design, Third Edition

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

Welcome to CSE 142! Whitaker Brand. University of Washington, Winter 2018

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

DM503 Programming B. Peter Schneider-Kamp.

Tools : The Java Compiler. The Java Interpreter. The Java Debugger

4 Programming Fundamentals. Introduction to Programming 1 1

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

Introduction to Java & Fundamental Data Types

Lecture 3. More About C

Chapter 2 Elementary Programming

2 rd class Department of Programming. OOP with Java Programming

Fundamentals of Programming

Values and Variables 1 / 30

Midterms Save the Dates!

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

Data Types. 1 You cannot change the type of the variable after declaration. Zheng-Liang Lu Java Programming 52 / 87

Fundamentals of Programming CS-110. Lecture 2

Datatypes, Variables, and Operations

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

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

These are reserved words of the C language. For example int, float, if, else, for, while etc.

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

Transcription:

Accelerating Information Technology Innovation http://aiti.mit.edu Cali, Colombia Summer 2012 Lesson 02 Variables and Operators

Agenda Variables Types Naming Assignment Data Types Type casting Operators 2

What is a Variable? In basic algebra, variables are symbols that can represent values in equations. y = x + 5 Similarly, variables in computer program represent data. In computer programming, variables can represent more than just numbers 3

An Analogy Think of variables as a box that you can put values in. We can label the box with a name like Box X and re-use it many times. Can perform tasks on the box without caring about what s inside: Move Box X to Shelf A Put item Z in box Open Box X Remove contents from Box X 4

Declaring Variables in Java type name; Variables are created by declaring their type and their name as follows: Declaring an integer named x : int x; Declaring a string named greeting : String greeting; Note that we have not assigned values to these variables 5

Java Types: Integer Types Integer Types: int: Most numbers you will deal with. long: Big integers; science, finance, computing. short: Smaller integers. Not as useful. byte: Very small integers, useful for small data. 6

Java Types: Other Types Floating Point (Decimal) Types: float: Single-precision decimal numbers double: Double-precision decimal numbers. Some phone platforms do not support FP. String: Letters, words, or sentences. boolean: True or false. char: Single Latin Alphanumeric characters 7

Assigning Values to Variables name = value; Assign values to variables using the syntax: For example: x = 100; greeting = Jambo ; Illegal to assign a variable the wrong type: x = Jambo ; x = 1.2; greeting = 123; We can declare and assign in one step: int x = 100; String greeting = Jambo ; 8

Naming Variables Variable names (or identifiers) may be any length, but must start with: A letter (a z, A-Z), A dollar sign ($), Or, an underscore ( _ ). Identifiers cannot contain special operation symbols like +, -, *, /, &, %, ^, etc. Certain reserved keywords in the Java language are illegal. int, double, String, etc. 9

Naming Variables Java is case sensitive A rose is not a Rose is not a ROSE Choose variable names that are informative Good: int studentexamgrade; Bad: int tempvar3931; Camel Case : Start variable names with lower case and capitalize each word: camelshavehumps. 10

Review Which of the following are valid variable names? $amount 6tally my*name salary _score first Name short 11

Integer Types There are 4 primitive integer types: byte, short, int, long. Each type has a maximum value, based on its underlying binary representation: Bytes: ± 128 (8 bits) Short: ± 2 15 32,000 (16 bits) Int: ± 2 31 2 billion (32 bits) Long: ± 2 63 really big (64 bits) 12

Overflow What happens when if we store Bill Gates s net worth in an int? Int: ± 2 31 2 billion (32 bits) Bill s net worth: > $40 billion USD Undefined! 13

Why use different types of integers? Why not simply use long values all the time? Storage requirements (data memory) Computational speed Power efficiency Use smallest type that will not overflow 14

Floating Point Types Initialize doubles as you would write a decimal number: double y = 1.23; double w = -3.21e-10; // -3.21x10-10 float z = 3.45; Doubles are more precise than Floats, but may take longer to perform operations. 15

Floating Point Types We must be careful with integer division: double z = 1/3; // z = 0.0 Why? At least one of the operands must be a double: double z = 1.0/3; // z = 0.333 16

Type Casting When we want to convert one type to another, we use type casting The syntax is as follows: Example code: (new type)variable double decimalnumber = 1.234; int integerpart = (int)decimalnumber; Results: decimalnumber == 1.234; integerpart == 1; 17

Boolean Type Boolean is a data type that can be used in situations where there are two options, either true or false. The values true or false are casesensitive keywords. Not True or TRUE. Booleans will be used later for testing properties of data. Example: boolean monsterhungry = true; boolean fileopen = false; 18

Character Type Character is a data type that can be used to store a single characters such as a letter, number, punctuation mark, or other symbol. Characters are a single letter enclosed in single quotes. Example: char firstletterofname = 'e' ; char myquestion = '?' ; 19

String Type Strings are not a primitive. They are what s called an Object, which we will discuss later. Strings are sequences of characters surrounded by double quotations. Strings have a special append operator + that creates a new String: String greeting = Ho + la ; String biggreeting = greeting +! ; String numgreeting = greeting + 25; 20

Review What data types would you use to store the following types of information?: Population of Colombia World Population Approximation of π Open/closed status of a file Your name First letter of your name $237.66 int long double boolean String char double 21

A Note on Statements A statement is a command that causes something to happen. All statements are terminated by semicolons ; Declaring a variable is a statement. Method (or function) calls are statements: System.out.println( Hello, World ); In lecture 4, we ll learn how to control the execution flow of statements. 22

What are Operators? Expressions can be combinations of variables, primitives and operators that result in a value Operators are special symbols used for: - mathematical functions - assignment statements - logical comparisons Examples with operators: 3 + 5 // uses + operator 14 + 5 4 * (5 3) // uses +, -, * operators 23

The Operator Groups There are 5 different groups of operators: - Arithmetic Operators - Assignment Operator - Increment / Decrement Operators - Relational Operators - Conditional Operators The following slides will explain the different groups in more detail. 24

Arithmetic Operators Java has the usual 5 arithmetic operators: +, -,, /, % Order of operations (or precedence): 1.Parentheses (Brackets) 2.Exponents (Order) 3.Multiplication and Division from left to right 4.Addition and Subtraction from left to right 25

Order of Operations (Cont d) Example: 10 + 15 / 5; The result is different depending on whether the addition or division is performed first (10 + 15) / 5 = 5 10 + (15 / 5) = 13 Without parentheses, Java will choose the second case You should be explicit and use parentheses to avoid confusion 26

Integer Division In the previous example, we were lucky that (10 + 15) / 5 gives an exact integer answer (5). But what if we divide 63 by 35? Depending on the data types of the variables that store the numbers, we will get different results. 27

Integer Division (Cont d) int i = 63; int j = 35; System.out.println(i / j); Output: 1 double x = 63; double y = 35; System.out.println(x / y); Output: 1.8 The result of integer division is just the integer part of the quotient! 28

Assignment Expression The basic assignment operator (=) assigns the value of expr to var name = value Java allows you to combine arithmetic and assignment operators into a single statement Examples: x = x + 5; is equivalent to x += 5; y = y * 7; is equivalent to y *= 7; 29

Increment/Decrement Operators ++ is called the increment operator. It is used to increase the value of a variable by 1. For example: i = i + 1; can be written as: ++i; or i++; -- is called the decrement operator. It is used to decrease the value of a variable by 1. i = i - 1; can be written as: --i; or i--; 30

Increment Operators (cont d) The increment / decrement operator has two forms : - Prefix Form e.g ++i; --i; - Postfix Form e.g i++; i--; 31

Prefix increment /decrement The prefix form first adds/subtracts 1 from the variable and then continues to any other operator in the expression Example: int numoranges = 5; int numapples = 10; int numfruit; numfruit = ++numoranges + numapples; numfruit has value 16 numoranges has value 6 32

Postfix Increment/ Decrement The postfix form i++, i-- first evaluates the entire expression and then adds/subtracts 1 to the variable Example: int numoranges = 5; int numapples = 10; int numfruit; numfruit = numoranges++ + numapples; numfruit has value 15 numoranges has value 6 33

Relational (Comparison) Operators Relational operators compare two values They produce a boolean value (true or false) depending on the relationship Operation a > b a >= b a == b a!= b a <= b a < b.is true when a is greater than b a is greater than or equal to b a is equal to b a is not equal to b a is less than or equal to b a is less than b Note: == sign! 34

Examples of Relational Operations int x = 3; int y = 5; boolean result; 1) result = (x > y); result is assigned the value false because 3 is not greater than 5 2) result = (15 == x*y); now result is assigned the value true because the product of 3 and 5 equals 15 3) result = (x!= x*y); now result is assigned the value true because the product of x and y (15) is not equal to x (3) 35

Conditional Operators Symbol &&! Name AND OR NOT Conditional operators can be referred to as boolean operators, because they are only used to combine expressions that have a value of true or false. 36

Truth Table for Conditional Operators x y x && y x y!x True True True True False True False False True False False True False True True False False False False True 37

Examples of Conditional Operators boolean x = true; boolean y = false; boolean result; Let result = (x && y); result is assigned the value false Let result = ((x y) && x); (x y) evaluates to true (true && x) evaluates to true now result is assigned the value true 38

Using && and false && true Java performs short circuit evaluation Evaluate && and expressions from left to right Stop when you are guaranteed a value 39

Short-Circuit Evaluation (a && (b++ > 3)); What happens if a is false? Java will not evaluate the right-hand expression (b++ > 3) if the left-hand operator a is false, since the result is already determined in this case to be false. This means b will not be incremented! (x y); What happens if x is true? Similarly, Java will not evaluate the right-hand operator y if the left-hand operator x is true, since the result is already determined in this case to be true. 40

Review 1) What is the value of result? int x = 8; int y = 2; boolean result = (15 == x * y); 2) What is the value of result? boolean x = 7; boolean result = (x < 8) && (x > 4); 3) What is the value of z? int x= 5; int y= 10; int z= y++ + x+ ++y; 41

new native long interfac e int return public protected private package switch super strictfp static short while violate void try transient throws throw this synchronized instanceof import implements if goto for float finally final extends else double do default continue const class char catch case byte break boolean assert abstract Appendix I: Reserved Keywords 42

Appendix II: Primitive Data Types This table shows all primitive data types along with their sizes and formats: Data Type byte short int long Description Variables of this kind can have a value from: -128 to +127 and occupy 8 bits in memory Variables of this kind can have a value from: -32768 to +32767 and occupy 16 bits in memory Variables of this kind can have a value from: -2147483648 to +2147483647 and occupy 32 bits in memory Variables of this kind can have a value from: -9223372036854775808 to +9223372036854775807 and occupy 64 bits in memory 43

Appendix II: Primitive Data Types Real Numbers Data Type float Description Variables of this kind can have a value from: 1.4e(-45) to 3.4e(+38) double Variables of this kind can have a value from: 4.9e(-324) to 1.7e(+308) Other Primitive Data Types char boolean Variables of this kind can have a value from: A single character Variables of this kind can have a value from: True or False 44