Presentation is loading. Please wait.

Presentation is loading. Please wait.

Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: From Scheme.

Similar presentations


Presentation on theme: "Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: From Scheme."— Presentation transcript:

1 Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: From Scheme to Java Prof. Dr. Max Mühlhäuser Dr. Guido Rößling

2 Dr. G. Rößling Prof. 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 Environment 2

3 Dr. G. Rößling Prof. 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

4 Dr. G. Rößling Prof. 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

5 Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T11 Distance from machine level in 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

6 Dr. G. Rößling Prof. 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

7 Dr. G. Rößling Prof. 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);

8 Dr. G. Rößling Prof. 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

9 Dr. G. Rößling Prof. 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

10 Dr. G. Rößling Prof. 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

11 Dr. G. Rößling Prof. 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 Java Bytecode Interpreter javac CounterTest.java java CounterTest

12 Dr. G. Rößling Prof. 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 Compiler Ex1.class Ex2.class Ex3.class class Ex1 {...} class Ex2 {...} class Ex3 {...} File.java

13 Dr. G. Rößling Prof. 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

14 Dr. G. Rößling Prof. 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!www.acm.org –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

15 Dr. G. Rößling Prof. 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

16 Dr. G. Rößling Prof. 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

17 Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T11 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: 17

18 Dr. G. Rößling Prof. 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

19 Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T11 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: 19

20 Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T11 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): 20

21 Dr. G. Rößling Prof. 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

22 Dr. G. Rößling Prof. 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 counter counterValue = 0; // increment the counter counterValue = counterValue + 1;

23 Dr. G. Rößling Prof. 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 param 1 … param n ), 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 counter int counterValue = 0; // increment the counter counterValue = counterValue + 1;

24 Dr. G. Rößling Prof. 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 OperationIn JavaExampleResult Addition+2 + 3 + 712 Subtraction-a – 213 Multiplication*a * 460 Division/a / 53 Remainder%a % 43 (as 15=3*4+3) Negation--a-15

25 Dr. G. Rößling Prof. 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

26 Dr. G. Rößling Prof. 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

27 Dr. G. Rößling Prof. 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 value counter = 10; counter = "hello"; Only operations defined for whole numbers are possible for counter. counter++; counter.move(); int counter; 4 memory cells counter

28 Dr. G. Rößling Prof. 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 2 3 4 delta size =+=+ Flow of control Evaluation order

29 Dr. G. Rößling Prof. 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

30 Dr. G. Rößling Prof. 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

31 Dr. G. Rößling Prof. 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 TypeMinimumMaximumMemory Used byte -1281271 Byte (8 Bit) short -32 76832 7672 Bytes (16 Bit) int -2 147 483 6482 147 483 6474 Bytes (32 Bit) long -2 63 2 63 -18 Bytes (64 Bit) float  1,402·10 -45  3,402·10 38 4 Bytes (32 Bit) double  4,94·10 -324  1,797·10 308 8 Bytes (64 Bit) booleanfalsetrue 1 Bit 31 Scheme abstracts from these hardware-dependent details.  easiert to use, less error-prone, but slower.

32 Dr. G. Rößling Prof. 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

33 Dr. G. Rößling Prof. 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

34 Dr. G. Rößling Prof. 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 falsetrue false

35 Dr. G. Rößling Prof. 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 (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)) 35 ABA && BA || B false truefalsetrue false true Similar to and, or in Scheme…

36 Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T11 Complex Boolean Expressions 36 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

37 Dr. G. Rößling Prof. 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

38 Dr. G. Rößling Prof. 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 2 b ) a >> b (shifts a by b positions to the right, same as dividing a by 2 b ) 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

39 Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T11 Bit Operations short i = 5  i = 0000 0000 0000 0101 short j = 3  j = 0000 0000 0000 0011 i & j = 0000 0000 0000 0001  i & j == 1 i | j = 0000 0000 0000 0111  i | j == 7 i > 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

40 Dr. G. Rößling Prof. 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

41 Dr. G. Rößling Prof. 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

42 Dr. G. Rößling Prof. 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==5 b = a++;// same as: b = a; a = a + 1;  a==6, b==5 b = ++a;// same as: a = a + 1; b = a;  a==7, b==7 b = a--;// same as: b = a; a = a – 1;  a==6, b==7

43 Dr. G. Rößling Prof. 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:

44 Dr. G. Rößling Prof. 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

45 Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T11 Operators: Priority and Associativity 45 Unary operators++, --, -, ~, !right Multiplication / Division / Remainder*, /, %left Addition/ Subtraction+, -left Shift >left Comparisons, =left Equality==, !=left bitwise and&left bitwise xor^left bitwise or|left logical and&&left logical or||left Conditional operator? :right Assignment=, +=, -=, *=, …right Priority Associativity In Scheme not necessary due to prefix notation

46 Dr. G. Rößling Prof. 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

47 Dr. G. Rößling Prof. 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

48 Dr. G. Rößling Prof. 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; }

49 Dr. G. Rößling Prof. 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

50 Dr. G. Rößling Prof. 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

51 Dr. G. Rößling Prof. 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 = | | | | | |

52 Dr. G. Rößling Prof. 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 ( ) [else ]

53 Dr. G. Rößling Prof. 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; }

54 Dr. G. Rößling Prof. 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; if (num < 0) x = 100; else x = 200; if (num < 0) x = 100; else x = 200; equivalent (if (< num 0) 100 200)

55 Dr. G. Rößling Prof. 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"]) )

56 Dr. G. Rößling Prof. 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( ) { } =... = case : = default: = |

57 Dr. G. Rößling Prof. 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

58 Dr. G. Rößling Prof. 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; }

59 Dr. G. Rößling Prof. 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

60 Dr. G. Rößling Prof. 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 

61 Dr. G. Rößling Prof. 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

62 Dr. G. Rößling Prof. 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

63 Dr. G. Rößling Prof. 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"

64 Dr. G. Rößling Prof. 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 ([ | ]; [ ];[ ]) 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"

65 Dr. G. Rößling Prof. 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 in accumulator style Iteration with assignments Natural Recursion

66 Dr. G. Rößling Prof. 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

67 Dr. G. Rößling Prof. 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 ( )

68 Dr. G. Rößling Prof. 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 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; } „Check if number is a prime"

69 Dr. G. Rößling Prof. 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

70 Dr. G. Rößling Prof. 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 ; while ( ) { ; } for ( ; ; )

71 Dr. G. Rößling Prof. 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 while ( ) must be of type boolean

72 Dr. G. Rößling Prof. 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

73 Dr. G. Rößling Prof. 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

74 Dr. G. Rößling Prof. 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: a 1, a 2, a 3,... Reference type "Array" Challenge: how can be offer fast access to a potentially very large number of elements, e.g. for sorting them?

75 Dr. G. Rößling Prof. 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 ::= [] ::= new [ ] Example: // create an array for 15 int values int[] scores = new int[15]; 75 A consecutive memory area with space for 15 int values is provided. This allows for efficient access.

76 Dr. G. Rößling Prof. 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 - 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

77 Dr. G. Rößling Prof. 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 equivalent

78 Dr. G. Rößling Prof. 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 objects int[] 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 14 ba

79 Dr. G. Rößling Prof. 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 0 0 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;

80 Dr. G. Rößling Prof. 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] 1 1 2 1 3 1 3 1 1 4 6 4 1

81 Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T11 Multi-dimensional Arrays table.length // 3 table[0].length // NullPointerException table[1].length // 2 table[1][2] // IndexOutOfBoundsException 81 042 table

82 Dr. G. Rößling Prof. 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

83 Dr. G. Rößling Prof. 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

84 Dr. G. Rößling Prof. 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

85 Dr. G. Rößling Prof. 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.jsphttp://java.sun.com/j2se/javadoc/index.jsp 85

86 Dr. G. Rößling Prof. 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 “ 86

87 Dr. G. Rößling Prof. 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

88 Dr. G. Rößling Prof. 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 roessling@acm.orgroessling@acm.org * @version 0.2 * @see #quicksort(array, int, int) */ public void quicksort(int[] array) { /* … */ } 88

89 Dr. G. Rößling Prof. 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

90 Dr. G. Rößling Prof. 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

91 Dr. G. Rößling Prof. 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

92 Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T11 The Eclipse Java Editor 92 Outline (Overview) Problems (compile errors, Warnings) Tabs for Views, here: Problems Code Editor Package Overview

93 Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T11 Eclipse: Showing JavaDoc 93

94 Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T11 Eclipse: Code Completion 94

95 Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T11 Eclipse: Content Assist 95

96 Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T11 Eclipse: Refactoring 96

97 Dr. G. Rößling Prof. 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

98 Dr. G. Rößling Prof. 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

99 Dr. G. Rößling Prof. 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 ShortcutEffect Ctrl-SpaceCode completion Ctrl-FSearch or replace text Ctrl-HSpecialized search (for classes, in files, …) Ctrl-JIncremental search („continue“) Ctrl-KJump to next occurrence Ctrl-Shift-KJump to previous occurrence Ctrl-F11Execute program F11Debug program

100 Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T11 Keyboard Shortcuts in Eclipse for Java ShortcutEffect F3Open the declaration of the element below the cursor F4Show class hierarchy in the view Alt-Shift-SShow source menu Alt-Shift-ZEnclose code block (e.g., using try/catch  T18) Shift-F2Open external Javadoc documentation Ctrl-/Comment / uncomment lines Ctrl-1Quick Fix (automatic correction) Ctrl-2Show shortcuts for Quick Assist Ctrl-Alt-HShow call hierarchy of the current method Ctrl-GSearch for class declaration in the workspace Ctrl-IAdapt indentation Ctrl-OShow outline (overview) Ctrl-TShow class hierarchy 100

101 Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T11 Keyboard Shortcuts in Eclipse for Java ShortcutEffect Ctrl-Shift-FAutomatically format code Ctrl-Shift-GSearch for references of the selected class in the workspace Ctrl-Shift-OAutomatically generate / adapt import statements (  T15) Ctrl-Shift-TQuick lookup for classes 101

102 Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T11 Code Refactoring ShortcutEffect Alt-Shift-CChange method signature (esp. parameters) Alt-Shift-IInline method Alt-Shift-MExtract method Alt-Shift-RRename Alt-Shift-TShow Refactoring menu Alt-Shift-VMove 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

103 Dr. G. Rößling Prof. Dr. M. Mühlhäuser RBG / Telekooperation © Introduction to Computer Science I: T11 Debugger Shortcuts The debugger also has a couple of shortcuts 103 ShortcutEffect F11Debug program Ctrl-Shift-BSet breakpoint at the current code line Ctrl-Shift-IInspect variable F5Step into (go “inside” method calls) F6Step over (ignore code of called methods) F7Step return (Execute method until return) F8Continue execution

104 Dr. G. Rößling Prof. 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

105 Dr. G. Rößling Prof. 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

106 Dr. G. Rößling Prof. 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/webtaskshttp://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

107 Dr. G. Rößling Prof. 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

108 Dr. G. Rößling Prof. 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


Download ppt "Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 11: From Scheme."

Similar presentations


Ads by Google