Download GP2

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
Introductory Programming (GP)
Spring 2006
Lecture 2
We start at 13:00
Slides are available from the course home page
Feel free to print them now
www.itu.dk/courses/GP/F2006
Martin Lillholm
GP2, Martin Lillholm
1
Practical Information
• News Group
– it-c.courses.GP
– Via http://webmail.itu.dk/
• Lab classes
– www.itu.dk/courses/GP/F2006
• Questions ?
GP2, Martin Lillholm
2
Last Week
• A basic computer and its infrastructure
– CPU, main memory, storage, networks, internet, WWW
• Program Development
– Problem, analysis, design, implementation (programming),
testing
• (Java) programs
– Classes, objects, syntax, semantics, reserved words, the simple
anatomy of Java programs
• Compilation and program execution
– Source code, editors (e.g. Notepad); bytecode, compilers
(javac), execution, runtime environment (java).
• Three kinds of Java programs
– ”Normal” via console, programs with GUI, Applets
GP2, Martin Lillholm
3
Today
• More about compilation, runtime environment, classes,
objects, the anatomy of Java programs
• Identifiers
• Variables
• (Primitive) types
• Operators
• Expressions
• Libraries
• Mere about Applets, GUI, and graphics
GP2, Martin Lillholm
4
What is Programming Anyway?
• Problem / task
• Analysis
• Design (evt. OO)
• Implementation (in e.g. Java)
• Compilation
• Testing
GP2, Martin Lillholm
5
From Source Code to Executable
Java Virtual Machine
Task
Source
solution
Compiler
(Editor)
Interpreter
(JVM)
JIT
Hello.java
text (ASCII)
Hello.class
(Java bytecode)
GP2, Martin Lillholm
Result
6
Compilation Time – Run Time
Source
Syntax and type errors
Compiler
Runtime and “semantic” errors
Fortolker
(JVM)
GP2, Martin Lillholm
7
Java Components (again)
• White spaces
– space, tabulator stops (\t), newline (\n)
• Comments
// Single line comment
/* Multiple line
comment ... */
• Reserved words; “core” Java.
• Identifiers
• Syntax rules …
GP2, Martin Lillholm
8
The Anatomy of a Java Program
class ClassName {
// Attributes;
Define the state of objects
// methods;
The work horses of objects
public static void main (String[] args) {
// statements and today’s focus area
}
}
It’s possible to have several classes in one .java file but only one
can and should have a main method.
GP2, Martin Lillholm
9
Methods – Informally Speaking
• Methods are used for grouping and naming sequences of
statements/command.
• Methods can receive input (parameters/arguments) and
output results (return values).
• Methods do “the hard” work in Java programs.
• Methods are typically invoked/called by other methods. A
method call is often a statement in itself.
• Program execution normally always start in the main-method.
• Methods enable task abstraction.
GP2, Martin Lillholm
10
Using Methods
•
If a class has a main method program execution starts with the first
statement here and continues statement by statement.
•
These statements can call other methods than the main method.
•
Methods are always called using zero or more parameters in
parentheses:
write()
area(10)
add(10,20)
•
// call/invoke zero parameter method write
// call/invoke one parameter method area
// call/invoke two parameter method add
Methods can be “hidden” in other classes and/or objects.
System.out.println(“Print a line of text”);
System.out.print(“Another line”);
System.out.println();
•
Notice the . operator
GP2, Martin Lillholm
11
Today’s Focus
• Today we focus on code/statements in the main method.
• But any of them can and will (next time) be used in other
methods.
GP2, Martin Lillholm
12
Identifiers - Names
• Used for all program elements that must be named
– Classes
– Attributes / fields
– Methods
– Parameters
– (Local) variables
– Packages
• Identifier rules:
– First character must be a Java letter
– Then 0 or more Java letter or Java numbers
– Java letter: A,...,Z, a,...z, $, _ (plus some others ...)
– Java number: 0,...,9
– No spaces!
– Syntax diagram ... (L&L page 32)
GP2, Martin Lillholm
13
More about Identifiers
• Examples:
– Legal: HelloWorld, HelloGUI, label, i, j, ...
– Illegal: 3label, !navn
• Conventions
– Classes and packages has an upper case first letter and
upper case all for the first letter of all new words (no
spaces): HelloApplet
– Attributes, parameters, variables, methods has a lower
case first letter and upper case for the first letter of all
new words (no spaces): labelColor
– (Named) constants only upper case and an _ (underscore)
to separate words: MAX_HEIGHT, PI
– More conventions in appendix F
GP2, Martin Lillholm
14
Literals – Constant Expressions
• “Atoms”
• Used for supplying specific data/information to programs
• Grouped in so-called types:
– Numbers
int:
1 2 3 45 -17 (Syntax diagram L&L page 75)
double: 0.1, -45.0, 243.89
– Characters/letters
char:
’a’ ’3’ ’K’ ’ ’
(In reality numbers: ASCII (256), UNICODE(65536))
– Text strings
string: ”Hello World” ”Welcome to GP!” ”h” ””
Escape Sequences: L&L page 67
– Boolean values (truth values)
boolean: true false
GP2, Martin Lillholm
15
Literals – an example
GP2, Martin Lillholm
16
(Local) variables
• A named slot in memory that can be assigned a value and
read one or several times. The actual physical space is
allocated by the runtime environment and the operating
system.
• Variables must be declared before use!
• A variable is local/automatic when declared in a method
• A variable always has a type
– Primitive types:
Integers: byte, short, int, long
Characters: char
Decimal numbers: float, double
Boolean values: boolean
• Why types? Memory usage, robustness, type safety.
GP2, Martin Lillholm
17
Types af numbers and their capacity ...
• Bits ?
Type
Storage
Min value
Max value
byte
short
int
long
8 bits
16 bits
32 bits
64 bits
-128
-32,768
-2,147,483,648
< -9 x 1018
127
32,767
2,147,483,647
> 9 x 1018
float
double
32 bits
64 bits
+/- 3.4 x 1038 with 7 significant digits
+/- 1.7 x 10308 with 15 significant digits
GP2, Martin Lillholm
18
Variable Declarations
• A variable must be declared before first use – why?
(final) type identifier;
int height;
char firstLetter;
boolean isDigit;
String firstName;
Syntax diagram L&L page 69
• Naming convention
GP2, Martin Lillholm
19
Assignments
• Assignment statements are used for assigning values to
variables. Values can be either literals or the result of an
expression – more on expressions later.
• Syntax diagram L&L page 72
• Examples:
height = 23;
firstLetter = ’m’;
isDigit = true;
firstName = ”Martin”;
GP2, Martin Lillholm
20
Simultaneous Declaration and Assignment
Initialisation
• Several variables of the same type can be declared on the
same line
• Variables can have values assigned when they are declared
(initialisation)
int height, weight=50, size;
char firstLetter=’M’;
double num1 = 12.23, num2, num3=-23.0;
• Syntax diagram L&L side 69
• Left- and right-hand side of assignment statements
GP2, Martin Lillholm
21
Example 1
GP2, Martin Lillholm
22
Eksempel 2
GP2, Martin Lillholm
23
(Named) Constants
•
Constants are used to name values that are used one or more times
in a program but doesn’t change value – contrary to variables.
•
Examples could be mathematical constants like PI or the maximally
allowable height MAX_HEIGHT.
•
Naming convention.
•
Why constants?
– No accidental change
– A name is more descriptive than a number
– Several uses  only one change
•
Declared and initialised. Can’t have new values assigned.
•
Declared and initialised like variable but with a final prefix.
final int MAX_HEIGHT = 180;
final double PI = 3.1416;
GP2, Martin Lillholm
24
Expressions
• An expression is a combination of one or more operands and
operators. Operands are values or other expressions. Mostly
used for calculations – later we shall, however, see examples
of String expressions.
• An arithmetic expression calculates numerical values and
consists of zero or more arithmetic operators.
+
-
*
/
%
(binary and unary operators)
• Operands are the input to an expression … the result of the
expression its “return” value.
• Operands can be literals, variables, and expressions.
• Variables used in expressions are (normally) only “read” not
changed. Expressions make up the right-hand side of
assignment statements. (Syntax diagram L&L page 72)
GP2, Martin Lillholm
25
Expressions … Examples
1+2+3+4
2+3*4
10/5
10/4
10.0/4, 10/4.0, 10.0/4.0
5%3
10%5
10
14
2
2
2.5
2
0
int
int
k =
k =
8
12
i=4, int j=4;
k;
i+j;
k+4;
double x=3, double y=1;
double z;
z = x/y + 4;
z = 1/3;
z = 1.0/3;
7.0
0.0
1/3=0.333333
GP2, Martin Lillholm
26
Operator Precedence
• Expressions are evaluated before assignment.
• In generals expressions are evaluated from left to right
• But multiplication and division takes precedence over addition
and subtraction – they have higher precedence.
Precedence level
Operator
1
Unary + -
2
*/%
3
+-+
4
=
String concatenation
• Parentheses are always evaluated first and thus can influence
“normal” evaluation order
GP2, Martin Lillholm
27
Example Expressions and Order of Evaluation
a + b + c + d + e
1
2
3
4
a + b * c - d / e
3
1
4
2
a / (b + c) - d % e
2
1
4
3
a / (b * (c + (d - e)))
4
3
2
1
If in doubt: Use parentheses but don’t overdo it!
GP2, Martin Lillholm
28
Example
GP2, Martin Lillholm
29
Specialised Operators
• Increment and decrement operators ++ and -int a = 5, b;
a++;
b = a++;
b = ++a;
a = a--;
// same as a = a + 1;
• Assignment operators +=, -=, *=, /= etc.
a += 5; // same as a = a + 5;
B *= a + 12 // same as b = b*(a+12);
• Oftentimes referred to as syntactic sugar
GP2, Martin Lillholm
30
Type Conversion
• Java is a strongly typed language.
• It can, however, be necessary and convenient to convert
between types.
• Sometimes, we e.g. want to use an integer as decimal
number 5 = 5.0.
• We never change the type of a variable per se – only its use
and context in expressions.
• Conversions should be and normally are lossless in terms of
information.
– 5  5.0
– 5.5  5
int to double lossless
double to int lossy
GP2, Martin Lillholm
31
Types of Type Conversion
• Widening conversion:
From a ”smaller” data type to a ”bigger”.
short -> int, float -> double.
Usually lossless and thus safe.
• Narrowing konvertering:
From a ”bigger” type to a ”smaller”.
int -> short, double -> float.
Usually lossy and thus unsafe.
GP2, Martin Lillholm
32
Assignment Conversion
• Assignment conversion occurs when a value (result of an
expression) is assigned to variable of a different type.
• Only happens (automatically) when Widening is involved.
• As always the types and values of variables on the right-hand
side of the assignment are unchanged.
int dollars;
float money;
money = dollars; // The value of dollars is
// automatically converted to
// float before assignment.
GP2, Martin Lillholm
33
Promotion Conversion
• Promotion conversion happens automatically when operators
promote the values of their operands in order to add, multiply
etc. them.
• Again – only widening.
float sum, average;
int count;
average = sum/count;
• Also happen during String concatenation – more later.
GP2, Martin Lillholm
34
Casting – Forced Type Conversion
• Programmer controlled and forced type conversion.
• Casting is a powerful tool and should be used judiciously.
• Both widening and narrowing is possible with casting.
• Executed by putting the desired type in parentheses before
the expression that needs to be converted.
int total, count;
float average;
average = (float) total/count;
• Note that casting has higher precedence than binary
operators.
GP2, Martin Lillholm
35
Strings
• String literals in quotation marks: ”Martin Lillholm”
• For now think of Strings as a primitive type – although
they’re not! Notice the capital S in String.
String name = ”Martin Lillholm”;
System.out.println(name);
System.out.println(”Martin Lillholm”);
name = “Jens Hansen”;
System.out.print(name);
GP2, Martin Lillholm
36
String concatenation – The + Operator Again
•
Evaluates from left to right
•
Promotes operands to String:
“A” + 5 = “A” + “5” = “A5”
GP2, Martin Lillholm
37
An Overview of Graphics and Digital Images
• Digital images and/or graphics is made up from pixels
(picture elements)
• An image is typically arranged as a rectangle of pixels
• The width and height measured as number of pixels is the
image’s resolution.
• The number (again in terms of width and height) pixel a
monitor/screen can display is the resolution of the monitor.
GP2, Martin Lillholm
38
Coordinate System
• Any point in an image, in a Window, or on the screen can be
identified by a pair of coordinates (x,y).
• Java and most computer systems use a coordinate system
with the origin in the upper left corner :
(Of the image, the Window, or the screen)
112
(0, 0)
X
40
(112, 40)
Y
GP2, Martin Lillholm
39
Black/white, Gray Scale, and Colour
• Black and white images are represented using black=0 and
white=1.
• Gray scale images typically as an integer number between 0255 (8-bit)
• Colour images typically as a triple (R,G,B) representing an
additive mixture of red, green, and blue.
• R,G, and B are normally integers between 0 og 255
– (0,0,0) er sort
– (255,255,255) is white
– (128,128,128) is a gray ”halfway” between black and
white
– (255,0,0) is red … etc.
GP2, Martin Lillholm
40
The Color Class in Java
• Colours in Java is represented using the class Color. It’s
contained in the package java.awt
• The class contains some predefined colours:
Object
RGB values
Color.black
Color.blue
Color.cyan
Color.orange
Color.white
Color.yellow
(0, 0, 0)
(0, 0, 255)
(0, 255, 255)
(255, 200, 0)
(255, 255, 255)
(255, 255, 0)
• Or can be used to mix new ones.
GP2, Martin Lillholm
41
Drawing Lines using the Graphics Class
10
150
X
20
45
Y
page.drawLine (10, 20, 150, 45);
eller
page.drawLine (150, 45, 10, 20);
GP2, Martin Lillholm
42
Drawing rectangles using the Graphics class
50
X
20
40
100
Y
page.drawRect (50, 20, 100, 40);
GP2, Martin Lillholm
43
Drawing ovals using the Graphics Class
175
X
20
80
bounding
rectangle
Y
50
page.drawOval (175, 20, 50, 80);
GP2, Martin Lillholm
44
More about Applets
•
A “normal” Java-program can be executed using the e.g. Sun runtime
environment (java).
•
A Java applet is designed to be downloaded via the internet and
executed in a browser.
•
Alternatively it can be executed using Sun’s appletviewer.
•
An applet doesn’t have a main method.
•
The paint method can be used instead.
•
The paint-method receives a parameter of type Graphics
•
Graphics objects among other things define a “drawing-context”
•
Example:
Einstein.java (L&L side 97)
GP2, Martin Lillholm
45
An HTML-shell for the Einstein Applet
<html>
<head>
<title>The Einstein Applet</title>
</head>
<body>
<applet code="Einstein.class" width=350 height=175>
</applet>
</body>
</html>
GP2, Martin Lillholm
46