Upload
sandra-beeman
View
215
Download
2
Embed Size (px)
Citation preview
Telecooperation/RBG
Technische Universität Darmstadt
Copyrighted material; for TUD student use only
Introduction to Computer Science ITopic 11: From Scheme to Java
Prof. Dr. Max MühlhäuserDr. Guido Rößling
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Contents• General Differences between Scheme and Java• Compilation of Java programs (abbreviated)• Variables in Java• Primitive data types• Operators for arithmetic, logic and bit
operations• Functions in Java• Flow of control in Java
– Conditionals, loops and recursion• Lists (Scheme) vs. Arrays (Java)• Commenting Java elements• Introduction to the Eclipse Development
Environment2
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
From Scheme to Java
• This slide set will present some of the most relevant elements of Java
• “Advanced” topics will follow later– Object orientation, inheritance, abstract classes, interfaces– Stepwise refinement– Java interpreter, compiler, virtual machine, runtime
environment• The goal of this slide set is to introduce Java based
on the similarities to Java
3
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
General Differences
• Scheme and Java follow two different styles of programming (“paradigms”)
• Scheme is a functional programming language– Functions and their application are central aspects– Problems are solved by decomposition and composition– “To solve problem X, decompose it into smaller problems
Y and Z. Define how to solve the smaller (atomic) problems and how Y and Z have to be composed to solve X.”
– Far removed from the actual machine level!– Often results in good, modular code
• Decompose the code in the same way as you decompose the problem
4
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Distance from machine levelin functional programming
5
(define (fold f n) (lambda (x) (if (empty? x) n (f (first x) ((fold f n) (rest x))))))
(define sumlist (fold + 0))(define multlist (fold * 1))
(sumlist ‘(3 4 5))12(multlist ‘(3 4 5)) 60
We do not even mention the list! Abstraction from the execution details
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
General Differences
• Java is an object oriented programming language– Objects should model real „things“ or contents
• Details will follow in T11+– Larger problems are solved by delegating tasks to other
objects– The underlying notation is imperative: thinking in
computation steps– “To solve problem X, execute the following sequence of
computation steps…”– Closer to the machine level– Only one message with a request for service is sent at
any time– If there are multiple objects, they can send messages to
each other • Subtasks can be delegated to known objects
6
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
A few words about the Java Syntax• Special symbols: ; { } . ( )
– { } enclose code blocks:• The definition of an object type (class body), • The definition of a method (method body)• Sequences of instructions, for example in the different
branches of conditional statements• …
– Expressions and statements including method calls (requests for services) within a block are separated by “;“
– . separates the receiver of a message from the message name
– ( ) encloses the list of parameters of a function or function call
7
(inc c2 5) c2.inc(5);
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
A few words about the Java Syntax
• Name (Identifier): c1, Counter, inc, dec– Names may only use a small subset of special
characters such as „_“, „$“, but for example not a „-“
• Keywords: new, void, …– Are used to structure the primitive instructions of
a program– Reserved – cannot be used as names– Upper/lower case is relevant!
• Void will be interpreted as a name, not as the keyword void
8
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
• General Differences between Scheme and Java• Compilation of Java programs (abbreviated)• Variables in Java• Primitive data types• Operators for arithmetic, logic and bit
operations• Functions in Java• Flow of control in Java
– Conditionals, loops and recursion• Lists (Scheme) vs. Arrays (Java)• Commenting Java elements• Introduction to the Eclipse Development
Environment
Contents
9
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Structure of a Java Program• A Java program can contain many classes, at least
one of which must contain a main method (main class)
• Responsibility of main:– Object generation the creation of an initially minimal
world• See slide set T12
– Calling the first operation– Normally, main should not control the program any
further– The main control flow is realized withing the object
operations– Do not forget: computation here is a cooperation of
multiple objects, where each object only computes a smaller subtask!
– Started and executed by the Java interpreter
10
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
How everything starts…• The „special “ method main will be called when a Java
program is executed…• For this to work, main must be part of a class
– More about this in T12
11
public class CounterTest { // ... public static void main(String[] args) { CounterConsumer cc = new CounterConsumer(); cc.doSomethingWithCounters(); } // ...} CounterTest.java
Java Compiler
JavaBytecode
Interpreter
javac CounterTest.java
java CounterTest
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Java Compilation
• Java Compiler– Input: a Java source code file, File.java, which
contains one or more class definitions• Such a file is called a compilation unit
– Output: per class Ex, exactly one file Ex.class will be created which contains the bytecode format of the class
12
Java C
om
pile
rEx1.class
Ex2.class
Ex3.class
class Ex1 {...}class Ex2 {...}class Ex3 {...}
File.java
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Performing computations• The task is decomposed into service requests
– Formulated as messages (method class) to objects• Each message contains:
– The name of the receiving object, for example c1– The name of the service (operation) that shall be
executed by the receiver• inc(), dec(), ...• The operation must be contained in the interface of the
receiver• Only one message with a service request is sent
at any point in time• If multiple objects exist, they can send messages
to each other– Delegation of subtaks to known objects
13
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Support: ACM JTF Library
• We use an auxiliary library for programming• This will allows us to…
– Write programs with a graphical user interface – from the start;
– Support graphical user interactions such as value inputs;– Use many examples (see the web page);– Simplify the program start using „main“
• This library is the „ACM JTF“ library– ACM: Association for Computing Machinery, the largest
organization for computer scientists and related fields world-wide
• See www.acm.org, joining as a student (for 19$ per year) is worthwhile!
– JTF: Java Task Force, consisting of 10 experienced Java instructors
– ACM JTF: the library developed by the ACM JTF• Provided as „acm.jar“ on the web page (about 400 kB)
14
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
General Structure of Using ACM JTF
• Your program inherits (T12) from one of these classes:– acm.program.ConsoleProgram – for a console prompt a la
DOS– acm.program.DialogProgram – for dialogue-based
in-/output– acm.program.GraphicsProgram – for graphics-based output
• There are only two operations in the main method:– Creation of a new object (T12) using „new MyProgram()“– Calling the method start(String[] args)
• This creates the output window etc.• Then, the method run() is called (you have to write this
method!)• This method should then cause all further actions
15
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Interesting methods in ConsoleProgram• void print(X value)
– Outputs value; X stands for any (arbitrary) type• void println(X value)
– Outputs value and adds a line feed• void println()
– Outputs a line feed• void clear()
– Clears the console window• void showErrorMessage(String message)
– Shows message as an error message (in red)• String readLine(String p) / int readInt(String p) /
double readDouble(String p)– Shows text p and the reads in a text line / int / double
16
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Example: Hello World - Consoleimport acm.program.ConsoleProgram; // Use "ConsoleProgram"public class HelloConsole extends ConsoleProgram {
public void run() { println("hello, world"); }
/* Standard Java entry point */ /* This method can be eliminated in most Java environments */ public static void main(String[] args) { new HelloConsole().start(); // startet Console, ruft "run" auf }}
Output window:
17
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Interactivity using DialogProgram
• The methods are identical to those of ConsoleProgram
• However, in- and output now uses dialogues– One corresponding window is used for each input or
output• To see an example, run the program „Add2Dialog“
18
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Example: Hello World - Dialogimport acm.program.DialogProgram; // Use "DialogProgram"public class HelloDialog extends DialogProgram {
public void run() { println("hello, world"); }
/* Standard Java entry point */ /* This method can be eliminated in most Java environments */ public static void main(String[] args) { new HelloDialog().start(); // startet Dialog, ruft "run" auf }}
Output window:
19
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Example: Hello World - Graphicalimport acm.graphics.GLabel; // Use GLabel (displayable text)import acm.program.GraphicsProgram; // Use "GraphicsProgram"public class HelloGraphics extends GraphicsProgram { public void run() { GLabel label = new GLabel("hello, world"); // new text
label.setFont("SansSerif-100"); // Font: no serifs double x = (getWidth() - label.getWidth()) / 2; // centered double y = (getHeight() + label.getAscent()) / 2; // centered add(label, x, y); // add text
} /* Standard Java entry point */ /* This method can be eliminated in most Java environments */ public static void main(String[] args) { new HelloGraphics().start(); //startet Graphics,ruft "run" auf }
} Output window (shrunk):
20
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
• General Differences between Scheme and Java• Compilation of Java programs (abbreviated)• Variables in Java• Primitive data types• Operators for arithmetic, logic and bit
operations• Functions in Java• Flow of control in Java
– Conditionals, loops and recursion• Lists (Scheme) vs. Arrays (Java)• Commenting Java elements• Introduction to the Eclipse Development
Environment
Contents
21
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Variablen in Java
• Data is usually stored in variables– Especially for assigning the result of a computation
• From Scheme, we know variables as bound names:
• In Java, assigments are done using "=":
22
;; provide initial value for counter(define counter-value 0);; increment the counter(set! counter-value (succ counter-value))
// provide initial value for countercounterValue = 0;// increment the countercounterValue = counterValue + 1;
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
A First Analysis of the Differences
• Comments use „//“ instead of „;“• A variable declaration is preceded by a type (here,
int)• Variable names cannot use „-“, instead use capitals• „(set! variable exp)“ becomes „variable = exp“• Instead of parentheses, statements end with „;“• Instead of prefix notation (operator param1 …
paramn), Java uses infix notation– (+ 1 2 3 4 5) therefore turns into 1 + 2 + 3 + 4 + 5 23
;; provide initial value for counter(define counter-value 0);; increment the counter(set! counter-value (+ counter-value 1))
// provide initial value for counterint counterValue = 0;// increment the countercounterValue = counterValue + 1;
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Arithmetic Operations• Java supports all important arithmetic operations• Keep in mind that infix notation is used!
– Let us assume a to be a int variable (whole number) with value 15
– The following table is incomplete; more will follow in a few slides
24
Operation In Java
Example
Result
Addition + 2 + 3 + 7
12
Subtraction - a – 2 13
Multiplication
* a * 4 60
Division / a / 5 3
Remainder % a % 4 3 (as 15=3*4+3)
Negation - -a -15
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
The Type of a Variable
• In Java, each variable has a type which defines…– what type of data can be stored in the variable,– how much memory is needed for storing the
value.• int 4 memory cells• long 8 memory cells• …
– what operations can be performed on an instance of this type.
• The type of the variable is placed before the name in a variable declaration:
int counter;
25
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Declarations in Java
• Declarations introduce names, often together with a value – (define …) in Scheme
• In Java, declarations also associate the name with a type: – This type defines how the names can be
used in the rest of the program statically typed language (more later)
26
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
The Type of a Variable
27
counter can only take whole numbers as a valuecounter = 10;counter = "hello";
Only operations defined for whole numbers are possible for counter.
counter++;counter.move();
int counter;int counter;
4 memory cells
counter
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Variables: Assignments & Expressions
28
1
size = size + delta;
Expression
• The left-hand side of an assignment must be something that can store values (in Scheme: a name in the environment)
• The right-hand side must be an expression.• The expression must result in a value
23
4
deltasize
= +
Flow of control Evaluation order
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
• General Differences between Scheme and Java• Compilation of Java programs (abbreviated)• Variables in Java• Primitive data types• Operators for arithmetic, logic and bit
operations• Functions in Java• Flow of control in Java• Conditionals, loops and recursion• Lists (Scheme) vs. Arrays (Java)• Commenting Java elements• Introduction to the Eclipse Development
Environment
Contents
29
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Primitive Data Types
• Java supports a set of primitive data types:– True/false values: type boolean with values true, false
– Whole numbers: byte, short, int, long, e.g., 3– Floating point numbers: float, double, e.g., 0.84– Characters: char, e.g., 'A'
• Not a primitive data type, but already predefined :– Strings: String, e.g., "Hello World"
30
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Primitive Data Types• Why are there multiple types for the same purpose?
– What is the difference between short and int?
Different types with a different range The larger the range, the more memory is needed
Type Minimum Maximum Memory Used
byte -128 127 1 Byte (8 Bit)
short -32 768 32 767 2 Bytes (16 Bit)
int -2 147 483 648
2 147 483 647
4 Bytes (32 Bit)
long -263 263-1 8 Bytes (64 Bit)
float 1,402·10-45 3,402·1038 4 Bytes (32 Bit)
double 4,94·10-324 1,797·10308 8 Bytes (64 Bit)
boolean false true 1 Bit
31
Scheme abstracts from these hardware-dependent details. easiert to use, less error-prone, but slower.
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
• General Differences between Scheme and Java• Compilation of Java programs (abbreviated)• Variables in Java• Primitive data types• Operators for arithmetic, logic and bit
operations• Functions in Java• Flow of control in Java• Conditionals, loops and recursion• Lists (Scheme) vs. Arrays (Java)• Commenting Java elements• Introduction to the Eclipse Development
Environment
Inhaltsübersicht
32
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Complex Expressions
Examples
33
double a; int i; char c; boolean b;
a = 3.1415 + 42; // a == 45.1415
i = 4 – 9; // i == -5
c = 'T'; // c == 'T'
i = i + 1; // i == -5 + 1 == -4
a = i * 2 + 3; // a == -4 * 2 + 3 == -8 + 3 == -5
a = i * (2 + 3); // a == -5 * (2 + 3) == -5 *5 == -25
b = true; // b == true
b = i > 0; // - 25 > 0 == false b == false
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Boolean Expressions
• Comparisons:– == for equality, != for inequality
• Caution: = alone stands for an assignment– <, <=, >=, > as usual, but using infix notation
• Logical negation (a): – true if a is false, else false– Notation in Java: !a– Notation in Scheme: (not a)
34
a !a
false true
true false
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Complex Boolean Expressions• Logical operators allow the composition of
multiple boolean values• Some operations are already known from logic
(and Scheme):• Logical And (AB): returns true only if A and B
are true (Java: A && B; Scheme: (and A B))– Logical Or (AB): returns false only if A and B are false (Java: A || B; Scheme: (or A B))
35
A B A && B A || B
false false false false
false true false true
true false false true
true true true true
Similar to and, or in Scheme…
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Complex Boolean Expressions
36
Examplesboolean a, b; int i; char c;
c = 'A'; i = 2; a = false;
b = c == 'A'; // b is now true
b = a && b; // b is now false
b = !b; // b is now true
b = i > 0 && 3 / i == 1;
// As i == 2: b == 2 > 0 and 3 /2 // With 3/2 == 1 (int division!) // b is now true
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Non-Strict Operators
• The logical operators a && b (logical and) a || b (logical or)
Evaluate the second operator only if this is really necessary
• Short-cut evaluation (non-strict evaluation)– Example: if (a != 0 && b / a > 1)– For a == 0, b/a would create an error message– But false && x is always false x will not be evaluated
37
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Bit Operations a & b (bitwise and) a | b (bitwise or) a ^ b (bitwise exclusive or, not same) ~a (bitwise egation) a << b (shifts a by b positions to the left,
same as multiplying a by 2b) a >> b (shifts a by b positions to the right,
same as dividing a by 2b) a >>> b (shifts a by b positions to the right,
but keeps the sign)
These operations are defined for the types byte, short, int, long and char.
38
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Bit Operations
• short i = 5 i = 0000 0000 0000 0101short j = 3 j = 0000 0000 0000 0011
• i & j = 0000 0000 0000 0001 i & j == 1i | j = 0000 0000 0000 0111 i | j == 7i << 1 = 0000 0000 0000 1010 i << 1 == 10i >> 1 = 0000 0000 0000 0010 i >> 1 == 2~i = 1111 1111 1111 1010 ~i == -6
• Why is ~i == -6?– Because short values are signed, negating them
changes the most significant bit (where the sign is stored) from negative to positive and vice versa. We need five more increments until we have reached -1 (all bits are 1)
39
Examples
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Assignment Operator• In Java, an assignment is an operator
– It is an expression, not a statement
• An assignment has a return value, apart from its essential side effect of changing the left-hand operator
40
a = b = c = 42;expression
expression
expression
expression
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Compound Assignment Operator
• Variable values are often changed similar to the following: i = i + STEP;
• The target variable occurs in the first place of the expression
• Java offers a short-hand notation for this purpose: i += STEP;
• Similar variants are available for almost all operators:+=, -=, *=, /=, |=, &=, ^=, %=, <<=, >>=, >>>=
• Helpful if the left-hand side is complex or shall be evaluated only once, e.g. a[i++]+=2; // Bad Style!
• Very popular with many programmers as a “short-cut” 41
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Unary Operators• Unary operators have only one operand
– Negation: !a (Scheme: (not a))– Minus as a sign, not as a binary operator: -a
• Increment/decrement operators– Other than typical unary operators, these have a side
effect++a, a++, --a, a--
– Prefix and postfix variants have different effects
Examples:
42
a = 4; a++; // same as: a = a + 1; a==5b = a++; // same as: b = a; a = a + 1; a==6, b==5b = ++a; // same as: a = a + 1; b = a; a==7, b==7b = a--; // same as: b = a; a = a – 1; a==6, b==7
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Operators and Priority• Many arithmetic expressions can be written
without parentheses– The evaluation rules follow those of standard
mathematics
43
a + b > 27 && b + c < 35 || a < 3
((((a + b) > 27) && ((b + c) < 35)) || (a < 3))
means
(or (and (> (+ a b) 27) (< (+ b c) 35)) (< a 3))
In Scheme:
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Operators: Priority and Associativity
• Operators and priority– In an expression with multiple operators, the operators with the
higher priority are applied before those with lower priority.– In Scheme, we did not encounter this situation due to the prefix
notation and parentheses.
• Operators and associativity: – What happens in expressions with multiple operators of the same
priority?• The operator to the left will be applied first if the operator is
associative from left to right.• The operator to the right will be applied first if the operator is
associative from right to left.
• The priority and associativity rules in Java are essentially identical to those you know from school
• This also applies to the use of parentheses to override these rules explicitly. 44
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Operators: Priority and Associativity
45
Unary operators ++, --, -, ~, ! rightMultiplication / Division / Remainder
*, /, % left
Addition/ Subtraction +, - leftShift <<, >> leftComparisons <, >, <=, >= leftEquality ==, != leftbitwise and & left bitwise xor ^ leftbitwise or | leftlogical and && leftlogical or || leftConditional operator ? : rightAssignment =, +=, -=, *=,
…right
Pri
ori
tyAssociativity
In Scheme not necessary due to prefix notation
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
• General Differences between Scheme and Java• Compilation of Java programs (abbreviated)• Variables in Java• Primitive data types• Operators for arithmetic, logic and bit
operations• Functions in Java• Flow of control in Java
– Conditionals, loops and recursion• Lists (Scheme) vs. Arrays (Java)• Commenting Java elements• Introduction to the Eclipse Development
Environment
Contents
46
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Calling Methods• In Scheme, we have often applied functions (Java:
methods)– We simply placed the function name, followed by all
parameters, in parentheses
• In Java, we give the name, followed by the parameters in one set of parentheses; multiple parameters are separated by comma:
– The semicolon is only needed if the statement ends here, so that „average“ is not used in further calculations in the same step
– Usually, the result of a function call will be assigned to a variable or used in further computations.
47
(average -42 50) ;; yields 4
average(-42, 50); // yields 4
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Defining Methods• In Scheme, define is used to declare functions:
• In Java, the notation is somewhat different:
– The type of the result value (int) is placed before the method name
– Parameters are placed in parentheses, separated by comma– Each parameter has a declared type
• Even if multiple succeeding parameters have the same type! – Curly braces delimit the method body (as „()“ in Scheme)– The result of the method is the expression following „return“
• Methods without a result have a result type of „void“48
(define (average x y) (/ (+ x y) 2))
int average(int x, int y) { return (x + y) / 2;}
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
49
Defining Methods in Java
Method header
Method body(implementation)
Explicit statement to return this as a result
/** * Increases the current value of counter by 1 */
int inc() {
currentVal = currentVal + 1; return currentVal;}
List of formal parameters (here:
empty)
Description of the effects
(more later)
;;inc: number;;effect: increases currentVal by 1 (define inc () (begin (set! currentVal (+ currentVal 1)) currentVal))
Return type
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
• General Differences between Scheme and Java• Compilation of Java programs (abbreviated)• Variables in Java• Primitive data types• Operators for arithmetic, logic and bit
operations• Functions in Java• Flow of control in Java
– Conditionals, loops and recursion• Lists (Scheme) vs. Arrays (Java)• Commenting Java elements• Introduction to the Eclipse Development
Environment
Contents
50
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Control Structures in Java
• Control structures influence the execution of programs• Two basic types:
– branching: statements are only executed if a condition is met
• if- and cond special forms in Scheme– loops: statements are executed multiple times
• The basic control structures of Java are given by the following syntaxrule:
51
<ControlStructures> = <If-Statement> | <Switch-Statement> |
<Return-Statement> | <Break-Statement> |<While-Loop> | <Do-Loop> | <For-Loop>
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Branching: if-Statements
• The evaluation of exp must be of type boolean
• The first statement will only be executed if the exp will be evaluated as true.
• Otherwise, the (optional) else-statement will be executed
• Statement can be a block—a sequence of expressions
• In Java, if statements do not return a value
• The else branch is optional
52
<If-Statement> = if (<exp>) <Statement> [else <Statement>]
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Branching statements: if
• In Scheme, an „if“ always consists of three parts:– the condition– the expression to be executed if the condition evaluates to
true– the expression to be executed if the condition evaluates to
false
• In Java, the notation is almost the same (focus on the „if“!)
53
(define (absolute x) (if (< x 0) (- x) x))
int absolute(int x) { if (x < 0) return –x; else return x;}
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
The expression equivalent to if
• Statement versus expression…
• In Scheme, if is an expression: it has a return value
– This expression returns either 100 or 200 as a result• A Scheme-like if also exists in Java with the construct
(condition) ? exp1 : exp2• If the condition is true, the result of the expression
equals exp1, else exp2
54
x = (num < 0) ? 100 : 200;x = (num < 0) ? 100 : 200;
if (num < 0) x = 100; else x = 200;
if (num < 0) x = 100; else x = 200; equivalent
(if (< num 0) 100 200)
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Extended Branching Statement: switch
55
• We want to write a simple program for distinguishing colors
• Depending on the parameter, a „fitting“ color name shall be printed
• Commonly used in graphical applications
• So-called „CLUT“ (Color Look-up Table)
(define (color-choice color) (cond [(= color 0) "black"] [(= color 1) "red"] [(= color 2) "yellow"] [else "Color cannot be identified"]) )
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
switch and break Statements
56
The switch statement is a generalized form of the if conditional
More or less equivalent to cond in Scheme
<Switch-Statement> = switch(<ConstantExpression>) {<SwitchBlockStatementGroup>}
<SwitchBlockStatementGroup> = <SingleCase> ... <SingleCase> <DefaultCase>
<SingleCase> = case <CaseLabel>: <LocalBlock> <DefaultCase> = default: <LocalBlock>
<LocalBlock> = <VariableDeclaration> | <Statement>
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
switch and break Statements
57
public class SwitchStatement1 { public static void main(String[] args) { int colorInput = 1; switch(colorInput) { case 0: System.out.println("black"); case 1: System.out.println("red"); case 2: System.out.println("yellow"); default: System.out.println(
"Color cannot be identified");
} } }
• There can be no more than one default case!
• ConstantExpression must be computable at compilation time
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Comparison of switch and cond
• Java allows only the use of a constant expression instead of multiple conditions
• All case labels must be constants• switch is only usable for some applications of cond• In general, coding a Scheme-like cond in Java is
done using a sequence of if statements
• As the method will be exited when we encounter return, we could also skip the final else here.
58
(define (absolute x) (cond [(> x 0) x] [(= x 0) 0] [else (- x)]))
int absolute(int x) { if (x > 0) return x; else if (x == 0) return 0; else return –x;}
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Semantics of the switch Statement
• The expression is evaluated and the case labels are searched for a fitting value
• If a fitting case label was found:– All subsequent statements are executed– Note: this also includes the statements of additional case / default
labels!
• If no fitting case label was found:– If present, execute the statements for the default label– Then execute all statements following the default label (if any)
59
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Semantics of the switch Statement
60
public class SwitchStatement1 { public static void main(String[] args) { int colorInput = 1; switch (colorInput ) { case 0: System.out.println("black"); case 1: System.out.println("red"); case 2: System.out.println("yellow"); default: System.out.println(
"Color cannot be identified");
} } }
Calling java SwitchStatement1 returns: red yellow Color cannot be identified
Not what we intended
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Semantics of the switch Statement
61
public class SwitchStatement2 { public static void main(String [] args) { int colorInput = 1; switch (colorInput ) { case 0: System.out.println("black"); break; case 1: System.out.println("red");
break; case 2: System.out.println("yellow"); break; default: System.out.println(
"Color cannot be identified");
} } }
Beispiel
Calling java SwitchAnweisung2 returns red
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Semantics of the switch Statement
• Notes:– The break (or return) statement can be used
to leave the switch block– If no default label is present and none of the
case label, the switch block is skipped– Usually, break should be the last statement in
a given case label• Unless you intentionally want to „spill over“
control to the next block!– The default label (if present) should be the
last label in the switch block
62
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Recursive Function Calls• In Scheme, we have used recursion to apply an operation
to multiple data elements
• We can do the same in Java:
• However, we will use loops for many such applications• A loop repeatedly executes the same block, according to
some criteria
63
(define (sum-until-n n) (if (<= n 0) 0 (+ n (sum-until-n (- n 1))) ))
int sumUntilN(int n) { if (n <= 0) return 0; return n + sumUntilN(n - 1);}
„Add all numbers from 1 to n"
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Loops• The simplest type of loop repeats a given instruction
for a fixed number of times („counting loop“)
• In Java: for loop
64
<For-Loop> = for ([<Statement> | <Variable-Declaration>]; [<Expression>];[<Statement>]) <Statement>
Expression must be of type boolean
for (int i = start; i < end; i++) // forwards...for (int i = end; i > start; i-=2) // backwards, step width 2
int sumUntilN(int n) { int sum = 0; for (int i = 1; i <= n; i++) sum += i; return sum;} „Add all numbers from 1 to n"
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Loops and Recursion
65
(define (factorial1 n) (if (= n 1) 1 (* n (factorial1 (- n 1))) )
(define (factorial2 n) (local ( (define (iter product counter) (if (> counter n) product (iter (* counter product) (+ counter 1)))))) (iter 1 1) )
(define (factorial3 n) (local ((define product 1) (define counter 1) (define (iter) (if (> counter n) product (begin (set! product (* counter product)) (set! counter (+ counter 1)) (iter))))) (iter)))
Recursion inaccumulator style
Iteration withassignments
Natural Recursion
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Loops and Recursion
66
class Example { public int factorial1(int n) { if (n == 1) { return 1;} else { return n * factorial1(n-1); } }
public int factorial2(int n) { return iter(1, 1, n); } private int iter(int product, int counter, int n) { if (counter > n) { return product; } else { return iter(counter * product, counter + 1, n); } }
public int factorial3(int n) { int product=1; for (int counter = 1; counter <= n; counter = counter + 1) { product = counter * product; } return product; }}
Natural Recursion
Linear Iteration
Iteration with Assignments
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
The while Loop
• Loops can often not be executed for a fixed number of times• A while loop executes the statement while the expression is
true
Expression must be of type boolean
• The expression is evaluated before each execution of the statement.
• If the expression is evaluated as false, the while loop ends.• Since this can happen right at the start, the statement may
not even be executed once!
67
<While-Loops> = while (<expression>) <Statement>
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
The while Loop: Example
68
At the end, we have either found a divisor less then number or factor has reached number.
// number is assumed to be greater than 0boolean isPrime(int number) { int factor = 2; // Check all factors until you find a divisor while (number % factor != 0) { factor = factor + 1; } return number == factor;}
„Check if number is a prime"
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Design Recipe for a while loop
1. Formulate the test that determines if the loop will
be executed again– E.g., (x - y*y) > 0.005 means the result is not precise
enough
2. Formulate the actions for the loop body which
will bring us one step closer to the end of the
loop– E.g., s = s + i; i++, adding values
3. You usually need to write an initialialization
before the loop and some post-processing after
the loop. 69
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Loops: while and for
• The general structure of a while loop is as follows:
• This fits the for loop very closely!– Applying the for loop to a fixed number of steps is
only a special case…!
70
<initialization>;while (<condition>) { <core loop body>;
<loop advancement>;}
for (<initialization>; <condition>; <loop advancement>) <core loop body>
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
The do-while Loop
• A do-while loop checks the condition after the execution of the loop body
• The loop body will be executed at least once
• If expression is false – evaluated after the execution of the loop body – the loop terminates
71
<Do-Loop> = do <Statement> while (<expression>)
<expression> must be of type boolean
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
• General Differences between Scheme and Java• Compilation of Java programs (abbreviated)• Variables in Java• Primitive data types• Operators for arithmetic, logic and bit
operations• Functions in Java• Flow of control in Java
– Conditionals, loops and recursion• Lists (Scheme) vs. Arrays (Java)• Commenting Java elements• Introduction to the Eclipse Development
Environment
Contents
72
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Lists in Scheme
• In Scheme, we often worked recursively on lists• Lists are defined recursively (first, rest) and very
well-suited for recursive algorithms• Lists are „hard-wired“ into Scheme, so we do not
have to define them– In contrast to our trees and graphs
• Lists do not have a fixed length– They just grow and shrink when new data is added or
removed• There are several specialized access functions
– first, second, third, …– Very easy to define, if not already present
• Is there something comparable in Java…?73
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Arrays: Motivation
• Using multiple variables (a1, a2, …) will not work– The number of elements would be fixed– Comparisons become unwieldy
• if (a1 < a2) { if (a1 < a3) ...– Creates code that is very difficult to adapt or scale
• Using a data structure with a sequential data access may be too inefficient– But that is exactly what Scheme offers us with its lists!
74
Maths: a1, a2, a3,...Reference type "Array"Challenge: how can be offer fast access to a potentially very large number of elements, e.g. for sorting them?
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Arrays
Solution: Array• A collection of multiple elements of the same
type, indexed by a array variable<Array-type> ::= <type>[]<Array-Creation> ::= new <type>[<size>]Example:
// create an array for 15 int valuesint[] scores = new int[15];
75
A consecutive memory area with space for 15 int values is provided. This allows for efficient access.
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Arrays
• To access a given array element, provide its index in []– E.g., a[0], a[1], a[3]
• In Java, the first array element always has index 0, the last will have the index <array size> - 1– Querying the length of an array a: a.length
• No parenthesis!– Using an illegal index will cause an Exception
(ArrayIndexOutOfBoundsException) runtime error• The advantage of a[0] over a0 is the potential use
of a variable expression for the index:int i = 5;a[i+1] = a[i] + a[i–1];
76
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Initialization of Arrays
77
int[] scores = new int[]{ 6, 4, 2, 8, 3 };
String[] predators = new String[] { "lion", "tiger", "shark"};
String[] predators = new String[3];predators[0] = "lion";predators[1] = "tiger";predators[2] = "shark";
Declares and defines an array of 5 int values
Declares and defines an array of 5 int values
equivalentequivalent
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Reference Type „Array“• Arrays look like objects
– Are created using "new" ( more in T12…)– Are deleted using Garbage Collection
• Array variables contain references to array objectsint[] a;int[] b = new int[]{ 3, 1, 4 };a = b; // a and b now access
// the same array!
• Differences to other reference types (T12)– new operator does not use a „constructor"– No inheritance between array types
78
3 1 4
b a
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Multi-dimensional Arrays
• Array may have arrays as an element– Declaration: int[][] table;– Creation:
79
table = new int[3][2]; table = new int[3][]; table[1] = new int[2];or
0
00
0
0
0 0
0
0 0
No dimension is specified. Advantage:
efficient storage of non-rectangular structures
such as triangular matrices
– Access: table[1][0] = 42;
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Multi-dimensional Arrays
int pascal[][] = new int[][] { { 1 },
{ 1, 2, 1}, { 1, 3, 3, 1}, { 1, 4, 6, 4,
1} }
80
pascal[3][1]
pascal[3][1]
1 1
2
1
3
1 3
1
1
4
6
4
1
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Multi-dimensional Arrays
table.length // 3table[0].length // NullPointerExceptiontable[1].length // 2table[1][2] // IndexOutOfBoundsException
81
042
table
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Arrays - Storage
• Multidimensional arrays…– …may use row-major order: a[2,4] is followed by a[2,5] – …may use column-major order: a[2,4] is followed by a[3,4] – The difference can be important for caching purposes
82
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Arrays -Storage
• Multi-dimensional arrays– In Java, can also be an „array of references to arrays“.
• What are the (dis-)advantages of „consecutive memory“ and „array of references to arrays“?– [Notation borrowed from C/C++!]
83
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
• General Differences between Scheme and Java• Compilation of Java programs (abbreviated)• Variables in Java• Primitive data types• Operators for arithmetic, logic and bit
operations• Functions in Java• Flow of control in Java
– Conditionals, loops and recursion• Lists (Scheme) vs. Arrays (Java)• Commenting Java elements• Introduction to the Eclipse Development
Environment
Contents
84
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Commenting Java Elements• If you use the correct notation for comments, Java
can automatically create a HTML-based documentation
• This is possible for all elements visible „on the outside“:– Classes– Constant– Class and object attributes– Methods
• Basic notation: place a comment of the following form before the given element
/** * Comment */• Far more details http://java.sun.com/j2se/javadoc/index.jsp
85
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Special Formats
• Java knows a set of special commands– They always start with „@“
• Each such commands belongs in a separate comment line– Do not forget the „*“ at the start of the comment line
• @param x text– Add comment „text“ to describe parameter „x“
• @return text– Comments what value this method returns– Of course, this is only useful if the method is not declared void!
• @author text– States the author of the element, often as „Name
<email>“86
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Special Formats II
• @throws type text– Describes the (possible) occurrence of an exception (
T18) with the Typ and „why / when“ this can happen• @version double
– States the version number for the element• @since text
– States when the element was introduced– In JDK, this is often „1.5“: introduced in 1.5/5.0
• @see reference– Cross-reference to other elements– If inside another class: @see
packagename.Class#method– Methods with parameters: give the type list of the
parameters• E. g., m(int, String, double) 87
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Example
/** * This method will sort the array passed in, thus * changing its elements. * Uses quicksort(array, 0, array.length-1) for sorting. * * @param array the array to be sorted * @throws IllegalArgumentException if the array is
null * @author Guido Roessling [email protected] * @version 0.2 * @see #quicksort(array, int, int) */public void quicksort(int[] array) { /* … */ }
88
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
• General Differences between Scheme and Java• Compilation of Java programs (abbreviated)• Variables in Java• Primitive data types• Operators for arithmetic, logic and bit
operations• Functions in Java• Flow of control in Java
– Conditionals, loops and recursion• Lists (Scheme) vs. Arrays (Java)• Commenting Java elements• Introduction to the Eclipse Development
Environment
Contents
89
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Integrated Development Environment
• An Integrated Development Environment (IDE) is a program to support developers in developing applications
• An IDE typically contains a source code editor, a compiler and / or interpreter, tools for automatically building the application, and a debugger– Many modern IDEs also offer a class browser, and
object inspector and a class hierarchy view which help in creating object-oriented applications.
• An DIE is typicall meant for a certain programming language, for example the Visual Basic IDE.
• IDEs, which support multiple programming languages include Eclipse, NetBeans, and Microsoft Visual Studio
90
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
The Eclipse Java Editor• The features offered by the built-in source code editor include code
completion and an automatic syntax check.
• Code completion offers a context-sensitive list of options that can be selected by keyboard or mouse:– A list of methods that can be called on the selected object, or a code
fragment to complete statements such as for or while– The code completion is started by pression Ctrl-Space
• yntax checking depends on incremental compilation – As the source code is saved or edited, it is compiled in the background
and checked for – Wenn der Quelltext gespeichert wird, wird er im Hintergrund übersetzt
und auf Syntaxfehler überprüft• Kein separater Übersetzungsschritt!
– Standardmäßig werden Syntaxfehler rot unterstrichen, und ein roter Punkt mit einem weißen "X" erscheint am linken Rand.
– Fehler, die durch eine Glühbirne am linken Rand des Editors angezeigt werden, kann der Editor selbst beheben Quick Fix
• Erreichbar durch Strg-1
91
• The built-in editor for Java also offers code completion and syntax checks
• Code completion provides a context-sensitive list of options that can be chosen by keyboard or mouse:• a list of methods that can be invoked on the selected object• a code fragment that completes the selected keyword, e.g., for, while
• Code completion is called by pressing Ctrl-Space
• Syntax checking depends on incremental compilation• While the source code is saved, it is compiled in the background
and checked for syntax errors• This also means we no longer need a separate compilation
step!• By default, syntax errors are marked with a red wavy underline,
and a red circle with a white „X“ appears on the left border• Errors that are marked with a light bulb can be fixed by the
editor• Using a so-called „Quick fix“• Press Ctrl-1 to let the editor fix the problem automatically
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
The Eclipse Java Editor
92
Outline (Overvie
w)
Problems(compile errors,
Warnings)
Tabs for Views, here:
Problems
Code Edito
r
Package Overvie
w
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Eclipse: Showing JavaDoc
93
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Eclipse: Code Completion
94
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Eclipse: Content Assist
95
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Eclipse: Refactoring
96
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Debugging Java Program with Eclipse
• The JDT debugger of Eclipse can execute a Java class line by line, e.g., to examine the values of variables at various points– One of the most powerful ways to find bugs in the
code– Similar to the stepwise execution in DrScheme
• To prepare debugging, you need to set a breakpoint in the code– When this line of code is reached, the debugger will
stop the execution and change to the debug perspective
– A breakpoint is set by double clicking in the grey frame to the left of the editor
• A blue ball will appear to indicate the break point• To debug a program, use „Debug“ from the
„Run“ menu, not „Run“!97
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
The Debug Perspective
98
The debug view shows the call stack and the state of all threats, including those already completed
Views to examine or modify variables and breakpoints
Step control
Editor view
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Important Keyboards Shortcuts for Eclipse
• Eclipse offers a very large set of great support options for programming
• These are the most relevant general keyboard shortcuts– For Windows; they may be slightly different for other
operating systems (Mac; in the RBG pool, …)
99
Shortcut Effect
Ctrl-Space Code completion
Ctrl-F Search or replace text
Ctrl-H Specialized search (for classes, in files, …)
Ctrl-J Incremental search („continue“)
Ctrl-K Jump to next occurrence
Ctrl-Shift-K Jump to previous occurrence
Ctrl-F11 Execute program
F11 Debug program
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Keyboard Shortcuts in Eclipse for JavaShortcut Effect
F3 Open the declaration of the element below the cursor
F4 Show class hierarchy in the view
Alt-Shift-S Show source menu
Alt-Shift-Z Enclose code block (e.g., using try/catch T18)
Shift-F2 Open external Javadoc documentation
Ctrl-/ Comment / uncomment lines
Ctrl-1 Quick Fix (automatic correction)
Ctrl-2 Show shortcuts for Quick Assist
Ctrl-Alt-H Show call hierarchy of the current method
Ctrl-G Search for class declaration in the workspace
Ctrl-I Adapt indentation
Ctrl-O Show outline (overview)
Ctrl-T Show class hierarchy 100
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Keyboard Shortcuts in Eclipse for Java
Shortcut Effect
Ctrl-Shift-F Automatically format code
Ctrl-Shift-G Search for references of the selected class in the workspace
Ctrl-Shift-O Automatically generate / adapt import statements ( T15)
Ctrl-Shift-T Quick lookup for classes
101
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Code Refactoring
Shortcut Effect
Alt-Shift-C Change method signature (esp. parameters)
Alt-Shift-I Inline method
Alt-Shift-M Extract method
Alt-Shift-R Rename
Alt-Shift-T Show Refactoring menu
Alt-Shift-V Move
102
• Refactoring supports the renaming of methods, changing their parameter number or types, etc.
• This is normally much manual work• Apart from the method itself, we also need to adapt
all code lines that call the method• Eclipse does this automatically for us
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Debugger Shortcuts
• The debugger also has a couple of shortcuts
103
Shortcut Effect
F11 Debug program
Ctrl-Shift-B Set breakpoint at the current code line
Ctrl-Shift-I Inspect variable
F5 Step into (go “inside” method calls)
F6 Step over (ignore code of called methods)
F7 Step return (Execute method until return)
F8 Continue execution
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
• General Differences between Scheme and Java• Compilation of Java programs (abbreviated)• Variables in Java• Primitive data types• Operators for arithmetic, logic and bit
operations• Functions in Java• Flow of control in Java
– Conditionals, loops and recursion• Lists (Scheme) vs. Arrays (Java)• Commenting Java elements• Introduction to the Eclipse Development
Environment• Summary
Contents
104
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Summary
• OOP is a programming paradigm that structures computations as set of objects cooperating using method calls.
• Classes and objects in Java are similar to constructor functions and their associated objects in Scheme– The differences are primarly syntactic– Dispatch mechanisms are hard-wired into the semantics of OO
languages (details follow later)
• Java is based on VM technology, combining the best of compilers and interpreters
• Java branching statements are similar to those in Scheme• Control flow statements are often used instead of
recursion• The Eclipse DIE helps you in developing Java programs
105
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Practicing in Java…
• The course web page contains a set of example programs– Add „acm.jar“ to your CLASSPATH, as described on the
page• The CS Dept. also offers you the special Webtasks
service– http://webtasks.informatik.tu-darmstadt.de/webtasks– LOTS of programming exercise from „very easy“ to „rather
hard“• Also some multiple choice tests for „more advanced students“
– Especially the tasks for arrays and loops are very well-suited for training – even for „experienced programmers“
– Submitted solutions are compiled with javac and tested with JUnit
– You will received feedback what „went wrong“, and can then adapt the code and re-submit it
– Once you have soved a given task, you can see all other valid solutions and can learn from them – or just comment them
• Usable with RBG login or with a freely chosen login
106
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Programming in both Styles• Programming in Java
– Encourages imperative style in different ways
• Helpful “syntactic sugar” for many constructs, e.g., different loop constructs for different goals
– First-class functions are missing• This makes it more difficult to express some interesting
patterns of functional programming• Can be simulated at least partially by objects
• Programming in Scheme– Very good support for the functional style– Also supports parts of the imperative style
• See the factorial3 example
107
Dr. G. RößlingProf. Dr. M. Mühlhäuser
RBG / Telekooperation©
Introduction to Computer Science I: T11
Programming in both Styles
• Scheme and Java allow you to program in both styles! – A good programmer should be an expert in both
styles. – Top goal of this lecture: you should master both
styles!
• “Object-oriented style” is a different topic!
108