1 / 68

Basic Java Expressions and Statements

Basic Java Expressions and Statements. Cheng-Chia Chen. Contents. References : chapter 6,7,11. Java Operators and Expressions Arithmetic and bit operations comparisons logical assignments others Java Statements variable declarations [and initialization] expression statements

lel
Télécharger la présentation

Basic Java Expressions and Statements

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Basic Java Expressions and Statements Cheng-Chia Chen

  2. Contents References : chapter 6,7,11. • Java Operators and Expressions • Arithmetic and bit operations • comparisons • logical • assignments • others • Java Statements • variable declarations [and initialization] • expression statements • block statement • control of flow statements: • if, switch, for, while, break, continue, return. • try, throw, synchronized statement. • Array

  3. Operators and Expressions • Arithmetic operators • +,-,*,/,% (binary) • +,- (unary) • pre/post Increment/Decrement operators : ++, -- • String Concatenation Operators • + • Comparison operators • ==, !=, < ,<=, >, >= • Boolean Operators • &&,, ||, !, &, |, ^ • Bitwise and shift operators • ~, &, |, ^ • <<, >>, >>> • Assignment operators • =, +=, -=, *=, /=, %=, • &=, |=, ^=, <<=, >>=, >>>=

  4. Operators and Expressions • The conditional operator • ?: • The instanceof operator • Special operators: • Object/class member access(.) • Array element access([]) • Method invocation(()) • Object creation(new) • Type conversion or casting( () ).

  5. Arithmetic operators and expressions operator type meaning - unary (prefix) unary negation + - binary, binary addition, subtraction * / % binary multiplication, division, modulus (remainder after integer division) ++ -- unary (prefix, postfix) increment, decrement (e.g., a++ is equivalent to a = a + 1) ex: • “total” + 3 + 4 // =“total34” • 7/3, 7/3.0f, 7/0 // = 2, 2.333333f, arithmeticException • 7/0.0, 0.0/0.0 // = Infinity, NaN. • 7 % 3, -7%3, 4.3%2.1 //=1, -1, 0.1.x%y = sign(x) |x| % |y|.

  6. Example: class ArithmeticOperators { public static void main(String args[]) { // Demonstration of arithmetic operators int anInt = 10; out.println( anInt ++ ); out.println( anInt-- ); out.println( -anInt ); // We can declare variables at any point! int anotherInt = 3; out.println( anInt / anotherInt ); out.println( anInt % anotherInt ); } }

  7. Expression • How many (sub)expressions are there in the expression: • out.println( anInt ++ ); • Ans: out.println( anInt ++ );

  8. comparison (or relational) operators • operator type meaning • > binary greater than • >= binary greater than or equal to • < binary less than • <= binary less than or equal to • == binary equality (i.e., "is identical to") • != binary inequality (i.e., "is not identical to") x == y return true iff 1. same primitive type and same value, or 2. same reference type and refer to same object or array, or 3. different primitive types but equal after conversion to the wider type. Note:1. +0f = -0f; NaN != NaN; NaN != any number 2. <,<=,>,>= apply to numeric types only. • b = true > false ; // error!

  9. Boolean Operators Operator type meaning && binary conditional AND || binary conditioanl OR ! unary logical NOT & binary logical AND | binary locigal OR ^ binary logical XOR • &&, || and ! can be applied to boolean values only. => !0, null || true, 1 | 0 // all errors 2. & and | require both operands evaluated; && and || are short-cut versions of | and &.. • a1=0; if (a1 == 1 & a1++ == 1) { } // a1==1 • a1=0; if (a1 == 1 && a1++ == 1) { } // a1==0

  10. Bitwise and shift operators • Bitwise operators: ~, &, |, ^ • byte b = ~12; // ~00001100 == 11110011, -13 • 10 & 7 // 00001010 & 00000111 = 00000010 or 2. • 10 | 7 //00001010 | 00000111 = 00001111 or 15. • 10 ^ 7 //00001010 ^ 00000111 = 00001101 or 13. • Shift operators: <<, >>(SSHR), >>> (unsigned SHR) • 10 << 1 // 00001010 << 1 = 00010100 = 20 = 10*2 • 7 << 3 // 00000111 << 3 = 00111000 = 7 * 8 = 56 • -1 << 2 // 0xffffffff << 2 =0xfffffffC = -4 = -1 x 4. • 10 >> 1 // = 10 /2 • 27 >> 3 // = 27/8 = 3. • -50 >> 2 // = -13 = -12 –1 = -50 /4 –1 = -50 / 4 – 1. • -16 >> 2 // = -4 = -16/4. • -50 >>> 2 // = 11001110 (204) >>> 2 = 00110011 = 51.

  11. Assignment operators • operator type meaning • = binary basic assignment • += binary a += 2 is a shortcut for a = a + 2 • -= binary a -= 2 is a shortcut for a = a - 2 • *= binary a *= 2 is a shortcut for a = a * 2 • /= binary a /= 2 is a shortcut for a = a / 2 • %= binary a %= 2 is a shortcut for a = a % 2 • &= binary a &= 2 is a shortcut for a = a & 2 • |= binary a |= 2 is a shortcut for a = a | 2 • ^= binary a ^= 2 is a shortcut for a = a ^ 2 • <<= binary a <<= 2 is a shortcut for a = a << 2 • >>= binary a >>= 2 is a shortcut for a = a >> 2 • >>>= binary a >>>= 2 is a shortcut for a = a >>> 2

  12. The Conditional Operator • syntax: • BooleanExpr ? expr1 : expr2 • Ex: • int max = (x > y) ? x : y; • String name; • name = (name != null)? name : “unknown”;

  13. Array and array Declaration (details deferred) Syntax: • arrayType arrayName[] ( = new arrayType[size] ); • arrayType[] arrayName ( = new arrayType[size] ); • arrayType[] arrayName = {initValue1, initValue2, ... initValueN}; • Ex: • int[] a; int[] c = {1,2,3}; • int[] b = new int[10]; // b[0] .. b[9] initialized to 0. • => c.length == 3 // true! • => b[2] == 0 // true • => a[2] == 0 // error!! no space assigned yet • => a == null // true

  14. Array Example class ArrayDeclaration { public static void main(String args[]) { // Demonstration of 3 techniques for array declaration; int a[] = new int[10]; int[] b = new int[10]; int[] c = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; //Like C/C++ arrays,Java arrays are indexed from 0 c[3] = 5; out.println(c[3]); b[4] = 0; b[4]++; out.println(b[4]); out.println(b[5]); } }

  15. The instanceof operator • Check if an object (reference) is an instance of the specified type. • syntax: • o instanceof type • Examples: • “string” instanceof String // true • “” instanceof Object // true • new int[ ] {1} instanceof int[] // true • new int[ ] {1} instanceof byte[] // false • new int[ ]{1} instanceof Object // true • null instanceof Object // false • // use instanceof to check if its safe to cast. • if(object instanceof Point) Point p = (Point) object;

  16. Java Statements • A statement is a single “command” that is executed by the java interpreter. • By default, the java interpreter run one statement after another, in the order they are written. • Like most PLs, many of the Java statements are flow-control statements that alter the default order of execution in well-defined ways. • IfThenElse, Switch, • WhileDo, DoWhile, For,…

  17. Java Statements summary • Statement purpose syntax • expression sideEffect var=expr ; expr++ ; (block) method() ; new type() ; • compound group statements { statement1 … statementn } (n ≥ 0) • empty doNothing ; • labled name a statementlabel: statement • variable declare a variable [final] type name [=val [, name = val]*]; • if conditional if (expr) statement [else statement] • switch conditional switch(expr) { [case expr: statements]* [default: statements] } • while loop while (expr) statement • do loop do statement while (expr); • for simplified loop for(init;test;increment) statement • enhanced for (1.5) for( Type var : arrayOfType) statement

  18. Java Statements summary (cont’d) • statement purpose syntax • break exit loop break [label]; • continue start next loop continue [label]; • return end method return [expr]; • synchronized critical section synchronized (expr) { statements} • throw throw exception throw expr; • try handle exception try{ statements } [ catch(type name) {statements}]* [finally {statements} ] • Note that some statements do not end with “;”.

  19. Expression Statements • Any Java expressions with side effect can be used as a statement simply by following it with a semicolon. • legal expression statements: • assignment, increment/decrement • method call, object creation. Ex: • a = 1 ;// assignment • x += 2;// assignment with operation • i++; // post increment • --c; // pre-decrement • System.out.println(“Hello”);// method call

  20. Compound statement (block) • A compound statement is any number of statements grouped together within curly braces. • can use compound statement anywhere a statement is required by java syntax. Ex: for(int i = 0; i < 0; i++) { a[i]++; { b--; c = a[i] ; }; } • quiz: How many statements are there in the body of the if statement ? • Ans: 5!

  21. The Empty Statement • written as a single semicolon. • do nothing but occasionally useful. Ex: for(int i = 0; i < 10, a[i++]++) // increment array element ;// loop body is empty statement Tip: Always append a semicolon after a statement if you do not assure if it must end with semicolon. Ex: while (i > 0){ a[i]++;// needed b[i]++; } ;// 1st‘;’ needed,2nd‘;’optional i = 0;

  22. Labeled statements • are statements prepended with an identifier (label) and a colon. • Labels are used by break and continue statements. • note: java has no goto statement. Ex: outerLoop: for (int i = 0; i < a.length; i++) { innerLoop: for(int j = 0; j < b.length; j++){ if(a[i] > b[j]) break; //= break innerLoop else if ( a[i] = b[j]) continue outerLoop; else break OuterLoop; } }

  23. Local Variable declaration statements • In java, variables means local variables ( which are declared within a method ), while global variables are called fields which are declared within a class and outside of any method.) • A local variable is • a symbolic name for a location where a value can be stored • defined within a method or a compound statement.

  24. Kinds of variables • Fields: // declared directly within class • class variable • instance variable • Array components • Parameters • Method parameters • Constructor parameters • exception-handler parameter • Local variables • are variable declared within the body of a method or initialization block.

  25. Example of variables class Point { static int numPoints; // numPoints is a class variable int[] w = new int[10]; // w[0]~w[9] are array components int x, y; // x and y are instance variables { int k = 10; // k and i are local variables for(int i = 0; i < w.length; i++) w[i] = k; } int setX(int x) { // x is a method parameter try{ int oldx = this.x; // oldx is a local variable this.x = x; } catch(Exception e) { // e is an catch-handler parameter e.printStackTrace(); } return oldx; } }

  26. (Local) Variable Declaration • [final] Type Name ; • [final] Type Name = initExpr ; • [final] Type Name [= initExpr [, name [=initExpr] ]* ; • Note: • InitExpr is a runTime Expression instead of limited to compile-time constants. • Final variable is readOnly and cannot be assigned new value once initialized. Ex: • int counter; // Syntax 1: no default value assigned! • String s; • int i = 0; // syntax 2 • String s=readLine();// s’value is unknown when compiling • int[] data = {x+1, x+2, x+3}; // array initializer • int x, y = 1, z; // x,z has no value yet! • float x = 1.0; y; • String q = “a good question”, ans,

  27. Final variables and default initial values • Variables declared with the “final” modifier are final variables. • Final variable is readOnly/writeOnce and cannot be assigned new value once initialized. • Ex: • final int x = 10; • x = x+1; // compile error! • final int y; // y has no value yet! • y = 10; y ++; // y = 10 ok! y++ error! • final int z = 10 // ok!

  28. Initial value of a (global) variable declared without initializer: • Initial value of a variable declared without initializer: • Integer types(byte,short,char,int) => 0 or \u0000 • floating-point type(float, double) => 0.0 • Reference(Object) Type(class,interface,array) => null • Note: • Applicable to global variables (i.e, fileds) only. • NOT applicable to local variables!! • Local variable has no value if befor it is assigned a value explicitely. • Ex: • class A { int x ; // ok! the default x value of every A instance is 0. } • => new A().x == 0 // true

  29. Notes about (local) variable declarations • must be declared before use. • must be written before reading. I.e., no default value mechanism • can occur anywhere in a method subject to the above constraint. Ex: { int i=0, j = 1; i = i + j ; int m = i + j;// ok, even some non-declaration // statements proceed it. k = i + j; //error, declaration must occur int k;//before reference. i = k + 1 // error since local k value not set yet! }

  30. Scope rules of local variables • The scope of a local variable declaration in a block is the rest of the block in which the declaration appears, starting with its own initializer. • may not be shadowed(i.e., redeclared in its scope). Ex: {int i=/*i declaration starts here until last }*/ (i=2)*2, m = i+1; { int j = 1; i = i + j; // outer i is visible i = k ; // error, k not declared yet! int i = 10; // error, i is in scope of outer i } int k,j = 10 ; // j can be redeclared since it is not in scope of any previous j. } j’s scope

  31. More Example: public class test1 { static int i = 10;// i behaves like global variable, can be // shadowed by local var. public static void main(String[] args){ int j = 3; for(int i = 1, j =2 ; i < 5; i++) // error, j is shadowed { int args;// error, parameter cannot be shadowed System.out.println("inner i=" + i); } System.out.println(“field i=“ + i ); // field i=10 { int i = test1.i; // int i = i; => error! why ? } int i = 0; // ok! why ? }}

  32. Flow of Control statements • Selection • IfThenElse • Switch • Iteration • For • whileDo • DoWhile

  33. IfThenElse statement • if (expr) statement • if (expr) statement else statement • if (expr) statement [ else if (expr) statement ]+ else statement Note: Syntax 3 is a special case of syntax 2. Ex: • if (x > 0 ) x = - x; • if(x>0&&y>0 || x<0&& y<0){z=x*y;}; //; must be removed else z = -x * y; // ; is needed. • if ( x > 0 ) y = -x //error!must append;,y=-x not a statement else y = x;

  34. Testing multiple conditions if(n == 1) { // do task 1 } elseif (n == 2){ // can’t useelseif ! // do task 2 } else if( n == 3) { // do task 3 } else{ //do task 4 }

  35. Dangling Else • when using nested if/else, make sure you know which else goes with which if statement. Ex: • if(i == j) if(j ==k) println(“i == k”); else println(“i != j);// wrong! • Dangling else is by default attached to the innermost if. • Correction: use block statement!! • if(i == j) { if(j ==k) println(“i == k”); }else println(“i != j);

  36. Switch statement switch (expr) { case expr1: [statements] [break;] ... case exprN: [statements] [break;] default: [statements][break;] } Notes: • same semantics as in C • Expr must be of integer type (byte, short, char or int; long, float and double are not allowed). • expr1…exprN must be compile-time constant expression. • Duplicate cases with the same values not allowed. • Multiple defaults not allowed. • Default need not occur at the last position.

  37. Example1: class Toomany { static void howMany(int k) { switch (k) { case 1: out.print("one "); case 2: out.print("too "); default : // same as case 3 case 3: out.println("many"); } } public static void main(String[] args) { howMany(3); // output: many howMany(2); // output: too many howMany(1); // output: one two many howMany(6); // output: many }}

  38. Example2: class Toomany { static void howMany(int k) { switch (k) { case 1: out.print("one "); break; case 2: out.print("too "); break; case 3: out.println("many"); break; // not needed! } } public static void main(String[] args) { howMany(1); // output: one howMany(2); // output: too howMany(3); // output: many } }

  39. Iteration • while (booleanExpr) statement • for ([initialization];[booleanExpr]; [iteration]) statement // basic for • for (Type var : arrayOfType) statement // enhanced for: java 1.5 or above • do statement while (booleanExpr);// semicolon is needed.

  40. Example class Iteration { public static void main(String args[]) { for (int index = 1; index <= 10; index++) { out.println("for: index = " + index); } int index = 1; while (index <= 10) { out.println("while: index = " + index); index++; } index = 1; do{ out.println("do while: index=" + index); index++; } while (index <= 10); } }

  41. Example : Enhanced For int sum(int[] a) { int sum = 0; for (int i : a) sum += i; return sum; } … sum( new int[] {1,2,3,4,5} )  15

  42. Some notes about for statement for([initialization];[booleanExpr];[increments]) statement • initialization allows declaration of multi-local variables scoped to the for-statement only. • can use comma to separate multiple variables declarations [in a single] initialization and increment expressions. Ex: • for(int i=2,j=i+10; i<10; i=i+1,j--) • print(“i+j=“ + i*j ) ; • print(i) // error! i not declared ! Note: Replace Line 1 by: for(int i =0,int j = 10; i < 10; i++, j--) is incorrect, even if ,int is changed to ;int. Hence it is impossible to declare variables with different types in initialization

  43. The break Statement break [Identifier ]; • A break statement transfers control out of an enclosing statement. • A break statement with no label attempts to end the innermost enclosing switch, while, do, or for statement of the immediately enclosing method or initializer block; this statement is called the break target. • A break statement with label Identifier attempts to end the enclosing labeled statement that has the same Identifier as its label. • In this case, the break target need not be a while, do, for, or switch statement.

  44. public Graph loseEdges(int i, int j) { int n = edges.length; nt[][] newedges = new int[n][]; for (int k = 0; k < n; ++k) { edgelist: { int z; search: { if (k == i) { for (z = 0; z < edges[k].length; ++z) if (edges[k][z] == j) break search; } else if (k == j) { for (z = 0; z < edges[k].length; ++z) if (edges[k][z] == i) break; } // No edge to be deleted; share this list. newedges[k] = edges[k]; break edgelist; } //search // Copy the list, omitting the edge at position z. int m = edges[k].length - 1; int ne[] = new int[m]; System.arraycopy(edges[k], 0, ne, 0, z); System.arraycopy(edges[k], z+1, ne, z, m-z); newedges[k] = ne; } //edgelist } return new Graph(newedges); }

  45. One more example public class Test { static int i = 10, k = 11; public static void main(String[] args){ lab1 : { int i = 0; if (i > 0) break lab1; // ok } lab2 : { int i = test1.i; if (i > 0) break ; // error, no enclosing switch or loop } }}

  46. The continue statement • A continue statement go to the end of the current iteration of a loop and starts the next one. • can be used only within a loop (while, do or for loop). • Without label => cause the innermost loop to start a new iteration. • With label => cause the named target loop to start a new iteration Ex: for(int i =0; i < 10; i++){ if( i % 2 == 0) continue; print(i); }. // only odd numbers are printed. goto here!

  47. public Graph loseEdges(int i, int j) { int n = edges.length; int[][] newedges = new int[n][]; edgelists:for (int k = 0; k < n; ++k) { int z; search: { if (k == i) { . . . } else if (k == j) { . . . } newedges[k] = edges[k]; continue edgelists; // edgelsits not needed here! } // search . . . } // edgelists return new Graph(newedges); }

  48. Return statement • syntax: • return; • return expr; • stops execution of the current method or construction with/without value returned. • Syntax 1 used in void method or constructor without returning value. • syntax 2 used in non-void method., which need return a value. Ex: • double square(double x){ return x * x; } • void printsqrt(double x){ if (x < 0 ) return;// ‘return null’ => error System.out.println(Math.sqrt(x));// return implicitly }

  49. The synchronized statement (skipped) • Synchronized statement: • form: synchronized( ObjExpr ) statement • Semantics: • 1. wait until ObjExpr is unlocked • 2. try to lock the ObjExpr and perform the statement. • 3. release the lock on ObjExpr (so that other thread waiting for the ObjExpr has chance to contrinue) • detail deferred until Multi-thread programming • Note: ObjExpr must evaluate to an object.

  50. Example of the synchronized statement (skipped!!) public static void SortArray(int[] a) { // sort the array a. this is synchronized so that other thread cannot // change elements of the array while we are sorting it. synchronized(a) { // do the actual sorting here … } } Note: The synchronized keyword is more frequently used as a method modifier serving the same role as in synchronized statement.

More Related