Chapter 2 Primitive Data Types and Operations

1 / 57
About This Presentation
Title:

Chapter 2 Primitive Data Types and Operations

Description:

To obtain input using the JOptionPane input dialog boxes ( 2.11) ... To become familiar with Java documentation, programming style, and naming conventions ( 2.14) ... –

Number of Views:47
Avg rating:3.0/5.0
Slides: 58
Provided by: yda57
Category:

less

Transcript and Presenter's Notes

Title: Chapter 2 Primitive Data Types and Operations


1
Chapter 2Primitive Data Types and Operations
2
Objectives
  • To write Java programs to perform simple
    calculations (2.2).
  • To use identifiers to name variables, constants,
    methods, and classes (2.3).
  • To use variables to store data (2.4-2.5).
  • To program with assignment statements and
    assignment expressions (2.5).
  • To use constants to store permanent data (2.6).
  • To declare Java primitive data types byte,
    short, int, long, float, double, and char (2.7
    2.10).

3
Objectives
  • To use Java operators to write expressions (2.7
    2.9).
  • To represent a string using the String type.
    (2.10)
  • To obtain input using the JOptionPane input
    dialog boxes (2.11).
  • To obtain input from console (2.13).
  • To become familiar with Java documentation,
    programming style, and naming conventions
    (2.14).
  • To distinguish syntax errors, runtime errors, and
    logic errors (2.15).
  • To debug logic errors (2.16).

4
Computing the Area of a Circle
  • Listing 2.1 ComputeArea.java (view animation)

public class ComputeArea public static void
main(String args) double radius //
Declare radius double area // Declare
area radius 20 // New value in radius
area radius radius 3.14159 // New value
in area System.out.println("The area for the
circle of radius " radius " is "
area)
5
Identifiers
  • An identifier is a sequence of characters that
    consist of letters, digits, underscores (_), and
    dollar signs ()
  • An identifier must start with a letter, an
    underscore (_), or a dollar sign ()
  • An identifier should not start with a digit
  • An identifier cannot be a reserved word
  • An identifier can be of any length
  • An identifier should be meaningful

6
Variable Declaration
  • Syntax
  • datatype variableName
  • datatype variable1, variable2, , variableN
  • Naming convention for variables
  • capitalize the first letter of each word except
    the first
  • The data type determines the amount of memory
    space to be allocated
  • Examples
  • int x, y, numOfBooks
  • double radius // radius can store floating
    point
  • char ch // ch can store 1
    character

7
Assignment Statements
  • Syntax
  • variable expression
  • variableN . . . variable1 expression
  • equal sign () is the assignment operator
  • Rules
  • variable and expression must be compatible in
    type
  • x 1 // correct if x is
    int/double type
  • radius 1.0 // incorrect if radius is int
    type
  • z y x 2 // correct
  • Assignment expression
  • The assigned value can be treated as an
    expression
  • System.out.println(x 1)

8
Variable Initialization and Constant
  • Variable Initialization
  • is to declare a variable and assign a value in
    one statement
  • int x 1
  • double d 1.4
  • Constants
  • are values which cannot be changed after
    initialization
  • Syntax
  • final datatype CONSTANTNAME value
  • Examples
  • final double PI 3.14159
  • final int SIZE 3

9
Primitive Data Types
10
Data Types Hierarchy
11
Expression, Operators, Operands
  • An expression always evaluate to a single value
  • e.g. 123 evaluates to 7
  • An expression consists of
  • Operators (e.g. , in above expression)
  • Operands (e.g. 1, 2, 3 in above expression)
  • Types of operators
  • Unary (operates on 1 operand)
  • Binary (operates on 2 operands)
  • Ternary (operates on 3 operands)

12
Numeric (Arithmetic) Operators
13
Operands of Different Types
  • Implicity type conversion occurs in an expression
    with operands of different types
  • Rules
  • Both operands are int, the result is int
  • 5/2 yields an integer 2 (it is called integer
    division)
  • 52 yields an integer 1
  • Any one operand is double, the result is double
  • 5.0/2 yields a double type value 2.5
  • 5.02 yields a double type value 10.0
  • Explicit type conversion (type casting) can
    convert a data to a desired type
  • (double)5/2 yields 2.5

14
Remainder Operator ()
  • Remainder is very useful in programming
  • e.g. an even number 2 is always 0 and an odd
    number 2 is always 1
  • Programming problem
  • Suppose today is Saturday, what day is after 10
    days ? The answer is Tuesday using the following
    expression

15
Example Displaying Time
  • Write a program that obtains hours and minutes
    from seconds
  • DisplayTime.java

int totalMinutes seconds / 60 int hours
totalMinutes / 60 int minutes totalMinutes
60
16
Number Literals
  • A literal is a constant value that appears
    directly in the program
  • For example, 34, 1,000,000, and 5.0 are literals
    in the following statements
  • int i 34
  • long x 1000000
  • double d 5.0

17
Rules about Integer Literals
  • An integer literal can be assigned to a variable
    if it can fit into the variable
  • A compilation error would occur if the literal is
    too large for the variable to hold
  • e.g. the statement byte b 1000would cause a
    compilation error, because 1000 requires at least
    two bytes to store this value or 1000 is not in
    the range 128 to 128

18
Floating-Point Literals
  • Floating-point literals
  • are written with a decimal point
  • Are by default, a floating-point literal (e.g.
    5.0) is treated as a double type value
  • You can make a number
  • a float by appending the letter f or F (e.g.
    100.2f or 100.2F)
  • a double by appending the letter d or D (e.g.
    100.2d or 100.2D)
  • Depends on the precision of the result you need

19
Scientific Notation
  • Floating-point literals can also be specified in
    scientific notation
  • e.g. 1.23456e2, same as 1.23456e2, is equivalent
    to 1.23456?102 or 123.456
  • e.g., 1.23456e-2 is equivalent to 1.23456?10-2 or
    0.0123456.
  • E (or e) represents an exponent of base-10 and it
    can be either in lowercase or uppercase.

20
Arithmetic Expressions
  • is translated to Java code as(34x)/5
    10(y-5)(abc)/x 9(4/x (9x)/y)

21
Example Converting Temperatures
  • Write a program that converts a Fahrenheit degree
    to Celsius using the formula
  • FahrenheitToCelsius.java

double fahrenheit 100 double celsius (5.0 /
9) (fahrenheit - 32)
22
Shortcut Assignment Operators
Operator Example Equivalent i 8 i i
8 - f - 8.0 f f - 8.0 i 8 i i
8 / i / 8 i i / 8 i 8 i i 8
23
Increment andDecrement Operators
Operator Name Description var preincrement The
expression (var) increments var by 1 and
evaluates to the new value in var after the
increment. var postincrement The expression
(var) evaluates to the original value in var
and then increments var by 1. --var predecrement
The expression (--var) decrements var by 1 and
evaluates to the new value in var after the
decrement. var-- postdecrement The expression
(var--) evaluates to the original value in var
and then decrements var by 1.
24
Increment andDecrement Operators, cont.
25
Increment Decrement Operators
  • makes expressions short, but it also makes them
    complex and difficult to read
  • avoid using these operators in expressions that
    modify
  • multiple variables, or
  • the same variable for multiple times such as this
  • int i 2
  • int k i i
  • System.out.println("i"i" k"k)
  • display i3 k6

26
Numeric Type Conversion
  • Consider the following statements
  • byte i 100
  • long k i 3 4
  • double d i 3.1 k / 2

27
Conversion Rules
  • When performing a binary operation involving two
    operands of different types, Java automatically
    converts the operand based on the following
    rules
  • Rule 1 If one of the operands is double, the
    other is converted into double.
  • Rule 2 Otherwise, if one of the operands is
    float, the other is converted into float.
  • Rule 3 Otherwise, if one of the operands is
    long, the other is converted into long.
  • Rule 4 Otherwise, both operands are converted
    into int.

28
Type Casting
  • Implicit casting
  • double d 3 (type widening)
  • Explicit casting
  • int i (int)3.0 (type narrowing)
  • int i (int)3.9 (Fractional part is truncated)
  • float rate (float)5.0
  • What is wrong in this statement ?
  • int x 5 / 2.0
  • float rate 5.0

29
Example Keeping Only Two Decimal Places
  • Write a program that displays the sales tax with
    two digits after the decimal point
  • SalesTax.java
  • Method format added since in JDK 1.5

(int)(tax 100) / 100.0
System.out.format(".2f", tax)
30
Character Data Type
  • Character literal use single qoute ' (not ")
  • char letter 'A' (ASCII)
  • char numChar '4' (ASCII)
  • char letter '\u0041' (Unicode)
  • JOptionPane.showMessageDialog(null,
    "","\u6B22\u8FCE Welcome",
    JOptionPane.INFORMATION_MESSAGE)
  • The increment and decrement operators can also be
    used on char type variables to get the next or
    preceding Unicode character
  • char ch 'a' System.out.println(ch)

31
Escape Sequences for Special Characters
Description Escape Sequence Unicode Backspace \b \
u0008 Tab \t \u0009 Linefeed \n \u000A Carriage
return \r \u000D Backslash \\ \u005C Single
Quote \' \u0027 Double Quote \" \u0022
32
Appendix B ASCII Character Set
33
ASCII Character (con't)
  • Display ASCII code of a character
  • int code 'A'System.out.format("Character
    'c'Decimald Hexx", code, code, code)
  • Automatic casting between char and int types
  • int i 'a'
  • Same as int i (int)'a'
  • char c 97
  • Same as char c (char)97

34
The String Type
  • A string represents a sequence of characters 
  • String message "Welcome to Java"
  • String literal use double quote " (not ')
  • It is a predefined class in Java library
  • It is a reference type (vs primitive type)
  • Any Java class can be used as a reference type
    for a variable

35
String Concatenation
  • is an overloaded operator besides performing
    addition
  • If one operand is a string, the result is string
    type
  • String message "Welcome " "home"
  • String s "Chapter" 2 
  • String s1 "Supplement" 'B'
  • What is wrong with the following ?
  • System.out.println("12" 1 2)should be
    corrected as
  • System.out.println("12" (1 2))

36
Operator Precedence and Association
37
Operator Precedence and Association (con't)
38
Operator Precedence and Association (con't)
  • For more information
  • Java Glossaryhttp//mindprod.com/jgloss/precedenc
    e.html

39
Operator Precedence Rule
  • Higher precedence operators are done first
  • igt5 jlt(float)97/2 ?
  • igt5 jlt((float)9)7/2 ?
  • igt5 jlt((float)9)(7/2) ?
  • igt5 jlt(((float)9)(7/2)) ?
  • (igt5) (jlt(((float)9)(7/2))) ?
  • ((igt5) (jlt(((float)9)(7/2))))
  • The precedence rule in Java language has
  • Advantage need fewer parentheses in expression
  • Disadvantage must memorise the table

40
Operator Association Rule
  • Operators with the same precedence level in an
    expression are evaluated based on their
    associativity
  • left-associative operators group from left to
    right
  • xyz is equivalent to (xy)z
  • right-associative operators group from right to
    left
  • yx3 is equivalent to y(x3)

41
Getting Input Input Dialog Boxes
  • String string JOptionPane.showInputDialog(null,
    "Prompting Message", "Dialog Title",
    JOptionPane.QUESTION_MESSAGE))

42
Getting Input Input Dialog Boxes
  • showInputDialog method is overloaded
  • String string JOptionPane.showInputDialog(null,
    "Prompting Message", "Dialog Title",
    JOptionPane.QUESTION_MESSAGE))
  • String string JOptionPane.showInputDialog(x)
  • where x is a string for the prompting message.

43
Convert String to int/float/double
  • Convert String to int
  • int year Integer.parseInt("1997")
  • Convert String to double
  • double width Double.parseDouble("3.14")
  • parseInt is a static method of class Integer
  • parseDouble is a static method of class Double
  • Is the following statement valid?
  • float price Float.parseFloat("2.3")

44
Example Compute Loan Payments
  • Computes monthly payment and total payment
  • ComputeLoan.java
  • String loanString JOptionPane.showInputDialog("E
    nter loan amount, for example 120000.95")double
    loanAmount Double.parseDouble(loanString)

45
Example Monetary Units
  • Enter the amount in decimal representing dollars
    and cents and output a report listing the
    monetary equivalent
  • ComputeChange.java

46
Example Displaying Current Time
  • A program that displays current time in GMT
    format
  • The currentTimeMillis method in the System class
    returns the current time in milliseconds since
    the midnight, January 1, 1970 GMT
  • ShowCurrentTime.java

47
Displaying Current Time
  • long totalMilliseconds System.currentTimeMillis(
    )
  • long totalSeconds totalMilliseconds / 1000
  • int currentSecond (int)(totalSeconds 60)
  • . . . . .
  • String output "Current time is " currentHour
    "" currentMinute "" currentSecond "
    GMT"
  • JOptionPane.showMessageDialog(null, output)

48
Getting Input Using Scanner
  • Create a Scanner object
  • Use the methods
  • next() to obtain a string
  • nextByte(), nextShort(), nextInt(), nextLong(),
    nextFloat(), nextDouble() to obtain a numeric
    data
  • nextBoolean() to obtain a boolean value
  • Example
  • Scanner scanner new Scanner(System.in)
  • double d scanner.nextDouble()

49
Good Programming Practice
  • Program documentation
  • Appropriate Comments
  • Programming style
  • Naming Conventions
  • Proper Indentation and Spacing Lines
  • Block Styles

50
Appropriate Comments
  • Include a summary at the beginning of the program
    to explain what the program does, its key
    features, its supporting data structures, and any
    unique techniques it uses.
  • Include your name, class section, instructor,
    date (creation date and modified date), and a
    brief description at the beginning of the
    program.

51
Naming Conventions
  • Choose meaningful and descriptive names.
  • Variables and method names
  • Use lowercase. If the name consists of several
    words, concatenate all in one, use lowercase for
    the first word, and capitalize the first letter
    of each subsequent word in the name.
  • For example, the variables radius and area, and
    the method computeArea.

52
Naming Conventions, cont.
  • Class names
  • Capitalize the first letter of each word in the
    name.
  • For example, the class name ComputeArea.
  • Constants
  • Capitalize all letters in constants, and use
    underscores to connect words.
  • For example, the constant PI and MAX_VALUE

53
Proper Indentation and Spacing
  • Indentation
  • Indent two to three spaces
  • You can set indentation/tab size in Eclipse
  • Spacing
  • Use blank line to separate segments of the code.

54
Block Styles
  • You can set the style for braces in Eclipse

 
55
Programming Errors
  • Syntax Errors
  • Discover during program compilation
  • Runtime Errors
  • Occurs during program execution. Causes the
    program to abort/terminate abnormally
  • e.g. int n 5 / 0
  • Exception handling should be used
  • Logic Errors
  • Occurs due to wrong program design. It is
    difficult to discover and correct logic errors
  • e.g. System.out.println("12" 1 2)

56
Debugging
  • It is the process of finding and correcting logic
    errors or program bugs
  • Debugging techniques may be used
  • Change some statements to comment
  • Hand-trace the program (i.e., catch errors by
    reading the program)
  • Insert print statements
  • to show the values of the variables
  • to find where the program stops execution
  • Debugger (useful for complex programs)

57
Debugger
  • Debugger (often is part of an IDE) is a program
    that facilitates debugging. You can use a
    debugger to
  • Step Into - Execute a single statement at a time
  • Step Over - Trace into or stepping over a method
  • Set breakpoints
  • Add Watch - Display variables
  • Display call stack
  • Modify variables
Write a Comment
User Comments (0)
About PowerShow.com