Chapter 4 Numeric Types.

Slides:



Advertisements
Similar presentations
L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
Advertisements

Types and Arithmetic Operators
Dale/Weems/Headington
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
1 Chapter 3 Arithmetic Expressions. 2 Chapter 3 Topics l Overview of Java Data Types l Numeric Data Types l Declarations for Numeric Expressions l Simple.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3: Numeric Data *Variables *Numeric data.
Aalborg Media Lab 21-Jun-15 Software Design Lecture 2 “ Data and Expressions”
Program Elements We can now examine the core elements of programming (as implemented in Java) We focuse on: data types variable declaration and use, constants.
ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
Chapter 3 Numerical Data. Topics Variables Numeric data types Assignment Expressions.
1 Chapter 3 Topics Constants of Type int and float l Evaluating Arithmetic Expressions l Implicit Type Coercion and Explicit Type Conversion l Calling.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Expressions An expression is a sequence of operands and operators that reduces to a single value expression operator operand An operator is a language-specific.
JavaScript, Third Edition
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
Data Types, Expressions and Functions (part I)
Performing Computations C provides operators that can be applied to calculate expressions: example: tax is 8.5% of the total sale expression: tax =
What is a variable?  A variable holds data in memory so the program may use that data, or store results.  Variables have a data type. int, boolean, char,
1 Chapter Two Using Data. 2 Objectives Learn about variable types and how to declare variables Learn how to display variable values Learn about the integral.
Expressions, Data Conversion, and Input
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
***** SWTJC STEM ***** Chapter 2-3 cg 29 Java Operators Recall Java’s programming components: Packages - Collection of classes (Programs) Classes - Collections.
 Value, Variable and Data Type  Type Conversion  Arithmetic Expression Evaluation  Scope of variable.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
1 Numeric Types, Expressions, and Output. 2 Chapter 3 Topics  Constants of Type int and float  Evaluating Arithmetic Expressions  Declaration for Numeric.
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
Numeric Types, Expressions, and Output ROBERT REAVES.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
CNG 140 C Programming Lecture Notes 2 Processing and Interactive Input Spring 2007.
A First Book of ANSI C Fourth Edition Chapter 3 Processing and Interactive Input.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
CH2 – Using Data. Constant Something which cannot be changed Data Type Format and size of a data item Intrinsic Data Types Pg. 47 – Table 2-1 Basic ones.
Chapter 2: Using Data.
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
CHAPTER 4 GC 101 Data types. DATA TYPES  For all data, assign a name (identifier) and a data type  Data type tells compiler:  How much memory to allocate.
Chapter 3 Arithmetic Expressions, Function Calls, and Output
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
COMP Primitive and Class Types Yi Hong May 14, 2015.
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
4. EXPRESSIONS. Display the value of pi, to 5 decimal places, right justified, in 9 columns Read in someone’s height in feet and inches using.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Lecture 5: Expressions and Interactivity Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Chapter 3 The New Math. C++ Data Types simple integral charshort intlong bool floating float double Long double enum address pointer reference structured.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
Expressions Version Topics Arithmetic expressions Conversions Operator precedence String class 2.
1 Lecture Three I/O Formatting and Arithmetic Dr. Sherif Mohamed Tawfik.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Chapter 2 Elementary Programming
Lecture 3: Operators, Expressions and Type Conversion
Multiple variables can be created in one declaration
Java Programming: From Problem Analysis to Program Design, 4e
Lecture 3 Expressions Richard Gesick.
Numerical Data Types.
Chapter 2: Basic Elements of Java
Chapter 3 The New Math.
Presentation transcript:

Chapter 4 Numeric Types

Knowledge Goals Discover why different numeric types have different ranges of values Understand the differences between integral and floating-point types See how precedence rules affect the order of evaluation in an expression Understand implicit type conversion and explicit type casting

Knowledge Goals Be able to use additional operations associated with the String class Understand how value-return methods work with numeric types

Skill Goals Declare named constants and variables of types int and double Construct simple arithmetic expressions Evaluate simple arithmetic expressions Construct and evaluate expressions that include multiple arithmetic operations Read numeric values using the methods in class Scanner

Skill Goals Use java math methods in expressions Format the statements in a class in a clear and readable fashion

Numeric Data Types

Numeric Data Types Integral Types can represent whole numbers and their negatives when declared as byte, short, int, or long can represent single characters when declared as char Floating-Point Types represent real numbers with a decimal point declared as float or double

Numeric Data Types Sizes of Integral Types byte 8 bits short 16 bits int 32 bits long 64 bits

Numeric Data Types Range of Integral Types byte 8 -128 127 Type Size in Bits Minimum Value to Maximum Value 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 to +9,223,372,036,854,775,807

Numeric Data Types 1 byte = 8 bits 0 1 1 0 0 0 1 1 0 1 1 0 0 0 1 1 How many different numbers can be represented in one byte using 0’s and 1’s? Each bit can hold either a 0 or a 1. So there are just two choices for each bit, and there are 8 bits. 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 = 28 = 256

Numeric Data Types How many numbers can be represented in 2 bytes? 0 1 0 0 1 0 1 0 0 1 1 0 0 0 1 1 216 = 65536 If we have only one number representing the integer zero, and half of the remaining numbers positive, and half negative, we can obtain the 65,536 numbers in the range -32768 . . . . 0 . . . . 32767

Numeric Data Types 27000.0 2.7E-4 means 2.7 x 10 - 4 = Scientific Notation 2.7E4 means 2.7 x 10 4 = 2.7000 = 27000.0 2.7E-4 means 2.7 x 10 - 4 = 0002.7 = 0.00027

Numeric Data Types Floating-point Types Numbers with an integer part and a fractional part, with a decimal point in between; either the integer part or the fractional part may be missing but not both 18.4 500. .8 -127.358 Scientific notation is also ok 1.84E1 5E2 8E-1 -.127358E3

Numeric Data Types Floating-point size and range Type Size in Bits Range of Values float 32 +1.4E - 45 to +3.4028235E+38 double 64 +4.9E - 324 to +1.7976931348623157E+308

Numeric Data Types Literal numeric values in Java Literal Type 0 int 0L long 2007 int 18005551212L long 18005551212 invalid (too long) 0.0 double 0.0f float 2.001E3 double 2.001E3F float 1.8E225F invalid (exponent too large)

Numeric Declarations Named constant declaration final double PI = 3.14159; final String HOME = “Texas”; final int TEXAS_TEMP = 95; Variable declaration double taxIncreae; char initial; int dailyTemp;

Arithmetic Expressions A valid arrangement of variables, constants, operators and parentheses An expression can be evaluated to compute a value of a given type The value of the expression 9.3 * 4.5 is 41.85

Arithmetic Expressions Arithmetic Operators + Unary plus - Unary minus + Addition - Subtraction * Multiplication / Division % Modulus Division and Modulus need more explanation

Arithmetic Expressions Division (/) The result of the division operator depends on the type of its operands If one or both operands has a floating type, the result is a floating-point type (float or double); otherwise, the result is an integral type 11 / 4 has value 2 11.0 / 4.0 has value 2.75 11 / 4.0 has value 2.75 11 / 0 invalid (cannot divide by 0) 11.0 / 0 has value infinity

Arithmetic Expressions Modulus (%) When used with integer type operands, the % operator returns the remainder from integer division; with floating-point operands, it returns the remainder after dividing the dividend by the divisor a whole number of times 11 % 4 has value 3 9 % 3 has value 0 3 % 5 has value 3 5 % 0 invalid (cannot divide by 0) 6.0%4.2 has value 0.12 6.0%0.0 has value not a number (NaN)

Arithmetic Expressions Remember the Scanner class? Scanner in = new Scanner(System.in); String line = in.nextLine(); int nextInt() Returns next token as an int long nextLong() Returns next token as a long float nextFloat() Returns next token as a float String next() Returns next token as a string Inputs next line What happens if the next token is not a number?

Arithmetic Expressions Exception An unusual condition in execution of Java code control is transferred to statements designed to handle the condition exception is thrown when the condition is detected exception is caught by the handling code

Arithmetic Exceptions Checked exceptions An exception in Java that must either be caught with a catch statement or explicitly thrown to the next level Unchecked exception An exception in Java that can optionally be caught or allowed to propagate automatically to the next level InputMismatchException is unchecked More on exceptions in Chapter 6

Arithmetic Expressions int number = in.nextInt(); float real = in.nextFloat(); long number2 = in.nextLong(); double real2 = in.nextDouble(); String string = in.next(); String string2 = in.next(); Data 33 12 333 44.22 End 3.13158 What is stored in number, real, number2, real2, string, string2 ?

Arithmetic Expressions int number = in.nextInt(); float real = in.nextFloat(); long number2 = in.nextLong(); double real2 = in.nextDouble(); String string = in.nextLine(); String string2 = in.nextLine(); Data 33 12 333 44.22 End 3.13158 Now, what is stored in number, real, number2, real2, string, string2 ?

Arithmetic Expressions String string = in.nextLine(); nextLine() returns the rest of the line Arithmetic reads do not consume the separator Thus, nextLine() following an arithmetic read returns the separator, the empty string if the arithmetic value was the last value on a line How can you solve the problem?

Arithmetic Expressions Java prefix increment operator: ++ int age; age = 8; ++age; 8 age 9 age

Arithmetic Expressions Java postfix increment operator: ++ int age; age = 8; age++; 8 age 9 age

Arithmetic Expressions Java prefix decrement operator: -- int dogs; dogs = 100; --dogs; 100 dogs 99 dogs

Arithmetic Expressions Java postfix decrement operator: -- int dogs; dogs = 100; dogs--; 100 dogs 99 dogs

Arithmetic Expressions Which form to use? When the increment (or decrement) operator is used in a “stand alone” statement solely to add one (or subtract one) from a variable’s value, it can be used in either prefix or postfix form USE EITHER dogs--; --dogs;

Compound Arithmetic Expressions Precedence Rules that determine which operator is applied first in an expression having several operators

Compound Arithmetic Expressions Operator Precedence Highest ( ) (operations within parentheses) ++ -- (postfix increment and decrement) ++ -- (prefix increment and decrement) + - (unary plus and minus) * / % (multiplication, division, modulus) Lowest + - (addition and subtraction) Can you see why increment and decrement operators might be problems in compound expressions?

Compound Arithmetic Expressions Left-to-right associativity In an expression having two operators with the same priority, the left operator is applied first In Java, the binary operators * , / , % , + , - are all left associative Expression 9 - 5 - 1 means (9 - 5) - 1 4 - 1 3

Evaluate the Expression 7 * 10 - 5 % 3 * 4 + 9 (7 * 10) - 5 % 3 * 4 + 9 70 - 5 % 3 * 4 + 9 70 - (5 % 3) * 4 + 9 70 - 2 * 4 + 9 70 - (2 * 4) + 9 70 - 8 + 9 (70 - 8) + 9 62 + 9 71

Parentheses Use parentheses to change the usual order Parts in () are evaluated first Evaluate (7 * (10 - 5) % 3) * 4 + 9 (7 * 5 % 3) * 4 + 9 (35 % 3) * 4 + 9 2 * 4 + 9 8 + 9 17

Compound Arithmetic Expressions But… When the increment (or decrement) operator is used in a statement with other operators, the prefix and postfix forms can yield different results Prefix Increment (or decrement) then use Postfix Use then increment (or decrement)

Compound Arithmetic Expressions int alpha; int num; num = 13; alpha = ++num * 3; What is alpha? alphs = num++ * 3; Did you foresee this problem from the precedence table ?

Compound Arithmetic Expressions Type conversion The implicit (automatic) conversion of a value from one data type to another Widening conversion One that does not result in a loss of information Narrowing conversion One that may result in a loss of information How do type conversions happen?

Compound Arithmetic Expressions Given int someInt; double someDouble; float someFloat; What happens in these cases? someDouble = 12; someInt = 4.5; someFloat = someDouble; someFloat = someInt * 3.5 + 4;

Compound Arithmetic Expressions Type casting The explicit conversion of a value from one data type to another (data type name) Expression someDouble = (double)12; someInt = (int)4.5; someFloat = (float)someDouble; someFloat = (float)someInt * 3.5 + (float)4;

Compound Arithmetic Expressions What values are stored? double loCost; double hiCost; loCost = 12.342; hiCost = 12.348; loCost = (double) ((int) (loCost * 100.0 + 0.5)) / 100.0; hiCost = (double) ((int) (hiCost * 100.0 + 0.5))

Compound Arithmetic Expressions What is the difference between these statements? String answer = "The results are: " + 27 + 9; and String answer = 27 + 9 + " The results are:"; Conversion from number to string occurs only with the concatenation operator

Compound Arithmetic Expressions What about converting from string to a numeric value? We instantiate a Scanner object with the string and use the Scanner input methods Scanner in = new Scanner("43 55.0"); int one = in.nextInt(); float two = in.nextFloat(); Scanner in = new Scanner(in.nextLine()) …

Value-Returning Methods Additional methods of class String Method length returns an int value that is the number of characters in the string String name = “Donald Duck”; numChars; numChars = name.length(); instance method What is returned ?

Value-Returning Methods Method indexOf searches a string to find a particular substring, and returns an int value that is the beginning position for the first occurrence of that substring within the string String stateName = “Mississippi”; int index; index = stateName.indexOf("is"); What is returned? (Remember the first position is 0 not 1) What is returned if the substring isn't there?

Value-Returning Methods Method charAt returns the character at a specified position within the string String stateName = “Mississippi”; char letter; letter = stateName.charAt(5); What is returned?

Value-Returning Methods Method substring returns a substring of a string, but does not change the string itself The first parameter specifies a starting position within the string The second parameter specifies the last position plus one String stateName = “Mississippi”; String substring; substring = stateName.substring(9, 11); What is returned?

Value-Returning Methods Method trim returns a copy of a string with all whitespace characters removed from either end String myString = " Good morning Susy Sunshine "; System.out.println(myString.length()); System.out.println(myString.trim().length()); What is printed?

Value-Returning Methods Class Math provides a collection of useful value-returning methods for common numeric functions Math.abs(x) returns the absolute value of X Math.cos(x) returns the cosine of X Math.sqrt(x) returns the square root of X Math.random()returns a random number between 0 and 1 … Why is Math uppercase?

Class Time Designing a class to represent time Immediately we have an ambiguous situation: Time of day with hours, minutes, and seconds Elapsed time where seconds only is appropriate Here we mean elapsed time, so our only attribute is seconds of type double

Class Time Constructors public Time() // default { seconds = 0.0; } public Time(double newSeconds) { seconds = newSeconds; } public Time(int hours, int minutes, double new Seconds) { seonds = (double)(hours*3600 + minutes * 60) + newSeconds; }

Class Time Observers public double getTime() { return seconds; } public int getHours() { return (int) seconds/3600; } public int getSeconds() { return seconds % 60.0) } getMinutes is more difficult…

Class Time We must remove hours before we can calculate minutes public int getMinutes() { int remainingSeconds = (int) seconds % 3600; return remainingSeconds/60; } 5463 seconds is 1 hours, 31 minutes, and 3 second Prove it to yourself

Why is a toString method useful? Class Time Other operations public String toString() { int hours = (int) sconds / 3600; int minutes = (int) seconds % 3600 / 60; return hours + ":" + minutes + ":" + seconds%60; } Why is a toString method useful?

Class Time Binary operation Time myTime(300); Time yourTime(200); Time ourTime = myTime.plus(yourTime); public Time plus(Time otherTime) { return (new Time(seconds + otherTime.seconds);) } 300 200 What are seconds and otherTime.seconds here? Time ourTime = yourTime.plus(myTime);

Class Time No class is complete until it is tested Test plan A document that specifies how a class is to be tested Test plan implementation Writing and running a driver that implements the test cases specified in a test plan to verify that the class methods produce the predicted results

Class Time Test Plan

Class Time Implemented test plan

Extras I designed both the Difference Engine and the Analytical Engine in the 1800s Who am I?

Extras - GUI Track Dialog box A small temporary panel that appears on the screen, with which user can interact