Variables, Types, Operations on Numbers

Similar documents
First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

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

Lecture Set 4: More About Methods and More About Operators

DATA TYPES AND EXPRESSIONS

Building Java Programs

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

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

Basics of Java Programming

Primitive Data, Variables, and Expressions; Simple Conditional Execution

The Math Class. Using various math class methods. Formatting the values.

Building Java Programs

Zheng-Liang Lu Java Programming 45 / 79

Building Java Programs

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

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

MODULE 02: BASIC COMPUTATION IN JAVA

Lecture 6: While Loops and the Math Class

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

Calculations, Formatting and Conversions

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

BASIC ELEMENTS OF A COMPUTER PROGRAM

Lecture Set 4: More About Methods and More About Operators

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.

Simple Java Reference

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

Chapter 4 Fundamental Data Types. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved.

2/9/2012. Chapter Four: Fundamental Data Types. Chapter Goals

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

Formatted Output (printf) CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

Elementary Programming

Expressions, Statements, Variables, Assignments, Types

Topic 4 Expressions and variables

Programming with Java

PROGRAMMING FUNDAMENTALS

CSE 201 JAVA PROGRAMMING I. Copyright 2016 by Smart Coding School

Full file at

CEN 414 Java Programming

Accelerating Information Technology Innovation

COMP 202 Java in one week

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

Chapter 2: Basic Elements of Java

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

Chapter-8 DATA TYPES. Introduction. Variable:

int: integers, no fractional part double: floating-point numbers (double precision) 1, -4, 0 0.5, , 4.3E24, 1E-14

Object-Oriented Programming

Lec 3. Compilers, Debugging, Hello World, and Variables

Computer Programming, I. Laboratory Manual. Final Exam Solution

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

Important Java terminology

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

Java Methods. Lecture 8 COP 3252 Summer May 23, 2017

COMP 202. Java in one week

Java Classes: Math, Integer A C S L E C T U R E 8

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

Full file at

Data Structure and Programming Languages

COMP-202 Unit 2: Java Basics. CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables

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

What did we talk about last time? Examples switch statements

Selected Questions from by Nageshwara Rao

Review for Test 1 (Chapter 1-5)

Visual Programming. Lecture 2: More types, Methods, Conditionals

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

Reserved Words and Identifiers

More types, Methods, Conditionals. ARCS Lab.

CIS133J. Working with Numbers in Java

Chapter 2: Data and Expressions

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

Chapter 2: Data and Expressions

Oct. 3 fixup - Here are notes and codes in the proper order that they should be.

Building Java Programs

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

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

AP Computer Science. Return values, Math, and double. Copyright 2010 by Pearson Education

CS 302: Introduction to Programming

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

AP Computer Science A. Return values

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

Methods (Functions) CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

Variables and Constants

A very simple program. Week 2: variables & expressions. Declaring variables. Assignments: examples. Initialising variables. Assignments: pattern

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

Spring 2013 COMP Midterm Exam Solutions March 07, 2013

Variables. Store information needed by the program

CS111: PROGRAMMING LANGUAGE II

Chapter 2. Elementary Programming

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

Data Structure and Programming Languages

Chapter 2 Elementary Programming

Expressions and Variables

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

Java Simple Data Types

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

More About Objects and Methods. Objectives. Outline. Chapter 6

More About Objects and Methods

Chapter 2 Primitive Data Types and Operations. Objectives

Chapter 2: Basic Elements of C++

3. Java - Language Constructs I

Transcription:

Variables, Types, Operations on Numbers CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington Updated 9/6/16 1

Summary Variable declaration, initialization, and use. Possible syntax errors Syntax rules for code that can compile. Types: Define what are legal values for a variable. Both variables and values have types. A variable can only have one type throughout the program. Common errors: Initialize a variable with a value of another type Use data of a wrong type for an operator(e.g. "catapult" - "cat" ) Wrong type: operator is not defined for strings Use data of a wrong type as function argument Function takes arguments of a different type. ++/--, +=/-= (not recommended in exams) Type conversion: Casting: (int) Casting and: Math.round(), Math.floor() or Math.ceil() Constant variables: "final int days_per_week = 7; "

Declaring a Variable At any point, you can create a variable, by doing a variable declaration. There are two ways to declare a variable: type variable_name; type variable_name = initial_value; // declare only: name and type // declare and initialize For example: int x; int number_of_fingers = 5; double radius = 20.231; 3

Declaration/Initialization before Use A variable must be declared before we try to use it. The code below illustrates a common mistake. Variable age is not declared anywhere. Java will refuse to run this code, complaining that it "cannot find symbol age". public class example1 // incorrect code public static void main(string[] args) age = 5; System.out.println(age); 4

Declaration/Initialization before Use A variable must be declared and initialized before we try to use it. The code below illustrates a common mistake. Variable age is declared but not initialized. Java will refuse to run this code, complaining that "variable age might not have been initialized". public class example1 // incorrect code public static void main(string[] args) int age; System.out.println(age); 5

Declaration/Initialization before Use One way to fix such problems is to provide an initial value for the variable at the same line where you declare the variable. The code below shows an example of doing that. The line shown in red declares and initializes a variable called age. public class example1 // correct code public static void main(string[] args) int age = 5; System.out.println(age); 6

Declaration/Initialization before Use Another way is to first declare the variable in one line, and then set the value of the variable in another line. The code below shows an example of doing that. The first line shown in red declares a variable called var. The second line shown in red sets the value of var to 5. public class example1 // correct code public static void main(string[] args) int age; age = 5; System.out.println(age); 7

Using Variables public class hello1 // incorrect code public static void main(string[] args) radius = 20.231; area = Math.PI * Math.pow(radius, 2); System.out.println(area); What is wrong with this code? 8

Using Variables public class hello1 // incorrect code public static void main(string[] args) radius = 20.231; area = Math.PI * Math.pow(radius, 2); System.out.println(area); What is wrong with this code? Variables "radius" and "area" are not declared. 9

Using Variables public class hello1 // correct code public static void main(string[] args) double radius = 20.231; double area = Math.PI * Math.pow(radius, 2); System.out.println(area); Corrected version. 10

Using Variables public class hello1 // incorrect code public static void main(string[] args) double area = Math.PI * Math.pow(radius, 2); double radius = 20.231; System.out.println(area); What is wrong with this code? 11

Using Variables public class hello1 // incorrect code public static void main(string[] args) double area = Math.PI * Math.pow(radius, 2); double radius = 20.231; System.out.println(area); What is wrong with this code? Variable "radius" is used before it has been declared. 12

Using Variables public class hello1 // correct code public static void main(string[] args) double radius = 20.231; double area = Math.PI * Math.pow(radius, 2); System.out.println(area); Corrected version. 13

Using Variables public class hello1 // incorrect code public static void main(string[] args) double radius = 20.231; double area = Math.PI * Math.pow(Radius, 2); System.out.println(area); What is wrong with this code? 14

Using Variables public class hello1 // incorrect code public static void main(string[] args) double radius = 20.231; double area = Math.PI * Math.pow(Radius, 2); System.out.println(area); What is wrong with this code? Variable "radius" is misspelled in the line where the area is computed. 15

Using Variables public class hello1 // correct code public static void main(string[] args) double radius = 20.231; double area = Math.PI * Math.pow(radius, 2); System.out.println(area); Corrected version. 16

Using Variables public class example1 // incorrect code public static void main(string[] args) int x = 5; int x = 3 * 5; System.out.println(x); What is wrong with this code? 17

Using Variables public class example1 // incorrect code public static void main(string[] args) int x = 5; int x = 3 * 5; System.out.println(x); What is wrong with this code? Variable x is being declared twice. 18

Using Variables public class example1 // correct code public static void main(string[] args) int x = 5; x = 3 * 5; System.out.println(x); Corrected version. 19

Types The type of a variable defines what are legal values for that variable. Java will never allow you to set a variable to a value incompatible with the type of the variable. Both the variables and the values have a type. 20

The Five Basic Types In this course we will use numbers and text (and boolean values). They will be represented by five basic types. int double boolean String char 21

int The Five Basic Types legal values? integers, like 0, 57, -1896 double legal values? real numbers, like 3.0, 5.2, -0.23 boolean illegal: 5,300 (comma). Use: 5300. legal values? only two: true and false. String legal values? text, like "hello", "a cat jumped on the table", NOTE: text for strings must be enclosed in double quotes. char legal values? singe characters, like 'c', '3', 'A', '#', NOTE: text for strings must be enclosed in single quotes. 22

Types Are NOT Interchangeable Not pay attention to types makes programming very hard and confusing. The following four values are NOT interchangeable: 2 2.0 "2" '2' Why? 23

Types Are NOT Interchangeable Not pay attention to types makes programming very hard and confusing. The following four values are NOT interchangeable: 2 this is an int 2.0 this is a double "2" this is a string '2' this is a character Why? Because they are different types. 24

Types Are NOT Interchangeable For example: Incorrect Correct String a1 = 2.5; String a1 = "2.5"; double a2 = "2.5"; double a2 = 2.5; int num = '5'; int num = 5; char c1 = 5; char c1 = '5'; String str = '5'; String str = "5"; int my_int = 2.0; int my_int = 2; boolean v = "true"; boolean v = true; String v = true; String v = "true"; 25

The ++ and -- Operators public class example1 public static void main(string[] args) double x = 5.5; x++; System.out.println(x); int y = 4; y--; System.out.println(y); Output 6.5 3 The ++ operator increments the value of a variable by 1. Syntax: variable_name++; The -- operator increments the value of a variable by 1. Syntax: variable_name--; 26

The ++ and -- Operators The following two lines do the EXACT SAME THING: variable_name++; variable_name = variable_name + 1; The following two lines do the EXACT SAME THING: variable_name--; variable_name = variable_name - 1; 27

The ++ and -- Operators public class example1 public static void main(string[] args) double x = 5.5; x = x+1; System.out.println(x); int y = 4; y = y-1; System.out.println(y); Output 6.5 3 An alternative version of the previous program, without using ++ and --. Whether you use ++ and -- or not is entirely up to you. However, you should understand what they do when you see them in code. 28

The += and -= operators public class example1 public static void main(string[] args) double x = 5.5; x += 3.2; int y = 20; y -= 5; System.out.println(x); System.out.println(y); Output 8.7 15 The += operator adds some value to a variable. Syntax: variable_name += value; The -= operator subtracts some value from a variable. Syntax: variable_name -= value; 29

The += and -= operators The following two lines do the EXACT SAME THING: variable_name += value; variable_name = variable_name + value; The following two lines do the EXACT SAME THING: variable_name -= value; variable_name = variable_name - value; 30

The += and -= operators public class example1 public static void main(string[] args) double x = 5.5; x = x + 3.2; int y = 20; y = y - 5; System.out.println(x); System.out.println(y); Output 8.7 15 An alternative version of the previous program, without using += and -=. Whether you use += and -= or not is entirely up to you. Do NOT use these in an exam (miss a symbol => wrong answer) However, you should understand what they do when you see them in code. 31

Multiple Ways to Add/Subtract 1 If we want to add 1 to x, in how many ways can we do it? If we want to subtract 1 from x, in how many ways can we do it? 32

Multiple Ways to Add/Subtract 1 If we want to add 1 to x, in how many ways can we do it? x++; x += 1; x = x+1; If we want to subtract 1 from x, in how many ways can we do it? x--; x -= 1; x = x-1; 33

Converting Doubles to Ints public class example1 public static void main(string[] args) double price = 18.53; int dollars = price; System.out.printf("Rounded price: %d dollars", dollars); The above code gives an error: 34

Converting Doubles to Ints public class example1 public static void main(string[] args) double price = 18.53; int dollars = price; System.out.printf("Rounded price: %d dollars", dollars); The above code gives an error: Java does not allow assigning a double value to an int variable. There are several ways to get around that. 35

Converting Doubles to Ints public class example1 public static void main(string[] args) double price = 18.53; int dollars = (int) price; System.out.printf("Rounded price: %d dollars", dollars); First approach: casting. Putting (int) in front of the double value asks Java to convert that value to an integer. Casting simply removes the decimal part. (int) 18.53 evaluates to 18. (int) -18.53 evaluates to -18. 36

Converting Doubles to Ints public class example1 public static void main(string[] args) double price = 18.53; int dollars = (int) Math.round(price); System.out.printf("Rounded price: %d dollars", dollars); Second approach: rounding. Math.round(number) rounds number to the closest integer. We still need to put (int), to convert the result of Math.round into an integer. (int) Math.round(18.53) evaluates to 19. (int) Math.round(-18.53) evaluates to -19. 37

Converting Doubles to Ints public class example1 public static void main(string[] args) double price = 18.53; int dollars = (int) Math.floor(price); System.out.printf("Rounded price: %d dollars", dollars); Third approach: rounding down (taking the floor). Math.floor(number) rounds number down to an integer. We still need to put (int), to convert the result of Math.floor into an integer. (int) Math.floor(18.53) evaluates to 18. (int) Math.floor(-18.53) evaluates to -19. 38

Converting Doubles to Ints public class example1 public static void main(string[] args) double price = 18.53; int dollars = (int) Math.ceil(price); System.out.printf("Rounded price: %d dollars", dollars); Fourth approach: rounding up (taking the ceiling). Math.ceil(number) rounds number up to an integer. We still need to put (int), to convert the result of Math.ceil into an integer. (int) Math.ceil(18.53) evaluates to 19. (int) Math.ceil(-18.53) evaluates to -18. 39

Constant Variables public class example1 public static void main(string[] args) int weeks = 12; final int days_per_week = 7; int days = weeks * days_per_week; System.out.printf("%d weeks = %d days\n", weeks, days); Some variables should never change value. Examples: Number of days in a week. Constants from math and physics such as pi and e. Other data specific to your application (e.g. minimum number of staff at a desk during a work day) 40

Constant Variables public class example1 public static void main(string[] args) int weeks = 12; final int days_per_week = 7; int days = weeks * days_per_week; System.out.printf("%d weeks = %d days\n", weeks, days); To tell Java that a variable is a constant, use the keyword final when you declare the variable. Syntax: final type variable_name = value; 41

Constant Variables public class example1 public static void main(string[] args) int weeks = 12; final int days_per_week = 7; int days = weeks * days_per_week; System.out.printf("%d weeks = %d days\n", weeks, days); If we remove the final keyword in the program above, it runs just as well. (Try it.) However using final is the better practice, because: The code is easier to read and understand (it is clear that days_per_week will not change throughout the program). The compiler will check and report errors such as modifying days_per_week. 42

Example Where final Is Useful public class example1 public static void main(string[] args) int days_per_week = 7; int weeks = 12; days_per_week++; int days = weeks * days_per_week; System.out.printf("%d weeks = %d days\n", weeks, days); What do you think will happen with this code? 43

Example Where final Is Useful public class example1 public static void main(string[] args) int days_per_week = 7; int weeks = 12; days_per_week++; int days = weeks * days_per_week; System.out.printf("%d weeks = %d days\n", weeks, days); What do you think will happen with this code? Java will run it, and it will give the wrong answer (12 weeks have 96 days). The days_per_week++ should not have happened, probably the programmer put it there by accident. However, Java cannot possibly know that it was a mistake. 44

Example Where final Is Useful public class example1 public static void main(string[] args) final int days_per_week = 7; int weeks = 12; days_per_week++; int days = weeks * days_per_week; System.out.printf("%d weeks = %d days\n", weeks, days); What do you think will happen with this code? 45

Example Where final Is Useful public class example1 public static void main(string[] args) final int days_per_week = 7; int weeks = 12; days_per_week++; int days = weeks * days_per_week; System.out.printf("%d weeks = %d days\n", weeks, days); What do you think will happen with this code? Java will refuse to run it, will give an error: A constant variable is not allowed to change. By declaring a variable as final, you tell Java that if you ever try to change it, you are probably making a mistake and it should not let you. 46