chapter 4 – fundamental data types. goals gain a firm understanding of the fundamental data types...
TRANSCRIPT
Chapter 4 – Chapter 4 – Fundamental Data Fundamental Data
TypesTypes
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
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
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
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
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!
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
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)
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);
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
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
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
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?
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
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
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
……
}}
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
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;
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?
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
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
ExampleExample
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
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
Increment OperatorIncrement Operator
items = items + 1;items = items + 1;
Postincrement:Postincrement:items++;items++;
Preincrement:Preincrement:++items;++items;
Decrement OperatorDecrement Operator
items = items - 1;items = items - 1;
Postdecrement:Postdecrement:items--;items--;
Predecrement:Predecrement:--items;--items;
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;
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
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
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 = ?
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 = ?
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;
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)
PrecedencePrecedence
HighHigh
subexpressions subexpressions ( )( )
unary operatorsunary operators -, +-, +
multiplicative operatorsmultiplicative operators *, /, %*, /, %
additive operatorsadditive operators +, -+, -
LowLow
PrecedencePrecedence
Parenthesis take precedenceParenthesis take precedence
(a + b) / 2(a + b) / 2 different than different than a + b /2a + b /2
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
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)
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)
In JavaIn Java(-b + Math.sqrt(b *b -4 (-b + Math.sqrt(b *b -4
*a * c)) / (2 * a)*a * c)) / (2 * a)
PrecedencePrecedence
Math Math ClassClass
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?
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
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
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);
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()
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
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?
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
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
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
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
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
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"
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);
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
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
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
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
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!
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();
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);
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
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()
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();
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?
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
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””);
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
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
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!