68
Java Programming Transparency No. 2-1 Basic Java Expressions and Statements Cheng-Chia Chen

Java Programming Transparency No. 2-1 Basic Java Expressions and Statements Cheng-Chia Chen

  • View
    258

  • Download
    0

Embed Size (px)

Citation preview

Java Programming

Transparency No. 2-1

Basic Java Expressions and

StatementsCheng-Chia Chen

Basic Java Syntax

Transparency No. 1-2

Contents

References : chapter 6,7,11.

1. Java Operators and Expressions1. Arithmetic and bit operations

2. comparisons

3. logical

4. assignments

5. others

2. Java Statements 1. variable declarations [and initialization]

2. expression statements

3. block statement

4. control of flow statements: if, switch, for, while, break, continue, return.

5. try, throw, synchronized statement.

3. Array

Basic Java Syntax

Transparency No. 1-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 =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=, >>>=

Basic Java Syntax

Transparency No. 1-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( () ).

Basic Java Syntax

Transparency No. 1-5

Arithmetic operators and expressions

operatortype 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|.

Basic Java Syntax

Transparency No. 1-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 );

} }

Basic Java Syntax

Transparency No. 1-7

Expression

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

Ans:

out.println( anInt ++ );

Basic Java Syntax

Transparency No. 1-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 wi

der type.Note:1. +0f = -0f; NaN != NaN; NaN != any number 2. <,<=,>,>= apply to numeric types only.

b = true > false ; // error!

Basic Java Syntax

Transparency No. 1-9

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 errors2. & 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

Basic Java Syntax

Transparency No. 1-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.

Basic Java Syntax

Transparency No. 1-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

Basic Java Syntax

Transparency No. 1-12

The Conditional Operator

syntax: BooleanExpr ? expr1 : expr2 Ex:

int max = (x > y) ? x : y; String name; name = (name != null)? name : “unknown”;

Basic Java Syntax

Transparency No. 1-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

Basic Java Syntax

Transparency No. 1-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]); } }

Basic Java Syntax

Transparency No. 1-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;

Basic Java Syntax

Transparency No. 1-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,…

Basic Java Syntax

Transparency No. 1-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 statement label: 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

Basic Java Syntax

Transparency No. 1-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 “;”.

Basic Java Syntax

Transparency No. 1-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

Basic Java Syntax

Transparency No. 1-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!

Basic Java Syntax

Transparency No. 1-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;

Basic Java Syntax

Transparency No. 1-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;

}

}

Basic Java Syntax

Transparency No. 1-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.

Basic Java Syntax

Transparency No. 1-24

Kinds of variables

1. Fields: // declared directly within class1. class variable

2. instance variable

2. Array components

3. Parameters1. Method parameters

2. Constructor parameters

3. exception-handler parameter

4. Local variables are variable declared within the body of a method or

initialization block.

Basic Java Syntax

Transparency No. 1-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; } }

Basic Java Syntax

Transparency No. 1-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,

Basic Java Syntax

Transparency No. 1-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 ne

w 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!

Basic Java Syntax

Transparency No. 1-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 e

xplicitely.

Ex: class A { int x ; // ok! the default x value of every A instanc

e is 0. } => new A().x == 0 // true

Basic Java Syntax

Transparency No. 1-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 occurint k; //before reference.i = k + 1 // error since local k value not set yet!

}

Basic Java Syntax

Transparency No. 1-30

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.

}

Scope rules of local variables

j’s scope

Basic Java Syntax

Transparency No. 1-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 ?}}

Basic Java Syntax

Transparency No. 1-32

Flow of Control statements

Selection IfThenElse Switch

Iteration For whileDo DoWhile

Basic Java Syntax

Transparency No. 1-33

IfThenElse statement

1. if (expr) statement2. if (expr) statement else statement3. 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;

Basic Java Syntax

Transparency No. 1-34

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}

Basic Java Syntax

Transparency No. 1-35

Dangling Else when using nested if/else, make sure you know which else g

oes 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);

Basic Java Syntax

Transparency No. 1-36

Switch statement

switch (expr) { case expr1: [statements] [break;] ... case exprN: [statements] [break;] default: [statements] [break;] } Notes:1. same semantics as in C2. Expr must be of integer type (byte, short, char or int; long, float and do

uble 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.

Basic Java Syntax

Transparency No. 1-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 }}

Basic Java Syntax

Transparency No. 1-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 }}

Basic Java Syntax

Transparency No. 1-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.

Basic Java Syntax

Transparency No. 1-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);

} }

Basic Java Syntax

Transparency No. 1-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

Basic Java Syntax

Transparency No. 1-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: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 inc

orrect, even if ,int is changed to ;int.Hence it is impossible to declare variables with different types in

initialization

Basic Java Syntax

Transparency No. 1-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 stat

ement.

Basic Java Syntax

Transparency No. 1-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); }

Basic Java Syntax

Transparency No. 1-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

}}}

Basic Java Syntax

Transparency No. 1-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 iteratio

n. With label => cause the named target loop to start a new iteratio

n

Ex:

for(int i =0; i < 10; i++){

if( i % 2 == 0) continue;

print(i);

}. // only odd numbers are printed.

goto here!

Basic Java Syntax

Transparency No. 1-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); }

Basic Java Syntax

Transparency No. 1-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 }

Basic Java Syntax

Transparency No. 1-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 f

or the ObjExpr has chance to contrinue) detail deferred until Multi-thread programming Note: ObjExpr must evaluate to an object.

Basic Java Syntax

Transparency No. 1-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.

Basic Java Syntax

Transparency No. 1-51

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}} }

Basic Java Syntax

Transparency No. 1-52

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;

Basic Java Syntax

Transparency No. 1-53

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

Basic Java Syntax

Transparency No. 1-54

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.

}

Basic Java Syntax

Transparency No. 1-55

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.

Basic Java Syntax

Transparency No. 1-56

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 c

ode files named A.class, B.class and C.class, respectivley.

Basic Java Syntax

Transparency No. 1-57

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 [][];

Basic Java Syntax

Transparency No. 1-58

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.

Basic Java Syntax

Transparency No. 1-59

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

Basic Java Syntax

Transparency No. 1-60

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.

}

Basic Java Syntax

Transparency No. 1-61

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) } ) ;

Basic Java Syntax

Transparency No. 1-62

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() }

Basic Java Syntax

Transparency No. 1-63

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 followi

ng 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

}

Basic Java Syntax

Transparency No. 1-64

prodprod[0]

prod[1]

prod[2]

prod[3]

prod[4]

prod[0][0]

prod[0][9]

prod[4][0]

Basic Java Syntax

Transparency No. 1-65

More examples

float [][][] g = new float[10][20][30]; // 6000 float spaces allocated float [][][] g = new float [10][][]; // 10 null array references allocat

ed > 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

Basic Java Syntax

Transparency No. 1-66

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 tableint[][] 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;

} }

Basic Java Syntax

Transparency No. 1-67

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.*;

Basic Java Syntax

Transparency No. 1-68

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!!