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

Similar documents
We now start exploring some key elements of the Java programming language and ways of performing I/O

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

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

Chapter. Let's explore some other fundamental programming concepts

ECE 122 Engineering Problem Solving with Java

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

Chapter 2: Data and Expressions

Classes and Objects Part 1

Chapter 2: Data and Expressions

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

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

Chapter 2: Data and Expressions

2: Basics of Java Programming

Data Conversion & Scanner Class

CMPT 125: Lecture 3 Data and Expressions

Full file at

Using Classes and Objects. Chapter

Program Elements -- Introduction

Chapter 2 ELEMENTARY PROGRAMMING

Chapter 2 Elementary Programming

Table of Contents Date(s) Title/Topic Page #s. Abstraction

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

Objectives of CS 230. Java portability. Why ADTs? 8/18/14

Variables, Constants, and Data Types

Primitive Data Types: Intro

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

Chapter 2. Elementary Programming

Formatting Output & Enumerated Types & Wrapper Classes

CS313D: ADVANCED PROGRAMMING LANGUAGE

Lecture 3: Variables and assignment

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

Computational Expression

More on variables and methods

AP Computer Science A

More Programming Constructs -- Introduction

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

Chapter 2 Primitive Data Types and Operations. Objectives

Java Review. Java Program Structure // comments about the class public class MyProgram { Variables

Using Classes and Objects

Using Java Classes Fall 2018 Margaret Reid-Miller

Computational Expression

Full file at

Declaration and Memory

Packages & Random and Math Classes

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

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

WEEK 4 OPERATORS, EXPRESSIONS AND STATEMENTS

COMP-202 Unit 8: Basics of Using Objects

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

Data Representation Classes, and the Java API

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

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

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

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

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

COMP 202 Java in one week

Program Fundamentals

Types and Expressions. Chapter 3

Chapter 2: Using Data

Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4

Lecture Set 2: Starting Java

Chapter 3: Using Classes and Objects

Chapter 2 Primitive Data Types and Operations

Basics of Java Programming

Getting started with Java

Lecture Set 2: Starting Java

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

COMP-202 Unit 5: Basics of Using Objects

Chap. 3. Creating Objects The String class Java Class Library (Packages) Math.random() Reading for this Lecture: L&L,

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

COMP 202 Java in one week

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

Programming with Java

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

Define a method vs. calling a method. Chapter Goals. Contents 1/21/13

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

Visual C# Instructor s Manual Table of Contents

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

A Java program contains at least one class definition.

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

Java Basic Introduction, Classes and Objects SEEM

CS111: PROGRAMMING LANGUAGE II

Section 2: Introduction to Java. Historical note

Basic Computation. Chapter 2

COMP 202. Java in one week

CS 106 Introduction to Computer Science I

Chapter 1 Introduction to java

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

Java Basic Introduction, Classes and Objects SEEM

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

2 rd class Department of Programming. OOP with Java Programming

VARIABLES, DATA TYPES,

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

ing execution. That way, new results can be computed each time the Class The Scanner

Important Java terminology

Example: Tax year 2000

4 Programming Fundamentals. Introduction to Programming 1 1

Transcription:

Variables A variable is a name for a location in memory A variable must be declared, specifying the variable's name and the type of information that will be held in it data type variable name int total; int count, temp, result; Multiple variables can be created in one declaration COMP 202 - week 2 1

Variables A variable can be given an initial value in the declaration int sum = 0; int base = 32, max = 149; When a variable is referenced in a program, its current value is used See ChickenFlight.java COMP 202 - week 2 2

Assignment An assignment statement changes the value of a variable The assignment operator is the = sign total = 55; The expression on the right is evaluated and the result is stored in the variable on the left The value that was in total is overwritten You can only assign a value to a variable that is consistent with the variable's declared type See Time.java COMP 202 - week 2 3

Constants A constant is an identifier that is similar to a variable except that it holds one value for its entire existence The compiler will issue an error if you try to change a constant In Java, we use the final modifier to declare a constant final int MIN_HEIGHT = 69; Constants: give names to otherwise unclear literal values facilitate changes to the code prevent inadvertent errors COMP 202 - week 2 4

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 COMP 202 - week 2 5

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

Characters A char variable stores a single character from the Unicode character set A character set is an ordered list of characters, and each character corresponds to a unique number The Unicode character set uses 16 bits 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' COMP 202 - week 2 7

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,... COMP 202 - week 2 8

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; COMP 202 - week 2 9

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 a floating point COMP 202 - week 2 10

Division and Remainder If both operands to the division operator (/) are integers, the result is an integer (the fractional part is discarded) 14 / 3 equals? 8 / 12 equals? 4 0 The remainder operator (%) returns the remainder after dividing the second operand into the first 14 % 3 equals? 8 % 12 equals? 2 8 COMP 202 - week 2 11

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 COMP 202 - week 2 12

Operator Precedence What is the order of evaluation in the following expressions? a + b + c + d + e a + b * c - d / e a / (b + c) - d % e a / (b * (c + (d - e))) COMP 202 - week 2 13

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

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 COMP 202 - week 2 15

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) See TempConverter.java COMP 202 - week 2 16

Increment and Decrement Operators The increment and decrement operators are arithmetic and operate on one operand The increment operator (++) adds one to its operand The decrement operator (--) subtracts one from its operand The statement count++; is essentially equivalent to count = count + 1; COMP 202 - week 2 17

Increment and Decrement Operators The increment and decrement operators can be applied in prefix form (before the variable) or postfix form (after the variable) When used alone in a statement, the prefix and postfix forms are basically equivalent. That is, count++; is equivalent to ++count; COMP 202 - week 2 18

Increment and Decrement Operators When used in a larger expression, the prefix and postfix forms have a different effect In both cases the variable is incremented (decremented) But the value used in the larger expression depends on the form: Expression count++ ++count count-- --count Operation add 1 add 1 subtract 1 subtract 1 Value of Expression old value new value old value new value COMP 202 - week 2 19

Increment and Decrement Operators If count currently contains 45, then total = count++; assigns 45 to total and 46 to count If count currently contains 45, then total = ++count; assigns the value 46 to both total and count COMP 202 - week 2 20

Assignment Operators Often we perform an operation on a variable, then store the result back into that variable Java provides assignment operators to simplify that process For example, the statement num += count; is equivalent to num = num + count; COMP 202 - week 2 21

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 COMP 202 - week 2 22

Assignment Operators The right hand side of an assignment operator can be a complete expression The entire right-hand expression is evaluated first, then the result is combined with the original variable Therefore result /= (total-min) % num; is equivalent to result = result / ((total-min) % num); COMP 202 - week 2 23

Data Conversions 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 are safest because they tend to go from a small data type to a larger one (such as a short to an int) Narrowing conversions can lose information because they tend to go from a large data type to a smaller one (such as an int to a short) COMP 202 - week 2 24

Data Conversions 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 //money is a float, dollars is an int money = dollars; Arithmetic promotion happens automatically when operators in expressions convert their operands //sum is a float or double, count is an int result = sum / count; COMP 202 - week 2 25

Data Conversions Casting is the most powerful, and dangerous, technique for conversion 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 For example, if total and count are integers, but we want a floating point result when dividing them, we can cast total: result = (float) total / count; The cast does not change the value in total for the rest of the program. COMP 202 - week 2 26

COMP 202 Week 2 cont d We now start exploring some key elements of the Java programming language and ways of performing I/O This module focuses on: Introduction to objects The String class String concatenation Creating objects Class libraries Wrapper classes Standard I/O Formatting output COMP 202 - week 2 27

Introduction to Objects Initially, we can think of an object as a collection of services that we can tell it to perform for us The services are defined by methods in a class that defines the object In the Hello program, we invoked the println method of the System.out object: System.out.println ( This course is fun!"); object method Information provided to the method (parameters) COMP 202 - week 2 28

The println and print Methods The System.out object provides another service as well The print method is similar to the println method, except that it does not advance to the next line Therefore anything printed after a print statement will appear on the same line See Countdown.java COMP 202 - week 2 29

Abstraction An abstraction hides (or ignores) the right details at the right time An object is abstract in that we don't really have to think about its internal details in order to use it We don't have to know how the println method works in order to invoke it Therefore, we can write complex software by organizing it carefully into classes and objects COMP 202 - week 2 30

The String Class Every character string is an object in Java, defined by the String class Every string literal, delimited by double quotation marks, represents a String object The string concatenation operator (+) is used to append one string to the end of another It can also be used to append a number to a string A string literal cannot be broken across two lines in a program See Facts.java COMP 202 - week 2 31

String Concatenation The plus operator (+) is also used for arithmetic addition The function that the + operator performs depends on the type of the information on which it operates If both operands are strings, or if one is a string and one is a number, it performs string concatenation If both operands are numeric, it adds them The + operator is evaluated left to right Parentheses can be used to force the operation order See Addition.java COMP 202 - week 2 32

Escape Sequences What if we wanted to print a double quote character? The following line would confuse the compiler because it would interpret the second quote as the end of the string System.out.println("I said "Hello" to you."); An escape sequence is a series of characters that represents a special character An escape sequence begins with a backslash character (\), which indicates that the character(s) that follow should be treated in a special way System.out.println ("I said \"Hello\" to you."); COMP 202 - week 2 33

Escape Sequences Some Java escape sequences: Escape Sequence \b \t \n \r \" \' \\ Meaning backspace tab newline carriage return double quote single quote backslash See Poem.java COMP 202 - week 2 34

Creating Objects A variable either holds a primitive type, or it holds a reference to an object A class name can be used as a type to declare an object reference variable String name; No object has been created with this declaration An object reference variable holds the address of an object The object itself must be created separately COMP 202 - week 2 35

Creating Objects We use the new operator to create an object name = new String ("Sparky the clown"); This calls the String constructor, which is a special method that sets up the object Creating an object is called instantiation An object is an instance of a particular class COMP 202 - week 2 36

Creating Objects Because strings are so common, we don't have to use the new operator to create a String object name = "Sparky the clown"; This is special syntax that only works for strings Once an object has been instantiated, we can use the dot operator to invoke its methods name.length() COMP 202 - week 2 37

String Methods The String class has several methods that are useful for manipulating strings, ex: String(String str), char charat(int index), int compareto(string str), String concat(string str), boolean equals(string str), boolean equalsignorecase(string str), int length(), String replace(char oldchar, char newchar), String substring(int offset, int endindex), String tolowercase(), String touppercase(), Many of the methods return a value, such as an integer or a new String object See the list of String methods in Appendix M See StringMutation.java COMP 202 - week 2 38

Class Libraries A class library is a collection of classes that we can use when developing programs There is a Java standard class library that is part of any Java development environment These classes are not part of the Java language per se, but we rely on them heavily The System class and the String class are part of the Java standard class library Other class libraries can be obtained through third party vendors, or you can create them yourself COMP 202 - week 2 39

Packages The classes of the Java standard class library are organized into packages Some of the packages in the standard class library are: Package java.lang java.applet (java.awt javax.swing java.net java.util Purpose General support Creating applets for the web Graphics and graphical user interfaces) Additional graphics capabilities and components Network communication Utilities COMP 202 - week 2 40

The import Declaration When you want to use a class from a package, you could use its fully qualified name java.util.random Or you can import the class, then just use the class name import java.util.random; To import all classes in a particular package, you can use the * wildcard character import java.util.*; COMP 202 - week 2 41

The import Declaration All classes of the java.lang package are automatically imported into all programs That's why we didn't have to explicitly import the System or String classes in earlier programs The Random class is part of the java.util package It provides methods that generate pseudo-random numbers We often have to scale and shift a number into an appropriate range for a particular purpose See RandomNumbers.java COMP 202 - week 2 42

Class Methods Some methods can be invoked through the class name, instead of through an object of the class These methods are called class methods or static methods The Math class contains many static methods, providing various mathematical functions, such as absolute value, trigonometry functions, square root, etc. temp = Math.cos(90) + Math.sqrt(delta); COMP 202 - week 2 43

Wrapper classes Two categories of data in Java : primitive data and objects. We use wrapper classes to manage primitive data as objects Each wrapper class represents a particular primitive type Integer everest = new Integer(8850); We have just «wrapped» the primitive integer value 8850 into an object referenced by the everest variable. All wrapper classes are part of the java.lang package: Byte, Short, Integer, Long, Float, Double, Character, Boolean, Void. COMP 202 - week 2 44

Some methods of the Integer class Integer (int value) byte bytevalue() double doublevalue() float floatvalue() int intvalue() long longvalue() static int parseint (String str) static String tobinarystring(int num) COMP 202 - week 2 45

The Scanner Class The Scanner class is part of the Java standard class library Part of the java.util package Contains several methods for reading input values for various types from various sources (keyboard, file) A Scanner object assumes that white space (delimiters) separates elements of the input (tokens) See Echo.java COMP 202 - week 2 46

Some methods of the Scanner class Scanner (InputStream source) Scanner (File source) Scanner (String source) String next () String nextline () double nextdouble () float nextfloat () int nextint () long nextlong () short nextshort () String nextboolean () Boolean hasnext () COMP 202 - week 2 47

Formatting Output The NumberFormat class has static methods that return a formatter object getcurrencyinstance() getpercentinstance() Each formatter object has a method called format that returns a string with the specified information in the appropriate format See PriceOfHappiness.java COMP 202 - week 2 48

Formatting Output The DecimalFormat class can be used to format a floating point value in generic ways For example, you can specify that the number be printed to three decimal places The constructor of the DecimalFormat class takes a string that represents a pattern for the formatted number See CircleStats.java COMP 202 - week 2 49