Primitive Data types - PowerPoint PPT Presentation

1 / 98
About This Presentation
Title:

Primitive Data types

Description:

A named location to store data. a container for data. It ... associates a name with a storage location in memory and. specifies the type of data it will store: ... – PowerPoint PPT presentation

Number of Views:50
Avg rating:3.0/5.0
Slides: 99
Provided by: lew122
Category:
Tags: data | primitive | types

less

Transcript and Presenter's Notes

Title: Primitive Data types


1
Chapter 2
Primitive Types and Simple I/O
  • Primitive Data types
  • Comments
  • Variables, Tokens, identifiers, Literals
  • Strings a class
  • Assignment
  • Expressions
  • Java Input and Output

2
Structure
  • Java Program Structure
  • A program is made up of one or more classes
  • A class contains one or more methods
  • A method contains program statements
  • A Java application always executes the main
    method

3
White Spaces
  • White Space
  • Spaces, blank lines, and tabs are collectively
    called white space and are used to separate words
    and symbols in a program
  • Extra white space is ignored
  • A valid Java program can be formatted many
    different ways
  • Programs should be formatted to enhance
    readability, using consistent indentation

4
Comments
  • Comments are an important part of every program.
  • They provide information thats useful for anyone
    who will need to read the program in the future.
  • Typical uses of comments
  • To document who wrote the program, when it was
    written, what changes have been made to it, and
    so on.
  • To describe the behavior or purpose of a
    particular part of the program, such as a
    variable or method.
  • To describe how a particular task was
    accomplished, which algorithms were used, or what
    tricks were employed to get the program to work.

5
Types of Comments
  • Single-line comments
  • // Comment style 1
  • Multiline comments
  • / Comment style 2 /
  • Doc comments
  • / Comment style 3 /
  • Doc comments are designed to be extracted by a
    special program, javadoc.

6
Problems with Multiline Comments
  • Forgetting to terminate a multiline comment may
    cause the compiler to ignore part of a program
  • System.out.print("My ") / forgot to close
    this comment...
  • System.out.print("cat ")
  • System.out.print("has ") / so it ends here /
  • System.out.println("fleas")

7
Single line comment
  • Many programmers prefer // comments to / /
    comments, for several reasons
  • Ease of use
  • Safety
  • Program readability
  • Ability to comment out portions of a program

8
Tokens
  • A Java compiler groups the characters in a
    program into tokens.
  • The compiler then puts the tokens into larger
    groups (such as statements, methods, and
    classes).
  • Tokens in the JavaRules program
  • public class JavaRules public static void
    main (
  • String args ) System . out .
    println (
  • "Java rules!" )

9
What is a program variable?
  • A named location to store data
  • a container for data
  • It can hold only one type of data
  • for example only integers, only floating point
    (real) numbers, or only characters

10
Creating Variables
  • All program variables must be declared before
    using them
  • A variable declaration
  • associates a name with a storage location in
    memory and
  • specifies the type of data it will store
  • Type Variable_1, Variable_2,
  • For example, to create three integer variables to
    store
  • number of baskets,
  • number of eggs per basket, and
  • total number of eggs
  • int numberOfBaskets, eggsPerBasket, totalEggs

11
Declaring Variables
  • Form of a variable declaration
  • The type of the variable
  • The name of the variable
  • A semicolon
  • Example
  • int i // Declares i to be an int variable
  • Several variables can be declared at a time
  • int i, j, k
  • Its often better to declare variables
    individually.

12
Initializing Variables
  • A variable is given a value by using , the
    assignment operator
  • i 0
  • Initializing a variable means to assign a value
    to the variable for the first time.
  • Variables always need to be initialized before
    the first time their value is used.
  • The Java compiler checks that variables declared
    in methods are initialized prior to their first
    use.

13
Assigning Initial Values to Variables
  • Initial values may or may not be assigned when
    variables are declared
  • //These are not initialized when declared
  • //and have unknown values
  • int totalEggs, numberOfBaskets, eggsPerBasket
  • //These are initialized to 0 when declared
  • int totalEggs 0
  • int numberOfBaskets 0
  • int eggsPerBasket 0
  • Programming tip it is good programming practice
    always to initialize variables.

14
Literals
  • A literal is a token that represents a particular
    number or other value.
  • Examples of int literals
  • 0 297 30303
  • Examples of double literals
  • 48.0 48. 4.8e1 4.8e1 .48e2 480e-1
  • The only boolean literals are true and false.
  • char literals are enclosed within single quotes
  • 'a' 'z' 'A' 'Z' '0' '9' '' '.' ' '

15
Using literals
  • Literals are often used as initializers
  • double x 0.0, y 1.0
  • boolean b true
  • char ch 'f'

16
Two Main Kinds of Types in Java
  • primitive data types
  • the simplest types
  • cannot decompose into other types
  • values only, no methods
  • Examplesint - integerdouble - floating point
    (real)char - character
  • class types
  • more complex
  • composed of other types (primitive or class
    types)
  • both data and methods
  • ExamplesString

17
Identifiers
  • An identifier is the name of something (e.g. a
    variable, object, or method) used in a Java
    program.
  • Syntax rules for identifiers tell what names are
    allowed.
  • Naming conventions are not required by the
    compiler but are good practice.

18
Syntax Rules for Identifiers
  • Identifiers
  • cannot be reserved words (e.g. if, for, etc.
    see App. 1)
  • must contain only letters, digits, and the
    underscore character, _.
  • cannot have a digit for the first character.
  • is allowed but has special meaning, so do not
    use it.
  • have no official length limit (there is always a
    finite limit, but it is very large and big enough
    for reasonable names)
  • are case sensitive!
  • junk, JUNK, and Junk are three valid and
    different identifiers, so be sure to be careful
    in your typing!
  • Note that no spaces or dots are allowed.

19
Examples of Identifiers
  • numberOfStudents
  • number_of_students
  • student1
  • score2grade
  • score_to_grade

20
Naming Conventions
  • Always use meaningful names, e.g. finalExamScore,
    instead of something like x, or even just score.
  • Use only letters and digits.
  • Capitalize interior words in multi-word names,
    e.g. answerLetter.
  • Names of classes start with an uppercase letter.
  • every program in Java is a class as well as a
    program.
  • Names of variables, objects, and methods start
    with a lowercase letter.

21
Primitive Numeric Data Types
  • integerwhole number
  • examples 0, 1, -1, 497, -6902
  • four data types byte, short, int, long
  • floating-point numberincludes fractional part
  • examples 9.99, 3.14159, -5.63, 5.0
  • Note 5.0 is a floating-point number even though
    the fractional part happens to be zero.
  • two data types float, double

22
The char Data Type
  • The char data type stores a single printable
    character
  • For example
  • char answer y
  • System.out.println(answer)
  • prints (displays) the letter y

23
Primitive Data Types
24
Which Ones to Know for Now
Display in text is for reference for now stick
to these simple primitive types
  • int
  • just whole numbers
  • may be positive or negative
  • no decimal point
  • char
  • just a single character
  • uses single quotes
  • for examplechar letterGrade A
  • double
  • real numbers, both positive and negative
  • has a decimal point (fractional part)
  • two formats
  • number with decimal point, e.g. 514.061
  • e (or scientific, or floating-point) notation,
    e.g. 5.14061 e2, which means 5.14061 x 102

25
Changing the Value of a Variable
  • Usually a variable is changed (assigned a
    different value) somewhere in the program
  • May be calculated from other values
  • totalEggs numberOfBaskets eggsPerBasket
  • or read from keyboard input
  • totalEggs readLineInt()

26
Assignment Statements
  • most straightforward way to change value of a
    variable
  • Variable Expression
  • answer 42
  • is assignment operator
  • evaluate expression on right-hand side of the
    assignment operator
  • variable on the left-hand side of the assignment
    operator gets expression value as new value

27
Assignment Operator
  • Not the same as the equals sign in algebra.
  • It means - Assign the value of the expression
    on the right side to the variable on the left
    side.
  • Can have the same variable on both sides of the
    assignment operator
  • int count 10// initialize counter to ten
  • count count - 1// decrement counter
  • new value of count 10 - 1 9

28
compound assignment operators
  • The compound assignment operators make it easier
    to modify the value of a variable.
  • A partial list of compound assignment operators
  • Combines addition and assignment
  • - Combines subtraction and assignment
  • Combines multiplication and assignment
  • / Combines division and assignment
  • Combines remainder and assignment

29
CONT
  • Examples
  • i 2 // Same as i i 2
  • i - 2 // Same as i i - 2
  • i 2 // Same as i i 2
  • i / 2 // Same as i i / 2
  • i 2 // Same as i i 2

30
Specialized Assignment Operators
  • A shorthand notation for performing an operation
    on and assigning a new value to a variable
  • General form var ltopgt expression
  • equivalent to var var ltopgt (expression)
  • ltopgt is , -, , /, or
  • Examples
  • amount 5
  • //amount amount 5
  • amount 1 interestRate
  • //amount amount (1 interestRate)
  • Note that the right side is treated as a unit
    (put parentheses around the entire expression)

31
Performing Calculations
  • In general, the right side of an assignment can
    be an expression.
  • A literal is an expression, and so is a variable.
  • More complicated expressions are built out of
    operators and operands.
  • In the expression 5 / 9, the operands are 5 and
    9, and the operator is /.
  • The operands in an expression can be variables,
    literals, or other expressions.

32
OPERATORS
  • Javas arithmetic operators
  • Addition
  • - Subtraction
  • Multiplication
  • / Division
  • Remainder
  • Examples
  • 6 2 ? 8
  • 6 - 2 ? 4
  • 6 2 ? 12
  • 6 / 2 ? 3

33
Integer Division
  • If the result of dividing two integers has a
    fractional part, Java throws it away (we say that
    it truncates the result).
  • Examples
  • 1 / 2 ? 0
  • 5 / 3 ? 1

34
double Operands
  • , -, , and / accept double operands
  • 6.1 2.5 ? 8.6
  • 6.1 - 2.5 ? 3.6
  • 6.1 2.5 ? 15.25
  • 6.1 / 2.5 ? 2.44
  • int and double operands can be mixed
  • 6.1 2 ? 8.1
  • 6.1 - 2 ? 4.1
  • 6.1 2 ? 12.2
  • 6.1 / 2 ? 3.05

35
Binary Operators
  • The , -, , and / operators are said to be
    binary operators, because they require two
    operands.
  • Theres one other binary arithmetic operator
    (remainder).
  • The operator produces the remainder when the
    left operand is divided by the right operand
  • 13 3 ? 1
  • is normally used with integer operands.
  • Its a good idea to put a space before and after
    each binary operator.

36
Unary operators
  • Java also has two unary arithmetic operators
  • Plus
  • - Minus
  • Unary operators require just one operand.
  • The unary and - operators are often used in
    conjunction with literals (-3, for example).

37
Round-Off Errors
  • Calculations involving floating-point numbers can
    sometimes produce surprising results.
  • If d is declared as follows, its value will be
    0.09999999999999987 rather than 0.1
  • double d 1.2 - 1.1
  • Round-off errors such as this occur because some
    numbers (1.2 and 1.1, for example) cant be
    stored in double form with complete accuracy.

38
Operator Precedence
  • Whats the value of 6 2 3?
  • (6 2) 3, which yields 24?
  • 6 (2 3), which yields 12?
  • Operator precedence resolves issues such as this.
  • , /, and take precedence over and -.
  • Examples
  • 5 2 / 2 ? 5 (2 / 2) ? 6
  • 8 3 - 5 ? (8 3) - 5 ? 19
  • 6 - 1 7 ? 6 - (1 7) ? 1
  • 9 / 4 6 ? (9 / 4) 6 ? 8
  • 6 2 3 ? 6 (2 3) ? 8

39
Associativity
  • Precedence rules are of no help when it comes to
    determining the value of 1 - 2 - 3.
  • Associativity rules come into play when
    precedence rules alone arent enough.
  • The binary , -, , /, and operators are all
    left associative
  • 2 3 - 4 ? (2 3) - 4 ? 1
  • 2 3 / 4 ? (2 3) / 4 ? 1

40
Parentheses in Expressions
  • Parentheses can be used to override normal
    precedence and associativity rules.
  • Parentheses in the expression (6 2) 3 force
    the addition to occur before the multiplication.
  • Its often a good idea to use parentheses even
    when theyre not strictly necessary
  • (x x) (2 x) - 1
  • However, dont use too many parentheses
  • ((x) (x)) ((2) (x)) - (1)

41
Returned Value
  • Expressions return values the number produced by
    an expression is returned (return value).
  • int numberOfBaskets, eggsPerBasket, totalEggs
  • numberOfBaskets 5
  • eggsPerBasket 8
  • totalEggs numberOfBaskets eggsPerBasket
  • in the last line numberOfBaskets returns the
    value 5 and eggsPerBasket returns the value 8
  • numberOfBaskets eggsPerBasket is an expression
    that returns the integer value 40
  • Similarly, methods return values
  • readLine() is a method that returns a string read
    from the keyboard

42
Assignment Compatibility
  • Can't put a square peg in a round hole
  • Can't put a double value into an int variable
  • Conversion for different types.
  • Casting converting a value from one type to
    another
  • automatic or implicit casting
  • explicit casting

43
Casting changing the data type of the returned
value
  • Casting only changes the type of the returned
    value
  • not the type of the variable
  • For example
  • double x
  • int n 5
  • x n
  • n is an integer and x is a double
  • the value returned by n must be converted to type
    double before it is assigned to x

44
Implicit Casting
  • Casting is done implicitly (automatically) when a
    lower type is assigned to a higher type
  • The data type hierarchy (from lowest to highest)
  • An int value will automatically be cast to a
    double value.
  • A double value will not automatically be cast to
    an int value.

45
Implicit Casting Exampleint to double
  • double x
  • int n 5
  • x n
  • the value returned by n is cast to a double, then
    assigned to x
  • x contains 5.000 (as accurately as it can be
    encoded as a floating point number)
  • This casting is done automatically because int is
    lower than double in the data type hierarchy
  • The data type of the variable n is unchanged is
    still an int

data type hierarchy
46
Data Types in an ExpressionMore Implicit Casting
  • Some expressions have a mix of data types
  • All values are automatically advanced (implicitly
    cast) to the highest level before the calculation
  • For example
  • n and x are automatically cast to type double
    before performing the multiplication and division

double a int n 2 float x 5.1 double y
1.33 a (n x)/y
47
Explicit Casting
  • Explicitly (manually) change the data type of the
    value for a single use of the variable
  • Precede the variable name with the new data type
    in parentheses
  • (ltdata typegt) variableName
  • For example
  • the value of x is converted from double to
    integer before assigning the value to n

int n double x 2.0 n (int)x
48
Explicit casting is required to assign a higher
type to a lower
  • ILLEGAL Implicit casting to a lower data type
  • int n
  • double x 2.1
  • n x //illegal in java
  • It is illegal since x is double, n is an int,
    and double is a higher data type than integer
  • LEGAL Explicit casting to a lower data type int
    n
  • double x 2.1
  • n (int)x //legal in java
  • Though not necessary, use an explicit cast where
    an implicit one will be done automatically.

49
Truncation When Casting a doubleto an Integer
  • Casting a double to integer does not round it
    truncates
  • the fractional part is lost (thrown away)
  • For example
  • the value of n is now 2 (truncated value of x)
  • the cast is required
  • This behavior is useful for some calculations
    (Case Study Vending Machine Change)

int n double x 2.99999 n (int)x
50
Characters as Integers
  • Characters are actually stored as integers
    according to a special code
  • each printable character (letter, number,
    punctuation mark, space, and tab) is assigned a
    different integer code
  • the codes are different for upper and lower case
  • for example 97 may be the integer value for a
    and 65 for A
  • ASCII (Appendix 3) and Unicode are common
    character codes
  • Unicode ASCII codes plus additional ones for
    languages with an alphabet other than English
  • Java uses Unicode

51
ASCII/Unicode
52
Casting a char to an int
  • Casting a char value to int produces the
    ASCII/Unicode value
  • For example, what would the following display?
  • char answer y
  • System.out.println(answer)
  • System.out.println((int)answer)
  • Answer the letter y on one line followed by
    the ASCII code for y (lower case) on the next
    line
  • gtygt89gt

53
GOTCHA Imprecision of Floating Point Numbers
  • Computers store numbers using a fixed number of
    bits, so not every real (floating point) number
    can be encoded precisely
  • an infinite number of bits would be required to
    precisely represent any real number
  • For example, if a computer can represent up to 10
    decimal digits, the number 2.5 may be stored as
    2.499999999 if that is the closest it can come to
    2.5
  • Integers, on the other hand, are encoded
    precisely
  • if the value 2 is assigned to an int variable,
    its value is precisely 2
  • This is important in programming situations you
    will see later in the course

54
More onArithmetic Operators
  • addition (), subtraction (-), multiplication
    (), division (/)
  • can be performed with numbers of any integer
    type, floating-point type, or combination of
    types
  • result will be the highest type that is in the
    expression
  • Example
  • result will be int if both amount and adjustment
    are int
  • result will be float if amount is int and
    adjustment is float

amount - adjustment
55
Truncation When DoingInteger Division
  • No truncation occurs if at least one of the
    values in a division is type float or double (all
    values are promoted to the highest data type).
  • Truncation occurs if all the values in a division
    are integers.
  • For example
  • int a 4, b 5, c
  • double x 1.5, y
  • y b/x//value returned by b is cast to double
  • //value of y is approximately 3.33333
  • c b/a//all values are ints so the division
  • //truncates the value of c is 1!

56
Vending Machine Change
java program 2
  • int amount, originalAmount,
  • quarters, dimes, nickels, pennies
  • . . . // code that gets amount from user not
    shown
  • originalAmount amount
  • quarters amount/25
  • amount amount25
  • dimes amount/10
  • amount amount10
  • nickels amount/5
  • amount amount5
  • pennies amount

If amount is 90 then there 90/25 will be 3, so
there are three quarters.
If amount is 90 then the remainder of 90/25 will
be 15, so 15 cents change is made up of other
coins.
57
Increment and Decrement Operators
  • Shorthand notation for common arithmetic
    operations on variables used for counting
  • Some counters count up, some count down, but they
    are integer variables
  • The counter can be incremented (or decremented)
    before or after using its current value
  • int count
  • count preincrement count count count 1
    before using it
  • count postincrement count count count 1
    after using it
  • --count predecrement count count count -1
    before using it
  • count-- postdecrement count count count -1
    after using it

58
Increment and Decrement Operator Examples
  • common code
  • int n 3
  • int m 4
  • int result
  • What will be the value of m and result after each
    of these executes?
  • (a) result n m//preincrement m
  • (b) result n m//postincrement m
  • (c) result n --m//predecrement m
  • (d) result n m--//postdecrement m

59
The String Class
  • A string is a sequence of characters
  • The String class is used to store strings
  • The String class has methods to operate on
    strings
  • String constant one or more characters in double
    quotes
  • Examples
  • char charVariable a//single quotes
  • String stringVariable "a"//double quotes
  • String sentence "Hello, world"

60
String Variables
  • Declare a String variable
  • String greeting
  • Assign a value to the variable
  • greeting "Hello!"
  • Use the variable as a String argument in a
    method
  • System.out.println(greeting)
  • causes the string Hello! to be displayed on
    the screen

61
Concatenating (Appending) Strings
  • Stringing together strings - the operator for
    Strings
  • String name "Mondo"
  • String greeting "Hi, there!"
  • System.out.println(greeting name "Welcome")
  • causes the following to display on the screen
  • gtHi, there!MondoWelcome
  • gt
  • Note that you have to remember to include spaces
    if you want it to look right
  • System.out.println(greeting " " name
  • " Welcome")
  • causes the following to display on the screen
  • gtHi, there! Mondo Welcome
  • gt

62
Escape Characters
  • How do you print characters that have special
    meaning?
  • For example, how do you print the following
    string?
  • The word "hard"
  • Would this do it?
  • System.out.println("The word "hard"")
  • No, it would give a compiler error - it sees the
    string The word between the first set of double
    quotes and is confused by what comes after
  • Use the backslash character, \, to escape the
    special meaning of the internal double quotes
  • System.out.println("The word \"hard\"") //this
    works

63
More Escape Characters
  • Use the following escape characters to include
    the character listed in a quoted string
  • \" Double quote.
  • \' Single quote.
  • \\ Backslash.
  • \n New line. Go to the beginning of the next
    line.
  • \r carriage return. Go to the beginning of the
    current line.
  • \t Tab. White space up to the next tab stop.

64
Screen Output print and println
  • Sometimes you want to print part of a line and
    not go to the next line when you print again
  • Two methods, one that goes to a new line and one
    that does not
  • System.out.println()//ends with a new line
  • System.out.print()//stays on the same line
  • For example
  • System.out.print("This will all ")
  • System.out.println("appear on one line")
  • System.out.print() works similar to the
    operator
  • System.out.println("This will all "
  • "appear on one line, too")

65
Keyboard Input Gotchas
Note the two variations for reading each type of
number
  • readLine variation
  • reads a whole line
  • asks the user to reenter if it is not the right
    format
  • Try to use these
  • ExamplesreadLineInt()readLineDouble()
  • read variation
  • reads just the number
  • aborts the program if it is not the right format
  • Avoid using these for now
  • ExamplesreadInt()readDouble()

66
User-Friendly Input
  • Print a prompt so that the user knows what kind
    of information is expected.
  • Echo the information that the user typed in so
    that it can be verified.
  • System.out.println("Enter the number of
    trolls")
  • int trolls readLineInt()
  • System.out.println(trolls " trolls")

Prints prompt
Sample output with user input in italic
Echoes user input
Enter the number of trolls 38 38 trolls
67
Named Constants
  • Named constantusing a name instead of a value
  • Example use MORTGAGE_INTEREST_RATE instead of
    8.5
  • Advantages of using named constants
  • Easier to understand program because reader can
    tell how the value is being used
  • Easier to modify program because value can be
    changed in one place (the definition) instead of
    being changed everywhere in the program.
  • Avoids mistake of changing same value used for a
    different purpose

68
Defining Named Constants
public static final double PI 3.14159
  • publicno restrictions on where this name can be
    used
  • staticmust be included, but explanation has to
    wait
  • finalthe program is not allowed to change the
    value
  • The remainder of the definition is similar to a
    variable declaration and gives the type, name,
    and initial value.
  • A declaration like this is usually at the
    beginning of the file and is not inside the main
    method definition.

69
Adding Constants to the FtoC Program
  • FtoC2.java
  • // Converts a Fahrenheit temperature to Celsius
  • public class FtoC2
  • public static void main(String args)
  • final double FREEZING_POINT 32.0
  • final double DEGREE_RATIO 5.0 / 9.0
  • double fahrenheit 98.6
  • double celsius
  • (fahrenheit - FREEZING_POINT)
    DEGREE_RATIO
  • System.out.print("Celsius equivalent ")
  • System.out.println(celsius)

70
2.9 Methods
  • A method is a series of statements that can be
    executed as a unit.
  • A method does nothing until it is activated, or
    called.
  • To call a method, we write the name of the
    method, followed by a pair of parentheses.
  • The methods arguments (if any) go inside the
    parentheses.
  • A call of the println method
  • System.out.println("Java rules!")

71
Methods in the Math Class
  • The Math class contains a number of methods for
    performing mathematical calculations.
  • These methods are called by writing Math.name,
    where name is the name of the method.
  • The methods in the Math class return a value when
    they have completed execution.

72
The pow and sqrt Methods
  • The pow method raises a number to a power
  • Math.pow(2.0, 3.0) ? 8.0
  • Math.pow(-2.0, 3.0) ? 8.0
  • Math.pow(2.0, -1.0) ? 0.5
  • The sqrt method computes the square root of a
    number
  • Math.sqrt(2.0) ? 1.4142135623730951
  • Math.sqrt(4.0) ? 2.0
  • Both pow and sqrt return values of type double.

73
The round Method
  • The round method rounds a double value to the
    nearest integer
  • Math.round(4.1) ? 4
  • Math.round(4.5) ? 5
  • Math.round(4.9) ? 5
  • Math.round(5.5) ? 6
  • Math.round(-4.1) ? 4
  • Math.round(-4.5) ? 4
  • Math.round(-4.9) ? 5
  • Math.round(-5.5) ? 5
  • round returns a long value rather than an int
    value.

74
Using the Result of a Method Call
  • The value returned by a method can be saved in a
    variable for later use
  • double y Math.abs(x)
  • Another option is to use the result returned by a
    method directly, without first saving it in a
    variable. For example, the statements
  • double y Math.abs(x)
  • double z Math.sqrt(y)
  • can be combined into a single statement
  • double z Math.sqrt(Math.abs(x))

75
Using the Result of a Method Call
  • Values returned by methods can also be used as
    operands in expressions.
  • Example (finding the roots of a quadratic
    equation)
  • double root1
  • (-b Math.sqrt(b b - 4 a c)) / (2
    a)
  • double root2
  • (-b - Math.sqrt(b b - 4 a c)) / (2
    a)
  • Because the square root of b2 4ac is used
    twice, it would be more efficient to save it in a
    variable
  • double discriminant Math.sqrt(b b - 4 a
    c)
  • double root1 (-b discriminant) / (2 a)
  • double root2 (-b - discriminant) / (2 a)

76
Using the Result of a Method Call
  • The value returned by a method can be printed
    without first being saved in a variable
  • System.out.println(Math.sqrt(2.0))

77
Obtaining Input from the User
  • The SimpleIO class (not part of standard Java)
    simplifies the task of obtaining input.
  • The SimpleIO.prompt method is first used to
    prompt the user
  • SimpleIO.prompt("Enter Fahrenheit temperature
    ")
  • Next, the SimpleIO.readLine method is used to
    read the users input
  • String userInput SimpleIO.readLine()

78
Obtaining Input from the User
  • If the users input represents a number, it will
    need to be converted to numeric form.
  • The Convert class (not part of standard Java)
    provides a toDouble method that converts a string
    to a double value
  • double fahrenheit Convert.toDouble(userInput)
  • To convert a string to an integer, the
    Integer.parseInt method is used instead
  • int n Integer.parseInt(userInput)

79
Packages
  • Java allows classes to be grouped into larger
    units known as packages.
  • The package that contains SimpleIO and Convert is
    named jpb (Java Programming From the Beginning).
  • Java comes with a large number of standard
    packages.

80
Import Declarations
  • Accessing the classes that belong to a package is
    done by using an import declaration
  • import package-name .
  • Import declarations go at the beginning of a
    program. A program that needs SimpleIO or Convert
    would begin with the line
  • import jpb.

81
Application Programming Interfaces
  • The packages that come with Java belong to the
    Java Application Programming Interface (API).
  • In general, an API consists of code that someone
    else has written but that we can use in our
    programs.
  • Typically, an API allows an application
    programmer to access a lower level of software.
  • In particular, an API often provides access to
    the capabilities of a particular operating system
    or windowing system.

82
Application Programming Interfaces
  • The packages that come with Java belong to the
    Java Application Programming Interface (API).
  • In general, an API consists of code that someone
    else has written but that we can use in our
    programs.
  • Typically, an API allows an application
    programmer to access a lower level of software.
  • In particular, an API often provides access to
    the capabilities of a particular operating system
    or windowing system.

83
Program Converting from Fahrenheitto Celsius
(Revisited)
  • FtoC3.java
  • // Converts a Fahrenheit temperature entered by
    the user to
  • // Celsius
  • import jpb.
  • public class FtoC3
  • public static void main(String args)
  • final double FREEZING_POINT 32.0
  • final double DEGREE_RATIO 5.0 / 9.0
  • SimpleIO.prompt("Enter Fahrenheit
    temperature ")
  • String userInput SimpleIO.readLine()
  • double fahrenheit Convert.toDouble(userInput
    )
  • double celsius
  • (fahrenheit - FREEZING_POINT)
    DEGREE_RATIO
  • System.out.println("Celsius equivalent "
    celsius)

84
Output
  • Welcome to the CSc 2310 average calculation
    program.
  • Enter Program 1 score 20
  • Enter Program 2 score 19
  • Enter Program 3 score 15
  • Enter Program 4 score 18.5
  • Enter Program 5 score 20
  • Enter Program 6 score 20
  • Enter Program 7 score 18
  • Enter Program 8 score 20
  • Enter Quiz 1 score 9
  • Enter Quiz 2 score 10
  • Enter Quiz 3 score 5.5
  • Enter Quiz 4 score 8
  • Enter Quiz 5 score 9.5
  • Enter Test 1 score 78
  • Enter Test 2 score 92

85
Design of the CourseAverage Program
  • 1. Print the introductory message ("Welcome to
    the CSc 2310 average calculation program").
  • 2. Prompt the user to enter eight program scores.
  • 3. Compute the program average from the eight
    scores.
  • 4. Prompt the user to enter five quiz scores.
  • 5. Compute the quiz average from the five scores.
  • 6. Prompt the user to enter scores on the tests
    and final exam.
  • 7. Compute the course average from the program
    average, quiz average, test scores, and final
    exam score.
  • 8. Round the course average to the nearest
    integer and display it.

86
CourseAverage.java
  • CourseAverage.java
  • // Program name CourseAverage
  • // Author K. N. King
  • // Written 1998-04-05
  • // Modified 1999-01-27
  • //
  • // Prompts the user to enter eight program scores
    (0-20), five
  • // quiz scores (0-10), two test scores (0-100),
    and a final
  • // exam score (0-100). Scores may contain digits
    after the
  • // decimal point. Input is not checked for
    validity. Displays
  • // the course average, computed using the
    following formula
  • //
  • // Programs 30
  • // Quizzes 10
  • // Test 1 15
  • // Test 2 15
  • // Final exam 30
  • //

87
CourseAverage.java
  • import jpb.
  • public class CourseAverage
  • public static void main(String args)
  • // Print the introductory message
  • System.out.println("Welcome to the CSc 2310
    average "
  • "calculation program.\n")
  • // Prompt the user to enter eight program
    scores
  • SimpleIO.prompt("Enter Program 1 score ")
  • String userInput SimpleIO.readLine()
  • double program1 Convert.toDouble(userInput)
  • SimpleIO.prompt("Enter Program 2 score ")
  • userInput SimpleIO.readLine()
  • double program2 Convert.toDouble(userInput)
  • SimpleIO.prompt("Enter Program 3 score ")
  • userInput SimpleIO.readLine()
  • double program3 Convert.toDouble(userInput)

88
Cont
  • SimpleIO.prompt("Enter Program 4 score ")
  • userInput SimpleIO.readLine()
  • double program4 Convert.toDouble(userInput)
  • SimpleIO.prompt("Enter Program 5 score ")
  • userInput SimpleIO.readLine()
  • double program5 Convert.toDouble(userInput)
  • SimpleIO.prompt("Enter Program 6 score ")
  • userInput SimpleIO.readLine()
  • double program6 Convert.toDouble(userInput)
  • SimpleIO.prompt("Enter Program 7 score ")
  • userInput SimpleIO.readLine()
  • double program7 Convert.toDouble(userInput)
  • SimpleIO.prompt("Enter Program 8 score ")
  • userInput SimpleIO.readLine()
  • double program8 Convert.toDouble(userInput)

89
Style Issues
  • Style issues raised by the CourseAverage program
  • Comment blocks
  • Blank lines
  • Short comments
  • Long lines

90
Improving the Program
  • The values of most variables in the CourseAverage
    program are used only once.
  • When a variables value is used only once, the
    variable can often be eliminated by substituting
    the value thats assigned to it. The lines
  • String userInput SimpleIO.readLine()
  • double program1 Convert.toDouble(userInput)
  • could be replaced by
  • double program1
  • Convert.toDouble(SimpleIO.readLine())

91
Improving the Program
  • The number of variables in CourseAverage can be
    reduced by keeping a running total of all
    scores entered so far, rather than storing each
    score in a separate variable
  • // Prompt the user to enter eight program
    scores.
  • SimpleIO.prompt("Enter Program 1 score ")
  • String userInput SimpleIO.readLine()
  • double programTotal Convert.toDouble(userInput)
  • SimpleIO.prompt("Enter Program 2 score ")
  • userInput SimpleIO.readLine()
  • programTotal Convert.toDouble(userInput)
  • ...
  • // Compute the program average from the eight
    scores.
  • double programAverage programTotal / 8

92
2.12 Debugging
  • Debugging is the process of finding bugs in a
    program and fixing them.
  • Types of errors
  • Compile-time errors
  • Run-time errors (called exceptions in Java)
  • Incorrect behavior

93
Fixing Compile-Time Errors
  • Strategies for fixing compile-time errors
  • Read error messages carefully. Example
  • Buggy.java8 Undefined variable i
  • System.out.println(i)
  • Buggy.java10 Variable j may not have been
    initialized
  • System.out.println(j)
  • Pay attention to line numbers.
  • Fix the first error.

94
Fixing Compile-Time Errors
  • Dont trust the compiler (completely). The error
    isnt always on the line reported by the
    compiler. Also, the error reported by the
    compiler may not accurately indicate the nature
    of the error. Example
  • System.out.print("Value of i ")
  • System.out.println(i)
  • A semicolon is missing at the end of the first
    statement, but the compiler reports a different
    error
  • Buggy.java8 Invalid type expression.
  • System.out.print("Value of i ")
  • Buggy.java9 Invalid declaration.
  • System.out.println(i)

95
Fixing Run-Time Errors
  • When a run-time error occurs, a message will be
    displayed on the screen. Example
  • Exception in thread "main"
  • java.lang.NumberFormatException foo
  • at java.lang.Integer.parseInt(Compiled
    Code)
  • at java.lang.Integer.parseInt(Integer.java
    458)
  • at Buggy.main(Buggy.java11)
  • Once we know what the nature of the error is and
    where the error occurred, we can work backwards
    to determine what caused the error.

96
Fixing Behavioral Errors
  • Errors of behavior are the hardest problems to
    fix, because the problem probably lies either in
    the original algorithm or in the translation of
    the algorithm into a Java program.
  • Other than simply checking and rechecking the
    algorithm and the program, there are two
    approaches to locating the source of a behavioral
    problem, depending on whether a debugger is
    available.

97
SummaryPart 1
  • Variables hold values and have a type
  • The type of a Java variable is either a primitive
    type or a class
  • Common primitive types in Java include int,
    double, and char
  • A common class type in Java is String
  • Variables must be declared
  • Parentheses in arithmetic expressions ensure
    correct execution order

98
SummaryPart 2
  • Good programming practice
  • Use meaningful names for variables
  • Initialize variables
  • Use variable names (in upper case) for constants
  • Use comments, e.g. to explain non-obvious code
  • Output a prompt when the user is expected to
    enter data from the keyboard
  • Echo the data entered by the user
Write a Comment
User Comments (0)
About PowerShow.com