D0010E Object- oriented programming and design An introduc<on to the basic syntax and seman<cs of Java 2014-01- 29 Håkan Jonsson LTU 1 1
1. Java programs Java is a modern programming language that is object- oriented. A Java program consists of classes. Also something called interfaces. Classes are stored in files (or databases). A file may also contain import and package declara<ons that effect the classes in the file. Exactly one class per file must be declared public. If the public class is named X, the file must have the name X.java. Class names could be of any length but have start with an upper- case lewer (A, B, C, ) and may not contain blanks. A class contains declara<ons of awributes (members). A declara<on specifies details and makes the declared known to the compiler. An awribute is a variable or a method. There are also other kinds of awributes, which we will learn about later on. 2014-01- 29 Håkan Jonsson LTU 4 Main Driver Car Tire... Engine > ls -la! total 600! drwxr-xr-x 7 hj staff 238 Jan 21 16:16.! drwxr-xr-x 9 hj staff 306 Jan 21 16:14..! -rw-r--r-- 1 hj staff 151300 Jan 21 16:16 Car.java! -rw-r--r-- 1 hj staff 47104 Jan 21 16:13 Driver.java! -rw-r--r-- 1 hj staff 28546 Jan 21 16:14 Engine.java! -rw-r--r-- 1 hj staff 23552 Jan 21 16:13 Main.java! -rw-r--r-- 1 hj staff 52098 Jan 21 16:15 Tire.java! >! 2014-01- 29 Håkan Jonsson LTU 5 2014-01- 29 /**! * This class represents a car.! *! * @author hj! */! public class Car {! private static int currentspeed;! private static double fuel = 0.0d;!! /**! * This methods starts the car.! */! public static void start() {! //...!!! /**! * A call to this method stops the car by reducing the speed to! * 0, turning off the engine, and unlocking the doors.! *! */! public static void stop() {! Brakes.activate(100);! Engine.halt();! Doors.unlock();!!! /**! * Computes the current speed of the car.! * @return the speed.! */! public static double speed() {! return currentspeed;!! //...! Håkan Jonsson LTU 6! 2
1a. The awribute variable A variable holds a value. Part of the state of the program. In Java, variables must be declared. Not in python, for instance. A declara<on always specifies the type. It could state the ini<al value (recommended). A variable in a method is a local variable. For non- local variables, the declara<on also specifies proper<es of the variable. public, protected, private, sta<c, final, vola<le, int numberofcars = 0;! long stars = 0L;! float degreeswarm = 21.34f;! char firstchar = A ;! double errormargin = 4.67e-16d;! boolean isok = false;! String s = "";! public static final double acc = 0.5d;! private static int steps = 0;! 2014-01- 29 Håkan Jonsson LTU 8 3
1b. The awribute method Methods must be declared. public class MyClass {! Proper<es, type, formal public static int maximum(int a, int b) {! parameters.! boolean test;! void instead of a type means the! method does not return a result. test = a < b;! It consists of statements and! declara<ons of local variables. if (test) {! return b;! Note: A method can not contain else {! other methods. return a;! Local variables are only available in! their methods.!! The variables contain data used in the method or arguments to the method....! int x, y;! The statements specify the...! sequence of ac<ons that should // how to call a static method! be performed when the method! if (MyClass.maximum(x, y) < MAXRANGE) {! is called....! A method can be called.! 2014-01- 29 Håkan Jonsson LTU 10 2. Expressions An expression is a precise rule that describes how a value of some sort is computed. There are three basic expressions: The name of a variable. Stands for the current value of the variable. Constants. 0, 1, A, 3.14f, C etc. Values returned by methods. Moreover, there is one composite expression: Expressions containing operators opera<ng on expressions. Yes, a recursive defini<on. Example: 100 + (x 1) / Math.sqrt(2.0 * y) 2014-01- 29 Håkan Jonsson LTU 12 4
Operators Associa<vity Type.! ++ - - + - right- to- lem unary * / % lem- to- right mul<plica<ve + - lem- to- right addi<ve < <= > >= lem- to- right comparison ==!= lem- to- right comparison && lem- to- right boolean lem- to- right boolean?: right- to- lem condi<onal = right- to- lem assignment 2014-01- 29 Håkan Jonsson LTU 13 Precedence Operators have precedence. Higher up in the table means higher precedence. In an expression, an operator with high precedence is computed before operators with low precedence. Examples: Operators Associa<vity Type.! ++ - - right- to- lem unary + - * / % lem- to- right mul<plica<ve + - lem- to- right addi<ve < <= > >= lem- to- right comparison ==!= lem- to- right comparison && lem- to- right boolean lem- to- right boolean?: right- to- lem condi<onal = right- to- lem assignment a) 1 + 3 * 4 means 1 + (3 * 4). b) x &&! y z means (x && (! y)) z. 2014-01- 29 Håkan Jonsson LTU 14 Associa<vity Operators can be associa<ve. Most are. Associa<vity determines the order in which operators with the same precedence should be applied. Lem(- to- right)- associa<ve: a b c means (a b) c. Right(- to- lem)- associa<ve: a b c means a (b c). Example: Binary subtrac<on ( ) is lem- to- right, so Operators Associa<vity Type.! ++ - - right- to- lem unary + - * / % lem- to- right mul<plica<ve + - lem- to- right addi<ve < <= > >= lem- to- right comparison ==!= lem- to- right comparison && lem- to- right boolean lem- to- right boolean?: right- to- lem condi<onal = right- to- lem assignment 2 4 2 means (2 4) 2 = 4 (and not 2 (4 2) = 2 2 = 0.) 2014-01- 29 Håkan Jonsson LTU 15 5
Parentheses Parentheses are used to break precedence and associa<vity. They work the same way in Java as in other languages. Example: In (1 + 2) / 3 the parentheses are needed, or 1 + 2 / 3 is interpreted as 1 + (2 / 3). Because of the precedence, and associa<vity, parentheses can omen be omiwed. However, this makes the program hard to read and easily leads to errors. Advice: Use parentheses! Operators Associa<vity Type.! ++ - - right- to- lem unary + - * / % lem- to- right mul<plica<ve + - lem- to- right addi<ve < <= > >= lem- to- right comparison ==!= lem- to- right comparison && lem- to- right boolean lem- to- right boolean?: right- to- lem condi<onal = right- to- lem assignment 2014-01- 29 Håkan Jonsson LTU 16 3a. Arithme<c operators +, -, *, / works as usual on numbers. Note that there are unary and binary forms of + and -. The binary forms starts with compu<ng the le4 operand. % gives the reminder amer an integer division. 13 % 3 = 1 (because 4*3+1=13). Numbers divide evenly if the reminder is 0. ++ and - - Unary operators that increments or decrements by 1 respec<vely. Could be prefixes as well as suffixes: x = ++p =» p is first increased by 1, then x=p. x = p++ =» first x=p, then p is increased by 1. (Similar for - -.) (These are also called assignment operators; see 3d.) Operators Associa<vity Type.! ++ - - right- to- lem unary + - * / % lem- to- right mul<plica<ve + - lem- to- right addi<ve < <= > >= lem- to- right comparison ==!= lem- to- right comparison && lem- to- right boolean lem- to- right boolean?: right- to- lem condi<onal = right- to- lem assignment Examples: int k = 9, num = 3, code; code = num * 23 - k / 2; // 65 // Is 2 because 65 % 3 = (3*21 + 2) % 3 = 2 code % num // Is 0 because 65 = 13*5 + 0 code % 5 2014-01- 29 Håkan Jonsson LTU 18 6
Be careful with ++ and - - Example with ++ (- - similar): int p = 0;! int i = 0;! for (i = 0; i < 10; i++) {! System.out.println( ++p );!!! gives 1,2,3,4,5,6,7,8,9,10. Advice: Be careful with ++ and - - if you do not know exactly what you are doing. Omen bewer to use p = p + 1 instead of ++p or p++ (stand- alone). int p = 0, i = 0;! for (i = 0; i < 10; i++) {! System.out.println( p++ );!!! gives 0,1,2,3,4,5,6,7,8,9. 2014-01- 29 Håkan Jonsson LTU 19 3b. Logical/Rela<onal operators Works on comparable values: <, <=, >, >=, ==,!= as usual. Works on boolean values:! means NOT and negates a logical expression. && means AND. means OR. Short- circui:ng (lazy evalua:on) Only effects the two expressions A && B A B First, A is evaluated. Then, B is only evaluated if needed. false && x = false, regardless of x true x = true, regardsless of x The idea is to skip calcula<ons that are not needed. Operators Associa<vity Type.! ++ - - right- to- lem unary + - * / % lem- to- right mul<plica<ve + - lem- to- right addi<ve < <= > >= lem- to- right comparison ==!= lem- to- right comparison && lem- to- right boolean lem- to- right boolean?: right- to- lem condi<onal = right- to- lem assignment boolean a, b, c, d; 1791 > 1657!a a && b a (b!= c) c = a (1 / 0 == 0); // works c = (1 / 0 == 0) a; // fails 2014-01- 29 Håkan Jonsson LTU 21 7
3c. The ternary operator If B is a logical expression, B? x : y means x if B==true and y otherwise. The types of x and y must be related. For now: The same. Later on: x and y must conform to the type of the expression. Similar to the if statement, but an expression. Can be used everywhere an expression of the type of x and y can be used. Operators Associa<vity Type.! ++ - - right- to- lem unary + - * / % lem- to- right mul<plica<ve + - lem- to- right addi<ve < <= > >= lem- to- right comparison ==!= lem- to- right comparison && lem- to- right boolean lem- to- right boolean?: right- to- lem condi<onal = right- to- lem assignment Example: 7 <= 4? "yes" : "no x < y? x < z? x : z : y < z? y : z 2014-01- 29 Håkan Jonsson LTU 23 8
(3d. The assignment operator) The assignment operator = works as follows: <var> = <expr> means <expr> but also assigns <expr> to the variable x. If apple is one of +, -, *, /, % (among a few), wri<ng <var> apple= <expr> is a short form for <var> = <var> apple <expr> Assignment expressions have liwle, if any, value today. They easy cause confusion and bugs. Advice: Avoid using them unless the context is very clear or their use is unavoidable. Operators Associa<vity Type.! ++ - - right- to- lem unary + - * / % lem- to- right mul<plica<ve + - lem- to- right addi<ve < <= > >= lem- to- right comparison ==!= lem- to- right comparison && lem- to- right boolean lem- to- right boolean?: right- to- lem condi<onal = right- to- lem assignment Examples: x = 10 + 19 is 29 and (also) assigns x this value. x += 6 means x = x + 6 // so our x becomes 35 if ( (x /= 7) > 0 ) { // true, since 35/7>0 so... System.out.println(x); //... prints 5 2014-01- 29 Håkan Jonsson LTU 25 4. Java statements Statements: Assignment Call to a method. Compound statement. Condi<onal statements: if, if- else, switch, (extended if- else) Repe<<ons: while, for, do- while Control statements: return, con<nue, break All statements, except the compound statement, must end with a semicolon, ;. However, not when used as (part of) an expression. 2014-01- 29 Håkan Jonsson LTU 27 9
4a. Assignment An assignment changes the value of a variable: <var> = <expr> NB! Remember that variables must be declared before used. (Since assignments are also expressions, <var1> = <var2> = <expr> Since = is right- to- lem, <var2> is first assigned <expr>, and then <var1> is assigned the value of <var2>. We could have any number of variables: <var1> = <var2> = = <varn> = <expr> Assignments: numberoftigers = 10; radius = 22.7; crossmark = X ; wellknownparadox = This sentence is false. ; Assignments with assignment expressions: (Assuming x and y are both doubles) x = y = 0.0; (Assuming k and i and both int:s) k = i = 5; 2014-01- 29 Håkan Jonsson LTU 29 4b. Call to a method A call to a method is wriwen <method- name> ( <args> ) when <method- name> is in the same class as the method call, or <class>. <method- name> ( <args> ) where <class> is the name of the (some other) class containing the method, or <ref>. <method- name> ( <args> ) where <ref> is a reference to an object that contains the method If the method returns a value, the call is an expression. Otherwise, it is a statement. It is called a call no mawer what. As an expression it can, for instance, be used in an assignment: <var> = <method- name> ( <args> ) Even if it is an expression, it is allowed to write <method- name> ( <args> ); on its own as a statement, in which case the call is made but the result is lost. Example: x = Math.sqrt(4.0); Engine.halt(); exit(0); 2014-01- 29 Håkan Jonsson LTU 30 10
4c. Compound statement A compound statement is a sequence of statements and declara<ons enclosed by braces, {. The contents becomes a unit. Example: { sessionid += 1; Brakes.ac<vate(sessionID); Brakes.process(sessionID, SLOW); Compound statements are very common and useful constructs. The Java Code Conven:ons s<pulates that they should be used whenever possible to reduce the number of bugs. All examples follow this conven<on (well, they should J ). It is required in this course. Eclipse helps with this, if you like. 2014-01- 29 Håkan Jonsson LTU 32 4d. Condi<onal statements if statement: if ( <logical expr> ) { <statements> <statements> is executed if, and only if, <logical expr> is true. if- else statement: if ( <logical expr> ) { <statements 1> else { <statements 2> If <logical expr> is true, <statements 1> is executed, and otherwise, <statements 2> is executed. Examples: if (a<b) { x = a; if (numberoftigers == hunters) { evenodds = true; else { evenodds = false; This last example is bewer wriwen: evenodds = numberoftigers == hunters? true : false; and even bewer as evenodds = numberoftigers == hunters 2014-01- 29 Håkan Jonsson LTU 33 11
Condi<onal statements A usual construct, although not a statement, is the extended if- else: if ( <logical expr 1> ) { <statements 1> else if (<logical expr 2> ) { <statements 2> else if else { <statements N> The logical expressions are tested one amer another star<ng with the first. As soon as one is true, its statements are executed. If none is true, the last statements are executed. Example: if (answer == 1) { ac<on = 1; ac<vate(); else if (answer == 2) { ac<on = 3; ac<vate(); else if (answer > 2) { ac<on = 4; inac<vate(ac<on); else { ac<on = 0; 2014-01- 29 Håkan Jonsson LTU 34 Condi<onal statements A special case of the extended if- else is the switch statement: switch ( <control expr> ) { case <expr 1> : <statements 1> break; case <expr 2> : <statements 2> break; case <expr 3> : <statements 3> break; default: <statements N> break; A switch is useful when we like to do different things depending on the value of an expression, the control expression (<control expr>). This value is first computed. It is then compared to the expressions <expr 1>, <expr 2>, <expr 3>, in order downwards. When a case with a match is encountered, the statements of that case are executed. If none is found, the statements at default are executed. Warning: Without the break statements, execu<on in one case will con<nue into the cases following it!! Forge ng breaks is a common cause of bugs - be careful! 2014-01- 29 Håkan Jonsson LTU 35 12
while statement: while ( <logical expr> ) { <statements> <statements> is repeatedly executed as long as <logical expr> is true. <logical expr> is tested before each execu<on of <statements>. If/when <logical expr> is false, execu<on con<nues amer the while- statement. 4e. Repe<<on Examples: while (number > 1) { performtask(); number = number 1; while (x < 0.0 && y < 0.0) { x = x + randomchange(); y = y + randomchange(); while (x < 0.0 && y < 0.0) { x += randomchange(); y += randomchange(); 2014-01- 29 Håkan Jonsson LTU 37 Repe<<on for statement: for ( <init> ; <logical expr> ; <expr> ) { <statements> First the expression <init> (usually an assignment) is computed. Then <statements> is repeatedly executed as long as <logical expr> is true. <logical expr> (usually a comparison) is tested before each execu<on of <statement>. If/when <logical expr> is false, execu<on con<nues amer the for- statement. Amer each execu<on of <statements>, <expr> (usually changing the loop variable thereby effec<ng the logical expression) is computed. Examples: int i, sum = 0; for (i = 100; i >= 1; i- - ) { System.out.println(i); for (i = 1; i <= 5; i = i + 1) { sum += i; // 15 double lengths = 0.0d; for (int j = 1; j <= 5; j++) { int j2 = j * j; lengths += Math.sqrt(j2 + j2); // 21.213203435596427 2014-01- 29 Håkan Jonsson LTU 38 More on for The for statement is very general and has been inherited from the (old) programming language C. It is perfectly fine to leave out any or all of the three expressions(!) For instance, for ( ; ; ) { <statements> and this results in an infinite loop. First, nothing is done; between itera<ons, nothing is computed as the logical expression and at this place in a Java program (and in C programs) this means true; finally, amer each itera<on nothing is done. There is also an enhanced for loop that iterates over collec:ons. We will learn about them shortly. 2014-01- 29 Håkan Jonsson LTU 39 13
Repe<<on A do- while statement is very similar to a while- statement: do { <statements> while ( <logical expr> ) However, as indicated by the syntax, <statements> are always executed once before <logical expr> is tested. This is the point with do- while, compared to for and while. The <statements> are then repeatedly executed as long as <logical expr> is true. Exactly as while works. Example: int laps = 1; do { System.out.println("Lap number " + Integer.toString(laps)); laps++; while (laps < 4); do { LaunchPad.fireMissile(); while (!MissileCommand.stopFiring()); 2014-01- 29 Håkan Jonsson LTU 40 while, for, and do- while The three loops are convenient to use in different situa<ons. However, note the equivalent rela<ons to the right. Since, for and do- while both can be formulated using while, this means we really only need while. But for and do- while help improve readability so they are s:ll essen:al. for (A; B; C) { D; is the same as A; while (B) { D; C; do { E; while (F) is the same as E; while (F) { E; 2014-01- 29 Håkan Jonsson LTU 41 14
4f. Control statements The return statement is used to return a result from a method and terminate the method: return <expression> Note that the type of <expression> has to conform with the return type of the method. Be the same. In methods that do not return a result, return without the <expression> can be used merely to terminate the execu<on of the method. Amer a return, program execu<on con<nues where the call was made. The program returns or jumps back. Examples: public sta<c double f(double x) { return 4*x*x + 3*x - 10; sta<c void firemissil() { if (vetoedbyhal9000) { return; else { LaunchPad.fireOne(); 2014-01- 29 Håkan Jonsson LTU 43 Control statements A con:nue statement ends the current itera<on in a for, while, or do- while statement. con:nue <label> ends the current itera<on of the loop whose first line contains <label>:. It has the same effect as if program control is immediately moved to directly amer the last statement inside the loop (as if the last statement had just been executed). Execu<on con<nues with more itera<ons if the normal condi<ons for doing so are fulfilled. while (getnext(line)) { if (line.isempty() line.iscomment()) { con<nue; // More code here to process real lines outer: for (int i = 0; i < 3; i++) { while (true) { System.out.println("Hello + Integer.toString(i)); con2nue outer; System.out.println("outer"); System.out.println("Good bye"); This outputs: Hello 0 Hello 1 Hello 2 Good bye 2014-01- 29 Håkan Jonsson LTU 44 Control statements A break statement jumps out of the current compound statement, for instance a switch, a loop, or an if statement: break break <label> ends the switch/loop/if etc whose first line contains <label>:. Note that this is different from how con:nue works. Examples: int shoes = 10; while (shoes > 0) { if (shoes == 3) { break; System.out.println(shoes); - - shoes; Prints: 10, 9, 8, 7, 6, 5, and 4 only. outer: for (int i = 500; i > 0; i- - ) { while (true) { System.out.println("Hello"); break outer; System.out.println( and"); System.out.println("Good Bye"); Prints: Hello, Good Bye (Note that and is not printed because the break jumps out of both loops.)... and that s IT for this <me! J 2014-01- 29 Håkan Jonsson LTU 45 15
You have now covered 16