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

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

IEEE Floating-Point Representation 1

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

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

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

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.

Logic is the anatomy of thought. John Locke ( ) This sentence is false.

Zheng-Liang Lu Java Programming 45 / 79

++x vs. x++ We will use these notations very often.

Arithmetic Compound Assignment Operators

Scanner Objects. Zheng-Liang Lu Java Programming 82 / 133

Values in 2 s Complement

Arithmetic Compound Assignment Operators

Java Programming. U Hou Lok. Java Aug., Department of Computer Science and Information Engineering, National Taiwan University

Motivating Examples (1.1) Selections. Motivating Examples (1.2) Learning Outcomes. EECS1022: Programming for Mobile Computing Winter 2018

Selections. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG

Programming with Java

Chapter 3: Operators, Expressions and Type Conversion

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Chapter 2 Elementary Programming

Java Programming Language. 0 A history

Chapter 2 ELEMENTARY PROGRAMMING

Important Java terminology

CEN 414 Java Programming

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

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

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

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 88 / 133

Full file at

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

Basic Operations jgrasp debugger Writing Programs & Checkstyle

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

Elementary Programming

Example: Monte Carlo Simulation 1

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

JAVA OPERATORS GENERAL

Chapter 2. Elementary Programming

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

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 89 / 137

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

Motivations. Chapter 2: Elementary Programming 8/24/18. Introducing Programming with an Example. Trace a Program Execution. Trace a Program Execution

Getting started with Java

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

Prof. Navrati Saxena TA: Rochak Sachan

Chapter 2 Elementary Programming. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.

Full file at

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

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

Program Fundamentals

Accelerating Information Technology Innovation

Fundamentals of Programming Data Types & Methods

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

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

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

1 class Lecture5 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199

Exercise (Revisited)

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

Chapter 2 Primitive Data Types and Operations. Objectives

SOFTWARE DEVELOPMENT 1. Operators 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

Computer System and programming in C

More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements

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

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

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

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

JAVA Programming Fundamentals

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Lecture Set 4: More About Methods and More About Operators

Tutorial # 4. Q1. Evaluate the logical (Boolean) expression in the following exercise

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

Basic data types. Building blocks of computation

Chapter 2: Data and Expressions

Elementary Programming. CSE 114, Computer Science 1 Stony Brook University

Date: Dr. Essam Halim

Elementary Programming

Chapter 02: Using Data

Computer Programming, I. Laboratory Manual. Experiment #3. Selections

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. A Guide to this Instructor s Manual:

Nested Loops. A loop can be nested inside another loop.

Lecture 3 Operators MIT AITI

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

Introduction to Programming Using Java (98-388)

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Chapter 2: Data and Expressions

bitwise inclusive OR Logical logical AND && logical OR Ternary ternary? : Assignment assignment = += -= *= /= %= &= ^= = <<= >>= >>>=

Section 2: Introduction to Java. Historical note

Common Errors double area; 3 if (r > 0); 4 area = r r 3.14; 5 System.out.println(area); 6... Zheng-Liang Lu Java Programming 101 / 141

Visual C# Instructor s Manual Table of Contents

Declaration and Memory

CPSC 3740 Programming Languages University of Lethbridge. Data Types

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

ECE 122 Engineering Problem Solving with Java

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

Research Group. 2: More types, Methods, Conditionals

switch-case Statements

Object-Oriented Programming

Chapter 3. Selections

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

JAVA Programming Concepts

Transcription:

Data Types Java is a strongly-typed 1 programming language. Every variable has a type. Also, every (mathematical) expression has a type. There are two categories of data types: primitive data types, and reference data types. 1 You cannot change the type of the variable after declaration. Zheng-Liang Lu Java Programming 52 / 87

Primitive Data Types 2 2 See Figure 3-4 in Sharan, p. 67. Zheng-Liang Lu Java Programming 53 / 87

Integers The most commonly used integer type is int. If the integer values are larger than its feasible range, then a overflow occurs. Zheng-Liang Lu Java Programming 54 / 87

Floating Points Floating points are used when evaluating expressions that require fractional precision. For example, sin(), cos(), and sqrt(). The performance for the double values is actually faster than that for float values on modern processors that have been optimized for high-speed mathematical calculations. Be aware that floating-point arithmetic can only approximate real arithmetic. 3 (Why?) 3 See https://en.wikipedia.org/wiki/numerical_error. Zheng-Liang Lu Java Programming 55 / 87

Example: 0.5-0.1-0.1-0.1-0.1-0.1 = 0? 1 public class FloatingPointsDemo { 2 public static void main(string args[]) { 3 System.out.println(0.5 0.1 0.1 0.1 0.1 0.1); 4 } 5 } The result is surprising. (Why?) You may try this decimal-binary converter. This issue is not only associated decimal numbers, but also big integers. 4 So double values are not reliable if the program runs for a high-precision calculation. 4 Thanks to a lively discussion on June 26, 2016. Zheng-Liang Lu Java Programming 56 / 87

Example: Loss of Significance For example, 1... 2 System.out.println(3.14 + 1e20 1e20); // output? 3 System.out.println(3.14 + (1e20 1e20)); // output? 4... Can you explain why? Zheng-Liang Lu Java Programming 57 / 87

IEEE Floating-Point Representation 5 x = ( 1) s M 2 E The sign s determines whether the number is negative (s = 1) or positive (s = 0). The significand M is a fractional binary number that ranges either between 1 and 2 ɛ, or between 0 and 1 ɛ. The exponent E weights the value by a (possibly negative) power of 2. 5 William Kahan (1985); Aka IEEE754. Zheng-Liang Lu Java Programming 58 / 87

Illustration 6 That is why we call a double value. 6 See Figure 2-31 in Byrant, p. 104. Zheng-Liang Lu Java Programming 59 / 87

Assignments An assignment statement designates a value to the variable. 1 int x; // make a variable declaration 2... 3 x = 1; // assign 1 to x The equal sign (=) is used as the assignment operator. For example, is the expression x = x + 1 correct? Direction: from the right-hand side to the left-hand side To assign a value to a variable, you must place the variable name to the left of the assignment operator. 7 For example, 1 = x is wrong. 1 cannot be resolved to a memory space. 7 x can be a l-value and r-value, but 1 and other numbers can be only r-value but not l-value. See Value. Zheng-Liang Lu Java Programming 60 / 87

Two Before Rules Every variable has a scope. The scope of a variable is the range of the program where the variable can be referenced. 8 A variable must be declared before it can be assigned a value. In practice, do not declare the variable until you need it. A declared variable must be assigned a value before it can be used. 9 8 The detail of variable scope is introduced later. 9 In symbolic programming, such as Mathematica and Maple, a variable can be manipulated without assigning a value. For example, x + x returns 2x. Zheng-Liang Lu Java Programming 61 / 87

Arithmetic Operators 10 Note that the operator depends on the operands involved. 10 See Table 2-3 in YDL, p. 46. Zheng-Liang Lu Java Programming 62 / 87

Tricky Pitfalls Can you explain this result? 1... 2 double x = 1 / 2; 3 System.out.println(x); // output? 4... Revisit 0.5 0.1 0.1 0.1 0.1 0.1 0.1 = 0. 11 1... 2 System.out.println(1 / 2 1 / 10 1 / 10 1 / 10 1 / 10 1 / 10); // output 0; however, this is not the real solution to the original problem. 3... 11 Thanks to a lively discussion on on June 7, 2016. Zheng-Liang Lu Java Programming 63 / 87

Type Conversion and Compatibility If a type is compatible to another, then the compiler will perform the conversion implicitly. For example, the integer 1 is compatible to a double value 1.0. However, there is no automatic conversion from double to int. (Why?) To do so, you must use a cast, which performs an explicit conversion for compilation. Similarly, a long value is not compatible to int. Zheng-Liang Lu Java Programming 64 / 87

Casting 1... 2 int x = 1; 3 double y = x; // compatible; implicit conversion 4 x = y; // incompatible; need an explicit conversion by casting 5 x = (int) y; // succeed!! 6... Note that the Java compiler does only type-checking but no real execution before compilation. In other words, the values of x and y are unknown until they are really executed. Zheng-Liang Lu Java Programming 65 / 87

Type Conversion and Compatibility (concluded) small-size types large-size types small-size types large-size types (need a cast) simple types complicated types simple types complicated types (need a cast) Zheng-Liang Lu Java Programming 66 / 87

Characters A character stored by the machine is represented by a sequence of 0 s and 1 s. For example, ASCII code. (See the next page.) The char type is a 16-bit unsigned primitive data type. 12 12 Java uses Unicode to represent characters. Unicode defines a fully international character set that can represent all of the characters found in all human languages. Zheng-Liang Lu Java Programming 67 / 87

ASCII (7-bit version) Zheng-Liang Lu Java Programming 68 / 87

Example Characters can also be used as an integer type on which you can perform arithmetic operations. 13 For example, 1... 2 // A single quoted value is the char type. 3 char x = a ; 4 System.out.println(x + 1); // output 98!! 5 System.out.println((char)(x + 1)); // output b 6... Notice that a double-quoted string is a String object, totally different from char values. 13 Widely used in information security! See https://en.wikipedia.org/wiki/cryptography. Zheng-Liang Lu Java Programming 69 / 87

Boolean Values The program is supposed to do decision making by itself, for example, Google Driverless Car. 14 To do this, Java has the boolean-type flow controls (selections and iterations). Only two possible values, true and false. Note that a boolean value cannot be cast into a value of another type, nor can a value of another type be cast into a boolean value. 14 See https://www.google.com/selfdrivingcar/. Zheng-Liang Lu Java Programming 70 / 87

Rational Operators 15 These operators take two operands. Rational expressions return a boolean value. Note that the equality comparison operator is double equality sign (==), not single equality sign (=). 15 See Table 3-1 in YDL, p. 82. Zheng-Liang Lu Java Programming 71 / 87

Example 1... 2 int x = 2; 3 boolean a = x > 1; 4 boolean b = x < 1; 5 boolean c = x == 1; 6 boolean d = x!= 1; 7 boolean e = 1 < x < 3; // sorry? 8... Be aware that e is logically correct but syntactically wrong. Usually, the boolean expression consists of a combination of rational expressions. For example, 1 < x < 3 should be (1 < x)&&(x < 3), where && refers to the AND operator. Zheng-Liang Lu Java Programming 72 / 87

Logical Operators 16 16 See Table 3-2 in YDL, p. 102. Zheng-Liang Lu Java Programming 73 / 87

Truth Table Let X and Y be two Boolean variables. Then the truth table for logical operators is as follows: X Y!X X&&Y X Y X Y T T F T T F T F F F T T F T T F T T F F T F F F Note that the instructions of computers, such as arithmetic operations, are implemented by logic gates. 17 17 See any textbook for digital circuit design. Zheng-Liang Lu Java Programming 74 / 87

Logic is the anatomy of thought. John Locke (1632 1704) This sentence is false. I know that I know nothing. anonymous Plato (In Apology, Plato relates that Socrates accounts for his seeming wiser than any other person because he does not imagine that he knows what he does not know.) Zheng-Liang Lu Java Programming 75 / 87

Arithmetic Compound Assignment Operators Note that these shorthand operators are not available in languages whose level is higher than Java, say Matlab, R, and Python. Zheng-Liang Lu Java Programming 76 / 87

Example 1... 2 int x = 1; 3 System.out.println(x); // output 1 4 x = x + 1; 5 System.out.println(x); // output 2 6 x += 2; 7 System.out.println(x); // output 4 8 x++; // equivalent to x += 1 and x = x + 1 9 System.out.println(x); // output 5 10... Zheng-Liang Lu Java Programming 77 / 87

The compound assignment operators are also useful for char values. 18 For example, 1... 2 char s = a ; 3 System.out.println(s); // output a 4 s += 1; 5 System.out.println(s); // output b 6 s++; 7 System.out.println(s); // output c 8... 18 Contribution by Mr. Edward Wang (Java265) on May 1, 2016. Zheng-Liang Lu Java Programming 78 / 87

++x vs. x++ The expression ++x first increments the value of x and then returns x. Instead, the expression x++ first returns the value of x and then increments itself. For example, 1... 2 int x = 1; 3 int y = ++x; 4 System.out.println(y); // output 2; aka preincrement 5 System.out.println(x); // output 2 6 7 int w = 1; 8 int z = w++; 9 System.out.println(z); // output 1; aka postincrement 10 System.out.println(w); // output 2 11... We will use these notations very often. Zheng-Liang Lu Java Programming 79 / 87

Operator Precedence 19 19 See Table3-10 in YDL, p. 116. Zheng-Liang Lu Java Programming 80 / 87

Using Parentheses Parentheses raise the precedence of the operations that are inside them. Zheng-Liang Lu Java Programming 81 / 87

Scanner Objects It is not convenient to modify the source code and recompile it for a different radius. Reading from the console enables the program to receive an input from the user. A Scanner object provides input methods, say the input received from the user or the database. Java uses System.in to refer to the standard input device, by default, the keyboard. Zheng-Liang Lu Java Programming 82 / 87

Example: Reading Input From The Console Write a program which receives a number as input, and outputs the area of the circle. 1 import java.util.scanner; 2... 3 Scanner input = new Scanner(System.in); 4 System.out.println("Enter r?"); 5 // input 6 int r = input.nextint(); 7 // algorithm 8 double area = r r 3.14; 9 // output 10 System.out.println(area); 11 input.close(); 12... Zheng-Liang Lu Java Programming 83 / 87

In the listing, Line 3 is to create a Scanner object by the new operator, as an agent between the keyboard and your program. Note that all objects are resided in the heap of the memory. To control this object, its memory address is then assigned to the variable input which is a variable in the stack of memory. So the variable input is a reference. We will discuss the objects and reference variables later. Zheng-Liang Lu Java Programming 84 / 87

Methods Provided by Scanner Objects 20 20 See Table 2-1 in YDL, p. 38. Zheng-Liang Lu Java Programming 85 / 87

Example: Sample Mean and Sample Standard Deviation Write a program which calculates the sample mean and the sample standard deviation of 3 numbers. Sample mean of 3 numbers is given by x = ( 3 i=1 x i Also, the sample standard deviation is given by S = 3 i=1 (x i x) 2. 3 You may use these two methods: Math.pow(double x, double y) for x y Math.sqrt(double x) for x See more methods within Math class. ) /3. Zheng-Liang Lu Java Programming 86 / 87

1... 2 Scanner input = new Scanner(System.in); 3 System.out.println("a =?"); 4 double a = input.nextdouble(); 5 System.out.println("b =?"); 6 double b = input.nextdouble(); 7 System.out.println("c =?"); 8 double c = input.nextdouble(); 9 10 double mean = (a + b + c) / 3; 11 double std = Math.sqrt((Math.pow(a mean, 2) + 12 Math.pow(b mean, 2) + 13 Math.pow(c mean, 2)) / 3); 14 15 System.out.println("mean = " + mean); 16 System.out.println("std = " + std); 17... Zheng-Liang Lu Java Programming 87 / 87