CIS 160 Variables and constants

Objectives

  • Discuss what variables are
  • Determine validity of variable names in Java
  • Discuss and enumerate the primitive data types in Java
  • Create variables and store data in variables
  • Cast variables to different data types
  • Declare constants

Variables

  • memory locations where values are stored
  • naming rules
    • must start with letter, '_', or '$'
    • can only contain letters, digits, '_', and '$'
    • case-sensitive
    • may not be one of Java's reserved words
  • declaring (e.g. "int num;")
  • initializing (e.g. "int num = 7;")

Data types

  • char: single characters (e.g. 'a', '%', '*', '2')
  • byte: -128 to 127
  • short: -32768 to 32767
  • int: -2147483648 to 2147483647
  • long: -922337203684547758808 to 922337203684547758807
  • float: numbers including fractional parts
  • double: larger, higher precision float
  • boolean: true or false

You can make a variable or value temporarily look like a different data type by "casting" it. You "cast" a variable by putting another data type name within parentheses in front of the value or variable. For example, the following code examples will display 5 instead of 5.9:

double x = 5.9; System.out.println((int) x); System.out.println((int) 5.9);

Notice that casting a floating point number to an integer truncates instead of rounding.

Constants

  • names of constants are usually uppercase by convention (but not required by compiler)
  • values of constants may not be changed after they are initialized
  • follow normal identifier naming rules
  • the final keyword is what makes it a constant
  • final double TAX_RATE = 7.5;
  • TestFinal.java: constants

External resource