Primitive%20Data%20Types,%20etc. - PowerPoint PPT Presentation

About This Presentation
Title:

Primitive%20Data%20Types,%20etc.

Description:

Unlike mathematical numbers, which are infinite, numbers stored in a computer ... Use the (plus) operator to concatenate (add) Strings (characters enclosed in ... – PowerPoint PPT presentation

Number of Views:30
Avg rating:3.0/5.0
Slides: 65
Provided by: williama3
Learn more at: http://www2.hawaii.edu
Category:

less

Transcript and Presenter's Notes

Title: Primitive%20Data%20Types,%20etc.


1
Primitive Data Types, etc.
  • Primitive Data Types
  • Arithmetic expressions
  • Relational operators
  • Logical operators
  • Conditional Statements
  • if, if-else, switch
  • Static Variables
  • Constants
  • Static Methods

2
Primitive Data Types
  • A built-in data type
  • Closely models the computers memory
  • Predefined by the Java language
  • Manipulated by built-in operators
  • Do not have methods or instance variables (very
    different than objects)
  • Java has 8 primitive data types
  • byte, short, int, long, double, float, char,
    boolean

3
Integer Data Types
  • Unlike mathematical numbers, which are infinite,
    numbers stored in a computer are restricted to a
    specific size
  • Type Storage Range
  • byte 1 byte (8 bits) -128 to 127
  • short 2 bytes (16 bits) -32,768 to 32,767
  • int 4 bytes (32 bits) -2,147,483,648 to
    2,147,483,647
  • long 8 bytes (64 bits) -9,223,372,036,854,775,
    808 to 9,223,372,036,854,775,807

4
Integer Assignment
  • Integer variables can be used in arithmetic
    expressions, sent as parameters, and assigned
    values, just like other variables
  • references to objects are assigned a default
    value of null
  • integers are assigned a default value of 0
  • Color color //color null
  • int number //number 0

5
Increment
  • Preincrement operator
  • Add 1, then assign/use value
  • int a 3
  • int b a //b4, a4
  • Postincrement operator
  • Assign/use old value, then add 1
  • a 3
  • b a //b3, a4
  • a 3
  • int c 10 a //c13, a4

6
Decrement
  • Predecrement operator
  • Subtract 1, then assign/use value
  • a 3
  • b --a //b2, a2
  • Postdecrement operator
  • Assign/use old value, then subtract 1
  • a 3
  • b a-- //b3, a2
  • a 3
  • c 10 a-- //c13, a2

7
Assignment Operators
  • x x 5
  • Can also be written as x 5
  • a b 5
  • Evaluates to a a (b 5)
  • And not a a b 5

8
Example Code
  • See Example1.java
  • Use the (plus) operator to concatenate (add)
    Strings (characters enclosed in parentheses)
    together, as well as to convert a primitive data
    type to a String
  • For example, this will display the String a3int
    a 3System.out.println("a" a)
  • Output is displayed in the console window
  • Method System.out.println() displays whatever is
    within the parentheses on a line

9
Follow Rules from Algebra
  • Three rules for evaluation
  • evaluation takes place from left to right, except
    that
  • expressions in parentheses are evaluated first,
    starting at the innermost level, and
  • operators are evaluated in order of precedence
  • , /, and have precedence over and

10
Integer Division
  • Integer division is different than the division
    that you are probably used to
  • Cuts-off digits after the decimal point (does
    not round up)
  • int i 1/3 // i0
  • i 2/3 // i0
  • i 3/3 // i1
  • i 4/3 // i1
  • i 5/3 // i1
  • i 6/3 // i2

11
Modulus Operator
  • is the modulus operator
  • Modulus is the remainder of a division
  • 4 5 is 4
  • 9 5 is 4
  • 19 6 is 1
  • 0 6 is 0
  • 1 7 is 1
  • 7 7 is 0
  • 50 7 is 1

12
Class Exercise
  • Evaluate the following expressions
  • 2 4 3 - 7
  • 10 3
  • 2 9
  • (2 3) (11 / 12)
  • (4 4) 3 (2 - (11 / 3))

13
Fractional Numbers
  • What if we want to represent fractional numbers?
  • In Java we can use floats (floating point) or
    doubles (double precision floating point)
  • floating point refers to where the decimal point
    is assumed to be internal implementation detail
  • use doubles for scientific computation because
    they have larger range

14
Floating Point Numbers
  • Type Storage Range
  • float 4 bytes (32 bits) -3.4 x 1038 to 3.4 x
    1038
  • (7 significant digits)
  • double 8 bytes (64 bits) -1.7 x 10308 to 1.7 x
    10308
  • (15 significant digits)
  • Example declarations
  • float f 123.456f
  • //f for float
  • double d 123.456
  • //double by default

15
Two Kinds of Division
  • Integer division
  • Cuts-off digits after the decimal point (does
    not round up)
  • int i 1/2 // i0
  • Floating point division
  • Returns a floating point (decimal point) value
  • double d 1.0/2.0 // d0.5
  • This returns an integer and then converts to a
    float
  • d 1/2 // d0.0

16
Mixing Integers Floats
  • Can use different types of numbers together, but
    be careful!
  • Can go from less to more precise, not the other
    way around!
  • Java will not let you lose precision
    implicitly int myInt 4
  • double myDouble 2.64
  • myInt myDouble
  • // cant assign a double to an int
  • Change above assignment to
  • myDouble myInt

17
Mixing Integers Floats
  • We can force Java to convert double to int
  • called casting or coercion
  • loss of precision
  • myInt (int) myDouble // myInt is now 2
  • Example code for last few slides
  • See Example2.java

18
Character Data Type
  • Stores a 2 byte (16 bit) Unicode character
  • See link from web page on Unicode
  • Have to use single quotes around the character
  • char character 'a'
  • Some special characters, which are called escape
    sequences, begin with a backslash character (\)
  • char newline '\n'
  • char tab '\t'
  • char double_quote '\"'
  • char single_quote '\''
  • char backslash '\\'

19
Booleans
  • Booleans, named in honor of British logician
    George Boole (1815-1864), are another base type
    (primitive data type) defined by Java.
  • They can have one of two values true or false
  • booleans are declared and assigned just like
    numbers
  • default value is false
  • boolean foo true
  • boolean bar false
  • foo bar // foo is now false...

20
Boolean Expression
  • A combination of operators operands that
    returns true or false
  • Used in selection repetition statements
  • Evaluated from left to right
  • Operands are what the operators operate upon
  • 3 Kinds of boolean operators
  • Equality operators , !
  • Relational operators gt, gt, lt, lt
  • Logical operators , , ! (and, or, not)

21
Logical Operators
  • Logical and, or, not , , !
  • Evaluated left to right
  • Returns true or false
  • Operands have to be boolean

22
Comparing References
  • We can check to see if two references are
    referring to the same instance of a class using
    or if they are referring to different
    instances using !
  • Object object1 new Object()
  • Object object2 new Object()
  • boolean isEqual (object1 object2)
    // false
  • object2 object1
  • isEqual (object1 object2) // true

23
Comparing References
  • We can also check to see if a reference is not
    referring to anything
  • Object object3 null
  • boolean isNull (object3 null) //
    true
  • object3 new Object()
  • isNull (object3 null) // false

24
Logical Operators And, Or, Not
  • And () takes two boolean expressions and
    returns true only if both expressions are true
  • Or () takes two boolean expressions and returns
    true if at least one expression is true
  • Not (!) takes one boolean expression and returns
    its negation

25
Logical Operators And, Or, Not
  • Examples
  • boolean bool1 (3 2) (2 lt 3) // false
  • boolean bool2 (!bool1) (5.6 gt 8.0) // true
  • boolean bool3 !(bool1 bool2) // true
  • Example code for booleans and characters
  • See Example3.java

26
Class Exercise
  • Was the output of the following code?
  • See Tracing.java
  • Make pairs discuss the problem with your
    partner
  • Similar code will be on the next exam

27
Selection Statements
  • Chooses which statement to be executed next
  • Also called conditional statement
  • Uses a boolean expression to choose which
    statement or group of statements to execute

28
Selection 3 Ways
  • 3 kinds of selection statements
  • if structure
  • single selection
  • if-else structure
  • double selection multiple selection
  • switch structure
  • multiple selection

29
if Statements
  • booleans help us make decisions with if
    statements
  • Syntax
  • if (ltboolean expressiongt)
  • // code to be executed if expression is true
  • Boolean expression is evaluated
  • if true, code in body if statement is executed
    and then rest of method is executed
  • if false, skips over body of if statement and
    continues with method

30
if Statements
  • If no parenthesis, then only the 1st statement
    following the if statement is associated with it
  • if(a gt b)
  • c 3
  • d 4
  • So d4 will always be evaluated
  • Example code
  • See Example4.java

31
Checking booleans
  • Note that you should never check if a boolean
    variable is true (or false) in the following way
  • if (myBoolean true)
  • System.out.println("true!")
  • What if you mistyped and instead wrote
  • if (myBoolean true)
  • System.out.println("true!")

32
Checking booleans
  • The value true would be assigned to myBoolean and
    the conditional statement would always evaluate
    to true
  • Assignments always evaluate to the result of the
    right side of the assignment
  • This is a HUGE source of bugs!! Remember to
    always use when checking for equality!
  • Instead, you should always say
  • if (myBoolean)
  • System.out.println("true!")

33
if The Flow Chart
34
Example Code
  • See DaisyApplication.java
  • Displays three daisies (Daisy.java)
  • Clicking on a Petal calls method petalPlucked()
    of class Daisy, which increments numPetalsPlucked
  • Example if statement
  • See method petalPlucked() of Class Daisy
  • Displays one of two messages
  • Click on the leftmost Daisys Petals

35
if-else
  • What if we want to do something different when
    expression is false?
  • We can add else clause to if!
  • public void petalPlucked()
  • numPetalsPlucked
  • if (numPetalsPlucked ! 9)
  • bubble.setText("Loves me not.")
  • stem.setColor(Color.orange)
  • else
  • bubble.setText("Loves me.")
  • center.setColor(Color.red)

36
if-else
  • We dont have to use braces if body of if or else
    is one statement
  • public void petalPlucked()
  • numPetalsPlucked
  • if (numPetalsPlucked ! 9)
  • bubble.setText("Loves me not.")
  • else
  • bubble.setText("Loves me.")

37
if-else The Flow Chart
38
Complex if statements
  • We may want more than one condition in our
    if-statements
  • We can add another if statement in elses body.
  • if (ltboolean expressiongt)
  • // body
  • else if (ltboolean expressiongt)
  • // body
  • We can also nest our if statements by putting one
    inside another.

39
Example Code
  • See DaisyApplication.java
  • Displays three daisies (Daisy2.java)
  • Clicking on a Petal calls method petalPlucked()
    of class Daisy, which increments numPetalsPlucked
  • Example if-else statements
  • See method petalPlucked() of Class Daisy
  • Displays several messages changes colors of
    Daisy
  • Click on the middle Daisys Petals

40
Short-Circuiting
  • What is the value of n after the following code
    has executed?
  • int n 1
  • if (false (n 2))
  • System.out.println("Went into the if clause")
  • System.out.println(n)
  • Answer n is 1
  • since the left side of the condition evaluated to
    false the right side is not evaluated

41
Short-Circuiting
  • The same holds for and true
  • if the left side of the conditional evaluates to
    true, the right side is not evaluated
  • This is called short-circuiting
  • part of the conditional is skipped
  • Java takes a shorter route to evaluate conditional

42
Short-Circuiting
  • Can avoid short-circuiting by using and
    operators (both sides always evaluated)
  • What if, in our above example, we always wanted
    to do the right side, which increments n?int n
    1if (false (n 2)) System.out.println(
    "Went into the if
    clause")System.out.println(n)
  • If we used this instead, n would be 2 but we
    would still not go in to the if clause.

43
Side-effecting
  • Note that the previous example updated a variable
    inside a conditional
  • if(false (n 2))
  • We only provide this as an example of C-style
    hacking which you might see when you look through
    someone elses code.
  • In ICS 111, you should never write something like
    this
  • Increment your variables outside of conditionals
  • As youve seen, updating them inside conditionals
    makes the code confusing and hard to read.

44
If... If... If...
  • What if we want lots of conditional statements?
  • Could keep writing if-statements
  • if (condition1) / body1 /
  • else if (condition2) / body2 /
  • else if (condition3) / body3 /
  • else if (condition4) / body4 /
  • ...
  • else / bodyn /

45
If... If... If...
  • In English, this means
  • if condition1, execute body1
  • otherwise, if condition2, execute body2
  • otherwise, if condition3, execute body3
  • otherwise, if condition4, execute body4
  • . . .
  • otherwise, execute bodyN
  • If all we want to do is something different for
    each value of a simple variable (e.g, age) cant
    we do something simpler?
  • Yes! We can use a switch statement!

46
switch Statement
  • switch is used to choose among more than two
    mutually exclusive choices, based on values of a
    variable.
  • Very special form of general if-else-if
  • switch is like vending machine.
  • When coins are deposited into machine they fall
    into ramp with holes for each different type of
    coin.
  • Smallest slot is for dimes largest, for quarters

47
switch Statement Selector
  • switch can pick out one action from among many
    using a simple key called a selector
  • Selectors cannot be floats, doubles, or
    references (objects)
  • Of types we have encountered so far, can be ints,
    shorts, bytes, longs, or chars

48
switch Statement Selector
  • Value of selector determines action to be taken.
  • Each possible value for selector should result in
    one action or set of actions (one block of code
    executed)
  • Sometimes selector does not cover all cases.
  • Use default value to specify what action(s)
    should be performed when selector does not fit
    any other values listed

49
switch The Flow Chart


50
Dont Forget break Statement
  • But theres a problem with code written according
    to the last diagram . . .
  • If nothing alters flow of control, switch
    statements fall through to next case
  • i.e., all case statements after one which matches
    selector are executed!
  • Must have way to stop case from falling through
  • break out of switch statement

51
Amendment to Previous Diagram


52
switch Statement
  • So switch should usually include break statements
  • If not, each case statement will be executed
    until encounter another break statement or reach
    end
  • However, if we want several cases to execute the
    same statements
  • Then list case statements one after another
    without using break statements

53
Example Code
  • See DaisyApplication.java
  • Displays three daisies (Daisy3.java)
  • Clicking on a Petal calls method petalPlucked()
    of class Daisy, which increments numPetalsPlucked
  • Example switch statements
  • See method petalPlucked() of Class Daisy
  • Displays several messages changes colors of
    center stem
  • Click on the right Daisys Petals

54
static Class Variables
  • Each instance of a class has different copies of
    instance variables. What if we want entire class
    to have same value for variable?
  • Can use reserved word static to make class
    variables, of which there is only one copy for
    entire class.
  • Each time any method of any instance changes the
    value of a static variable, all instances have
    access to that new value.
  • Example code See SquaresFame.java (see Squares
    numberOfInstances getNumberOfInstances())

55
Constants
  • Constants are used to represent values which
    never change in a program
  • weve seen constants before the red, blue,
    green, etc., values of the java.awt.Color class
  • They should be
  • static, so there is exactly one value for entire
    class
  • final, so their values cant be changed
  • and public, so they are widely available

56
Constants
  • If we want a new value for SIDE, we can change
    our entire program very easily, by changing the
    value of our constant and recompiling
  • See SquaresFrame.java give it a try!
  • See code in Square class (at top of class)
  • Constants never change after declaration
  • ltconstantgt ltexprgt in a method wont work
  • Cannot do this SIDE 2
  • See code in Square constructor (towards the
    bottom)

57
Constants
  • Constants have descriptive names literal numbers
    (such as 42) dont
  • SIDE is called a symbolic constant
  • 5 is called a literal constant
  • Always use constants when possible
  • makes your program easier to change
  • makes your code easier to read
  • Literal numbers should never (well, hardly ever)
    appear in programs.
  • 0, 1 are common exceptions

58
Using Interfaces with Constants
  • So far we have only used interfaces to declare
    methods we can also use them to declare
    constants
  • What if many classes use same constants?
  • Can put constants in an interface and have
    classes implement it!
  • then public, static, and final are implicit
  • interface SquareConstants
  • int THICKNESS 5

59
Using Interfaces with Constants
  • All classes that implement the SquareConstants
    interface have access to THICKNESS
  • By changing the constants in the interface, we
    can change all the objects of all the classes
    that implement the interface
  • For example, change THICKNESS and recompile run
    SquaresFrame.java
  • What changes do you see?

60
Java Math Class
  • We can use Math class which is predefined by
    Java!
  • Provides all kinds of cool methods
  • Math.sin(x)
  • Math.cos(x)
  • Math.abs(x)
  • Math.pow(x,y) raises x to the power of y
  • Math.log(x)
  • Math.sqrt(x) square root of x
  • ... and more!

61
Java Math Class
  • Math also defines two symbolic constants
  • Math.E 2.71...
  • Math.PI 3.14...
  • Why can we call methods on Math without
    instantiating it?
  • Because its methods are static!

62
static Class Methods
  • static methods, or class methods, are invoked on
    behalf of entire class, not on specific instance
    of class no instance variables needed (nor are
    you allowed to access any)!
  • In Math class, methods are declared
  • public static double sin(double a)
  • ...
  • When calling static method, dont have to
    instantiate class, just send message to class
  • double d Math.abs(-5.0) //d5.0

63
Example Code
  • Uses Math.random() method
  • See Java 5.0 API for details on how this works
  • Returns a double value with a positive sign,
    greater than or equal to 0.0 and less than 1.0.
  • Used in Utilities.randomNumber()
  • See Utilities.java
  • Displays seven circles at random
  • See RandomCirclesFrame.java

64
Class Exercise
  • Was the output of the following code?
  • See Tracing2.java
  • Similar code will be on the next exam
  • In order to help you trace through the code, each
    box is has a different color
  • On the actual exam, all the boxes will be black
Write a Comment
User Comments (0)
About PowerShow.com