Download Prolog: Lecture 4

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
CSCI1402: Lecture 1 Week 2
Dr. David A. Elizondo
Centre for Computational Intelligence
School of Computing
Office: Gateway 6.61
email: [email protected]
Computer Storage









Variables store values (data)
Identifiers are names for variables
Type is a set of values which can be stored in a variable
A computer can represent data by using two states: high
voltage & low voltage. Represented by binary digits :
digit 1
digit 0
Combinations of these digits allow representation of numbers
and characters in the computer memory.
Characters are mapped onto a numerical code. (Unicode,
ASCII)
One bit = a binary digit with value 1 or 0
One byte = a sequence of 8 bits
One word = a smallest unit of computer memory (with16, 32,
48, 60 or 64 bits)
Computer memory
It consists of cells
 Cell capacity = word size of the computer.
 The cells are numbered consecutively from zero.
The numbers are called addresses. Each cell has a
unique address and can store simple data.
 More complicated data structures are stored in
consecutive cells.

Data types
Data type is defined as a range of values + types
of operators
 Each data type (and its operations) takes up
different size in the computer memory.
 WHY do we need different data types?
 allowing for different types of operation,
 different precision
 economy of memory storage and speed of
processing

Data Types
Java is strongly typed language:
 Every variable must have a declared type
 All expressions and values have a certain type
 All operations are checked by the compiler for
compatibility.
 Advantage: prevention of errors, better reliability

Simple Data Types in Java
Java has two forms of data types - simple types and
objects
 Simple types represent individual values.
 Object data types are more complex.
 Java has eight simple (primitive or elemental) types.
 Range of sizes : 1 bit to 64 bits of memory.

Simple Data Types in Java
Numerical types :
byte,
short, int,
long,
float, double
 Boolean type
: boolean represents the truth
value
 Character type
: char represents characters
from the Unicode character set defined by the ISO
(International Standards Organisation).
 Java is prescriptive about the sizes and ranges of
values of its simple types.
 This is important for the portability of the
programs.

The Integer Types
Type: byte, short, int, long
 Values: positive and negative integers (whole
numbers)
 Integer Ranges

size in bits
range of values
byte
8 (a single byte)
-128
to`+127
short
16
- 32 768
to +32 767
int
32
-2 147 483 648
to +2 147 483 647
long
64
-9 223 372 036 854 775 808
to +9 223 372 036 854 775 807
The Integer Types




Possible representation
byte - ordinary small whole numbers - the traffic lights, the
colours of the rainbow, the numbers of letters in the alphabet,
tracks on a CD, etc.
Byte is mostly used to represent the raw binary data being
processed by a program from an external source (such as an
encrypted message passed across a network, or the
compressed version of a data file).
short - adequate for relatively small values - the numbers of
cards in a player's hand, channels on a TV set, people in an
organization, ships in a harbour etc. This type is stored in a
special format, applicable to 16-bit computers.
The Integer Types
int is most frequently used type, numbers are in
tens of thousands and small billions - populations of
European countries, number of aphids in a field of
barley, number of positions analysed per second by
a PC-based chess program….
 long type should be used for larger whole-number
quantities, - elapsed time in milliseconds, total world
population etc.

 the int type is most used
 For wider range use type long
The Integer Types

Example:
/* Length of the Equator is 40,075 km,
compute its length in cm */
int lengthInKm= 40075;
int lengthInCm= 40075 * 100000; //error !
System.out.println(lengthInCm);

When the expression is evaluated, the final value of the
lengthInCm is too big. We need to change the variable to type
long.
The Floating Point Types





The floating point types are used to represent values from the
set of real numbers, numbers with an integer and a fractional
part - for example 3.4 , 0.0, -7.33, -11.019 .
Java uses the IEEE 754-1985[Ins85] standard for
representing floating point numbers and performing
calculations using these types.
The E format suffix permits using exponent notation, using an
upper or lower case e character.
The exponent e denotes the power of 10.
For example
3.92e +5 denotes 3.92 * 105
or 392,000
3.92e -5 denotes 3.92 * 10-5
or 0.0000392
Floating Point Ranges






The size and approximate ranges of these types are as
follows:
float occupies 32 bits and can store positive and negative
values in range 1.4e-045 to
3. 4e+038 (accuracy to 7 significant digits)
double occupies 64 bits and can store positive and negative
values in range 4.9e-324 to 1.8e+308 (accuracy to 15
significant digits)
Either type should be used where a fractional part may be
needed to represent a value that is not a whole number.
For instance, the 100 metre athletics world record time in
seconds, the number of light years to the nearest galaxy ,the
mean mark obtained by all students taking an assignment (the
individual marks might be whole numbers but the mean is
probably a real number).
Floating Point Ranges



Type double can store values which are both bigger and more
precisely represented than the float type. Applications should
probably always use double in preference to float, where
better precision is more important than conserving memory
space.
The double type is also the default real type used by other
parts of the Java language.
It is worth noting that some numbers cannot be exactly
represented in either the double or the float types - numbers
such as pi, l/3, and the square root of 2. Their values can only
be approximated using the primitive real data types, either
because they have an infinite number of decimal places or
simply because the primitive data types have only a limited
precision.
Floating Point Ranges

Example
/* calculate the cost of a product after a sales tax has been
added */
double price, tax, cost ;
//declaring three variables
price = 500;
//set price
tax = 17.5;
//set tax rate
cost = price * (1 + tax/100); //calculate cost

Question: Can we reduce the number of variables in the
above code?
The Type char
The type char occupies 16 bits. Each char holds a
representation of one character from the ISO
Unicode character set, such as A, x, %, 5, ? etc.
 Unicode is a character code set where each
character is mapped to a number. Unicode
represents characters from all human languages,
variety of symbols (punctuation, operators etc.) and
non-printable control characters (carriage return,
bell etc.)

The Type char
ASCII - American Standard Code for Information
Interchange - is a subset of the Unicode character set
normally used on an English language keyboard.
Letters A - Z are mapped to numbers 65 - 90,
a -z are mapped to numbers 97 - 122.



Questions :
How many letters are there in the alphabet?
 26

What is the code for letters X and x?
 88, 120

Digits 0 -9 are mapped from 48 - to ?
 57
The Type char

Example:
//char variables: assigning and displaying values,
//using arithmetic operators
public class UsingChars {
public static void main (String args[]) {
char ch, ch1;
ch = 'A';
//ASCII value 65
System.out.println("value is " + ch);
ch++;
System.out.println("value is " + ch);
ch1 = 90;
//WHAT IS THE VALUE ??
System.out.println("value is " + ch1);
int num = ch1 - ch;
//'Z'-'B'
System.out.println("result is " + num);
}
}
num = 'Z'-'A';
System.out.println("result is " + num);
The Type char

Program Output:
value is A
value is B
value is Z
result is 24
result is 25
The boolean Type









The boolean type is used to represent a state that can only be
either true or false. This requires only a single binary digit of
memory. Java uses reserved words true and false to represent
a boolean value.
Expressions that yield a Boolean value are commonly used to
control the flow of execution through a sequence of
statements. They are used as conditions for if-statements and
in loops (to be discussed in later lectures).
boolean b, boo;
b = true;
boo = 1 > 10;
System.out.println(b); //output is: . . . . .
System.out.println(boo); //output is: . . . . .
Variable Scope
Variable can be declared within any block
 A block is begun with an opening curly brace and
ended by a closing curly brace

{
}
Each time you start a new block, you are creating a
new scope.
 A scope determines what objects are visible to
other parts of your program and the lifetime of
those objects.

Variable Scope


Variables declared inside a scope are not visible (accessible) to code
that is defined outside that scope.
Example:
class ScopeDemo {
public static void main(String args [] ) {
int x; // known to all code within main
int y; // known to all code within main
x = 10;
y = 5;
if (x == 10) { //start a new scope
//int y; // Error y is already declared
int z;
z = 30;
y = 20;
System.out.println("Value of Y inside if -> " + y);
}
System.out.println("Value of Y outside if -> " + y);
//System.out.println("Value of Z outside if -> " + z); // Error z not known here
}
}
Variable Scope
The variables x and y are declared at the start of
main()’s scope and accessible to all subsequent code
within main().
 Within the if block, z is declared. Thus, z is not
visible outside the if block.
 Value of Y inside if -> 20
 Value of Y outside if -> 20

Life time of a variable
public class VarInitDemo {
public static void main(String args []) {
int x;
for (x=0;x<3;x++) {
int y = -1; // y is init each time block is entered
System.out.println(“y is: ” + y);
y = 100;
System.out.println(“y is now: “ + y);
}
}
}
Life time of a variable

Output generated:
y is: -1
y is now: 100
y is: -1
y is now: 100
y is: -1
y is now: 100
y is always reinitialized to -1 each time the inner for
loop is entered. The value of 100 is lost everytime.
The assignment operator

The assignment operator is the single equal sign, =.
var = expression
The type of var must be compatible with the type of
expression.
 Chain assignments are allowed:

int x, y, z;
x = y = z = 100; // set x, y, and z to 100

The value of z = 100 is 100, which is then assigned
to y, which in turn is assigned to x.
Short hand assignments
Short hand assignments simplify the coding of
certain assignment statements.
 x = x + 10; can be written as x += 10;
 x = x – 10; can be written as x -= 10;
 x = x * 10; can be written as x *= 10;
 x = x / 10; can be written as x /= 10;

Type conversion assignments


It is common to assign one type of variable to another.
An integer value can be assign to a float variable.
int i;
float f;
i = 10;
f = i; //assign an int to a float


The value of i is converted into a float, and then assigned to
f.
Generally we can assign a value of any type in the list below
to variables of any type which appears further down in the
list:
byte  short  int  long  float  double
Type conversion assignments
Can be done if:
 The two types are compatible
 The destination type is larger than the source type.

int x;
double y;
y = 10.12;
x = y // Error precision problem.
Type Casting
Is used for converting types in an assignment
 Involves changing the type of a value to another
compatible type
 The casting is done by placing brackets around the
name of target data type
 The cast operator is a unary operator (takes one
operand)
 Cast operators are available for any data type
 Syntax:
(target-type) expression

Type Casting

Example - storing a double value in an integer
variable
double guess;
//var of type double
guess = 7.8;
//assignment of correct type
int answer;
//var of type int
//answer = guess ;
//illegal expression
answer = (int)guess;
//cast double to int
//value of guess is 7.8 - not changed
//value of answer is 7 - truncated
Type Casting
Change the code to : guess = 8; will this compile ?
If so, will you still need to use casting?
 Type Casting of characters and integers
 char symbol = '7';
 //display the numerical value of var symbol
 System.out.println((int)symbol);
//The output is:
...

Type Conversion in expressions







Compatible data types can be mixed in expressions
Java uses Type promotion rule inside the expression:
char, byte, short are promoted to int
if one operand is long
- all types are promoted to long
if one operand is float
- all types are promoted to float
if one operand is double - all types are promoted to double
Ouside the expression the variables will keep values of their
original type
Java Keywords
Java contains 49 keywords which have a specific
meaning in the language.
 For a table with explanations see Schildt p.32 or
your handout.
 Other reserved words represent values: true, false,
and null.
 These words cannot be used for naming variables,
methods or other items in the code.

Java Identifiers









An identifier is a name given to a variable , method or any
other recognised element of the code (method, class, object
etc.) by the programmer
A variable identifier in Java
should start with a letter (underscore, or $ are special cases,
so avoid them)
followed by letters or digits 0-9 (underscore and $ are
allowed, but avoid )
may have any number of characters
is case sensitive
Valid identifiers:
x, Y, x1, Num1, num_1, sum, box, aBox, Total, $start, _end
first_floor, firstFloor, FirstFloor are three valid and
different identifiers
Java Identifiers









By convention variable names should
start with a lower case letter
be short if possible
convey the purpose of the variable. Each new word in the
identifier should start in capital letter
avoid using names of standard methods or classes (main,
String, System etc.)
Take care with these characters 1 (one), l (lower case el), 0
(zero), O (oh)
Other conventions apply for names of Java classes and
methods.
Q: Why are the following variable identifiers invalid?
1_floor, 1stFloor, 2003, go-to, do.this, my name, Mike’s, double
Example program
Program Example2.java
/*
This program demonstrates use of variables.
Call this file Example2.java.
*/
public class Example2 {
public static void main(String args[]) {
int var1; // this declares a variable
int var2; // this declares another variable
var1 = 1024; // this assigns 1024 to var1
System.out.println("var1 contains " + var1);
var2 = var1 / 2;
}
}
System.out.print("var2 contains var1 / 2: ");
System.out.println(var2);
Example program
Program Output:
var1 contains 1024
var2 contains var1 / 2: 512