chapter 4 – fundamental data types. goals gain a firm understanding of the fundamental data types...

75
Chapter 4 – Chapter 4 – Fundamental Data Fundamental Data Types Types

Upload: hugo-davis

Post on 17-Jan-2016

227 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

Chapter 4 – Chapter 4 – Fundamental Data Fundamental Data

TypesTypes

Page 2: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

GoalsGoals

Gain a firm understanding of the Gain a firm understanding of the fundamental data types and their fundamental data types and their properties and limitationsproperties and limitations

Understanding stringsUnderstanding strings Dealing with user input, and Dealing with user input, and

program outputprogram output

Page 3: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

Number TypesNumber Types

All values are either references to objects All values are either references to objects or one of 8 primitivesor one of 8 primitives

A numeric computation A numeric computation overflowsoverflows if the 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. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

PrimitivesPrimitives

So far we’ve seen 6 number typesSo far we’ve seen 6 number types byte, short, int, longbyte, short, int, long for whole numbers for whole numbers float, doublefloat, double for reals for reals

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

Reals can also have Reals can also have underflow underflow (rounding (rounding errors)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. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding
Page 6: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

ConversionConversion

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

Increase in precision(Increase in precision(int int to to longlong, , bytebyte to to floatfloat)) More memory being usedMore memory being used Allowed in Java – Java does this Allowed in Java – Java does this automaticallyautomatically Ex. Ex. int dollars = 100;int dollars = 100;

double balance = dollars; //OKdouble balance = dollars; //OK

Page 7: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

ConversoinConversoin

Decrease in precisionDecrease in precision Representing a number with less Representing a number with less

memorymemory Error in Java – the compiler will yell at Error in Java – the compiler will yell at

youyou Example:Example:double balance = 13.75;double balance = 13.75;

int dollars = balance; //ERROR!int dollars = balance; //ERROR!

Page 8: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

Type CastingType Casting

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

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

Page 9: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

Type Casting: SyntaxType Casting: Syntax

(<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 part) Truncates (removes fractional part) when going from real (ie when going from real (ie doubledouble) to whole ) to whole number (ie number (ie intint)) Can cast to any type you want (including Can cast to any type you want (including

objects)objects)

Page 10: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

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 11: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

ConstantsConstants In math, equations have variables and In math, equations have variables and

constantsconstants

In programming, the sameIn programming, the same Already learned about variablesAlready learned about variables Numbers that do change but have specific Numbers that do change but have specific

meanings are importantmeanings are important

Randomly placed numbers in a program Randomly placed numbers in a program can be confusing, so we give them can be confusing, so we give them symbolic namessymbolic names

Page 12: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

ConstantsConstants

Use a Use a constantconstant to hold the value to hold the value Can’t change after assigned when Can’t change after assigned when

declareddeclared

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

Naming Convention for constantsNaming Convention for constants USE_ALL_CAPS_WITH_UNDERSCORESUSE_ALL_CAPS_WITH_UNDERSCORES

Page 13: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

ConstantsConstants

Constants often used for important Constants often used for important numbersnumbers

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

Make changes to code a lot easierMake changes to code a lot easier

Page 14: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

Constants: ExampleConstants: Example

public double getPay ()public double getPay ()

{{double pay = numHours * 6.70;double pay = numHours * 6.70;return pay;return pay;

}}

What is 6.70 doing?What is 6.70 doing?

Why is it there?Why is it there?

Page 15: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

Constants: ExampleConstants: Example

public double getPay ()public double getPay (){{

final int PAY_RATE = 6.70;final int PAY_RATE = 6.70;double pay = numHours * PAY_RATE;double pay = numHours * PAY_RATE;return pay;return pay;

}}

Much easier to understand now when Much easier to understand now when reading the codereading the code

Much easier to change now as wellMuch easier to change now as well

Page 16: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

Class ConstantsClass Constants

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

To do this, make a constant instance To do this, make a constant instance fieldfield

Page 17: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

Class ConstantsClass Constants

Differences in the declarationDifferences in the declaration Make it Make it publicpublic since we don’t have to worry since we don’t have to worry

about the value being changedabout the value being changed Add Add staticstatic modifier to make it part of the modifier to make it part of the

class, so all objects of that class share it (more class, so all objects of that class share it (more on this later)on this 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 18: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

Class ConstantsClass Constants

One copy of the variable (static)One copy of the variable (static)

Available to all classes (public)Available to all classes (public)

Example: You have a class where Example: You have a class where you want to calculate circumferenceyou want to calculate circumferencedouble circumference = Math.PI * diameterdouble circumference = Math.PI * diameter

Page 19: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

Constant DefinitionConstant Definition

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

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 20: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding
Page 21: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding
Page 22: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding
Page 23: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

ConstantsConstants

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)

ExampleExampletime = duration * 60;time = duration * 60;

Is this converting minutes to Is this converting minutes to seconds or hours to minutes?seconds or hours to minutes?

Page 24: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

Assignment, Increment, Assignment, Increment, and Decrementand Decrement

= is the assignment operator= is the assignment operator On the left, place the variableOn the left, place the variable On the right, place the expression/valueOn the right, place the expression/value

Not an equality sign!!!Not an equality sign!!!

Action is to copy the right side to the Action is to copy the right side to the variable on the left sidevariable on the left side

Page 25: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

Interesting twists on =Interesting twists on =

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

Page 26: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

ExampleExample

Page 27: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

ExampleExample

int items = 1;int items = 1;

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

Do right side first Do right side first 2 2

Assign to items Assign to items items = 2items = 2

Page 28: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

Increment OperatorIncrement Operator

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

++ operator increases the value of a ++ operator increases the value of a variable by onevariable by one

Page 29: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

Increment OperatorIncrement Operator

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

Postincrement:Postincrement:items++;items++;

Preincrement:Preincrement:++items;++items;

Page 30: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

Decrement OperatorDecrement Operator

items = items - 1;items = items - 1;

Postdecrement:Postdecrement:items--;items--;

Predecrement:Predecrement:--items;--items;

Page 31: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

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;

Page 32: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

ArithmeticArithmetic Already seen some symbols, here are allAlready seen some symbols, here are all

OperatorsOperators – mathematical operations – mathematical operations

++ additionaddition

-- SubtractionSubtraction

** MultiplicationMultiplication

// DivisionDivision

%% Modulo (Remainder)Modulo (Remainder)

OperandsOperands – the values to which the – the values to which the operator is appliedoperator is applied

Page 33: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

ExamplesExamples

int x = 3 + 5;int x = 3 + 5; // 8// 8

x = 10/2;x = 10/2; // 5// 5

x = 10 * 3 – 4;x = 10 * 3 – 4; // 26// 26

x = 12 % 5x = 12 % 5 ;; // 2// 2

Page 34: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

DivisionDivision

Returns quotientReturns quotient When both operands are integers, an When both operands are integers, an

integer is returnedinteger is returned x = 10/2 … x = ?x = 10/2 … x = ? y = 6/3 … y = ?y = 6/3 … y = ?

When either or both operands are When either or both operands are real, a real is returnedreal, a real is returned z = 2.5/0.5 … z = ?z = 2.5/0.5 … z = ?

Page 35: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

Integer DivisionInteger Division

When dividing two integers, only the When dividing two integers, only the whole numberwhole number is returned is returned

Examples:Examples:

6/4 = ?6/4 = ?

1/5 = ?1/5 = ?

-3/4 = ?-3/4 = ?

6/3 = ?6/3 = ?

Page 36: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

Integer DivisionInteger Division

Why does Java do this?Why does Java do this? Easier for the computerEasier for the computer Has it’s advantages:Has it’s 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 37: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

Modulo OperatorModulo Operator

Returns remainderReturns remainder 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 38: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

PrecedencePrecedence

HighHigh

subexpressions subexpressions ( )( )

unary operatorsunary operators -, +-, +

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

additive operatorsadditive operators +, -+, -

LowLow

Page 39: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

PrecedencePrecedence

Parenthesis take precedenceParenthesis take precedence

(a + b) / 2(a + b) / 2 different than different than a + b /2a + b /2

Page 40: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

Math ClassMath Class

Provided automatically (it’s in the Provided automatically (it’s in the java.lang java.lang

package)package)

ExponentiationExponentiation

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

Square RootsSquare Roots

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

Page 41: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

Math ClassMath Class Translating expressions from Translating expressions from

mathematics to Java is a little differentmathematics to Java is a little different

Java has no exponents, symbols, or Java has no exponents, symbols, or fraction bars so we can’t writefraction bars so we can’t write 6^36^3 √√55

Quadratic EquationQuadratic Equation (-b + Math.sqrt(b * b -4 * a * c)) / (2 (-b + Math.sqrt(b * b -4 * a * c)) / (2

* a)* a)

Page 42: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

Math ClassMath Class

In mathematical notation:In mathematical notation:

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

Page 43: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

In JavaIn Java(-b + Math.sqrt(b *b -4 (-b + Math.sqrt(b *b -4

*a * c)) / (2 * a)*a * c)) / (2 * a)

Page 44: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

PrecedencePrecedence

Page 45: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

Math Math ClassClass

Page 46: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

QuestionsQuestions

What is the value of What is the value of 1729 / 100?1729 / 100? 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 if What if s1, s2, s3s1, s2, s3 are integers? are integers?

Page 47: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

StyleStyle

White space inside equations can go a White space inside equations can go a far way – placing spaces before and far way – placing spaces before and after arithmetic symbols is very helpfulafter arithmetic symbols is very helpful

White space can also be helpful to White space can also be helpful to group codegroup code i.e. have 5 lines for calculating some i.e. have 5 lines for calculating some

information, then a blank line followed by information, then a blank line followed by a series of outputa series of output

Page 48: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

StyleStyle

Important property for good Important property for good programming – never have two lines programming – never have two 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 49: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

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);

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);

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

Page 50: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

Static MethodsStatic Methods

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 PathPath class belonged to an class belonged to an individual objectindividual object Each had its own Each had its own xDistance, yDistancexDistance, yDistance

A method call was on the object itselfA method call was on the object itself p.getX()p.getX() different then different then q.getX()q.getX()

Page 51: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

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 made Both of these are classes, yet we made calls on them to either fields (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 the of the

class or class or SystemSystem class class

Page 52: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

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 class, – belonging to the class,

not an individual objectnot an individual object

In other words, these methods did not In other words, these methods did not depend on an objectdepend 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 53: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

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, They do not operate on object, thoughthough Don’t have any internal data to deal Don’t have any internal data to deal

withwith

Page 54: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

Static Methods: SyntaxStatic Methods: Syntax

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 55: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

Static MethodsStatic Methods

How can we tell if methods are How can we tell if methods are static?static? Java follows conventions: for example, Java follows conventions: for example, MathMath is capitalized, so we know it’s a is capitalized, so we know it’s a classclass

Look at javadocs - static methods will Look at javadocs - static methods will be listed with the static modifierbe listed with the static modifier

Page 56: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

StringsStrings

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 Unlike numbers, Strings are objectsobjects

Already learned about Already learned about length()length() method method String str = “four”;String str = “four”; System.out.println(str.length())System.out.println(str.length()) 4 4 “” “” is the is the empty stringempty string

Page 57: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

StringsStrings

Strings are sequences of charactersStrings are sequences of characters Each character is stored at an Each character is stored at an indexindex

of the stringof the string Indexing begins at 0!Indexing begins at 0! The The charAtcharAt method returns the method returns the

character at the specified indexcharacter at the specified index

D o n n a

0 1 2 3 4

Page 58: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

ConcatenationConcatenation Putting strings togetherPutting strings together

If If eithereither left or right side is a String, the left or right side is a String, the result is String (no matter what the other result is String (no matter what the other side is)side is)

Works Works left to rightleft to right

How does Java interpret: How does Java interpret: A + B + CA + B + C"A" + "B" + "C""A" + "B" + "C"1 + 2 + 31 + 2 + 3"1" + 2 + 3"1" + 2 + 3"(1+2+3)""(1+2+3)"1 + 2 + "3"1 + 2 + "3"

Page 59: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

ConcatenationConcatenation

Concatenation is useful for Concatenation is useful for outputting resultsoutputting results

System.out.print(“My age is ”);System.out.print(“My age is ”);System.out.println(age);System.out.println(age);

vs.vs.

System.out.println(“My age is ” + age);System.out.println(“My age is ” + age);

Page 60: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

Number to String Number to String ConversionConversion

Converting from a number to String is Converting from a number to String is easyeasyint number = 15;int number = 15;

String string = "" + number;String string = "" + 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 61: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

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 62: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

StringsStrings

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 63: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

Reading InputReading 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 to get data input and perform user to get data input and perform operations on that dataoperations on that data

Page 64: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

Reading InputReading Input

Output uses the Output uses the System.out System.out objectobject

You would think input should then You would think input should then use use 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 65: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

Reading InputReading Input

Input used to be a pain in Java Input used to be a pain in Java (relatively speaking)(relatively speaking)BufferedReader buf = new BufferedReader buf = new BufferedReader( new BufferedReader( new InputStreamReader(System.in));InputStreamReader(System.in));

int a = Integer.parseInt(buf.readLine());int a = Integer.parseInt(buf.readLine());

Java 5.0 now includes a Java 5.0 now includes a Scanner Scanner classclass Easily connect to keyboard to get inputEasily connect to keyboard to get inputScanner stdin = new Scanner(System.in);Scanner stdin = new Scanner(System.in);int a = stdin.nextInt();int a = stdin.nextInt();

Page 66: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

Reading InputReading Input

Scanner can be associated with files, Scanner can be associated with files, but for now we will learn about but for now we will learn about keyboard inputkeyboard input

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

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

Page 67: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

Reading InputReading Input

To read numbers from user, use the To read numbers from user, use the methodsmethods

nextInt(), nextDouble()nextInt(), nextDouble()

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

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

Page 68: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

Reading InputReading Input

To get a String, use To get a String, use nextLine()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 StringString object object

To read just one word (not entire To read just one word (not entire line), use line), use next()next()

Page 69: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

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();

Page 70: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

CharactersCharacters

char char stores one character (one letter stores one character (one letter or one digit or one symbol)or one digit or one symbol)

Computer thinks of everything as Computer thinks of everything as numbers including charactersnumbers including characters

‘‘0’0’ (48) + (48) + ‘A’‘A’ (65) is equal to (65) is equal to ‘q’‘q’ (113)(113)

How do we know what numbers How do we know what numbers different characters correspond to?different characters correspond to?

Page 71: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

CharactersCharacters

Encodings: specify what number a Encodings: specify what number a character ischaracter is ASCII – basic 128 charactersASCII – basic 128 characters

Stores only English letters, digits, and a few Stores only English letters, digits, and a few symbolssymbols

Unicode – every symbol used on computersUnicode – every symbol used on computers Stores accented characters, Chinese characters, Stores accented characters, Chinese characters,

Greek letters, etcGreek letters, etc ASCII is a ASCII is a subsetsubset of Unicode of Unicode Java uses Unicode, but we’re really only Java uses Unicode, but we’re really only

concerned with ASCII in this courseconcerned with ASCII in this course

Page 72: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

Escape SequencesEscape Sequences

Backslashs signal Backslashs signal escape escape sequencessequences

Suppose you wanted to printSuppose you wanted to printHe said, “We need more cows”He said, “We need more cows”

What’s the problem withWhat’s the problem withSystem.out.println(System.out.println(

““He said, “We need more cows””);He said, “We need more cows””);

Page 73: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

Escape SequencesEscape Sequences

Solution:Solution:System.out.println(System.out.println(

““He said, \“We need more cows\””);He said, \“We need more cows\””);

Other useful escape sequences:Other useful escape sequences: \n\n new linenew line \t\t tabtab \’\’ single quotesingle quote

Page 74: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

Formatting NumbersFormatting Numbers

println()println() will print out all available will print out all available digits for a real numberdigits for a real number

To change, new method To change, new method printf()printf() is is available in the available in the PrintStreamPrintStream class class ((System.outSystem.out))

System.out.printf(“Total:%5.2f”, total);System.out.printf(“Total:%5.2f”, total);

Used in other programming languagesUsed in other programming languages

Page 75: Chapter 4 – Fundamental Data Types. Goals Gain a firm understanding of the fundamental data types and their properties and limitations Gain a firm understanding

Productivity HintProductivity Hint

Those error messages you get for Those error messages you get for runtime errors can actually be your runtime errors can actually be your friend!friend!

Provide two pieces of informationProvide two pieces of information The error (interpreting will be easier The error (interpreting will be easier

later in the semester)later in the semester) More importantly: The line of the error!More importantly: The line of the error!