Lecture 2. Basic Java Syntax by ivz21134

VIEWS: 35 PAGES: 135

									                     Java Programming




    Lecture 2.
Basic Java Syntax
   Cheng-Chia Chen




                        Transparency No. 2-1
                                                Basic Java Syntax
     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




                                         Transparency No. 1-2
                                                                 Basic Java Syntax
    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
  which 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
                                                          Transparency No. 1-3
                                                          Basic Java Syntax
Java Program Structure
                         class modifier
                                          class name

   // comments about the class
   public class MyProgram
   {
                                    class Header


             class body


                  Comments can be added almost anywhere

   }
                                                                          4
                                                   Transparency No. 1-4
                                                  Basic Java Syntax
Java Program Structure



   // comments about the class
   public class MyProgram
   {                 Method modifiers

       // comments about the method
       public static void main (String[] args)
       {
                 method body            method header
                                        Method name
       }                  Return type



   }
                                                                  5
                                           Transparency No. 1-5
                                                        Basic Java Syntax
    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
                                                 Transparency No. 1-6
                                                            Basic Java Syntax
    What is a well-formed program ?
/* proc1:                             /* proc2:
this is a well-formed C                this is an ill-formed C
   procedure */                          procedure */
void copy_chars()  {                 void copy_chars()      {
 character ch;                        character c h; int ;
while((ch = getchar()) != EOF)        while((ch = getchar()) ! = EOF)
   putchar(ch));                         putchar(chs));
}                                     }

 This procedure has no             This procedure have 
  error.                                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.
                                                     Transparency No. 1-7
                                                      Basic Java Syntax
   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

                                               Transparency No. 1-8
                                                                Basic Java Syntax

  Two-Layer view of a [programming] language


                          Thisprocedure    no
                                         has error.
                            . . . ‘p’ ‘s’ ‘i’ ‘h’ ‘T’

  syntax
                                Lexical
  analysis ‘This’ ‘procedure’ …
                                analysis
  Syntax                                                 char stream
           Word/token stream             Lexical
   rules
                                          rules
(grammars)

Note: Not all characters (e.g.  contribute to tokens
                                )

                                                         Transparency No. 1-9
                                                              Basic Java Syntax
   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
                                                  nouns
     delimit tokens and increases                            verbs
     readability ?
    java =>WhiteSpace, comment
3. How many kinds of tokens are
                                                      verb
    there in a PL ?
4. What character strings belong       advs
    to which tokens?
5. For java, input element =
    token + whiteSpace +
    comment; every input char
    belongs to one input
    Element                      The set of all char strings
                                                       Transparency No. 1-10
                                                             Basic Java Syntax
  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:
      +, -, *, /, %, <=, >, …
                                                      Transparency No. 1-11
                                                               Basic Java Syntax
   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
    system => using unicode escape :
    eg: „⊗‟ => \u2297 , „A‟ => \u0041, …

                                                        Transparency No. 1-12
                                                            Basic Java Syntax
Unicode, ASCII and ISO-8859-1

                                                    ASCII

                          ISO-8859-1             0x00 ~0x7F
                                                 ( 1 bytes)
                           0x00~0xFF
                             (1 byte)

                      1. ASCII and the first 128 chars of UNICODE
    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.
 0x0000~0xFFFF
 [two bytes in UTF16 or UCS2]
 [1~3 bytes in UTF8]
                                                     Transparency No. 1-13
                                                         Basic Java Syntax




                                    This step can also be
                                         done offline
                                     using native2ascii
                                          command

                                             Non-Unicode
                                             java Source
          Unicode (ASCII)                    program
compile                     preconversion
           char streams                      (e.g., Big5 )




             javac


                                                  Transparency No. 1-14
                                               Basic Java Syntax
   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.

                                        Transparency No. 1-15
                                                             Basic Java Syntax

Lexical translation process used in Java PL



                          Unicode stream      Eliminate      Unicode stream
      Decompose
                                              unicode
       Into lines                                              containing
                                              escapes      Unicode escapes

               • Non-line-terminator chars +
               • Line terminators (LF,CR)
                                                                Token stream
      Decompose Input elements:                Passing
          Into                                 Tokens
    Input elements • Comments,
                         • whiteSpaces,
                         • Tokens



                                                      Transparency No. 1-16
                                                    Basic Java Syntax
  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




                                             Transparency No. 1-17
                                                     Basic Java Syntax
   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.              Transparency No. 1-18
                                                          Basic Java Syntax
   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




                                                   Transparency No. 1-19
                                                     Basic Java Syntax
   Reserved Words
 The Java reserved words:
 abstract   default   goto         operator synchronized
 boolean    do        if           outer     this
 break      double    implements   package throw
 byte       else      import       private throws
 byvalue    extends   inner        protected transient
 case       false     instanceof   public    true
 cast       final     int          rest      try
 catch      finally   interface    return    var
 char       float     long         short     void
 class      for       native       static    volatile
 const      future    new          super     while
 continue   generic   null         switch

 • Reserved words cannot be used as identifiers

                                                                  20
                                              Transparency No. 1-20
                                                  Basic Java Syntax
   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


                                           Transparency No. 1-21
                                                               Basic Java Syntax
    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

                                                        Transparency No. 1-22
                                                                  Basic Java Syntax
     Floating-Point Literals
 FloatingPointLiteral:
     Digits . Digits? Exp? FloatType?
     . Digits Exp? FloatType?
     Digits Exp FloatType?
     Digits Exp? FloatType
   Exp: [eE] [+-]? Digits
                                                         Space in the literal
   FloatType: [fFdD]
                                                         not allowed
   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

                                                           Transparency No. 1-23
                                                  Basic Java Syntax
   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




                                           Transparency No. 1-24
                                                    Basic Java Syntax
   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
  appear after the opening ' and before the closing '.

                                             Transparency No. 1-25
                                                  Basic Java Syntax
   Example:
 The following are examples of char literals:
  'a'      '%'           '\t'     '\\'      '\''
  '\u03a9' '\uFFFF'      '\177'   '‟       „„
 Which of the following are correct literals:
  „\u000a‟,
  „\n‟,
  „\u000D‟,
  „\r‟




                                           Transparency No. 1-26
                                                    Basic Java Syntax
   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

                                             Transparency No. 1-27
                                                Basic Java Syntax
   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‟

                                         Transparency No. 1-28
                                                                Basic Java Syntax
   Escape Sequences for Character and String Literals
 Escape sequences allow for the representation of some
  nongraphic 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]
                                                         Transparency No. 1-29
                                                        Basic Java Syntax
   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
   (        )   {   }   [    ]      ;   ,   .

                                                 Transparency No. 1-30
                                                         Basic Java Syntax
  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
  ^=    %=        <<= >>= >>>=



                                                  Transparency No. 1-31
                                                          Basic Java Syntax
    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.

                                                   Transparency No. 1-32
                                                   Basic Java Syntax
    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'




                                            Transparency No. 1-33
                                                                   Basic Java Syntax
   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.
                                                            Transparency No. 1-34
                                                                    Basic Java Syntax
    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
  computed 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.




                                                             Transparency No. 1-35
                                                                     Basic Java Syntax
IEEE 754 float-point single precision layout

                    (exponent)
     s                   e

     b31 b30 b29 b28 b27 b26 b25 b24 b23 b22 b21 b20 b19 b18 b17 b16

                  (man’tissa)
                      m


     b15 b14 b13 b12 b11 b10 b9 b8 b7 b6 b5 b4 b3 b2 b1 b0


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
                                                              Transparency No. 1-36
                                                                            Basic Java Syntax
   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 = 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;




                                                                     Transparency No. 1-37
                                                          Basic Java Syntax
    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 = 65600; //err, assign int to char
    char achar = (char) 65500 // ok! = „@‟
                                                   Transparency No. 1-38
                                                                        Basic Java Syntax
   Type conversions
 Java allows conversions between values of various numeric
  types.
    Except for boolean, values of all primitive types can be converted.
 Basic types of conversions:
    Widening conversion:
    int  long; float double; char  int; …
         always safe except for int float, double; longdouble.
         automated performed by Java
    Narrowing conversion: long  int; double  float;…
         must use the cast () operators; (except for int literal, which can be
         downcasted to the required integral type automatically if it is inside the
         range of the left variable ).
         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.

                                                                 Transparency No. 1-39
                                                                   Basic Java Syntax
   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

                                                            Transparency No. 1-40
                                                                   Basic Java Syntax
      Java Primitive Type Conversion rules
LR        boolean   byte short char         int   long        float        double

boolean -            N     N       N         N     N           N            N

byte       Not       -     Y       C         Yes   Y           Y            Y
           allowed
short      N         Cast -        C         Y     Y           Y            Y

char       N         C     C       -         Y     Y           Y            Y

int        N         C     C       C         -     Y           Y*     Y
                                                               (loss)
long       N         C     C       C         C     -           Y*     Y*

float      N         C     C       C         C     C           -            Y

double     N         C     C       C         C     C           C            -
                                                          Transparency No. 1-41
                                          Basic Java Syntax
   Operators and Expressions
 Arithmetic operators
    +,-,*,/,%, -(unary)
 Increment/Decrement operators
    ++, --
 String Concatenation Operators
   +
 Comparison operators
    ==, !=, < ,<=, >, >=
 Boolean Operators
    &&,, ||, !, &, |, ^
 Bitwise and shift operators
    ~, &, |, ^
    <<, >>, >>>
 Assignment operators
    =, +=, -=, *=, /=, %=,
    &=, |=, ^=, <<=, >>=, >>>=
                                   Transparency No. 1-42
                                            Basic Java Syntax
  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(()).




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

                                                               Transparency No. 1-44
                                             Basic Java Syntax
  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 );
} }


                                      Transparency No. 1-45
                                                         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 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
   wider type.
Note:1. +0f = -0f; NaN != NaN; NaN != any number
  2. <,<=,>,>= apply to numeric types only.
    b = true > false ; // error!
                                                  Transparency No. 1-46
                                                                   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 &..
    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
                                                            Transparency No. 1-47
                                                      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-48
                                                          Basic Java Syntax
     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

                                                   Transparency No. 1-49
                                            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-50
                                                       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-51
                                                          Basic Java Syntax
   4. Array and array Declaration

Syntax:
 arrayType arrayName[] ( = new arrayType[size] );
 arrayType[] arrayName ( = new arrayType[size] );
 arrayType[] arrayName = {initValue1, initValue2, ... initValueN};




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

                                             Transparency No. 1-53
                                                Basic Java Syntax
   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,…




                                         Transparency No. 1-54
                                                                    Basic Java Syntax
       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
   enhanced for (1.5)                for( Type var : arrayOfType) statement


                                                             Transparency No. 1-55
                                                                 Basic Java Syntax
     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 “;”.




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




                                     Transparency No. 1-58
                                                      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-59
                                                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-60
                                                 Basic Java Syntax
   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; …}
                                          Transparency No. 1-61
                                                                Basic Java Syntax
   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) i; 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
    the 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).
                                                         Transparency No. 1-62
                                                              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-63
                                                     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-64
                                                                         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-65
                                                                              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:
       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,
                                                                       Transparency No. 1-66
                                                              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 = 10;
   x = x+1;               // compile error!
   final int        y;// y has default value 0 if non-
    final.
   y = 10; y        ++;   // y = 10 ok! y++ 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
                                                      Transparency No. 1-67
                                                        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-68
                                                        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) except for
  inside inner local class.
Ex:
{int i=/*i declaration starts here until last }*/
         (i=2)*2, m = i+1;
                                   j’s scope
 { 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.
 }                                           Transparency No. 1-69
                                                           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-70
                                       Basic Java Syntax
   Flow of Control statements
 Selection
   IfThenElse
   Switch
 Iteration
   For
   whileDo
   DoWhile




                                Transparency No. 1-71
                                                   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-72
                                       Basic Java Syntax
  Testing multiple conditions
if(n == 1) {
   // do task 1
}
    i
else•f (n == 2){ // can‟t use elseif !
 // do task 2
}
else if( n == 3) {
 // do task 3
}
else{
 // do task 4
}
                                Transparency No. 1-73
                                                          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.

 if(i == j)
    if(j ==k)
      println(“i == k”);
    else
      println(“i != j); // wrong!should be j!=k

                                                   Transparency No. 1-74
                                          Basic Java Syntax
  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!
                                   Transparency No. 1-75
                                                                 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-76
                                             Basic Java Syntax
  Example1:
class Toomany {
  static void howMany(int k) {
   switch (k) {
    case 1: System.out.print("one ");
    case 2: System.out.print("too ");
    default : // same as case 3
    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
   howMany(6); // output: many
  }}
                                      Transparency No. 1-77
                                            Basic Java Syntax
  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
 }
}
                                     Transparency No. 1-78
                                             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-79
                                                         Basic Java Syntax
   Equivalence of Different Loop statements
Notes:
 for(init; expr; incr) statement
  is almost 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.
                                                  Transparency No. 1-80
                                                              Basic Java Syntax
   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!!



                                                       Transparency No. 1-81
                                             Basic Java Syntax
  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);
  } }
                                      Transparency No. 1-82
                                        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-83
                                                             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-84
                                                               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-85
                                                                              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-86
                                                             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-87
                                                         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;
 print(i);               goto here!
}.      // only odd numbers are printed.
                                                  Transparency No. 1-88
                                                                                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;
                 } // search
                 ...
           } // edgelists
           return new Graph(newedges);
       }                                                              Transparency No. 1-89
                                                       Basic Java Syntax
   Return statement
 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-90
                                                       Basic Java Syntax
  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
   for the ObjExpr has chance to contrinue)
  detail deferred until Multi-thread programming
  Note: ObjExpr must evaluate to an object.



                                                Transparency No. 1-91
                                                           Basic Java Syntax
   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.

                                                    Transparency No. 1-92
                                                        Basic Java Syntax
   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}}
  }
                                                 Transparency No. 1-93
                                                   Basic Java Syntax
   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;


                                            Transparency No. 1-94
                                                         Basic Java Syntax
   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
    nearest enclosing try-blocks, if it can find one. Otherwise,
 2. throw the same exception to the calling method.

                                                  Transparency No. 1-95
                                                            Basic Java Syntax
   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.ArrayOutOfBoundsException,…

                                                     Transparency No. 1-96
                                                       Basic Java Syntax
  Checked and unchecked exceptions
 Unchecked exceptions:
  including instances of java.lang.Error or
   java.lang.RunTimeException
  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.RunTimeException
  can only be thrown at well-understood circumstance.
  ex: FileNotFoundException will be thrown only if you try to
   access files.
                                                Transparency No. 1-97
                                                            Basic Java Syntax
   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.RunTimeException, it need not be declared with
   a throws clause.
  the exception ArgTooBigException is a user-defined non
   RunTimeException, so it must be declared.
                                                     Transparency No. 1-98
                                                          Basic Java Syntax
  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.




                                                   Transparency No. 1-99
                                                               Basic Java Syntax
    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().


                                                        Transparency No. 1-100
                                                         Basic Java Syntax
   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
                                                  Transparency No. 1-101
                                                          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-102
                                                              Basic Java Syntax
   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.

                                                       Transparency No. 1-103
                                                               Basic Java Syntax
   Use finally-clause to remedy the inquivalence of for-loop and
   while-loop transformation
for(init; test; incr) statement
is , again, almost equivalent to
{ init;
  while(test) {
     try{ statement }
     fially{incr}       }}
==>// provided there is no break in statement!
int i = 0;
while( i < 10) {
 try { if ( i % 2 == 0 ) continue;
        System.out.print(i); }
 finally { i++; } } // output: 13579
                                                        Transparency No. 1-104
                                               Basic Java Syntax
  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.



                                        Transparency No. 1-105
                                                          Basic Java Syntax
   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
   exception types.
                                                   Transparency No. 1-106
                                                       Basic Java Syntax
   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
  IllegaArgumentException { … }
 protected abstract String readText(File f, String
  encoding) throws FieNotFoundException,
  UnSupportedEncodingExceptin { … }

                                                Transparency No. 1-107
                                                    Basic Java Syntax
   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().

                                             Transparency No. 1-108
                                                             Basic Java Syntax
    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

}


                                                      Transparency No. 1-109
                                                    Basic Java Syntax
   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)
   calsses; constructor (methods) are used to create its
   [object] instances
 Class is the fundamental unit of Java program
  All Java statements appear within methods (and
   initialization 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.

                                             Transparency No. 1-110
                                                    Basic Java Syntax
   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); }



                                             Transparency No. 1-111
                                                                   Basic Java Syntax

   Note about 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.
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.




                                                            Transparency No. 1-112
                                                                   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-113
                                                                 Basic Java Syntax
    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.

                                                          Transparency No. 1-114
                                                           Basic Java Syntax
   Object Literals
 In Java, strings are objects of type java.lang.String
 java allows you to use the string literal notation to represent a
  String object.
Ex:
String lastName = “ Chen “;
String firstName=“Cheng-Chia”;
String fullName = new String(lastName + “ “ + firstname)




                                                    Transparency No. 1-115
                                                         Basic Java Syntax
   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.




                                                  Transparency No. 1-116
                                                       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 :
  1. byte b;
  2. byte[][] ArrayofAarrayOfBytes;
  3. byte[] ArrayofArrayOfBytes[];
  3. byte ArrayOfArrayOfBytes [][];

                                                Transparency No. 1-117
                                                   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-118
                                                             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-119
                                                          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 initializatin block.
…
}



                                                   Transparency No. 1-120
                                                              Basic Java Syntax
   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) } ) ;


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


                                            Transparency No. 1-122
                                                           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][]; // not int[][10] or int[][5]
for(int i = 0; i < 5; i++ )
  prod[i] = new int[10] ; // create 5 subarrays of 10 elements




                                                    Transparency No. 1-123
                              Basic Java Syntax




           prod[0]
prod
            prod[1]
            prod[2]

             prod[3]
             prod[4]




       prod[4][0]                prod[0][0]




                                prod[0][9]

                       Transparency No. 1-124
                                                           Basic Java Syntax
    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




                                                    Transparency No. 1-125
                                                                   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-126
                                                    Basic Java Syntax
  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




                                             Transparency No. 1-127
                                                     Basic Java Syntax
   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


                                              Transparency No. 1-128
                                                   Basic Java Syntax
   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.


                                            Transparency No. 1-129
                                                               Basic Java Syntax

   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.
                                                        Transparency No. 1-130
                                                          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-131
                                                    Basic Java Syntax
  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
   violated.
  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.




                                             Transparency No. 1-132
                                                    Basic Java Syntax
   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.




                                             Transparency No. 1-133
                                                                   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.
 Only class B can be used outside package a.b.c; all other
   classes (A,C) can only be used inside package a.b.c.
                                                            Transparency No. 1-134
                                                      Basic Java Syntax
   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
   packages like java, javax, tw
  Java 2 defined 3 kinds of root dirctories/jars:
  System bootstrap jars: JAVA_HOME\jre\lib\rt.jar
  extension root jars: all jars at JAVA_HOME\jre\lib\ext
  user root dir/jars: specified by programmers via the
   system variables: CLASSPATH or the –classpath/cp
   option.

                                               Transparency No. 1-135

								
To top