39
FIT1002 2006 1 Objectives 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

FIT1002 2006 1 Objectives By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give

  • View
    221

  • Download
    0

Embed Size (px)

Citation preview

Page 1: FIT1002 2006 1 Objectives By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give

FIT1002 2006

1

ObjectivesObjectives

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

Page 2: FIT1002 2006 1 Objectives By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give

FIT1002 2006

2

Example Algorithm (Interest)Example Algorithm (Interest)

calculate interest input: balance, interest rateoutput: interest

interest = balance * interest rate

balance interestRate interest

1000 5.0 50

variables

Page 3: FIT1002 2006 1 Objectives By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give

FIT1002 2006

3

VariablesVariables

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.

Page 4: FIT1002 2006 1 Objectives By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give

FIT1002 2006

4

Variables (in Java)Variables (in Java)

...

int interestRate;int balance;int interest;

interestRate = 5; balance = 1000; interest = balance * interestRate / 100;

...

Page 5: FIT1002 2006 1 Objectives By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give

FIT1002 2006

5

Data Types in JavaData 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.

Page 6: FIT1002 2006 1 Objectives By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give

FIT1002 2006

6

A Computer Program (in A Computer Program (in Java)Java)

...

int interestRate;int balance;int interest;

interestRate = 5; balance = 1000; interest = balance * interestRate / 100;

...

Page 7: FIT1002 2006 1 Objectives By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give

FIT1002 2006

7

A Computer Program (in A Computer Program (in Java)Java)

...

int interestRate;int balance;int interest;

interestRate = 5; balance = 1000; interest = balance * interestRate / 100;

...

interestRate

Page 8: FIT1002 2006 1 Objectives By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give

FIT1002 2006

8

A Computer Program (in A Computer Program (in Java)Java)

...

int interestRate;int balance;int interest;

interestRate = 5; balance = 1000; interest = balance * interestRate / 100;

...

interestRate

balance

Page 9: FIT1002 2006 1 Objectives By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give

FIT1002 2006

9

A Computer Program (in A Computer Program (in Java)Java)

...

int interestRate;int balance;int interest;

interestRate = 5; balance = 1000; interest = balance * interestRate / 100;

...

interestRate

balance

interest

Page 10: FIT1002 2006 1 Objectives By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give

FIT1002 2006

10

A Computer Program (in A Computer Program (in Java)Java)

...

int interestRate;int balance;int interest;

interestRate = 5; balance = 1000; interest = balance * interestRate / 100;

...

interestRate

balance

interest

5

Page 11: FIT1002 2006 1 Objectives By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give

FIT1002 2006

11

A Computer Program (in A Computer Program (in Java)Java)

...

int interestRate;int balance;int interest;

interestRate = 5; balance = 1000; interest = balance * interestRate / 100;

...

interestRate

balance

interest

1000

5

Page 12: FIT1002 2006 1 Objectives By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give

FIT1002 2006

12

A Computer Program (in A Computer Program (in Java)Java)

...

int interestRate;int balance;int interest;

interestRate = 5; balance = 1000; interest = balance * interestRate / 100;

...

interestRate

balance

interest

1000

5

50

Page 13: FIT1002 2006 1 Objectives By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give

FIT1002 2006

13

Type Type intint

An int is a whole number (e.g. 21). You can do arithmetic with an int.

int age = 21;

addition +subtraction -multiplication *division /modulus %

Note that a declaration can also contain the an initialization (initial assignment)

age

21

int age = 15;age + 32 * age - 4age / 2age % 10

Page 14: FIT1002 2006 1 Objectives By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give

FIT1002 2006

14

Initialising a VariableInitialising 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.

Page 15: FIT1002 2006 1 Objectives By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give

FIT1002 2006

15

The Assignment OperatorThe 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 ".

int anAge = 0;allocates a memory location big enough for an integer, calls it anAge, and puts 0 in it.

anAge = 10;puts 10 into an existing memory location called anAge.

anAge

0

anAge

10

Page 16: FIT1002 2006 1 Objectives By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give

FIT1002 2006

16

Whole Number TypesWhole 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 -128 to 127 (8 bits)

short -32,768 to 32,767 (16 bits)

int -2,147,483,648 to 2,147,483,647 (32 bits)

long -9,223,372,036,854,775,808 to

9,223,372,036,854,775,807 (64 bits)

Page 17: FIT1002 2006 1 Objectives By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give

FIT1002 2006

17

Type Type doubledouble

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;price

3.95

addition +subtraction -multiplication *division /modulus %

price * 0.10price / 2price + price * 0.1

Page 18: FIT1002 2006 1 Objectives By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give

FIT1002 2006

18

Floating Point Number Floating Point Number TypesTypesThe 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.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 real-valued numbers are always dangerous.

Page 19: FIT1002 2006 1 Objectives By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give

FIT1002 2006

19

Overflow and UnderflowOverflow 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=256i*i=65536i^4=0

This is called an overflow. “i” has exceeded the representational range of an integer.

Page 20: FIT1002 2006 1 Objectives By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give

FIT1002 2006

20

Overflow and UnderflowOverflow and UnderflowIn the same way you can get an underflow when the variable cannotrepresent 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-991/(d*d)=1.0000000000000001E-1981/(d^4)=0.0

This is called an underflow. “d” has exceeded the precision of a double.

Page 21: FIT1002 2006 1 Objectives By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give

FIT1002 2006

21

Limits of Number TypesLimits 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.

Page 22: FIT1002 2006 1 Objectives By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give

FIT1002 2006

22

Type Type charchar

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';

You cannot add '3' and '2' and get '5'.

response

'Y'

Page 23: FIT1002 2006 1 Objectives By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give

FIT1002 2006

23

The The charchar Type 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).

Page 24: FIT1002 2006 1 Objectives By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give

FIT1002 2006

24

ASCII CodeASCII Code

Page 25: FIT1002 2006 1 Objectives By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give

FIT1002 2006

25

Type Type booleanboolean

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.

boolean isStudent = true;

isStudent

true

Page 26: FIT1002 2006 1 Objectives By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give

FIT1002 2006

26

The The booleanboolean Type 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);

Page 27: FIT1002 2006 1 Objectives By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give

FIT1002 2006

27

Incompatible TypesIncompatible 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;

float answer = Math.pow(2.3, 4.9);

Possible loss of precision

Page 28: FIT1002 2006 1 Objectives By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give

FIT1002 2006

28

Integer DivisionInteger 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

Page 29: FIT1002 2006 1 Objectives By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give

FIT1002 2006

29

Casting (Explicit Casting (Explicit Conversion)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.

Page 30: FIT1002 2006 1 Objectives By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give

FIT1002 2006

30

Type CoercionType CoercionA “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 anythingfloat can be promoted to doublelong can be promoted to float or doubleint can be promoted to long, float or doublechar 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

Page 31: FIT1002 2006 1 Objectives By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give

FIT1002 2006

31

StringsStrings

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;

Page 32: FIT1002 2006 1 Objectives By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give

FIT1002 2006

32

Type CheckingType 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 messageincompatible types -found java.lang.String but expected int

String aName = 77;produces the error message incompatible types - found int but expected java.lang.String.

Page 33: FIT1002 2006 1 Objectives By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give

FIT1002 2006

33

ExpressionsExpressionsAn 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;aNumberaNumber = 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);

Page 34: FIT1002 2006 1 Objectives By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give

FIT1002 2006

34

Precedence Rules for Precedence Rules for Evaluating ExpressionsEvaluating Expressions

Parentheses (brackets)Unary operators + - ! Binary arithmetic operators * / %Binary arithmetic operators + -Relational operators < > <= >= Relational operators == !=Logical operator &&Logical operator ||

Highest precedence

Lowest precedence

Page 35: FIT1002 2006 1 Objectives By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give

FIT1002 2006

35

Constants 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;

Page 36: FIT1002 2006 1 Objectives By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give

FIT1002 2006

36

Calculating the Area of a Calculating the Area of a CircleCircle

... 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?

Page 37: FIT1002 2006 1 Objectives By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give

FIT1002 2006

37

Built-in MathematicsBuilt-in Mathematics

... double a = Math.sqrt(10); double b = Math.log(5);...

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.

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.

Page 38: FIT1002 2006 1 Objectives By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give

FIT1002 2006

38

Numerical ErrorsNumerical Errors

... double x = 1/0; System.out.println(x); x = Math.log(0);

System.out.println(x); x = Math.sqrt(-1); System.out.println(x);

...

Mathematically, the value of some expressions is not well-defined. Computing such an expression usually returnssome special (non-numeric) value.

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.

Page 39: FIT1002 2006 1 Objectives By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give

FIT1002 2006

39

Inifinity and NaNInifinity and NaN

... 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);

...

The non-numerical values inifinity and NaN propagate throughexpressions. For example,

• inifinity + infinity = infinity • 3.5 / NaN = NaN

etc.The details of this are, however, complicated. For now it is safestto think of Infinity and NaN results as results that are not allowed. You can test for these values: