CS
99
Summer
2001 07.03
Named storage location in
memory with an associated type
Syntax:
<type>
name [= init] [, name = init]
;
Examples:
int y;
int x = y;
double pi =
3.14;
String hi =
Hi!;
int a = 1,
b, c = 2;
Every value in a program
has a type
Every variable, since it
holds values, also has a type
Java has some built-in
types called intrinsic types or primitive types
Programmers can also create
their own types using classes
Integers
Numbers that are whole valued and signed
e.g., 5, -1000, 42, 0
Java types byte, short, int, long
Floating point numbers
Numbers that have a decimal component
e.g., 3.14, 1.78, .9944, -1.69, 1.0, 0.0
Java types float, double
Well
usually use int and double
Characters
The symbols in a character set, such as letters, numerals, punctuation, etc.
e.g., a, b, c, X, Y, Z, 1, %
Java type char
Booleans
Values that are either true or false
Java type boolean
The
String type
String is technically not a primitive type, but an
object type
Strings are sequences of characters
e.g., Hello, world!, 1 + 1 = 2
Follow Style Guide
First character in name
must be a letter
Remaining characters can be
letters, numbers, $, or the underscore _ (e.g., cs99_2000su)
Can be (practically) as
long a name as you want
Variables are placeholders
for values in a program
Literals are actual values
written directly in a program:
int x = 5;
double y = x + 2;
String s = 5 + 2 = + y;
Literals above: 5, 2, 5 + 2 =
Syntax:
variable = value
Examples:
x = 5;
y = x;
z = x + y;
d =
Math.round(b) 1;
Values combined by
operators
Have a value, and therefore
a type; but not all expressions return values.
Operators allow values to
be combined
Categories of operators
Arithmetic
Relational
Logical
Modulus
%
Increment
++
Decrement
--
Addition
assignment += (also -=, *=, /=, %=)
Division
/
Multiplication
*
Subtraction
-
Addition
+
<= (less than or equal to), >= (greater or equal to), < (less than), > (greater than), != (not equal to).
== (equal to)
For equality operators:
Operands must be of the same type
For ordering operators:
Operands must be of numeric type
For both:
Resulting value is a boolean
Common error:
Using the assignment operator instead of the equality operator
Logical
Operators
!
(NOT), || (OR), && (AND)Operands
and resulting values are boolean