3a-VariablesAndTypes..

advertisement
FIT1002 2006
Objectives
By the end of this lecture, students should be able to:
• explain the concepts of variables, operators, expressions,
keywords
• give examples of operators and keywords
• give examples of variables of types int, double, char
and boolean
• understand promotion and use casting where necessary
• understand the difference between variables that hold
basic data and variables that hold objects
• Reading: Savitch, Section 1.2
1
FIT1002 2006
Example Algorithm (Interest)
calculate interest
input: balance, interest rate
output: interest
interest = balance * interest rate
1000
balance
5.0
interestRate
variables
50
interest
2
FIT1002 2006
Variables
A variable is a name for a value or an object.
A variable can have an assigned value or be
unassigned (not yet assigned).
In a computer program the value of a variable is
effectively stored in a particuar memory location
and the variable itself is a name for this location.
3
Variables (in Java)
FIT1002 2006
...
int interestRate;
int balance;
int interest;
interestRate = 5;
balance = 1000;
interest = balance * interestRate / 100;
...
4
FIT1002 2006
Data Types in Java
Data is of different types. The type of a variable tells Java
what can be done with it, and how much memory needs to
be put aside for it.
When we declare a variable in Java, we need to specify:
• the type of the value we want to put in there, and
• the name we will use for that variable.
int age;
A Declaration like this effectively allocates the memory
space required to store a value of this type.
5
A Computer Program (in Java)
FIT1002 2006
...
int interestRate;
int balance;
int interest;
interestRate = 5;
balance = 1000;
interest = balance * interestRate / 100;
...
6
A Computer Program (in Java)
FIT1002 2006
...
int interestRate;
int balance;
int interest;
interestRate
interestRate = 5;
balance = 1000;
interest = balance * interestRate / 100;
...
7
A Computer Program (in Java)
FIT1002 2006
...
int interestRate;
int balance;
int interest;
interestRate
balance
interestRate = 5;
balance = 1000;
interest = balance * interestRate / 100;
...
8
A Computer Program (in Java)
FIT1002 2006
...
int interestRate;
int balance;
int interest;
interestRate
balance
interest
interestRate = 5;
balance = 1000;
interest = balance * interestRate / 100;
...
9
A Computer Program (in Java)
FIT1002 2006
...
int interestRate;
int balance;
int interest;
5
interestRate
balance
interest
interestRate = 5;
balance = 1000;
interest = balance * interestRate / 100;
...
10
A Computer Program (in Java)
FIT1002 2006
...
int interestRate;
int balance;
int interest;
5
1000
interestRate
balance
interest
interestRate = 5;
balance = 1000;
interest = balance * interestRate / 100;
...
11
A Computer Program (in Java)
FIT1002 2006
...
int interestRate;
int balance;
int interest;
5
1000
50
interestRate
balance
interest
interestRate = 5;
balance = 1000;
interest = balance * interestRate / 100;
...
12
FIT1002 2006
Type int
An int is a whole number (e.g. 21). You can do arithmetic
with an int.
int age = 21;
addition +
subtraction multiplication *
division /
modulus %
21
age
int
age
2 *
age
age
age = 15;
+ 3
age - 4
/ 2
% 10
Note that a declaration can also contain the an initialization
(initial assignment)
13
FIT1002 2006
Initialising a Variable
If a variable is not initialised in the declaration,
Java gives it a default value (e.g. 0 for int).
Generally, you should never rely on automatic
initalization, but give an initial value to a
variable when you define it.
Relying on automatic initalization is dangerous
and therefore bad style.
Most other programming languages do not
initialize automatically, and an unitialized
variable has a random value.
14
FIT1002 2006
The Assignment Operator
In Java, the assignment operator is =.
This causes a value to be put in a memory location.
It is read as “becomes” or "takes on the value of ".
0
int anAge = 0;
anAge
allocates a memory location big enough for an
integer, calls it anAge, and puts 0 in it.
10
anAge = 10;
puts 10 into an existing memory location called
anAge.
anAge
15
FIT1002 2006
Whole Number Types
The whole number types are stored with one bit
for the sign. The pattern for the number 13
stored as an int would be
00000000000000000000000000001101
byte
short
int
long
-128 to 127 (8 bits)
-32,768 to 32,767 (16 bits)
-2,147,483,648 to 2,147,483,647 (32 bits)
-9,223,372,036,854,775,808 to
9,223,372,036,854,775,807 (64 bits)
16
FIT1002 2006
Type double
The type called double is used to store a real
number , i.e. a number with a decimal point. It
is stored in a different format from an int.
You can do arithmetic on a double.
double price = 3.95;
addition +
subtraction multiplication *
division /
modulus %
3.95
price
price * 0.10
price / 2
price + price * 0.1
17
FIT1002 2006
Floating Point Number Types
The number types with a decimal point are stored with a
sign bit, a mantissa and an exponent, in a base 2 system.
(In the decimal system, 257.3 could be expressed as
2
2.573 * 10 where the sign is positive, the mantissa is 2.573 and the
exponent is 2.)
float -3.4e38 to +3.4e38
double -1.7e308 to +1.7e308
Most built-in methods for mathematics use the double type
to be on the safe side.
Generally, real-valued numbers cannot be expressed exactly
by a computer. Therefore, precise comparisons of realvalued numbers are always dangerous.
18
FIT1002 2006
Overflow and Underflow
Java
int i=256;
System.out.println("i="+i);
i=i*i;
System.out.println("i*i="+i);
i=i*i;
System.out.println("i^4="+i);
i=256
i*i=65536
i^4=0
This is called an overflow.
“i” has exceeded the representational range of an integer.
19
FIT1002 2006
Overflow and Underflow
In the same way you can get an underflow when the variable cannot
represent the true result with sufficient precision. The Java code
double d=1/1e99;
System.out.println("1/d="+d);
d=d*d;
System.out.println("1/(d*d)="+d);
d=d*d;
System.out.println("1/(d^4)="+d);
1/d=1.0E-99
1/(d*d)=1.0000000000000001E-198
1/(d^4)=0.0
This is called an underflow.
“d” has exceeded the precision of a double.
20
FIT1002 2006
Limits of Number Types
The language contains the smallest and largest number
each type can represent as constants.
Note: For Integer, the MIN_VALUE is the smallest
(negative) integer, but for Float and Double the
MIN_VALUE is the smallest positive Value, ie. the
precision that is available.
Integer.MIN_VALUE, Integer.MAX_VALUE,
Long.MIN_VALUE, Long.MAX_VALUE,
Float.MIN_VALUE, Float.MAX_VALUE,
Double, MIN_VALUE, Double.MAX_VALUE, etc…
The name of the constant is the type name with the initial letter capitalized
followed by a dot and MIN_VALUE or MAX_VALUE.
21
FIT1002 2006
Type char
A char is a character, i.e. a bit pattern you can
produce by pressing a key (or a combination of
keys) on a keyboard.
Examples are
'a' 'A'
'3' '?' '!'
char response = 'Y';
'Y'
response
You cannot add '3' and '2' and get '5'.
22
FIT1002 2006
The char Type
A character may be represented as a bit pattern in several
different ways, depending on the code that is used. The best
known code is ASCII (American Standard Code for
Information Interchange) which uses patterns of 8 bits.
Java uses Unicode, which adds an extra 8 bits to the ASCII
sequences, to represent up to 65, 536 different characters.
ASCII is a subset of Unicode
A character literal is shown in single quotes, e.g. 'a'.
Some special characters are represented by an escape sequence,
using the escape character \, e.g.
'\t' tab character
'\n' newline character (the Enter key).
23
FIT1002 2006
ASCII Code
24
FIT1002 2006
Type boolean
A boolean variable can have a value of only
true or false. This can be stored as one bit
A Person object may or may not represent a
student. We could have an attribute of Person
called isStudent which would be either true
or false for a particular Person instance.
true
boolean isStudent = true;
isStudent
25
FIT1002 2006
The boolean Type
The boolean type needs only 1 bit for storage because it
uses 0 to represent false and 1 for true (or vice versa -- it
doesn't matter which).
A boolean variable can be assigned the result of any
boolean expression, e.g.
boolean inRange = (number >= 1 && number <= 6);
26
FIT1002 2006
Incompatible Types
Java is a strongly typed language. This means that every
variable has a fixed type, and Java makes sure that you
don't put a value of the wrong kind into it.
int number = 2.3;
will produce a syntax error. So will
long bigNumber = 0;
int number = bigNumber;
Possible loss of precision
float answer = Math.pow(2.3, 4.9);
27
FIT1002 2006
Integer Division
The operator / performs an integer division. The
answer is an integer. Any remainder will be
discarded.
If you want to know what the remainder is, the
operator % (called modulus) will give it to you.
int number1 = 13, number2 = 5;
number1 / number2 returns 2
number1 % number 2 returns 3
28
FIT1002 2006
Casting (Explicit Conversion)
Sometimes we need a value to be converted to a different type, e.g.
when a library method returns a value that is a different type
from what we want, or when we want a double answer from an
integer division. We can specify a conversion, or cast the value
into the new type:
int dieRoll = (int)(Math.random() * 6) + 1;
float answer = (float)Math.pow(2.3, 4.9);
double kilometerage = (double) kilometres / litres;
A cast creates a temporary storage area. It does not change the type
of the initial value.
29
FIT1002 2006
Type Coercion
A “safe” typecast is sometimes performed
automatically in Java, if there is no danger of loss of
information (based on the types, not the values).
Such an automatic typecast is called a coercion. It
does not change the type of any existing variable.
double cannot be promoted to anything
float can be promoted to double
long
can be promoted to float or double
int
can be promoted to long, float or double
char
can be promoted to int, long, float or double
short can be promoted to int, long, float or double
byte
can be promoted to short, int, long, float or double
boolean cannot be promoted to anything
int x = 0;
float y = x;
performs a coercion
30
FIT1002 2006
Strings
int, char, double, boolean etc. are examples of primitive data
types. These are built-in to Java and are the basis of other types.
A string is a collection of characters (e.g. "Sally"). A String
object has this collection of chars in its attribute area.
e.g. String name = "Sally";
A String value is always written in double quotes. You can have
an empty String, shown as "".
!!! String is not a primitive data type.
!!! It is a class.
Even though this is not just a minor issue, we will ignore this for
now and pretend it is a datatype. Java contains a lot of built-in
String operations that we will introduce later. A simple example
is string concatenation:
String title = “When Harry met “+name;
31
FIT1002 2006
Type Checking
Java will not allow a value of the wrong type to be
put into a variable.
If we write, for example,
int aNumber = "3";
BlueJ will give the error message
incompatible types -found java.lang.String but expected int
String aName = 77;
produces the error message
incompatible types - found int but expected java.lang.String.
32
FIT1002 2006
Expressions
An expression returns a value. The value replaces
the expression in the code. We evaluate the
expression to get its value.
The value can be assigned to a variable, or passed
to a method as an argument, or used in another
expression.
An expression has a type, and in an assignment
the left-hand side and right-hand side types
must be identical.
int aNumber = 0;
aNumber
aNumber = aNumber + 1;
aNumber * 10 / 2 - 1;
The simplest thing you might want to do with a
value is print it out:
System.out.println(aNumber/2);
33
FIT1002 2006
Precedence Rules for Evaluating
Expressions
Parentheses (brackets)
Unary operators + - !
Binary arithmetic operators * / %
Binary arithmetic operators + Relational operators < > <= >=
Relational operators == !=
Logical operator &&
Logical operator ||
Highest
precedence
Lowest
precedence
34
FIT1002 2006
Constants
Sometimes a class or a method wants a variable to
have a value that cannot be changed. This is
called a constant.
In order to make sure that the value cannot be
changed, the variable is declared as final.
final int NUMBER_OF_PLACES = 10;
final String HEADING = "Monash";
final double PI = 3.142;
35
FIT1002 2006
Calculating the Area of a Circle
...
final double PI = 3.142;
double radius = 2.5;
System.out.println("Radius of circle is "
+ radius + " metres");
System.out.println("Area is "
+ PI * radius * radius
+ " square metres");
...
Which type will the expression PI * radius * radius produce?
36
FIT1002 2006
Built-in Mathematics
You will want to use more complex mathematical operations,
such as square root, logarithms etc. These are built-in,
but you need a special syntax to use them.
...
double a = Math.sqrt(10);
double b = Math.log(5);
...
The explanation for this syntax is that these operations are
pre-defined static methods in the “service” class Math.
We will encounter these concepts in the next week.
37
FIT1002 2006
Numerical Errors
Mathematically, the value of some expressions is
not well-defined. Computing such an expression usually returns
some special (non-numeric) value.
...
double x = 1/0;
System.out.println(x);
x = Math.log(0);
System.out.println(x);
x = Math.sqrt(-1);
System.out.println(x);
...
This will print the values “infinity”, “-infinity” and “NaN” .
We see that Java takes the limit value, where it can and produces
“NaN” (not a number) where this is not defined.
38
FIT1002 2006
Inifinity and NaN
The non-numerical values inifinity and NaN propagate through
expressions. For example,
• inifinity + infinity = infinity
• 3.5 / NaN = NaN
etc.
The details of this are, however, complicated. For now it is safest
to think of Infinity and NaN results as results that are not
allowed. You can test for these values:
...
double x = 1/0.0;
boolean a = Double.isInfinite(x);
System.out.println(a);
x = Math.log(0);
a = Double.isInfinite(x);
System.out.println(a);
x = Math.sqrt(-1);
a = Double.isNaN(x);
System.out.println(a);
...
39
Download