Transcript Variables

Java the UML Way
http://www.tisip.no/JavaTheUmlWay/
Variables, Data Types, and Expressions
The Case
Algorithms and errors
Test data set
Statements, blocks and names
About names
Variables
Data types for integers
Data types for decimal numerals
Data types for boolean values and characters
A data type for texts: String
Assignments and arithmetical expressions
Type converting
version 2002-04-17
page 2-3
page 4
page 5
page 6
page 7
page 8-9
page 10-11
page 12
page 13
page 14
page 15
page 16-17
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 2
The Case
• To renovate an apartment:
– How much paint, or wallpaper, will you need for a wall? Or how much
flooring?
• Here: A little program calculating the area of a surface, e.g. a floor or a
wall.
• We'll work with this case throughout the book. At last we'll have a useful
program with graphical user interface (Fig. 15.8)
• Basic questions when solving a programming problem:
– Output data: What do we expect to get? What will the program display to the
user?
– Input data: What has the user to input for the program to produce the given
output?
• In this case:
– Output data: the area in square meters
– Input data: length and width
/* Example Run:
Length: 5.8 m
Unfortunately, it is rather difficult to read
Height: 2.4 m
data into a program in Java. We will
The area of the wall is 13.92 square meters.
postpone this until chapter 3. Instead we
will do some simplifications.
*/
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 2, page 2
The Source Code
input data are coded directly
into the program, rather than
read from the user
class WallCalculations {
public static void main(String[] args) {
double length = 5.0;
double height = 2.3;
calculation
double area = length * height;
System.out.println("The area of the wall is " + area + " square meters.");
}
}
/* Example Run:
ouput data
The area of the wall is 11.5 square meters.
*/
5.0
2.3
length
height
11.5
area
Three variables. A variable is a place of storage
in the computer's memory. The contents of a
variable are interpreted according to the data type.
Here the type is a decimal numeral (double).
Solve problem no. 2 on page 26.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 2, page 3
Algorithms and program errors
• An algorithm is a limited and ordered set of well-defined rules
(instructions) for solving a problem. Examples include instruction
manuals and cake recipes.
• Algorithm to calculate the area of a surface:
– Input length and height.
– Calculate the area according to the formula.
– Print out the area.
• The syntax are rules that the compiler set to our code.
• The program logics tells us which problems the program solves for us.
• Program errors:
– Syntax error: Words and punctuation are not coded according to the syntax
rules.This type of errors are told us by the compiler.
– Logical errors: Either we have not programmed the algorithm correct, or the
algorithm itself is not correct. The compiler doesn't tell us about these errors.
Problem: Create some syntax errors and logical errors in the program at slide 3
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 2, page 4
Test Data
• A test data set is a set of input and output data whose purpose is to
detect logical errors in the program.
– Will test the program's outer limits
– Test data is seldom realistic data
– An example:
• An archive system for a library has to work for 0 books and for 1000000
books, as well. Most of the realistic data are somewhere between these limits.
– Test data for the Area Program:
Data set No.
1
2
3
4
Length
Height
0.0
100
2.3
-2.5
0.0
10
4.5
3
Expected Result
0.0
1000
10.35
error message
Problem: Show how we may test our program with these data sets.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 2, page 5
Statements, Blocks and Names
• A statement is an instruction to the computer. It ends with a semicolon.
• A block is one or more statements surrounded by curly braces {}.
• The words in a program are either keywords (see Appendix B) or
words which are explained to the compiler by declarations. A
declaration introduces a new word to the compiler, and it states what
it's a name for. In addition to all the declarations that come with Java,
we also make our own declarations.
Problem: Mark all the blocks, the keywords, the declarations that come with Java,
and our own declarations in this well-known program:
class WallCalculations {
public static void main(String[] args) {
double length = 5.0;
double height = 2.3;
double area = length * height;
System.out.println("The area of the wall is " + area + " square meters.");
}
}
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 2, page 6
About Names
• Syntax:
– A name (or identifier) can consist of letters, digits, the underscore
character _, and $.
– The first character cannot be a digit.
– Names cannot include spaces.
– Upper- and lower-case letters are distinct characters.
– There are no limits on the number of characters in the name.
• Examples of different valid names:
– number, Number, numberOfChildren, student21.
• Names should evoke immediate associations to the reality the program
is modeling.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 2, page 7
Variables
•
•
A variable is a place of storage in the computer's memory. A variable contains
one value, for example a number or a character.
The content of a variable may be changed several times:
double price = 14.50;
price = 21.70;
price = 29.90;
•
•
A variable declared inside a method is called a local variable.
A local variable has to be given a value before it can be used. As a rule the
variable gets it's value in the declaration. The variable is initialized. But we
may also do it in this way:
double price; // this is a declaration without initializing
price = 14.50; // here the variable gets it's start value
•
•
A variable's scope is the part of a program where the declaration is valid. The
scope of a local variable is the rest of the block in which it is declared.
A variable may have constant content:
final double tax = 23.0;
•
final is a modifier; that means it is a keyword that changes the meaning of
what follows it. Here the variable gets the property of being non-changeable.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 2, page 8
Variables, cont.
• Why do we create a tax variable with constant content instead of just
writing the number 23 when we need it?
– The name tells the reader more than the number.
– If the tax is changed, we only have to change the number in one place,
namely the place where the tax variable is declared.
– Decimal numerals are the same everywhere. We don't use for example
3.14 one place and 3.14159 in another place.
• tax is what we call a named constant, while 23 is an anonymous
constant or a literal.
• We make the following recommendations when naming variables:
– Use lower case.
– Avoid using underscore and $
– If a name is composed of more than one word, every new word should
start with a capital letter. For example: numberOfCitiesInBelgium.
Solve problems 1 and 2, page 33
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 2, page 9
Data Types for Integers
• A data type (or just “type”) describes a set of values. We start looking
at data types describing integers.
• Literals: 105, -67, 0, 67890123456789L
• Variables of integer types:
int number = 30;
long largeNumber = 1234567891234L;
• Summary of the integer data types:
name
no. of bytes
byte
1
short
2
int
4
long
8
char
2
range
[-128, 127]
[-32 768, 32 767]
[-2 147 483 648, 2 147 483 647]
[-9 223 372 036 854 775 808,
9 223 372 036 854 775 807]
[0, 65 535]
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 2, page 10
Data Types for Integers, cont.
• An integer literal starting with the 0 digit is interpreted according to
the Base 8 system (the octal system). This is the cause for many
strange errors.
System.out.println(”Printing 056 gives ” + 056);
gives the following printout:
Printing 056 gives 46
• If we try to store a too large number in an integer variable, we get a
compilation error. An example: number = 123456789056666;
• However, we do not get an error message if the big number is the
result of an integer calculation. What we get is a wrong numerical
answer.
• Division by zero gives an error message, and the program stops.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 2, page 11
Data Types for Decimal Numerals
•
•
Literals:
1.25, -0.0067, 6.7e10 (= 6.71010), 3.256e-5 (= 3.25610-5), -4.67F
Variables:
double number1 = 2.35;
float number2 = 2.35f;
•
We have two data types for decimal numerals:
– float, 4 bytes, range approx. ±[10-38, 10+38]. The no. of sign digits is approx. 7.
– double, 8 bytes, range approx. ±[10-308, 10+308]. The no. of sign digits is approx. 15.
•
•
•
•
•
The 0.0 value is included in the ranges.
Decimal calculations which bring us outside the range, give us an answer. We
get Infinity or 0. (This is as opposed to integer calculations, where we get a
wrong numerical answer, and no message.)
Division by zero gives the Infinity value as the answer. (Integer division by zero
gives us an error message and program stop.)
The value of the expression 0.0/0.0 is NaN (Not-a-Number).
Although we get values as answers, there is no point to continue calculation after
we've got values as Infinity and NaN.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 2, page 12
Data Types for Boolean Values and for Characters
• A data type for boolean values - boolean
– A variable of this type may have true or false as it's value.
boolean allWallsArePainted = false;
allWallsArePainted = true;
• A data type for characters - char
Literals are surrounded by apostrophes:: 'O', '7', '#'
Variables:
char letter = 'A';
char digit = '4';
• Every character has its own code number.
–
Most programming languages use the ASCII character set. This character set is
defined so that each character uses one byte of memory. That means that it can only
contain 256 different values. Of these, only the values 0 to 127 are standardized.
The other values vary from platform to platform and from country to country.
– Java uses the Unicode character set. With two bytes per character at its disposal, it’s
possible to store 65,536 different characters. The characters with numbers from 0–
127 correspond to the characters with the same numbers in ASCII. Appendix D
shows the standardized portion of the ASCII character set.
• Note the difference between a variable that contains the character '5'
(data type char), and one that contains the integer 5 (data type int)
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 2, page 13
A Data Type for Texts: String
•
Literals of this type are surrounded by double quotes:
"This is a text " "A" ""
•
Examples:
String city = "Trondheim";
String text = "This is four words.";
int number = 17;
System.out.println("We have " + number + " groups");
String cities = city + " Bergen";
System.out.println(cities);
Problem 1: What is printed if this code excerpt is inserted into a program and
run?
Problem 2: Solve problem 3 page 39.
•
•
Variables of the String type are called ”text strings”, or only ”strings”.
NB! Simple quotes for characters, double quotes for strings.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 2, page 14
Assignments and Arithmetical Expressions
• The four basic arithmetical operations + - * /
– Multiplication and division have higher priority than addition and subtraction.
– If we in a compound expression have more than one operation with the same
priority these are interpreted from left to right.
– The priority may be overridden by parentheses:
– 8 + 7 * 2 = 22
(5 + 7) * 5 = 60
6.0 / 3.0 *4.0 = 8.0
6.0 / (3.0 * 4.0) = 0.5
– Dividing integers gives no remainder (integer division):
5/2=2
•
1/3=0
-1 / -3 = 0
The modulo operator % gives only the remainder (this has nothing to do with
percent)
3%4=3
•
-5 / 2 = -2
-3.7 % 2 = -1.7
10 % 3 = 1
-5.5 % -2.2 = -1.1
In program code, the = symbol means assignment. The expression on the right side
is calculated, and the result is stored in the variable on the left side.
int number = 4;
number = number + 8;
// after this statement the number variable has the value 12
Solve problems 1 and 3 page 42.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 2, page 15
Type Converting
•
•
•
If the operands in an expression are of different type, the operand belonging to
the smallest type is converted to the other data type. One data type is smaller
than another data type if the type's range is smaller than the other type's range.
Here is the order of the number types (from the largest to the smallest): double,
float, long, int, short, byte.
An example:
double sum = 5674.33;
int number = 14;
double average = sum / number; // calculates 5674.33/14.0 = 405.31
•
Sometimes we need to override the type conversion. One common case is
when integer division is performed. An example:
int theNumberOfKids = 5;
”casting”
int theNumberOfApples = 23;
double applesPerKid = (double) theNumberOfApples / (double) theNumberOfKids;
•
•
•
The answer is 4.6.
Controlled type conversion is called casting.
Question: The example above. What is the result without casting?
Note that the content of the variable is not changed by casting. The value is
fetched out, and then converted before it is used in the calculation.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 2, page 16
Conversion from Decimal Numerals to Integers
• Truncating, not rounding
• Examples:
int a = (int) 1.7; // a gets the value 1
int b = (int) (1.6 + 1.7); // b gets the value 3
int c = (int) 1.6 + (int) 1.7; // c gets the value 2
• Rounding is performed by adding 0.5 to the original value:
int a = (int)(1.7 + 0.5); // a gets the value 2, not 1 as above
Solve problems, 1 and 3, page 45.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 2, page 17