Post on 02-Jan-2016
description
transcript
Java Programming
Transparency No. 2-1
Lecture 2. Basic Java Syntax
Cheng-Chia Chen
Basic Java Syntax
Transparency No. 1-2
Contents
1. Java Program Structure
2. The lexical structure of Java PL.
3. Java Variables and Data Types
4. Array
5. Java Operators and Expressions
6. Java Statements
Basic Java Syntax
Transparency No. 1-3
Java Program Structure
• A program is made up of one or more files (compilation units)• A file consists of one or more classes (or interfaces), among wh
ich there is at most one public one.• A class contains one or more methods and fields• A method contains program statements• A Java application always executes the main method
class Person { public static void main (String[] args) { System.out.println ("Whatever you are, be a good one."); } // method main
int age; String name;} // class Person
Basic Java Syntax
4 Transparency No. 1-4
Java Program Structure
public class MyProgram{
}
// comments about the class
class Headerclass Header
class bodyclass body
Comments can be added almost anywhereComments can be added almost anywhere
class nameclass modifier
Basic Java Syntax
5 Transparency No. 1-5
Java Program Structure
public class MyProgram{
}
public static void main (String[] args)
{
}
// comments about the class
// comments about the method
method headermethod headermethod bodymethod body
Method nameReturn type
Method modifiers
Basic Java Syntax
Transparency No. 1-6
2. The lexical structure of a Java program
Multi-layer view of a programming language Kinds of tokens of Java Unicode Lexical Translation process of Java White Spaces Comments Identifiers Keywords Literals Separators Operators
Basic Java Syntax
Transparency No. 1-7
What is a well-formed program ?
/* proc1: this is a well-formed C proced
ure */void copy_chars() { character ch;while((ch = getchar()) != EOF)
putchar(ch));}
This procedure has no error.
/* proc2: this is an ill-formed C proced
ure */void copy_chars() { character c h; int ;while((ch = getchar()) ! = EOF)
putchar(chs));}
This procedure have many errors.
• A program is just a character string satisfying some constraints. Fine! but still hard to explain the difference b/t proc 1 & 2.
Basic Java Syntax
Transparency No. 1-8
Traditional explanation
Lexical rules: “This” : pronoun[s]. “procedure” noun[s] “has” :verb[s]; “have” is a verb[m] “no”, “many” : adj, adj[m]. “error”, “errors” : noun[s], noun[m] is a separator “.” is a special symbol indicating end of a sentence.
Syntax rules: pronoun[s] noun[s] -> NP[s], adj[x]noun[x] -> NP[x] verb[s] NP -> VP[s] NP[s] VP[s] . -> S
Basic Java Syntax
Transparency No. 1-9
Lexical analysis
Lexical rules
syntax analysis
Syntax rules
(grammars)
Thisprocedurehasnoerror.
char stream
. . . ‘p’ ‘s’ ‘i’ ‘h’ ‘T’
‘This’ ‘procedure’ …
Word/token stream
Note: Not all characters (e.g. ) contribute to tokens
Two-Layer view of a [programming] language
Basic Java Syntax
Transparency No. 1-10
Basic issues about the lexical structure of a PL
1. What is a character ? C => ASCII (0x00~0x7f) java => Unicode(0x0000~0xffff)
2. What are token delimiters? Whose only purpose is to delim
it tokens and increases readability ?
java =>WhiteSpace, comment
3. How many kinds of tokens are there in a PL ?
4. What character strings belong to which tokens?
5. For java, input element = token + whiteSpace + comment; every input char belongs to one input Element
verb
nouns
advs
verbs
The set of all char strings
Basic Java Syntax
Transparency No. 1-11
Kinds of tokens in Java
Token: Identifier
used for the name of package, type, method, (local)variable, parameter,etc.
Keyword (reserved words) if, then, else, while, do, switch, case, class, method, public, static, final, abstract,… int, boolean, double, long, …
Literal user for constant values. ‘c’, 123, 123L, true, 0.2e23, ”s String”, …
Separator { } ( ) [ ] , ; .
Operator: +, -, *, /, %, <=, >, …
Basic Java Syntax
Transparency No. 1-12
Unicode
java Programs are written using the Unicode character set. detail about unicode can be found at http://www.unicode.org Each character is represented by two bytes. (so there are at most 65536
characters that can be represented). The first 128 chars are identical to ASCII and the first 256 chars are identical to Extended ASCII (ISO-8859-1) can have different encodings (representations): UTF8, UTF16, etc… ASCII and UNICODE have the same UTF8 representations. Source program can still be written in OS’s native non-ASCII character
system like Big5, with the help of preconversion of java compiler. Unicode characters not directly representable in native character syste
m => using unicode escape : eg: ‘⊗’ => \u2297 , ‘A’ => \u0041, …
Basic Java Syntax
Transparency No. 1-13
Unicode, ASCII and ISO-8859-1
ISO-8859-1
ASCII
UNICODE
0x00 ~0x7F( 1 bytes)
0x00~0xFF (1 byte)
0x0000~0xFFFF[two bytes in UTF16 or UCS2][1~3 bytes in UTF8]
1. ASCII and the first 128 chars of UNICODE have the same UTF8 representations and mapping.
2. ISO8859-1 and the first codepage of UNICODE have the same mapping but different UTF8 representations
3. ISO-8859-1 to UNICODE transformation in UTF16:
Simply add one extra 0x00 byte before each ISO-8859-1 character representation.
Basic Java Syntax
Transparency No. 1-14
preconversion
Non-Unicode java Sourceprogram
(e.g., Big5 )compile
Unicode (ASCII)
char streams
javac
This step can also be done offline
using native2ascii command
Basic Java Syntax
Transparency No. 1-15
Where Unicode character are used
Where non-ASCII unicode characters are used ? comments, content of character literal, content of string literal, identifiers.
all other input elements are formed only from ASCII characters WhiteSpace, Key Words, Non-character literals, Operators Separators.
Basic Java Syntax
Transparency No. 1-16
Eliminateunicode escapes
DecomposeInto lines
DecomposeInto
Input elements
Passing Tokens
Unicode stream
containingUnicode escapes
Unicode stream
• Non-line-terminator chars +• Line terminators (LF,CR)
Input elements:
• Comments,• whiteSpaces,• Tokens
Token stream
Lexical translation process used in Java PL
Basic Java Syntax
Transparency No. 1-17
White Space
WhiteSpace: the ASCII SP character, also known as "space“ the ASCII HT character, also known as "horizontal tab“ the ASCII FF character, also known as "form feed“ LineTerminator: CR, LF or CR LF
Basic Java Syntax
Transparency No. 1-18
Comments
There are two kinds of comments: /* text multi-line comment … */ // text end-of-line comment
Notes:
1. Comments do not nest.
2. /* and */ have no special meaning in comments that begin with //.
3. // has no special meaning in comments that begin with /* or /**.
Ex: /* this comment /* // /** ends here: */
is a single complete comment.
Basic Java Syntax
Transparency No. 1-19
Identifiers
Used for class name, method name, variables etc.
no predefined meaning except as specified by the programmer made up of letters, digits, the underscore character (_), and the
dollar sign They cannot begin with a digit
Java is case sensitive, Total and total are different identifiers
Basic Java Syntax
20 Transparency No. 1-20
Reserved Words
The Java reserved words:
defaultdodoubleelseextendsfalsefinalfinallyfloatforfuturegeneric
abstractbooleanbreakbytebyvaluecasecastcatchcharclassconstcontinue
gotoifimplementsimportinnerinstanceofintinterfacelongnativenewnull
operatorouterpackageprivateprotectedpublicrestreturnshortstaticsuperswitch
synchronizedthisthrowthrowstransienttruetryvarvoidvolatilewhile
• Reserved words cannot be used as identifiers
Basic Java Syntax
Transparency No. 1-21
Literals
A literal is the source code representation of a value of a primitive type, the String type, or the null type.
Literal: IntegerLiteral : 123
FloatingPointLiteral: 123.4, 1.2e12, 12f
BooleanLiteral: true, false
CharacterLiteral: ‘a’, ‘\u123’, ‘\377’,…
StringLiteral: “a book”, “a tab \t and newline \n”
NullLiteral: null
Basic Java Syntax
Transparency No. 1-22
Integer Literals
An integer literal may be expressed in decimal (base 10), hexadecimal (base 16), or octal (base 8):
It is of type int unless suffixed with ‘L’ or ‘l’. IntegerLiteral:
DecimalIntegerLiteral HexIntegerLiteral OctalIntegerLiteral
DecimalIntegerLiteral: 0 [1-9] [0-9]* [lL]? Ex: 123, 123l, 1243L
HexIntegerLiteral: 0 [xX] [0-9a-fA-F]+ [lL]? Ex: 0X1aB4, 0x23L, 0xffff
OctalIntegerLiteral: 0 [0-7]+[lL]? Ex: 000, 0377, 01177L
Basic Java Syntax
Transparency No. 1-23
Floating-Point Literals
FloatingPointLiteral: Digits . Digits? Exp? FloatType? . Digits Exp? FloatType? Digits Exp FloatType? Digits Exp? FloatType
Exp: [eE] [+-]? Digits FloatType: [fFdD] Digits: [0-9]+ A FP literal is of type double unless it is suffixed with ‘F’ or ‘f’. Ex:
12.34e12d, 1.23E-2, <= cf: 12�.�34�e�12�d .11, .12E12f, 12e-2, 1e12D <= cf: 0x1e12L 33e2f, 33D
Space in the literalnot allowed
Basic Java Syntax
Transparency No. 1-24
Boolean Literals
The boolean type has two values, represented by the literals true and false, formed from ASCII letters.
A boolean literal is always of type boolean. BooleanLiteral:
true false
Basic Java Syntax
Transparency No. 1-25
Character Literals
expressed as a character or an escape sequence, enclosed in ASCII single quotes.
A character literal is always of type char. CharacterLiteral:
' SingleCharacter ' ' EscapeSequence '
SingleCharacter: Any Character but not any of ' \ CR LF
‘c �‘ => compile-time error It is a compile-time error for a line terminator to app
ear after the opening ' and before the closing '.
Basic Java Syntax
Transparency No. 1-26
Example:
The following are examples of char literals: 'a' '%' '\t' '\\' '\'' '\u03a9' '\uFFFF' '\177' '’ ‘‘
Which of the following are correct literals: ‘\u000a’, ‘\n’, ‘\u000D’, ‘\r’
Basic Java Syntax
Transparency No. 1-27
String Literals
consists of zero or more characters enclosed in double quotes.
Each character may be represented by an escape sequence.
always of type String StringLiteral:
" StringCharactersopt " StringCharacters:
StringCharacter StringCharacters StringCharacter
StringCharacter: Any Character but not any of " \ CR LF EscapeSequence
Basic Java Syntax
Transparency No. 1-28
Example:
“a b c \u000d sd \u000a” // error!! “This is a two-line
string“ //err! string can not across multilines “ a b c \r sd \n” // OK "" // the empty string "\"" // a string containing " alone "This is a string" // a string containing 16 chars "This is a " + // actually a string-valued “two-line strings” // constant expression, formed
// from two string literals
cf: we use octal literal 036 to represent int number 0x1e (= 30) but use ‘\36’ or ‘\036’ to represent char ‘\u001e’
Basic Java Syntax
Transparency No. 1-29
Escape Sequences for Character and String Literals Escape sequences allow for the representation of some nong
raphic characters, the single quote, double quote, and backslash characters in character and string literals.
EscapeSequence: \ b /* \u0008: backspace BS */ \ t /* \u0009: horizontal tab HT */ \ n /* \u000a: linefeed LF */ \ f /* \u000c: form feed FF */ \ r /* \u000d: carriage return CR */ \ " /* \u0022: double quote " */ \ ' /* \u0027: single quote ' */ \ \ /* \u005c: backslash \ */ OctalEscape /* \u0000 to \u00ff: from octal value */
OctalEscape: // can represent only the first 256 chars \ OctalDigit // [0-7] \ OctalDigit OctalDigit // [0-7][0-7] \ ZeroToThree OctalDigit OctalDigit // [0-3][0-7][0-7]
Basic Java Syntax
Transparency No. 1-30
The Null Literal and separators
The null type has one value, the null reference, represented by the literal null, which is formed from ASCII characters.
A null literal is always of the null type. NullLiteral:
null
Separators
The following nine ASCII characters are the separators (punctuators):
Separator: one of ( ) { } [ ] ; , .
Basic Java Syntax
Transparency No. 1-31
Operators
The following 37 tokens are the operators, formed from ASCII characters:
Operator: one of > < == <= >= != // relational + - * / % // arithmetic ! && || // conditional logical operations ?: // ternary conditional operation ++ -- // PRE/POST INCR/DECR & | ^ ~ << >> >>> // Bit and boolean operation = += -= *= /= &= |= // Assignment ^= %= <<= >>= >>>=
Basic Java Syntax
Transparency No. 1-32
3. Java Variables and Data Types
Data Types supported by Java: primitive types
numeric types integer type: byte, char, short, int, long floating-point type: float, double boolean
reference types class interface array
Notes:
1. instances of primitive types are not objects; only instances of reference types are objects.
2. Instances of reference type are pointers to object (or structure) instead of objects.
Basic Java Syntax
Transparency No. 1-33
Integer types
name representation range byte 8-bit 2's complement -128~127 short 16-bit 2's complement -32768~32767 int 32-bit 2's complement -2147483648 to
2147483647 long 64-bit 2's complement -263~263-1(19 digits) char 16-bit Unicode '\u0000' to '\uffff'
Basic Java Syntax
Transparency No. 1-34
floating-point and boolean types name representation range float 32-bit, IEEE 754 1.40239846e-45 to
3.40282347e+38 double 64-bit, IEEE 754 4.94065645841246544e-324 to 1.79769313486231570e+308
Representation: non-zero value: v = S x M x 2^E
For float: S is +/- 1, M is a positive integer less than 2^24, and E is an integer in the inclusive range -149 to 104.
For double: S is +/- 1, M is a positive integer less than 2^53, and E is an integer in the inclusive range -1045 to 1000.
special values defined in IEEE 754: +0, -0, +infinity, -Infinity, NaN. note: 0/0.0 => NaN, 1/0.0 => Infinity instead of overflow or divide by zero.
Basic Java Syntax
Transparency No. 1-35
IEEE 754 float-point single precision layout
0x7f800000 => positive infinity. 0xff800000 => negative infinity. 0x7f800001 ~ 0x7fffffff or 0xff800001~0xffffffff => NaN. Java use 0x7fc00000 as the canonical value of NaN. Distinct values of NaN are only accessible by use of the
Float.floatToRawIntBits(float) In all other cases, let s, e, and m be three values that can be c
omputed from the argument: int s = ((bits >> 31) == 0) ? 1 : -1; int e = ((bits >> 23) & 0xff); // s bit is ignored by mask of 0xff int m = (e == 0) ? (bits & 0x7fffff) << 1 : (bits & 0x7fffff) | 0x800000; the floating-point result is s · m · 2 e-150.
Basic Java Syntax
Transparency No. 1-36
b31 b30 b29 b26b28 b27 b25 b16b17b18b19b21 b20b22b23b24
es(exponent)
b15 b14 b13 b10b12 b11 b9 b0b1b2b3b5 b4b6b7b8
m(mantissa)
value is determined as follows:0. s = (b31 == 0 ? 1: -1);1. 255> e > 0 => value = s x (1.m)2 x 2 e –127 = s x (1m) x 2 e - 150
2. e = 0 => value = s x (b22.b21---b00)2 x 2 e-127 = s x (m 0)2 x 2 e - 127-23
3. e=255 && m == 0 => value = ( s == 0 ? Infinity : -Infinity)4. e = 255 && m != 0 => value = NaN; canonical NaN = 0181022
IEEE 754 float-point single precision layout
Basic Java Syntax
Transparency No. 1-37
The Modulo Operator: a%b
Used with integer types Returns the remainder of the division of b by a For example:
int a = 57; b = 16, c;
c = a%b; c now has the value 9, the remainder when 57 is divided by 16
Integer / and % in java not the same as in normal arithmetic: x / y = sign(x/y) | x/ y| = x/y with fraction part removed; x%y = x – (x/y) *y = sign(x) (|x|%|y|) always holds ex: -10 / -3 = 3; -10 % -3 = -1; // -10 / 3 = ? ; -10 % 3 = ? ex: 10 / -3 = -3; 10 % -3 = 1;
Basic Java Syntax
Transparency No. 1-38
Variables and variable Declaration
primitiveType variableName [ = initialValue ]; Ex:
byte aByte = 127; short aShort = 32767; int anInt = 2147483647; long aLong = 9223372036854775807L; float aFloat = 3.40282347E+38F; double aDouble = 1.79769313486231570E+308; char aChar = 'z'; boolean aBoolean = true; Questions: What happen if short aShort = 32768; // err, assign int to short. short b = (short) 32768 // ok! but b = -32768. int aint = 2147483648; // err numberFormException char aChar = 56; //err, assign int to char char achar = (char) 56 // ok!
Basic Java Syntax
Transparency No. 1-39
Type conversions
Java allows conversions between values of various numeric types. Except for boolean, values of all primitive types can be co
nverted. Basic types of conversions:
Widening conversion: int long; float double; char int; …
always safe except for int float, double; longdouble. automated performed by Java
Narrowing conversion: long int; double float;… must use the cast () operators not always safe.
Ex: int i =13; byte b = i; // compiler error short s = 134 ; // ok!! though 134 is int type , it is a literal.
Basic Java Syntax
Transparency No. 1-40
Use cast for narrowing conversion
Ex: int i = 13; byte b = (byte) i; // force i to be converted to a byte i = (int) 13.456 // force double literal 13.456 to int 13 i = (int) –12.6 // i == -12 i = Integer.MAX_VALUE // i = 2147483647 float j = i // need not cast, but data loss; j = 2.14748365E9 j == i ? true : false // will return true! why ?
Math.round(), Math.floor(), Math.ceil() perform other types of conversion.
short v.s. char: short s = (short) 0xffff; // s = -1; 2’s comlement char c = ‘\uffff’; // char behaves like unsigned short int i1 = s; // i1 = -1 int i2 = c; // i2 = 65535
Basic Java Syntax
Transparency No. 1-41
Java Primitive Type Conversion rules
LR boolean byte short char int long float double
boolean - N N N N N N N
byte Not allowed
- Y C Yes Y Y Y
short N Cast - C Y Y Y Y
char N C C - Y Y Y Y
int N C C C - Y Y* (loss)
Y
long N C C C C - Y* Y*
float N C C C C C - Y
double N C C C C C C -
Basic Java Syntax
Transparency No. 1-42
Operators and Expressions Arithmetic operators
+,-,*,/,%, -(unary) Increment/Decrement operators
++, -- String Concatenation Operators
+ Comparison operators
==, !=, < ,<=, >, >= Boolean Operators
&&,, ||, !, &, |, ^ Bitwise and shift operators
~, &, |, ^ <<, >>, >>>
Assignment operators =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=, >>>=
Basic Java Syntax
Transparency No. 1-43
Operators and Expressions
The conditional operator ?:
The instanceof operator Special operators:
Object member access(.) Array element access([]) Method invocation(()) Object creation(new) Type conversion or casting(()).
Basic Java Syntax
Transparency No. 1-44
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-45
Example:
class ArithmeticOperators {
public static void main(String args[]) {
// Demonstration of arithmetic operators
int anInt = 10;
System.out.println( anInt++ );
System.out.println( anInt-- );
System.out.println( -anInt );
// We can declare variables at any point!
int anotherInt = 3;
System.out.println( anInt / anotherInt ); System.out.println( anInt % anotherInt );
} }
Basic Java Syntax
Transparency No. 1-46
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 equal to") != binary inequality (i.e., "is not equal 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-47
Boolean Operators
Operatortype 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 || tr
ue, 1 | 0 // all errors2. & and | require both operands evaluated; && and || are short-cut
versions of | and &.. a[1]=0; if (a[1] == 1 & a[1]++ == 1) { } // a[1]==1 a[1]=0; if (a[1] == 1 && a[1]++ == 1) { } // a[1]==0
Basic Java Syntax
Transparency No. 1-48
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-49
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-50
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-51
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-52
4. Array and array Declaration
Syntax:
arrayType arrayName[] ( = new arrayType[size] );
arrayType[] arrayName ( = new arrayType[size] );
arrayType[] arrayName = {initValue1, initValue2, ... initValueN};
Basic Java Syntax
Transparency No. 1-53
Array Example
class ArrayDeclaration { public static void main(String args[]) {// Demonstration of 3 techniques for array declaration;
int arrayA[] = new int[10]; int[] arrayB = new int[10]; int[] arrayC = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; //Like C/C++ arrays,Java arrays are indexed from 0 arrayC[3] = 5;
System.out.println(arrayC[3]); arrayB[4] = 0;
arrayB[4]++; System.out.println(arrayB[4]); System.out.println(arrayB[5]);
} }
Basic Java Syntax
Transparency No. 1-54
5. 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-55
Java Statements summary Statement purpose syntax expression sideEffect var=expr; expr++;
(block) method(); new type(); compound group statements { statements } 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
Basic Java Syntax
Transparency No. 1-56
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-57
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-58
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--;
}
Basic Java Syntax
Transparency No. 1-59
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-60
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-61
Variables in Java
A variable is a storage location and has an associated type, sometimes called its compile-time type, that is either a primitive type or a reference type
A variable always contains a value that is assignment compatible (§5.2) with its type.
A variable's value is changed by an assignment or by a prefix/postfix ++/-- operator.
class Variable { // properties of a variable
private Location loc;
public Type type;
public Object value; …}
Basic Java Syntax
Transparency No. 1-62
Relationship between the type of a variable and the type of the value of the variable A variable of a primitive type always holds a value of that exact
primitive type. int i = 5, j ; // j = 0; short k = (short) k; float f = (float) i;
A variable of reference type can hold either of the following: A null reference A reference to any object whose class is assignment compatible with t
he type of the variable Person p1, p2 ; // p1,p2 is null if not assigned. Student s1 = new Student(“Chen”); p1 = s1; // ok! since every student is a person. s2 = s1; // s2 and s1 are (pointers to ) the same student s2 = p1 ; // compiler error since some persons are not students s2 = (Student) p1 ; // ok! but it’s programmers’ responsibility to make // sure that p1 is really a Student or its subclass (eg. BoyStudent).
Basic Java Syntax
Transparency No. 1-63
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-64
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-65
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-66
(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: 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 = 0, z = 0 if no InitExpr. float x = 1.0; y; String q = “a good question”, ans,
Basic Java Syntax
Transparency No. 1-67
Final variables and default initial values
Variables declared with the “final” modifier are final variables. Final variable is readOnly and cannot be assigned new value on
ce initialized. Ex:
final int x = 10; x = x+1; // compile error! final int y; // y has default value 0. y = 10; // compile error! final int z = 10 // ok!
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
Basic Java Syntax
Transparency No. 1-68
Notes about (local) variable declarations
must be declared before used. can occur anywhere in a method subject to the above constraint.Ex:
int i, 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.
Basic Java Syntax
Transparency No. 1-69
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) except for inside inner local class.
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-70
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 } int i = 0; // ok! why ?}}
Basic Java Syntax
Transparency No. 1-71
Flow of Control statements
Selection IfThenElse Switch
Iteration For whileDo DoWhile
Basic Java Syntax
Transparency No. 1-72
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;
Basic Java Syntax
Transparency No. 1-73
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-74
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.
if(i == j) if(j ==k) println(“i == k”); else
println(“i != j); // wrong!
Basic Java Syntax
Transparency No. 1-75
Dangling Else
if(i == j)
if(j == k)
println(“i == k”);
else
println(“i != k); // correct!
if(i == j){
if(j == k)
println(“i == k”);
}
else println(“i != j); // correct!
Basic Java Syntax
Transparency No. 1-76
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-77
Example1:
class Toomany { static void howMany(int k) { switch (k) { case 1: System.out.print("one "); case 2: System.out.print("too "); case 3: System.out.println("many"); } } public static void main(String[] args) { howMany(3); // output: many howMany(2); // output: too many howMany(1); // output: one two many }}
Basic Java Syntax
Transparency No. 1-78
Example2:
class Toomany { static void howMany(int k) { switch (k) { case 1: System.out.print("one "); break; case 2: System.out.print("too "); break; case 3: System.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-79
Iteration
while (booleanExpr)
statement for ([initialization];[booleanExpr]; [iteration])
statement do statement
while (booleanExpr); // semicolon is needed.
Basic Java Syntax
Transparency No. 1-80
Equivalence of Different Loop statements
Notes: for(init; expr; incr) statement is equivalent to:
init; while(expr){ statement incr; } //suppose there is no break/continue in statement
do statement while(expr); is equivalent to
statement while(!expr) statement
1. So theoretically, For and DoWhile is not needed.
Basic Java Syntax
Transparency No. 1-81
Inequivalence of for-loop and while loop transformation
for (int i = 0; i < 10; i++) {
if ( i % 2 == 0 ) continue;
System.out.print(i); } // output: 13579
int i = 0;
while( i < 10) {
if ( i % 2 == 0 ) continue;
System.out.print(i);
i++; } // will not terminate!!
Basic Java Syntax
Transparency No. 1-82
Example
class Iteration {
public static void main(String args[]) {
for (int index = 1; index <= 10; index++) {System.out.println("for: index = " + index);}
int index = 1;
while (index <= 10)
{ System.out.println("while: index = " + index);
index++; }
index = 1;
do{
System.out.println("do while: index=" + index);
index++;
}while (index <= 10);
} }
Basic Java Syntax
Transparency No. 1-83
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-84
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.
Basic Java Syntax
Transparency No. 1-85
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-86
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, break outside switch or loop
}}}
Basic Java Syntax
Transparency No. 1-87
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-88
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; } // search . . . } // edgelists return new Graph(newedges); }
Basic Java Syntax
Transparency No. 1-89
Return statement
return; return expr; stops execution of the current method or construction with/with
out value returned. Syntax 1 used in void method or constructor without returning v
alue. 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-90
The synchronized statement
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 (or array)
Basic Java Syntax
Transparency No. 1-91
Example of the synchronized statement
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-92
Synchronized method
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-93
The throw statement
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-94
Example:
public static double factorial(int x) throws ArgTooBigException // checked exception must be declared { if(x < 0 ) throw new IllegalArgumentException(“x must >=0”); if(x > 50) throw new ArgTooBigException(“x must < =50”);double fact;for(fact=1.0; x > 0; fact *= x, x--);return fact; }Note: throw behaves as follows: 1. return control to the matching catch statement of the most nea
rest enclosing try-blocks, if it can find one. Otherwise, 2. throw the same exception to the calling method.
Basic Java Syntax
Transparency No. 1-95
Exception Types
An exception in java is an object of type java.lang.Throwable.
two subclasses: java.lang.Error
indicating unrecoverable error: OutOfMemoryError, FileCorrupted, FileUnReadable,… can be caught and handled, but rare to do so.
java.lang.Exception: for less severe errors can be subclssed by programmers usually will be caught and handled java.io.EOFException, java.io.FileNotFoundException java.lang.ArrayO
utOfBoundsException,…
Basic Java Syntax
Transparency No. 1-96
Checked and unchecked exceptions
Unchecked exceptions: including instances of java.lang.Error or java.lang.RunTimeE
xception can occur virtually at any place at any time. Ex: NullPointerException, OutOfMemoryError,… hard to predicate when and where it will occur.
Checked Exceptions: including all instances of java.lang.Exception but java.lang.R
unTimeException can only be thrown at well-understood circumstance. ex: FileNotFoundException will be thrown only if you try to a
ccess files.
Basic Java Syntax
Transparency No. 1-97
Java rules for checked and unchecked exceptions
For any checked exception that will be thrown but not caught in a method, it must be indicated at the throws clause of the method header.
Since virtually nearly all unchecked exceptions can occur in a method, it is impractical ( and hence not necessary) to include all possible exceptions at the
throws clause of the method header.
Ex: in the previous method factorial(), the exception IiigalArgumentException is a java.lang.RunT
imeException, it need not be declared with a throws clause.
the exception ArgTooBigException is a user-defined non RunTimeException, so it must be declared.
Basic Java Syntax
Transparency No. 1-98
How to know what checked exceptions will be thrown from a method invocation ?
1. look at its method signature, or
2. look at the error message of compilation.
Problem 2: what checked exceptions do I have to declare at the throws clause in my method header ?
Ans: collect all checked exceptions that your method would not catch and are declared at any method called in your method or are thrown in your method.
Basic Java Syntax
Transparency No. 1-99
Example:
class A { void m1() throws E11,E12,E { … }void m2() throws E21, E22,E {…}void m3() throws _______?_________ { try{ … m1(); m2(); … throws new E3(); … }catch(E11 e1){…} catch(E2 e2) {…} // suppose E2 is superclass of E21,E22 and E… // in the try-block only E3,E12 are not caught m2(); throws new E4();… }
=> we need put ‘E4, E21,E22,E, E3,E12’ on the header of m3().
Basic Java Syntax
Transparency No. 1-100
The try-catch-finally statement
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-101
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-102
Inequivalence of for-loop and while loop transformation
for (int i = 0; i < 10; i++) { if ( i % 2 == 0 ) continue; System.out.print(i); } // output: 13579
int i = 0;while( i < 10) { if ( i % 2 == 0 ) continue; System.out.print(i); i++; } // will not terminate!! The inequivalence lies in that the increment i++ is not executed
when continue is executed. the try-finally statement can help remedy this defect.
Basic Java Syntax
Transparency No. 1-103
Use finally-clause to remedy the inquivalence of for-loop and while-loop transformation
for(init; test; incr) statementis equivalent toinit;while(test) { try{ statement } fially{incr} }==>int i = 0;while( i < 10) { try { if ( i % 2 == 0 ) continue; System.out.print(i); } finally { i++; } } // output: 13579
Basic Java Syntax
Transparency No. 1-104
Methods
a named collection of Java Statements that can be invoked by other Java code.
when invoked, it is passed zero or more value known as arguments
The method performs some computations and optionally return a value.
A method invocation is an expression that is evaluated by the Java interpreter.
Since method invocation has side effects, they can also be used as expression statements.
Basic Java Syntax
Transparency No. 1-105
The form of a method
modifiers type name (parameterlist) [throws exceptions]
// method header (signature)
{ … } // method body
where: modifiers are a list of keywords from: public, protected, private,
static, synchronized, final, abstract, native. type are any primitive or user-defined type: int, int[],
Object, Person,…. serving as the type of the return value. parameterList is a comma-separated list of type- variable pairs:
ex: int[] a, int length exceptions are a comma-separated list of uncaught checked exc
eption types.
Basic Java Syntax
Transparency No. 1-106
Method Examples
public static void main(String[] args) { …} public static synchronized int indexOf(Object e, int idx )
{ … } double distance() { … } static double squareRoot(double x) throws IllegaArgum
entException { … } protected abstract String readText(File f, String encodin
g) throws FieNotFoundException, UnSupportedEncodingExceptin { … }
Basic Java Syntax
Transparency No. 1-107
Method Overloading
Java allow you to define in a class multiple methods of the same name but with different signatures, which are method name together with the list of parameter types ordered by their occurrences in the parameterList
Ex:
public static void main(String[] args) => main(String[]) public static synchronized int indexOf(Object e, int idx )
=> indexOf(Object, int) double distance() => distance().
Basic Java Syntax
Transparency No. 1-108
Example
pubic class Test {
public static void main(String[] args ) {…}
public static void main(String[][] args ) {…} // ok
private int main(String[] xx) throws IOException { … }
// error, method already defined
public void main(int args) {… } // ok
public void main(String[] args, int len) {… } // ok
}
Basic Java Syntax
Transparency No. 1-109
Classes and Objects
A class is a named collection of fields (variables) that hold data values and methods that operate on these values. Classes may also contain classes called nested (inner) cal
sses; constructor (methods) are used to create its [object] instances
Class is the fundamental unit of Java program All Java statements appear within methods (and initializati
n blocks) All methods are defined within classes Java interpreter and compiler cannot recognize java code
smaller than a class. basic execution unit of java interpreter/loader A class define a new data type.
Basic Java Syntax
Transparency No. 1-110
Defining a class
a possible definition of a plane Point class:
pubic class Point {
public double x,y; // the coordinates of the point
Point(double x, double y) { // constructor
this.x = x;
this.y = y; }
public distanceFrom(double x1, double y1) {
double dx = x – x1, dy = y – y1
return Math.sqrt(dx*dx + dy*dy); }
Basic Java Syntax
Transparency No. 1-111
Note about java source file and java class definitons
1. Source file is the compilation unit of Java.
2. Each source file may contain multiple java class (and/or interface) definitions.
3. Each file may contain at most one public class (or interface).
4. If a source file contains a public class of name Point, then this source file must be named as Point.java
5. 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-112
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-113
Creating an object (instance) of a class
After defining the class Point, we can use Point as a new data type. and declare variable of type Point.
Point p; // p now has value null.
// Create a Point instance representing (2, -3.5) and store it in
// variable p
p = new Point(2.0, -3.5); // 1. p is a scalar pointer (or reference)
// pointing to a structure representing an Point instance.
// 2. Point(double,double) match the constructor signature.
// Create some other objects as well
Date d = new Date() // d represent the current time
Vector v = new Vector() // v can hold a list of objects
Object o = Class.forName( aClassName).newInstance();
// dynamically create an object of type unknown at compile-time.
Basic Java Syntax
Transparency No. 1-114
Object Literals
In Java, strings are objects of type java.lang.String java allows you to use the string literal notation to represent a S
tring object.
Ex:
String lastName = “ Chen “;
String firstName=“Cheng-Chia”;
String fullName = new String(lastName + “ “ + firstname)
Basic Java Syntax
Transparency No. 1-115
Using an Object
Given an object o of type T, we can access its fields or invoke its methods as follows:
Point p = new Point(2,3);
double x = p.x // getter
p.y = 4 // setter
double d = p.distanceFrom(0,0)
// invoke a method of the object p
// note: () is required even if the method need not parameters.
Basic Java Syntax
Transparency No. 1-116
Array types revisited
Declare variables of array type: 1. byte b; // b == null now! 2. byte[] ArrayofBytes // == null // 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 : 1. byte b; 2. byte ArrayofBytes[] 3. byte[] ArrayofArrayOfBytes[]; 3. byte ArrayOfArrayOfBytes [][];
Basic Java Syntax
Transparency No. 1-117
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-118
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-119
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 initializatin block.
…
}
Basic Java Syntax
Transparency No. 1-120
Array Literals
char[] passwd = null ;
int[] pOfTwo = {1,2,4,8,16};
// 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-121
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. Instead, 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-122
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][]; // not int[][10] or 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-123
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-124
More example
float [][][] g = new float[10][20][30]; float [][][] g = new float [10][][];
// 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-125
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-126
Package and java Namespace
A package is a named collection of classes (including interfaces) and subpackages
Package are used to group related classes and define a namespace for the classes they contain.
Known packages in Java plateform: java, javax, org.omg, java.lang // contians
Basic Java Syntax
Transparency No. 1-127
Some Java 2 packages
java.lang : Classes providing wrapper types for primitives, system information, meta-classes
java.io : Classes for various forms stream input to/output from files, keyboard, screen and strings
java.util : Classes for abstract data structures and random numbers
java.net : Classes for network communication using sockets (TCP and UDP), datagrams and URLs
java.awt : Abstract Window Toolkit graphical component classes
java.awt.image : Classes containing platform-specific GUI libraries for mapping to AWT
java.applet : Classes for creating WWW-based Applets
Basic Java Syntax
Transparency No. 1-128
Defining a package
We use the package directive:
package a.b.c;
appearing at the beginning of a java source file to declare that all classes defined in that file are part of the package named a.b.c
If no package directive appearing in a source file, all classes of that file belong to a default unnamed package.
non-public classes of a package can be directly accessed only from within classes of the same package.
Basic Java Syntax
Transparency No. 1-129
Simple class name and fully qualitified class name
Every class in java can be named in two ways: simple name: are the name given in the definition fully quantified name: are name of its containing package
+ simple name. Ex: the String class is part of the package java.lang, so its
fqName is java.lang.String
Naming rules: Classes of the same package can refer to each other
by their simple names (or full name). Classes from different packages must be referred to
in a class by their fully quantified names except for those declared in an import statement.
Basic Java Syntax
Transparency No. 1-130
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-131
Suggested package naming scheme
Simple class name as well as package name is very likely to collide with others. the goal of a global unique package and class name violat
ed. a package naming scheme needed.
Proposed naming scheme: Reverse internet domain name: I have a internet domain: xml.cs.nccu.edu.tw => all my java packages begin with the word: tw.edu.nccu.cs.xml.
Basic Java Syntax
Transparency No. 1-132
Java File structure
A java source file consists of : an optional package directive, zero or more import directives, one or more public/non-public classes/interfaces
definitions.
Basic Java Syntax
Transparency No. 1-133
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.Systemimport 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. Only class B can be used outside package a.b.c; all other cla
sses (A,C) can only be used inside package a.b.c.
Basic Java Syntax
Transparency No. 1-134
Java package structure
principle of physical package locations: All files in the same package must be located in the same
physical directories. package p located at directory d => subpackage p.q located at directory p/q
root directories/jars: the directories/jars where java/javac find top level package
s like java, javax, tw Java 2 defined 3 kinds of root dirctories/jars: system root jars: JAVA_HOME\ extension root jars: all jars at JAVA_HOME\jre\lib\ext user root dir/jars: specified by programmers via the syste
m variables: CLASSPATH or the –classpath/cp option.