Variables and memory - PowerPoint PPT Presentation

1 / 30
About This Presentation
Title:

Variables and memory

Description:

Variables and memory – PowerPoint PPT presentation

Number of Views:155
Avg rating:3.0/5.0
Slides: 31
Provided by: michaelc7
Category:

less

Transcript and Presenter's Notes

Title: Variables and memory


1
Variables and memory
  • Every variable has
  • a name, a type, a size, and a value
  • Concept name corresponds to a memory location
  • If primitive type actual value stored there
    long needs more space than int, and so on
  • If object type just reference to object stored
    there (just need space for memory address)
  • Actual object is somewhere else
  • But reference can be null means no actual object

2
Variables and constants
  • Java is strongly-typed
  • Must declare type for memory locations used
  • e.g., declare 2 doubles, and one String
    reference
  • double a, b
  • String s
  • Declaring allocates space, but value is
    undefined
  • Must assign value, or compiler wont let you use
    it
  • final variables are constants
  • May only assign value once usually when
    declared
  • e.g., final double TAX_RATE 0.0775

3
Identifiers
  • Names of classes, variables, methods
  • 3 simple rules
  • Must consist of a sequence of letters, digits, _,
    or
  • No other characters allowed including no
    spaces
  • Must not begin with a digit
  • No Java reserved words allowd
  • Unwritten rule Use meaningful names
  • Conventions
  • NameOfClass begin with uppercase
  • other or otherName, unless name of constant, like
    PI

4
java.lang.Math static methods
  • Maths public methods are all static
  • So invoke by class name and the dot .
    operator
  • double r Math.toRadians(57.)
  • System.out.println(Sine of 57 degrees is
  • Math.sin(r))
  • Some methods in chapter 4, Table 2 (p. 150)
  • Math.max(x,y) and Math.min(x,y)
  • Math.random() (and more versatile
    java.util.Random class)
  • e.g., int dice (int)(Math.random()6) 1
  • Math is in the package called java.lang (the one
    you neednt import)

5
Standard Output, and Strings
  • System.out an object of type PrintStream
  • println(string) prints string and newline
  • print(string) prints string, no newline
  • String delimited by quotes a string
  • Remember special characters start with \
  • e.g., \n is a newline character
  • So println(Hi) is same as print(Hi\n)
  • concatenates e.g., a 5 b becomes
    a5b
  • Note first 5 is converted to a String.

6
Some String methods
  • Accessing sub-strings (Note positions start
    at 0, not 1)
  • substring(int) returns end of string
  • substring(int, int) returns string from first
    position to just before last position
  • charAt(int) returns single char
  • length() the number of characters
  • toUpperCase(), toLowerCase(), trim(),
  • valueOf() converts any type to a String
  • But converting from a String is more difficult

7
Standard input, and more Strings
  • Normally have to read keyboard or other input as
    a String (also requires error handling and a
    reader object)
  • And must parse string to interpret numbers or
    other types
  • e.g., String s1 426, s2 93.7
  • Then s1 can be parsed to find an int or a double,
    and s2 can be parsed to find a double
  • int n Integer.parseInt(s1)
  • double d Double.parseDouble(s2)

8
java.util.Scanner
  • Important Java 5 enhancement
  • Greatly simplifies processing standard input
  • No need to handle IOExceptions
  • No need to deal with parsing input strings
  • First construct a Scanner object pass it
    System.in
  • Scanner in new Scanner(System.in)
  • Then get next string, int or double (others too)
  • int x in.nextInt()
  • double y in.nextDouble()
  • String s in.next()
  • String wholeLine in.nextLine()

9
Other ways to get data from user
  • JOptionPane simplest type of GUI
  • Quick way to get an input String from the user
  • Must parse string to convert to numbers/other
  • e.g., old texts InputTest.java
  • Before Java 5 harder to read standard input
  • Basically, associate a Reader object with
    System.in
  • Must handle or throw IOExceptions
  • Data actually are integers representing char
  • Reader object converts whole line to a String
    then parse
  • e.g., old texts ConsoleInputTest.java

10
Formatted printing with printf
  • Java 5 printf(String format, Object... args)
  • Method of PrintStream class so System.out has
  • System.out.printf(x d, x) // x is an
    integer
  • d means print integer as decimal. Can be octal
    or hex too
  • printf(octal onhex xn, x, x)
  • Note variable length argument list also new
    Java 5 feature
  • f or e or g for floating point, and s for
    strings
  • Also control field width, precision, and other
    formatting
  • printf(-9s7.2fn, Value, v)
  • See Tables 3 and 4, p. 168
  • Complete details in java.util.Formatter
  • Format dates, times, Works for String objects
    too
  • String s String.format(pt d, d", x, y)

11
Some operators
  • is the assignment operator
  • Basic arithmetic operators , -, , /,
  • is modulus operator (remainder)
  • Compound arithmetic/assignment operators
  • e.g., a 5 // same as a a 5
  • Also -, , /, and
  • Increment and decrement operators
  • is same as 1 and -- is same as - 1
  • e.g. counter // increments counter by 1

12
Pre vs. post or --
  • Post-increment is not exactly the same as
    pre-increment (same goes for decrement)
  • i.e., x is not exactly the same as x, but the
    final value of x is the same in both cases
  • Post uses value then changes it pre is reverse
  • e.g., say x 7, then
  • System.out.println(x) // would print 7
  • System.out.println(x) // would print 8
  • In either case, x equals 8 after the print.

13
Type conversions
  • Automatically applies to promotions only
  • e.g., int n 5 double d n // okay
  • n is promoted to double before assignment
    happens
  • e.g., int n 5 double d n/2.0 // okay
  • n promoted to double before division result is
    double
  • Must cast to force other conversions
  • e.g., double d 5. int n d // error
  • double d 5. int n (int)d // okay
  • But not all casts are legal (basically must make
    sense)
  • String s dog int n (int)s // error

14
Some object reference issues
  • null a reference to no object at all
  • Cannot send message to no object, of course
  • e.g., BankAccount mySavings null
  • mySavings.withdraw(100) // error at runtime
  • this an objects reference to itself
  • Often used just for clarity
  • e.g., in a BankAccount method, balance 0 is
    same as this.balance 0
  • Also used to call one constructor from another
    one
  • e.g., public BankAccount() this(0)
  • Copying a reference does not copy the object.

15
Copying values
  • Copying values (of primitive data types) actually
    does copy the value
  • int balance1 1000
  • int balance2 balance1
  • // now there are separate copies of the value
    1000

16
vs. copying references
  • Copying references to objects does just that
  • BankAccount account1 new BankAccount(1000)
  • BankAccount account2 account1
  • // now there are separate copies of the
    reference
  • // but there is still just one bank account
    object

17
Java has 7 control structures
  • 1st is trivial sequence structure
  • 3 choices of selection structures (decisions)
  • if
  • if/else
  • switch
  • 3 choices of iteration structures (loops)
  • while
  • for (Note Java 5 also has two versions of it)
  • do/while

18
Sequence (it really is a structure)
19
if Selection Structure
20
Implementing if
  • Either
  • if (boolean expression)
  • one statement
  • Or
  • if (boolean expression)
  • multiple statements
  • separated by
  • boolean expressions evaluate to true or false

Indented here too
Note indentation
21
Simple boolean expressions
  • Relational operators , , , !
  • e.g., int x1, y2, z3
  • x y // false
  • x z - y // true
  • Note lower precedence than arithmetic
  • x z y // false
  • Note not same as x z y // makes x be 5
  • z ! x y // false (if x still is 1)

22
Comparing objects, like Strings
  • Do NOT use to test equality
  • That just compares references! For example,
  • String s1 dog
  • String s2 DOG.toLowerCase()
  • s1 s2 // false! different objects
  • Use equals method instead (if defined by class)
  • s1.equals(s2) // true same contents
  • But not all classes define equals method. Be
    careful.
  • Some objects (like Strings) are Comparable, so
  • s3.compareTo(s4) // returns -1, 0, or 1

23
if/else Selection Structure
24
Implementing if/else
  • With if and else
  • if (grade 60)
  • message Pass
  • else
  • message Fail
  • Or with selection operator
  • message grade 60 ? Pass Fail
  • // same result as if/else above
  • This version does not allow blocks or nesting
    but it returns a value, so more useful in many
    cases

25
Nesting indenting
  • No such thing as multiple else blocks others
    actually nested inside else block
  • e.g.,
  • if (grade 90)
  • message Excellent
  • else
  • if (grade 60)
  • message Pass
  • else
  • message Fail
  • Can get very deeply indented if many nesting
    levels

26
Nesting/indenting (cont.)
  • Usually avoid excessive indents this way
  • if (grade 90)
  • message Excellent
  • else if (grade 60)
  • message Pass
  • else
  • message Fail
  • Note importance of testing relations in the
    correct order
  • Easy to remember if realize nesting rule

27
Boolean operators , , !
  • For combining simple boolean expressions into
    more complex expressions
  • Operands are boolean expressions
  • e.g., grade A weight 10
  • Note relational operators have higher
    precedence
  • Truth tables see text page 207
  • op1 op2 - true if both operands are true
  • op1 op2 - true if either operand is true
  • !op - true if operand is false
  • Note has greater precedence than

28
boolean variables
  • A primitive type to store true or false
  • e.g., boolean done false
  • if (!done)
  • done true
  • Often used just for readability
  • boolean pass grade 70
  • if (pass) ...

29
More?Less?
30
WednesdayIndependence Day
Write a Comment
User Comments (0)
About PowerShow.com