Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Java Programming Basic Java Expressions and Statements Cheng-Chia Chen Transparency No. 2-1 Basic Java Syntax Contents References : chapter 6,7,11. 1. Java Operators and Expressions 1. 2. 3. 4. 5. Arithmetic and bit operations comparisons logical assignments others 2. Java Statements 1. 2. 3. 4. variable declarations [and initialization] expression statements block statement control of flow statements: if, switch, for, while, break, continue, return. 5. try, throw, synchronized statement. 3. Array Transparency No. 1-2 Basic Java Syntax 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 =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=, >>>= Transparency No. 1-3 Basic Java Syntax 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( () ). Transparency No. 1-4 Basic Java Syntax Arithmetic operators and expressions operator +*/% type unary (prefix) binary, binary ++ -- unary meaning unary negation binary addition, subtraction multiplication, division, modulus (remainder after integer division) (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|. Transparency No. 1-5 Basic Java Syntax 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 ); } } Transparency No. 1-6 Basic Java Syntax Expression How many (sub)expressions are there in the expression: out.println( anInt ++ ); Ans: out.println( anInt ++ ); Transparency No. 1-7 Basic Java Syntax 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! Transparency No. 1-8 Basic Java Syntax Boolean Operators Operator type meaning && binary conditional AND || binary conditioanl OR ! unary logical NOT & binary logical AND | binary locigal OR ^ binary logical XOR 1. &&, || 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 Transparency No. 1-9 Basic Java Syntax 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. Transparency No. 1-10 Basic Java Syntax Assignment operators operator = += -= *= /= %= &= |= ^= <<= >>= >>>= type binary binary binary binary binary binary binary binary binary binary binary binary meaning basic assignment a += 2 is a shortcut for a = a + 2 a -= 2 is a shortcut for a = a - 2 a *= 2 is a shortcut for a = a * 2 a /= 2 is a shortcut for a = a / 2 a %= 2 is a shortcut for a = a % 2 a &= 2 is a shortcut for a = a & 2 a |= 2 is a shortcut for a = a | 2 a ^= 2 is a shortcut for a = a ^ 2 a <<= 2 is a shortcut for a = a << 2 a >>= 2 is a shortcut for a = a >> 2 a >>>= 2 is a shortcut for a = a >>> 2 Transparency No. 1-11 Basic Java Syntax The Conditional Operator syntax: BooleanExpr ? expr1 : expr2 Ex: int max = (x > y) ? x : y; String name; name = (name != null)? name : “unknown”; Transparency No. 1-12 Basic Java Syntax 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 Transparency No. 1-13 Basic Java Syntax 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]); } } Transparency No. 1-14 Basic Java Syntax 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; Transparency No. 1-15 Basic Java Syntax 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,… Transparency No. 1-16 Basic Java Syntax Java Statements summary Statement purpose expression sideEffect (block) compound group statements empty doNothing labled name a statement variable declare a variable if conditional switch conditional while loop do loop for simplified loop enhanced for (1.5) syntax var=expr ; expr++ ; method() ; new type() ; { statement1 … statementn } (n ≥ 0) ; label: statement [final] type name [=val [, name = val]*]; if (expr) statement [else statement] switch(expr) { [case expr: statements]* [default: statements] } while (expr) statement do statement while (expr); for(init;test;increment) statement for( Type var : arrayOfType) statement Transparency No. 1-17 Basic Java Syntax Java Statements summary (cont’d) statement break continue return synchronized throw try purpose exit loop start next loop end method critical section throw exception handle exception syntax break [label]; continue [label]; return [expr]; synchronized (expr) { statements} throw expr; try{ statements } [ catch(type name) {statements}]* [finally {statements} ] Note that some statements do not end with “;”. Transparency No. 1-18 Basic Java Syntax 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 Transparency No. 1-19 Basic Java Syntax 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! Transparency No. 1-20 Basic Java Syntax 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; Transparency No. 1-21 Basic Java Syntax 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; } } Transparency No. 1-22 Basic Java Syntax 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. Transparency No. 1-23 Basic Java Syntax Kinds of variables 1. Fields: // declared directly within class 1. class variable 2. instance variable 2. Array components 3. Parameters 1. Method parameters 2. Constructor parameters 3. exception-handler parameter 4. Local variables are variable declared within the body of a method or initialization block. Transparency No. 1-24 Basic Java Syntax 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; } } Transparency No. 1-25 Basic Java Syntax (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, Transparency No. 1-26 Basic Java Syntax 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 = x+1; final int y = 10; y final int x = 10; // compile error! y; // y has no value yet! ++; // y = 10 ok! y++ error! z = 10 // ok! Transparency No. 1-27 Basic Java Syntax 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 Transparency No. 1-28 Basic Java Syntax 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! } Transparency No. 1-29 Basic Java Syntax 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; j’s scope 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. } Transparency No. 1-30 Basic Java Syntax 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 ? }} Transparency No. 1-31 Basic Java Syntax Flow of Control statements Selection IfThenElse Switch Iteration For whileDo DoWhile Transparency No. 1-32 Basic Java Syntax IfThenElse statement 1. if (expr) statement 2. if (expr) statement else statement 3. 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; Transparency No. 1-33 Basic Java Syntax Testing multiple conditions if(n == 1) { // do task 1 } else• if (n == 2){ // can’t use elseif ! // do task 2 } else if( n == 3) { // do task 3 } else{ // do task 4 } Transparency No. 1-34 Basic Java Syntax 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); Transparency No. 1-35 Basic Java Syntax Switch statement switch (expr) { case expr1: [statements] [break;] ... case exprN: [statements] [break;] default: [statements] [break;] } Notes: 1. same semantics as in C 2. Expr must be of integer type (byte, short, char or int; long, float and double are not allowed). 3. expr1…exprN must be compile-time constant expression. 4. Duplicate cases with the same values not allowed. 5. Multiple defaults not allowed. 6. Default need not occur at the last position. Transparency No. 1-36 Basic Java Syntax 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 }} Transparency No. 1-37 Basic Java Syntax 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 } } Transparency No. 1-38 Basic Java Syntax 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. Transparency No. 1-39 Basic Java Syntax 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); } } Transparency No. 1-40 Basic Java Syntax 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 Transparency No. 1-41 Basic Java Syntax 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: 1. for(int i=2,j=i+10; i<10; i=i+1,j--) 2. print(“i+j=“ + i*j ) ; 3. 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 Transparency No. 1-42 Basic Java Syntax 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. Transparency No. 1-43 Basic Java Syntax 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); } Transparency No. 1-44 Basic Java Syntax 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 } }} Transparency No. 1-45 Basic Java Syntax 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; goto here! print(i); }. // only odd numbers are printed. Transparency No. 1-46 Basic Java Syntax 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); Transparency No. 1-47 } Basic Java Syntax 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 } Transparency No. 1-48 Basic Java Syntax 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. Transparency No. 1-49 Basic Java Syntax 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. Transparency No. 1-50 Basic Java Syntax Synchronized method (skipped!!) 1. the instance method: synchronized type method1(…) { statements } is equivalent to the following: type method1(…) { synchronized(this) { statements} } 2. the class method in class CLS: class CLS { … synchronized static type method2(…) { statements } } is equivalent to the following: class Cls { … static type method2(…) { synchronized(Cls.class) { statements}} } Transparency No. 1-51 Basic Java Syntax The throw statement (skipped!!) An exception is a signal (or simply object) indicating that some sort of exceptional condition or error has occurred. To throw an exception is to signal an exception condition. To catch an exception is to handle it – to take whatever actions required to recover from it. detail deferred Form: throw ExceptionExpr; Transparency No. 1-52 Basic Java Syntax The try-catch-finally statement (skipped!!) Java’s exception handling mechanism. try { statements1… } catch (Exception1 e1) { // statements for handling exceptions (1) of type Exception1 or // its subclass and (2) are thrown from statements1 …} … catch(EsxceptionN, eN) // N >=0 // statements for handling exceptions (1) of type ExceptionN or // its subclass ,(2)thrown from statements1 and (3) are not caught // by previous catches. … } // see next slide Transparency No. 1-53 Basic Java Syntax The try-catch-finally statement (continued) finally { statements2 // finally clause is optional // this block contains statements that are always executed after leaving the try-block, regardless of whether we leave if: // 1. normally, after reaching the bottom of the block // 2. because of break, continue or return // 3. with an exception handled by a catch handler //4. with an exception uncaught. // if terminated by executing System.exit() in the try-block, // finally clause will not executed. … } Transparency No. 1-54 Basic Java Syntax Java source file and java class definitions 1. Source file is the compilation unit of Java. 2. Each source file may contain multiple java class (and/or interface) definitions. But each file may contain at most one public class (or interface). 3. If a source file contains a public class of name Point, then this source file must be named as Point.java 4. If a source file contains a class named A then javac will produce a single file named A.class for the generated java byte code for such class. Transparency No. 1-55 Basic Java Syntax Example: The source file contains the following code : package a.b.c; // this file and its contained classes are in package a.b.c. import java.lang.*; // import statement let you use simple class name like // System in place of its fully quantified name: java.lang.System import java.io.IOException; … class A { … } public class B { … } interface C { … } must be named B.java After successful compilation, javac will produce three byte code files named A.class, B.class and C.class, respectivley. Transparency No. 1-56 Basic Java Syntax Array types revisited Declare variables of array type: 1. byte b; // b == 0 or undefined now! 2. byte[] ArrayofBytes // == null or undefined // byte[] is an array type: array of bytes 3. byte[][] ArrayofArrayOfBytes // byte[][] is an array type: // array of byte[] 4. Points[] points ; // Point[] is an array of Point objects Equivalent declarations (not recommended!!): 1. byte b; 2. byte[][] ArrayofAarrayOfBytes; 3. byte[] ArrayofArrayOfBytes[]; 3. byte ArrayOfArrayOfBytes [][]; Transparency No. 1-57 Basic Java Syntax Creating Arrays Form: new Type[size] ; Ex: byte[] buffer = new byte[1024]; String[] lines = new String[50]; int size = getFromInput(); String[] lines2 = new String[size]; // note: size is not known until runtime. Default values for array elements: interger => 0; float => 0.0 boolean => false reference => null. Transparency No. 1-58 Basic Java Syntax Using Arrays By index String[] resp = new String[2]; resp[0] = “yes”; // Java array is 0-based resp[1] = “no” resp[ resp.length ] = “fault” ; // length is a public field of array object containing // the number of elements of the array. // this will raise ArrayIndexOutOfBoundsException Transparency No. 1-59 Basic Java Syntax Initialization of large regular arrays use initialization block: class A { … int [] a = new int[size] ; int total = 0; { int len = a.length; // len is local var for(int i = 0; i < len; ) a[i] = i++; } // end of first instance initialization block. … } Transparency No. 1-60 Basic Java Syntax Array Literals char[] passwd = null ; int[] pOfTwo = new int[] {1,2,4,8,16}; // new int[] may be skipped!! // pOfTwo.length == 5 // anonymous arrays (literal): String resp = askQ( “Do you want to quit?”, new String[] {“yes”, “no”} ); double d = computeAreaOfTriangle( new Point[] { new Point(1,2), new Point(3,4), new Point(5,6) } ); Transparency No. 1-61 Basic Java Syntax How javac deal with array literals int [] pn = {6, 8}; is compiled into code equivalent to: int[] pn= new int[2]; { pn[0]= 6; pn[1] = 8; } Hence it is not a good idea to include a large amount of data in an array literal. You should store them in an external file and read them at runtime. Array literals need not be constants. Point[] points = {c1.getPoint(), c2.getPoint() } Transparency No. 1-62 Basic Java Syntax Multidimensional Arrays Consider the declaration: int [][] prod = new int[5][10]; // prod has length 5!! Some PL may produce a block of 100 int values Java does not work this way: Instead java treat it like the following code: int prod[][] = new int[5][]; // neither int[][10] nor int[][5] ! { for(int i = 0; i < 5; i++ ) prod[i] = new int[10] ; // create 5 subarrays of 10 elements } Transparency No. 1-63 Basic Java Syntax prod prod[0] prod[1] prod[2] prod[3] prod[4] prod[4][0] prod[0][0] prod[0][9] Transparency No. 1-64 Basic Java Syntax More examples float [][][] g = new float[10][20][30]; // 6000 float spaces allocated float [][][] g = new float [10][][]; // 10 null array references allocated > int x[][] = new int[10][]; > x[2] null !! // an array of length 10 of type int[][] float [][][] g = new float [10][20][]; float [][][] g = new float [10][][30]; // error float [][][] g = new float [][20][30]; //error Transparency No. 1-65 Basic Java Syntax Use array literal to create non-rectangular array: int [][] prod = { {0,0,0}, {1,1,1}, {2,2,,2}, {3,3,3}}; // prod.length == 4; prod[1].length = 3. int [][] p2 = { {0}, {1,1}, {2,2,2},{3,3,3,3}}; // p2.length = 4; p2[i].length = i + 1. Use for loop to create a large triangular table int[][] p = new int[12][]; // an array of 12 int[] { for (int r = 0; r < 12; r++) { p[r] = new int[r+1]; for(int c = 0; c < r+1; c++) p[r][c] = r * c; }} Transparency No. 1-66 Basic Java Syntax Importing classes and packages An import directive of the form: import a.b.C; appearing after the package directive allows you to refer to class C by its simple name C instead of its full name a.b.C. Similarly, the directive: import a.b.*; allows you to refer to all classes C of package a.b by simple name C instead of a.b.C. The package java.lang are used very frequently and hence by default is imported to all file: import java.lang.*; Transparency No. 1-67 Basic Java Syntax Importing static methods and fields ( new in java 5.0) An import directive of the form: import static a.b.C.m1; or import static a.b.C.field2; allows you to refer to class method C.m1() by method name m1() or static variable C.field2 by fields2 without using the class name C or a.b.C. Similarly, the directive: import static a.b.C.*; allows you to refer to all static members (fields or methods) of class C without using the class name C or a.b.C. ex: import static java.lang.System.*; ==> out.println(“abc”); in.read(); exit(0) ; // all are legal!! Transparency No. 1-68