chapter 4 – fundamental data types. chapter goals to understand integer and floating-point numbers...

46
Chapter 4 – Chapter 4 – Fundamental Data Fundamental Data Types Types

Upload: isabella-hart

Post on 13-Jan-2016

232 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

Chapter 4 – Chapter 4 – Fundamental Data Fundamental Data

TypesTypes

Page 2: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

Chapter GoalsChapter Goals To understand integer and floating-point To understand integer and floating-point

numbers numbers To recognize the limitations of the To recognize the limitations of the

numeric types numeric types To become aware of causes for overflow To become aware of causes for overflow

and roundoff errors and roundoff errors To understand the proper use of To understand the proper use of

constants constants To write arithmetic expressions in Java To write arithmetic expressions in Java To use the String type to define and To use the String type to define and

manipulate character strings manipulate character strings To learn how to read program input and To learn how to read program input and

produce formatted output produce formatted output

Page 3: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

4.1 Number Types4.1 Number Types

Recall: All values are either references Recall: All values are either references to objects or one of 8 primitivesto objects or one of 8 primitives

A numeric computation overflows if the A numeric computation overflows if the result falls outside the range for the result falls outside the range for the number typenumber type

int n = 1000000;int n = 1000000;System.out.println(n * n); System.out.println(n * n);

// prints -727379968 // prints -727379968

Page 4: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

PrimitivesPrimitives

So far: 6 number typesSo far: 6 number types byte, short, int, long for whole numbersbyte, short, int, long for whole numbers float, double for realsfloat, double for reals

Numbers can have overflow(value Numbers can have overflow(value too large)too large)

Reals can also have Reals can also have underflow(rounding errors)underflow(rounding errors)

double f = 4.35;double f = 4.35;

System.out.println(100 * f); System.out.println(100 * f);

// prints 434.99999999999994 // prints 434.99999999999994

Page 5: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To
Page 6: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

ConversionConversion

2 types of conversion – increase in 2 types of conversion – increase in precision, decrease in precisionprecision, decrease in precision

int+/- 2E9

double+/- 1E308

Increase in precision

Java won’t complain

Decrease in precision

Java will say it’s an error

Page 7: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

Type castingType casting

Error is because compiler wants us Error is because compiler wants us to know that we are going to to know that we are going to possibly lose informationpossibly lose information 4.0 to 4, not a big deal4.0 to 4, not a big deal 0.99 to 0, is a big deal0.99 to 0, is a big deal

To override this (i.e. tell the To override this (i.e. tell the compiler to convert anyways) we compiler to convert anyways) we must use the type cast operatormust use the type cast operator

Page 8: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

Type castingType casting

(<type>) (<type>) expressionexpression

ExampleExample

double balance = 12.45;double balance = 12.45;

int dollar = (int) balance; //stores 12int dollar = (int) balance; //stores 12

Truncates, removes fractional partTruncates, removes fractional part Can cast to any type you want Can cast to any type you want

(including objects)(including objects)

Page 9: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

RoundingRounding

What if you want to round instead of What if you want to round instead of truncate?truncate?

2 solutions:2 solutions: Hack: add 0.5 to number then truncateHack: add 0.5 to number then truncate Real solution: Use Math.round()Real solution: Use Math.round()long rounded = Math.round(balance);long rounded = Math.round(balance);

Page 10: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

4.2 Constants4.2 Constants In math, equations have variables In math, equations have variables

and constantsand constants

Constants are numbers that do not Constants are numbers that do not change but have specific meanings change but have specific meanings are importantare important

Randomly placed numbers in a Randomly placed numbers in a program can be confusing (and hard program can be confusing (and hard to change later), so we give them to change later), so we give them symbolic namessymbolic names

Page 11: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

ConstantsConstants Use a Use a constantconstant to hold the value to hold the value

Value cannot change once it is setValue cannot change once it is set

Use reserved word Use reserved word finalfinal to modify to modify declarationdeclaration final doublefinal double PI = 3.14159 PI = 3.14159

Remember Naming ConventionRemember Naming Convention USE_ALL_CAPS_WITH_UNDERSCORESUSE_ALL_CAPS_WITH_UNDERSCORES

Page 12: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

UsesUses

Constants often used for important Constants often used for important numbersnumbers

Make meaning of code easier to Make meaning of code easier to understandunderstand

Ex. Go back to Ex. Go back to BankAccountBankAccount

Want to add something to withdraw Want to add something to withdraw methodmethod

Page 13: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

public void withdraw(double amount)public void withdraw(double amount)

{{double newBalance = balance – amount - 5;double newBalance = balance – amount - 5;balance = newBalance;balance = newBalance;

}}

What is the 5 doing?What is the 5 doing?

Why is it there?Why is it there?

Page 14: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

public void withdraw(double amount)public void withdraw(double amount)

{{final int BANK_FEE = 5; final int BANK_FEE = 5;

double newBalance = balance – amount – BANK_FEE;double newBalance = balance – amount – BANK_FEE;balance = newBalance;balance = newBalance;

}}

Page 15: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

Constant FieldsConstant Fields

Often, we want to use the same Often, we want to use the same constant across several methods in a constant across several methods in a classclass

Make a constant field (class Make a constant field (class constant)constant)

Page 16: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

Constant FieldsConstant Fields

Two differencesTwo differences Make it public since we don’t have to worry Make it public since we don’t have to worry

about the value being changedabout the value being changed Add static modifier to make it part of the class, Add static modifier to make it part of the class,

so all objects of that class share it (more later)so all objects of that class share it (more later)

public class Math{public class Math{

……

public static final double E = 2.71828public static final double E = 2.71828

public static final double PI = 3.14159public static final double PI = 3.14159

……

}}

Page 17: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

public static final int BANK_FEE = 5;public static final int BANK_FEE = 5;

public void withdraw(double amount)public void withdraw(double amount)

{{

double newBalance = balance – amount – BANK_FEE;double newBalance = balance – amount – BANK_FEE;balance = newBalance;balance = newBalance;

}}

Page 18: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

Constant DefinitionConstant Definition

In a method (local constant)In a method (local constant)final final <type> <name> = <value>;<type> <name> = <value>;

final final int HOURS_IN_DAY = 24;int HOURS_IN_DAY = 24;

In a class (class constant)In a class (class constant)<accessSpecifier> static final <accessSpecifier> static final <type> <type> <name> = <value>;<name> = <value>;

public static final public static final int HOURS_IN_DAY = int HOURS_IN_DAY = 24;24;

Page 19: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

Magic NumbersMagic Numbers

So when should I use a constant?So when should I use a constant?

In general if the number has In general if the number has significance, give it a symbolic name significance, give it a symbolic name (make it a constant identifier)(make it a constant identifier)

Ex.Ex.time = duration * 60;time = duration * 60;

Is this converting minutes to seconds? Is this converting minutes to seconds? Hours to minutes?Hours to minutes?

Page 20: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

items = items + 1;items = items + 1;

Expression to right is always Expression to right is always computed firstcomputed first Add Add items + 1;items + 1;

The value of the expression is The value of the expression is assigned to the variable afterwardsassigned to the variable afterwards

4.3 Assignment, Increment, and Decrement

Page 21: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

IncrementIncrement

Net result is to Net result is to incrementincrement itemsitems by 1 by 1 Increment is so common, java uses a Increment is so common, java uses a

shorthand for itshorthand for it Increment items by oneIncrement items by one

items++; Decrement (subtract) by oneDecrement (subtract) by one

items--;

Page 22: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

Other ShortcutsOther Shortcuts

Arithmetic modifications to a Arithmetic modifications to a variable can use shorthand variable can use shorthand operationsoperations

items = items + 5; items = items + 5; items += 5; items += 5;

items = items * 2; items = items * 2; items *= 2; items *= 2;

items = items – 2*5; items = items – 2*5; items -= 2*5; items -= 2*5;

items = items / x; items = items / x; items /= x; items /= x;

Page 23: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

ModuloModulo

Returns remainder of divisionReturns remainder of division 23 % 5 = 323 % 5 = 3 4 % 2 = ?4 % 2 = ?

Mainly used for integers (possible Mainly used for integers (possible for reals also, but not as useful)for reals also, but not as useful)

Page 24: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

PrecedencePrecedence

HighHigh

Subexpressions Subexpressions ( )( )

unary operatorsunary operators - (negative)- (negative)

multiplicative operatorsmultiplicative operators *, /, %*, /, %

additive operatorsadditive operators +, -+, -

LowLow

Page 25: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

Integer DivisionInteger Division

When dividing two integers, only the whole When dividing two integers, only the whole number is returnednumber is returned Has its advantagesHas its advantages

int totalTime = 503;int totalTime = 503;

int MINUTES_PER_HOUR = 60;int MINUTES_PER_HOUR = 60;

int hours = totalTime / MINUTES_PER_HOUR;int hours = totalTime / MINUTES_PER_HOUR;

int minutes = totalTime % MINUTES_PER_HOUR;int minutes = totalTime % MINUTES_PER_HOUR;

Page 26: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

Math ClassMath Class

Provided automatically (package Provided automatically (package java.langjava.lang))

PowerPower

Math.pow(x,n)Math.pow(x,n) x xnn

SquarerootSquareroot

Math.sqrt(x)Math.sqrt(x) x x0.50.5

Page 27: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

In JavaIn Java(-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a)(-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a)

oror

(-b + Math.sqrt(Math.pow(b,2) - 4 * a * c)) / (2 * a)(-b + Math.sqrt(Math.pow(b,2) - 4 * a * c)) / (2 * a)

Page 28: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

CheckCheck

What is the value of 1729 / 100? Of What is the value of 1729 / 100? Of 1729 % 100? 1729 % 100?

Computing Average: Is this correct?Computing Average: Is this correct?

double average = s1 + s2 + s3 / 3;double average = s1 + s2 + s3 / 3;

What do we have to worry about if What do we have to worry about if s1, s2, s3s1, s2, s3 are integers? are integers?

Page 29: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

Avoid Redundant CodeAvoid Redundant Code

Important property for good Important property for good programming – never have to lines programming – never have to lines of code doing the exact same thingof code doing the exact same thing Won’t be heavily enforced, but good to Won’t be heavily enforced, but good to

get practiceget practice Inefficient – making computer do work Inefficient – making computer do work

twicetwice Error prone – when there is a bug, you Error prone – when there is a bug, you

may only fix it one placemay only fix it one place

Page 30: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

Example – Quadratic EqnExample – Quadratic Eqn

x1 = (-b + Math.sqrt(b * b – 4 * a * c)) / x1 = (-b + Math.sqrt(b * b – 4 * a * c)) / (2 * a);(2 * a);

x2 = (-b - Math.sqrt(b * b – 4 * a * c)) / x2 = (-b - Math.sqrt(b * b – 4 * a * c)) / (2 * a);(2 * a);

versusversus

double root = Math.sqrt(b * b – 4 * a * c);double root = Math.sqrt(b * b – 4 * a * c);

x1 = (-b + root) / (2 * a);x1 = (-b + root) / (2 * a);

x1 = (-b - root) / (2 * a);x1 = (-b - root) / (2 * a);

Page 31: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

4.5 Calling Static 4.5 Calling Static MethodsMethods

So far we have been discussing So far we have been discussing classes as templates and objects as classes as templates and objects as the entitiesthe entities

All the methods and instance fields All the methods and instance fields for the for the BankAccountBankAccount class belonged to class belonged to an individual objectan individual object Each had its own Each had its own balancebalance A method call was on the object itselfA method call was on the object itself

harrysChecking.getBalance()harrysChecking.getBalance() different different then then myChecking.getBalance()myChecking.getBalance()

Page 32: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

Static MethodsStatic Methods

Has everything we’ve used been an Has everything we’ve used been an object?object? SystemSystem MathMath

Both of these are classes, yet we Both of these are classes, yet we made calls on them to either fields made calls on them to either fields ((System.outSystem.out) or methods () or methods (Math.sqrt()Math.sqrt())) We never created an instance We never created an instance Math Math of of

the class or the class or SystemSystem class class

Page 33: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

Other Other Math Math Class Class

MethodsMethods

Page 34: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

Static MethodsStatic Methods

The calls on the Math class were The calls on the Math class were uniqueunique They were They were staticstatic – belonging to the – belonging to the

class, not an individual objectclass, not an individual object

In other words, these methods did In other words, these methods did not depend on an objectnot depend on an object Math.sqrt()Math.sqrt() will ALWAYS do the same will ALWAYS do the same

thing, so why create an object whenever thing, so why create an object whenever we use it?we use it?

Page 35: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

Static MethodsStatic Methods

Static methods are defined in the Static methods are defined in the classes like normal methodsclasses like normal methods

They do not operate on object, and They do not operate on object, and don’t have any internal data to deal don’t have any internal data to deal withwith

Static means the method/variable Static means the method/variable “belongs” to the class“belongs” to the class

Non-static (instance) means the Non-static (instance) means the method/variable “belongs” to the method/variable “belongs” to the objectobject

Page 36: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

SyntaxSyntax

ClassName.methodNameClassName.methodName((parametersparameters))

Example:Example:  Math.sqrt(4)Math.sqrt(4)

Purpose:Purpose:

To invoke a static method (a method To invoke a static method (a method that does not operate on an object) that does not operate on an object) and supply its parameters and supply its parameters

Page 37: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

4.6 Strings(Revisted)4.6 Strings(Revisted)

Along with numbers, the most Along with numbers, the most commonly used data type in commonly used data type in programmingprogramming Unlike numbers, Strings are objectsUnlike numbers, Strings are objects

Already learned about Already learned about length()length() methodmethod Empty String (length is 0) Empty String (length is 0) """"

Page 38: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

Number to StringNumber to String

Converting from number to String is easyConverting from number to String is easyint number = 15;int number = 15;

String strnum = "" + number;String strnum = "" + number;

How about the reverse?How about the reverse?int result = Integer.parseInt(someString);int result = Integer.parseInt(someString);

double result = Double.parseDouble(someString);double result = Double.parseDouble(someString);

Similar for all other number typesSimilar for all other number types

Page 39: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

ParsingParsing

Only works if entire string is a numberOnly works if entire string is a number

"19" "19" // Works for parseInt() & parseDouble()// Works for parseInt() & parseDouble()

"15.23""15.23" // Works for parseDouble() only// Works for parseDouble() only

"123a" "123a" // Error for both// Error for both

Page 40: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

substringsubstring

String subString()String subString() method method

String greeting = "Hello, World!";String greeting = "Hello, World!";

String sub = greeting.subString(0,5); String sub = greeting.subString(0,5);

//sub is "Hello“//sub is "Hello“

Note that the first parameter is the Note that the first parameter is the first letter you want (zero based first letter you want (zero based indexing) and the second parameter indexing) and the second parameter is the first letter you DON’T wantis the first letter you DON’T want

Page 41: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

4.7 Reading Input4.7 Reading Input

All examples so far have been pretty All examples so far have been pretty basicbasic Do not vary, we code in all values when Do not vary, we code in all values when

testingtesting

Most useful programs interact with a Most useful programs interact with a user of the terminal (computer) to user of the terminal (computer) to get data input and perform get data input and perform operations on that dataoperations on that data

Page 42: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

Output is Output is System.outSystem.out

You would think Input should then You would think Input should then be be System.inSystem.in

Exists, but not very powerfulExists, but not very powerful Takes in only one byte of information at Takes in only one byte of information at

a time, when all characters on the a time, when all characters on the keyboard are 2 bytes!keyboard are 2 bytes!

Page 43: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

ScannerScanner

Can be associated with files, but for Can be associated with files, but for now we will learn about keyboard now we will learn about keyboard inputinput

A A ScannerScanner object must be created, object must be created, associated with associated with System.in System.in as follows:as follows:

Scanner in = new Scanner(System.in);Scanner in = new Scanner(System.in);

Page 44: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

ScannerScanner

To read numbers from userTo read numbers from usernextInt(), nextDouble()nextInt(), nextDouble()

When called, these methods wait for When called, these methods wait for the user to type input and then hit the user to type input and then hit the enter key. The number inputted the enter key. The number inputted is returnedis returned Usually, the program will Usually, the program will promptprompt the the

user for information – give instructions user for information – give instructions via System.outvia System.out

Page 45: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

Get StringGet String

To get a String, useTo get a String, usenextLine()nextLine()

Allows user to type as much as they Allows user to type as much as they want. When they hit enter, all want. When they hit enter, all characters typed are returned as a characters typed are returned as a String objectString object

To read just one word (not entire To read just one word (not entire line)line)

next()next()

Page 46: Chapter 4 – Fundamental Data Types. Chapter Goals To understand integer and floating-point numbers To understand integer and floating-point numbers To

ExampleExample

ScannerScanner stdinstdin = new Scanner(System.in);= new Scanner(System.in);

System.out.print("Enter name: ");System.out.print("Enter name: ");

String name = String name = stdinstdin.nextLine();.nextLine();

System.out.print("Enter age: ");System.out.print("Enter age: ");

int age = int age = stdinstdin.nextInt();.nextInt();