Introduction to Computer Science I

Download Report

Transcript Introduction to Computer Science I

Technische Universität Darmstadt
Telecooperation/RBG
Introduction to Computer Science I
Topic 11: From Scheme to Java
Prof. Dr. Max Mühlhäuser
Dr. Guido Rößling
Copyrighted material; for TUD student use only
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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 Environment
Introduction to Computer Science I: T11
2
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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
Introduction to Computer Science I: T11
3
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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
Introduction to Computer Science I: T11
4
Distance from machine level
in functional programming
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
(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
We do not even mention the list!
(multlist ‘(3 4 5)) Abstraction from the execution
 60
details
Introduction to Computer Science I: T11
5
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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
Introduction to Computer Science I: T11
6
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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
(inc c2 5)
c2.inc(5);
Introduction to Computer Science I: T11
7
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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
Introduction to Computer Science I: T11
8
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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 Environment
Introduction to Computer Science I: T11
9
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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
Introduction to Computer Science I: T11
10
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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
public class CounterTest {
// ...
public static void main(String[] args) {
CounterConsumer cc = new CounterConsumer();
cc.doSomethingWithCounters();
}
// ...
CounterTest.java
}
Java
Compiler
Java
Bytecode
Interpreter
javac CounterTest.java
java
CounterTest
Introduction to Computer Science I: T11
11
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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
class Ex1 {...}
class Ex2 {...}
class Ex3 {...}
Java Compiler
File.java
Introduction to Computer Science I: T11
Ex1.class
Ex2.class
Ex3.class
12
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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
Introduction to Computer Science I: T11
13
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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)
Introduction to Computer Science I: T11
14
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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
Introduction to Computer Science I: T11
15
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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
Introduction to Computer Science I: T11
16
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Example: Hello World - Console
import 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:
Introduction to Computer Science I: T11
17
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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“
Introduction to Computer Science I: T11
18
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Example: Hello World - Dialog
import 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:
Introduction to Computer Science I: T11
19
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Example: Hello World - Graphical
import 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):
Introduction to Computer Science I: T11
20
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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 Environment
Introduction to Computer Science I: T11
21
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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:
;; provide initial value for counter
(define counter-value 0)
;; increment the counter
(set! counter-value (succ counter-value))
• In Java, assigments are done using "=":
// provide initial value for counter
counterValue = 0;
// increment the counter
counterValue = counterValue + 1;
Introduction to Computer Science I: T11
22
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
A First Analysis of the Differences
;; provide initial value for counter
(define counter-value 0)
;; increment the counter
(set! counter-value (+ counter-value 1))
•
•
•
•
•
•
// provide initial value for counter
int counterValue = 0;
// increment the counter
counterValue = counterValue + 1;
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
Introduction to Computer Science I: T11
23
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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
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
Introduction to Computer Science I: T11
24
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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;
Introduction to Computer Science I: T11
25
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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)
Introduction to Computer Science I: T11
26
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
The Type of a Variable
counter can only take
whole numbers as a value
int counter;
counter = 10;
counter = "hello";
Only operations defined for
whole numbers are possible for
counter.
counter
4 memory cells
counter++;
counter.move();
Introduction to Computer Science I: T11
27
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Variables: Assignments & Expressions
Expression
size =
4
size
+ delta;
1
=
3
+
2
delta
size
Flow of control
Evaluation order
• 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
Introduction to Computer Science I: T11
28
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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 Environment
Introduction to Computer Science I: T11
29
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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"
Introduction to Computer Science I: T11
30
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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
byte
Minimum
Maximum
-128
Memory Used
127 1 Byte (8 Bit)
-32 768
32 767 2 Bytes (16 Bit)
-2 147 483 648
2 147 483 647 4 Bytes (32 Bit)
-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)
short
int
long
boolean
false
true 1 Bit
Scheme abstracts from these hardware-dependent details.
 easiert to use, less error-prone, but slower.
Introduction to Computer Science I: T11
31
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Inhaltsübersicht
•
•
•
•
•
•
•
•
•
•
•
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
Introduction to Computer Science I: T11
32
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Complex Expressions
Examples
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
Introduction to Computer Science I: T11
33
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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)
a
!a
false
true
true
false
Introduction to Computer Science I: T11
34
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Complex Boolean Expressions
• Logical operators allow the composition of multiple
boolean values
• Some operations are already known from logic (and
Scheme):
• Logical And (AB): returns true only if A and B are
true (Java: A && B; Scheme: (and A B))
– Logical Or (AB): returns false only if A and B are false
(Java: A || B; Scheme: (or A B))
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…
Introduction to Computer Science I: T11
35
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Complex Boolean Expressions
Examples
boolean 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
Introduction to Computer Science I: T11
36
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Non-Strict Operators
• The logical operators
a && b
a || b
(logical and)
(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
Introduction to Computer Science I: T11
37
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Bit Operations
a & b
a | b
a ^ b
~a
a << b
a >> b
a >>> b
(bitwise and)
(bitwise or)
(bitwise exclusive or, not same)
(bitwise egation)
(shifts a by b positions to the left, same
as multiplying a by 2b)
(shifts a by b positions to the right, same
as dividing a by 2b)
(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.
Introduction to Computer Science I: T11
38
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Bit Operations
Examples
i = 5  i = 0000 0000 0000 0101
j = 3  j = 0000 0000 0000 0011
= 0000 0000 0000 0001  i & j
= 0000 0000 0000 0111  i | j
i << 1 = 0000 0000 0000 1010  i << 1
i >> 1 = 0000 0000 0000 0010  i >> 1
~i
= 1111 1111 1111 1010  ~i
• Why is ~i == -6?
• short
short
• i & j
i | j
==
==
==
==
==
1
7
10
2
-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)
Introduction to Computer Science I: T11
39
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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 lefthand operator
a = b = c = 42;
expression
expression
expression
expression
Introduction to Computer Science I: T11
40
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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”
Introduction to Computer Science I: T11
41
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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:
a = 4;
a++;
b = a++;
b = ++a;
b = a--;
//
//
//
//
same
same
same
same
as:
as:
as:
as:
a
b
a
b
=
=
=
=
a + 1;
a; a = a + 1;
a + 1; b = a;
a; a = a – 1;
Introduction to Computer Science I: T11




a==5
a==6, b==5
a==7, b==7
a==6, b==7
42
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Operators and Priority
• Many arithmetic expressions can be written without
parentheses
– The evaluation rules follow those of standard mathematics
a + b > 27 && b + c < 35 || a < 3
means
((((a + b) > 27) && ((b + c) < 35)) || (a < 3))
In Scheme:
(or (and (> (+ a b) 27) (< (+ b c) 35))
Introduction to Computer Science I: T11
(< a 3))
43
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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.
Introduction to Computer Science I: T11
44
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Operators: Priority and Associativity
Priority
Associativity
Unary operators
Multiplication / Division / Remainder
Addition/ Subtraction
Shift
Comparisons
Equality
bitwise and
bitwise xor
bitwise or
logical and
logical or
Conditional operator
Assignment
++, --, -, ~, !
*, /, %
+, <<, >>
<, >, <=, >=
==, !=
&
^
|
&&
||
?:
=, +=, -=, *=, …
right
left
left
left
left
left
left
left
left
left
left
right
right
In Scheme not necessary due to prefix notation
Introduction to Computer Science I: T11
45
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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 Environment
Introduction to Computer Science I: T11
46
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Calling Methods
• In Scheme, we have often applied functions (Java: methods)
– We simply placed the function name, followed by all parameters, in
parentheses
(average -42 50) ;; yields 4
• In Java, we give the name, followed by the parameters in
one set of parentheses; multiple parameters are separated
by comma:
average(-42, 50); // yields 4
– 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.
Introduction to Computer Science I: T11
47
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Defining Methods
• In Scheme, define is used to declare functions:
(define (average x y)
(/ (+ x y) 2))
• In Java, the notation is somewhat different:
int average(int x, int y) {
return (x + y) / 2;
}
– 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“
Introduction to Computer Science I: T11
48
Defining Methods in Java
Description of the
effects (more
later)
©
;;inc:  number
;;effect: increases currentVal by 1
(define inc ()
(begin
(set! currentVal (+ currentVal 1))
currentVal))
/**
* Increases the current value of counter by 1
*/
Return type
List of formal parameters
(here: empty)
int inc() {
Method header
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
currentVal = currentVal + 1;
return currentVal;
}
Method body
(implementation)
Explicit statement to
return this as a result
Introduction to Computer Science I: T11
49
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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 Environment
Introduction to Computer Science I: T11
50
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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:
<ControlStructures> =
<If-Statement> | <Switch-Statement> |
<Return-Statement> | <Break-Statement> |
<While-Loop> | <Do-Loop> | <For-Loop>
Introduction to Computer Science I: T11
51
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Branching: if-Statements
<If-Statement> =
if (<exp>) <Statement> [else <Statement>]
• 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
Introduction to Computer Science I: T11
52
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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
(define (absolute x)
(if (< x 0)
(- x)
x))
• In Java, the notation is almost the same (focus on the „if“!)
int absolute(int x) {
if (x < 0)
return –x;
else
return x;
}
Introduction to Computer Science I: T11
53
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
The expression equivalent to if
• Statement versus expression…
• In Scheme, if is an expression: it has a return value
(if (< num 0) 100 200)
–
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
if (num < 0)
x = 100;
else
x = 200;
x = (num < 0) ? 100 : 200;
equivalent
Introduction to Computer Science I: T11
54
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Extended Branching Statement: switch
• 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"])
)
Introduction to Computer Science I: T11
55
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
switch and break Statements
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>
Introduction to Computer Science I: T11
56
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
switch and break Statements
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
Introduction to Computer Science I: T11
57
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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
(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;
}
• As the method will be exited when we encounter return,
we could also skip the final else here.
Introduction to Computer Science I: T11
58
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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)
Introduction to Computer Science I: T11
59
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Semantics of the switch Statement
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
Not what we
yellow
intended 
Color cannot be identified
Introduction to Computer Science I: T11
60
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Semantics of the switch Statement
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
Introduction to Computer Science I: T11
61
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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
Introduction to Computer Science I: T11
62
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Recursive Function Calls
• In Scheme, we have used recursion to apply an operation to
multiple data elements
(define (sum-until-n n)
(if (<= n 0) 0
(+ n (sum-until-n (- n 1)))
)
„Add all numbers
)
from 1 to n"
• We can do the same in Java:
int sumUntilN(int n) {
if (n <= 0) return 0;
return n + sumUntilN(n - 1);
}
• However, we will use loops for many such applications
• A loop repeatedly executes the same block, according to some
criteria
Introduction to Computer Science I: T11
63
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Loops
• The simplest type of loop repeats a given instruction for a
fixed number of times („counting loop“)
• In Java: for loop
<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
Introduction to Computer Science I: T11
1 to n"
64
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Loops and Recursion
(define (factorial1 n)
(if (= n 1) 1 (* n (factorial1 (- n 1))) )
Natural
Recursion
(define (factorial2 n)
(local (
(define (iter product counter)
Recursion in
(if (> counter n)
accumulator style
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)))
Introduction to Computer Science I: T11
Iteration with
assignments
65
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Loops and Recursion
class Example {
public int factorial1(int n) {
if (n == 1) { return 1;}
else { return n * factorial1(n-1); }
}
Natural Recursion
public int factorial2(int n) {
Linear Iteration
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;
}
Iteration with
return product;
}
Assignments
Introduction to Computer Science I: T11
66
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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
<While-Loops> = while (<expression>) <Statement>
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!
Introduction to Computer Science I: T11
67
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
The while Loop: Example
„Check if number is a prime"
// number is assumed to be greater than 0
boolean isPrime(int number) {
int factor = 2;
// Check all factors until you find a divisor
while (number % factor != 0) {
factor = factor + 1;
}
return number == factor;
}
At the end, we have either found a divisor less
then number or factor has reached number.
Introduction to Computer Science I: T11
68
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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.
Introduction to Computer Science I: T11
69
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Loops: while and for
• The general structure of a while loop is as follows:
<initialization>;
while (<condition>) {
<core loop body>;
<loop advancement>;
}
• This fits the for loop very closely!
– Applying the for loop to a fixed number of steps is only a
special case…!
for (<initialization>; <condition>; <loop advancement>)
<core loop body>
Introduction to Computer Science I: T11
70
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
The do-while Loop
• A do-while loop checks the condition after the
execution of the loop body
<Do-Loop> = do <Statement> while (<expression>)
<expression> must be of type boolean
• The loop body will be executed at least once
• If expression is false – evaluated after the
execution of the loop body – the loop terminates
Introduction to Computer Science I: T11
71
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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 Environment
Introduction to Computer Science I: T11
72
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Lists in Scheme
• In Scheme, we often worked recursively on lists
• Lists are defined recursively (first, rest) and very wellsuited 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…?
Introduction to Computer Science I: T11
73
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Arrays: Motivation
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?
• 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!
Introduction to Computer Science I: T11
74
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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 values
int[] scores = new int[15];
A consecutive memory area with space for 15 int
values is provided. This allows for efficient access.
Introduction to Computer Science I: T11
75
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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];
Introduction to Computer Science I: T11
76
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Initialization of Arrays
int[] scores = new int[]{ 6, 4, 2, 8, 3 };
Declares and defines an array of 5 int values
String[] predators = new String[] {
"lion", "tiger", "shark"};
String[] predators = new String[3];
predators[0] = "lion";
predators[1] = "tiger";
equivalent
predators[2] = "shark";
Introduction to Computer Science I: T11
77
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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 objects
int[] a;
int[] b = new int[]{ 3, 1, 4 };
a = b; // a and b now access
// the same array!
3
b
1
4
a
• Differences to other reference types (T12)
– new operator does not use a „constructor"
– No inheritance between array types
Introduction to Computer Science I: T11
78
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Multi-dimensional Arrays
– Declaration: int[][] table;
– Creation:
No dimension is specified.
Advantage: efficient
storage of non-rectangular
structures such as
triangular matrices
or
table = new int[3][];
table[1] = new int[2];
• Array may have arrays as an element
table = new int[3][2];
0
0
0
0
0
0
0
0
– Access:
table[1][0] = 42;
Introduction to Computer Science I: T11
79
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Multi-dimensional Arrays
int pascal[][] = new int[][] {
{ 1 },
{ 1, 2, 1},
{ 1, 3, 3, 1},
{ 1, 4, 6, 4, 1} }
1
1
1
1
2
3
4
1
3
6
1
4
pascal[3][1]
1
Introduction to Computer Science I: T11
80
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Multi-dimensional Arrays
table
42 0
table.length
table[0].length
table[1].length
table[1][2]
//
//
//
//
3
NullPointerException
2
IndexOutOfBoundsException
Introduction to Computer Science I: T11
81
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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
Introduction to Computer Science I: T11
82
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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++!]
Introduction to Computer Science I: T11
83
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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 Environment
Introduction to Computer Science I: T11
84
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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
Introduction to Computer Science I: T11
85
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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>“
Introduction to Computer Science I: T11
86
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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)
Introduction to Computer Science I: T11
87
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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) { /* … */ }
Introduction to Computer Science I: T11
88
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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 Environment
Introduction to Computer Science I: T11
89
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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
Introduction to Computer Science I: T11
90
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
The Eclipse Java Editor
for by
Java
offerssource
code completion
syntax
checks
•• The
Thebuilt-in
featureseditor
offered
thealso
built-in
code editor and
include
code
completion and an automatic syntax check.
• Code completion provides a context-sensitive list of options that can be
chosen by keyboard or mouse:
• Code
completion
offers
context-sensitive
optionsobject
that can be
• a list
of methods
thata can
be invoked on list
theof
selected
selected
byfragment
keyboardthat
or mouse:
• a code
completes the selected keyword, e.g., for,
– while
A list of methods that can be called on the selected object, or a code fragment
complete
statements
such as
or while
• to
Code
completion
is called
byfor
pressing
Ctrl-Space
–
The code completion is started by pression Ctrl-Space
• Syntax checking depends on incremental compilation
• While
the source
code on
is saved,
it is compiled
in the background and
• yntax
checking
depends
incremental
compilation
for syntax
– checked
As the source
code iserrors
saved or edited, it is compiled in the background and
•
This
also
means
we no longer need a separate compilation step!
checked for
default,
syntax gespeichert
errors are wird,
marked
a Hintergrund
red wavy underline,
andauf
a
– • By
Wenn
der Quelltext
wirdwith
er im
übersetzt und
red
circle with
a white „X“ appears on the left border
Syntaxfehler
überprüft
• Errors
that
are marked
with a light bulb can be fixed by the editor
• Kein
separater
Übersetzungsschritt!
• Using a so-called
„Quick fix“rot unterstrichen, und ein roter Punkt mit
– Standardmäßig
werden Syntaxfehler
• Press
Ctrl-1
to let the
editorRand.
fix the problem automatically
einem
weißen
"X" erscheint
am linken
–
Fehler, die durch eine Glühbirne am linken Rand des Editors angezeigt werden,
kann der Editor selbst beheben  Quick Fix
• Erreichbar durch Strg-1
Introduction to Computer Science I: T11
91
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
The Eclipse Java Editor
Package
Overview
Outline
(Overview)
Code
Editor
Tabs for Views,
here: Problems
Problems
(compile errors, Warnings)
Introduction to Computer Science I: T11
92
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Eclipse: Showing JavaDoc
Introduction to Computer Science I: T11
93
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Eclipse: Code Completion
Introduction to Computer Science I: T11
94
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Eclipse: Content Assist
Introduction to Computer Science I: T11
95
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Eclipse: Refactoring
Introduction to Computer Science I: T11
96
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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“!
Introduction to Computer Science I: T11
97
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
The Debug Perspective
Step control
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
Editor view
Introduction to Computer Science I: T11
98
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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, …)
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
Introduction to Computer Science I: T11
99
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Keyboard Shortcuts in Eclipse for Java
Shortcut
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
Introduction to Computer Science I: T11
100
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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
Introduction to Computer Science I: T11
101
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Code Refactoring
• 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
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
Introduction to Computer Science I: T11
102
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
Debugger Shortcuts
• The debugger also has a couple of shortcuts
Shortcut
F11
Effect
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
Introduction to Computer Science I: T11
103
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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 Environment
Summary
Introduction to Computer Science I: T11
104
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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
Introduction to Computer Science I: T11
105
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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
Introduction to Computer Science I: T11
106
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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
Introduction to Computer Science I: T11
107
Dr. G. Rößling
Prof. Dr. M. Mühlhäuser
RBG / Telekooperation
©
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!
Introduction to Computer Science I: T11
108