ch11 (12)


developer.com - Reference Click here to support our advertisers SHOPPING JOB BANK CLASSIFIEDS DIRECTORIES REFERENCE Online Library LEARNING CENTER JOURNAL NEWS CENTRAL DOWNLOADS COMMUNITY CALENDAR ABOUT US Journal: Get the weekly email highlights from the most popular journal for developers! Current issue developer.com developerdirect.com htmlgoodies.com javagoodies.com jars.com intranetjournal.com javascripts.com All Categories : Java Chapter 11 Language Summary CONTENTS The package Statement The import Statement Comments Identifiers Reserved Words Primitive Data Types and Literal Values Class Declarations Variable Declarations Constructor Declarations Access Method Declarations Static Initializers Interfaces Blocks and Block Bodies Local Variable Declarations Statements Empty Statement Block Statement Method Invocation Allocation Statements Assignment Statements The if Statement Statement Labels The switch Statement The break Statement The for Statement The while Statement The do Statement The continue Statement The synchronized Statement The try Statement The return Statement Operators Summary In the previous chapters you've covered most of the elements of the Java language and learned how to use those elements through programming examples. This chapter provides a summary of the Java language syntax. You can use it to review what you've learned so far, and also as a quick reference guide when you need to look up a particular aspect of the language. The package Statement Java programs are organized into packages. Packages contain the source code declarations of Java classes and interfaces. Packages are identified by the package statement. It is the first statement in a source code file: package packageName; If a package statement is omitted, the classes and interfaces declared within the package are put into the default package-the package with no name. The package name and the CLASSPATH are used to find a class. Only one class or interface may be declared as public for a given source code file. The import Statement The import statement is used to reference classes and interfaces that are declared in other packages. There are three forms of the import statement: import packageName; import packageName.className; import packageName.*; The first form allows classes and interfaces to be referenced using the last component in the package name. The second form allows the identified classes and interfaces to be referenced without specifying the name of their package. The third form allows all classes and interfaces in the specified package to be referenced without specifying the name of their package. Comments Java provides three styles of comments: /* This is a comment. */ // This is a comment. /** This is a javadoc comment */ The first comment style supports traditional C-language comments. All text appearing between /* and */ is treated as a comment. Comments of this style can span multiple lines. The second comment style supports C++ comments. All text following the // until the end of the line is treated as a comment. Comments of this style do not span multiple lines. The third comment style is used by the javadoc documentation-generation tool. All text between the /** and */ is treated as a javadoc comment. javadoc comments may span multiple lines. Comments cannot be nested and cannot appear within string and character literals. Identifiers Identifiers are used to name Java language entities. They begin with a letter and consist of letters and digits. Identifiers are case sensitive and cannot be the same as a reserved word. Reserved Words The following words are reserved by the Java language; they cannot be used as names or identifiers: abstractdo implements package throw booleandouble import privatethrows breakelse inner protectedtransient byteextends instanceof public try casefinal intrest var castfinally interface returnvoid catchfloat longshort volatile charfor native staticwhile classfuture newsuper   constgeneric nullswitch   continuegoto operator synchronized   defaultif outer this  Note Some of the reserved words have not yet been implemented. Primitive Data Types and Literal Values Java defines eight primitive types. Variables that are declared as a primitive type are not objects; they are only placeholders to store primitive values. The eight primitive types are byte, short, int, long, float, double, char, and boolean. The byte, short, int, and long types represent 8-, 16-, 32-, and 64-bit integer values. The literal values of these types are written using positive or negative decimal, hexadecimal, or octal integers. Hexadecimal values are preceded by 0x or 0X and use the letters a through f (upper- or lowercase) to represent the digits 10 through 15. Octal numbers are preceded by 0. Long decimal values have an l or L appended to the end of the number. The float and double types represent 32- and 64-bit IEEE 754 floating-point numbers. float numbers have the f or F suffix. Double numbers have d or D. If no suffix is provided, the default double type is assumed. Floating-point numbers may be written in any of the following four forms: digits . optionalDigits optionalExponentPart suffix . digits optionalExponentPart suffix digits exponentPart suffix NaN suffix is optional. It consists of f, F, d, or D, as described previously. exponentPart is optional in the first two forms and required in the third form. It consists of an e or E followed by a signed integer. It is used to identify the exponent of 10 of the number written in scientific notation. For example, 1000000.0 could be represented as 1.0E6. The special value NaN is used to represent the value "not a number" that occurs as the result of undefined mathematical operations such as division by zero. The char type represents 16-bit Unicode characters. Unicode is a 16-bit superset of the ASCII character set that provides many foreign-language characters. A single character is specified by putting the character within single quotes ('). There are three exceptions: single quote ('), double quote ("), and backslash (\). The backslash character (\) is used as an escape code to represent special character values. The character escape codes are shown in Table 11.1. Table 11.1. Character escape codes. Escape Code Character \bbackspace \ttab \nlinefeed \fform feed \rcarriage return \"double quote \'single quote \\backslash The backslash can also be followed by an 8-bit octal value or by a u or U followed by a four-digit hexadecimal value. The four-digit value is used to specify the value of Unicode characters. The boolean type represents the logical values true and false. String literals are also provided by Java even though strings are not primitive values. Strings consist of characters enclosed by double quotes ("). The character escape codes may be used within strings. The literal value null is used to identify the fact that an object is not assigned to a value. It may be used with any variable that is not of a primitive data type. Class Declarations Class declarations allow new classes to be defined for use in Java programs. Classes are declared as follows: classModifiers class className extendsClause implementsClause classBody The class modifiers, extends clause, and implements clause are optional. The class modifiers are abstract, public, and final. An abstract class provides an abstract class declaration that cannot be instantiated. Abstract classes are used as building blocks for the declaration of subclasses. A class that is declared as public can be referenced outside its package. If a class is not declared as public, it can be referenced only within its package. A final class cannot be subclassed. A class cannot be declared as both final and abstract. The extends clause is used to identify the immediate superclass of a class and thereby position the class within the overall class hierarchy. It is written as follows: extends immediateSuperclass The implements clause identifies the interfaces that are implemented by a class. It is written as follows: implements interfaceNames interfaceNames consists of one or more interface names separated by commas. The class body declares the variables, constructors, and access methods of a class. It is written as follows: { fieldDeclarations } fieldDeclarations consists of zero or more variable, constructor, or access method declarations or static initializers. Variable Declarations Variables are used to refer to objects and primitive data types. They are declared as follows: variableModifiers type extendedVariableName variableInitialization ; variableModifiers and variableInitialization are optional. A variable's type may be a primitive data type, class type, or interface type. The extendedVariableName is a variable name followed by zero or more bracket sets ([]) indicating that the variable is an array. variableInitialization consists of an equals sign (=) followed by a variable initialization. A variable initialization is an expression yielding a value of the variable's type. If the variable being declared is an array, it can be assigned to an array initializer. Array initializers are written as follows: {elementInitializers} elementInitializers are expressions that yield values that are consistent with the element type of the array. There are seven variable modifiers: public, protected, private, static, final, transient, and volatile. The public, protected, and private modifiers are used to designate the specific manner in which a variable can be accessed. Variables that are declared as public can be accessed anywhere that the class in which they are defined can be accessed. Variables that are declared as protected can be accessed within the package in which they are declared and in subclasses of the class in which they are defined. Variables that are declared as private are only accessible in the class in which they are defined and not in any of its subclasses. If a variable is declared as neither public, protected, nor private, it can be accessed only within the package in which it is declared. A variable that is declared as static is associated with its class and is shared by objects that are instances of its class. A static variable is also known as a class variable. A variable that is declared as final is a constant and cannot be modified. Final variables must be initialized when they are declared. A variable that is declared as transient refers to objects and primitive values within the Java virtual machine. Transient variables have not been implemented within Java 1.0. A variable that is declared as volatile refers to objects and primitive values that can be modified asynchronously. They are treated in a special manner by the compiler to control the manner in which they can be updated. Constructor Declarations Constructors are methods that are used to initialize newly created objects of a class. They are declared as follows: constructorModifiers constructorNameAndParameters throwsClause constructorBody The constructor modifiers are public, protected, and private. They control access to the constructor and are used in the same manner as they are for variables. The constructor name is the same as the class name in which it is declared. It is followed by a parameter list, written as follows: (parameterDeclarations) The parameter list consists of an opening parenthesis followed by zero or more parameter declarations followed by a closing parenthesis. The parameter declarations are separated by commas. Parameter declarations are written as follows: type parameterName Each parameter declaration consists of a type followed by a parameter name. A parameter name may be followed by sets of matched brackets ([]) to indicate that it is an array. The throws clause identifies all uncaught exceptions that are thrown within the constructor. It is written as follows: throws uncaughtExceptions The exceptions are separated by whitespace characters. The body of a constructor specifies the manner in which an object of the constructor's class is to be initialized. It is written as follows: {constructorCallStatement blockBody} The constructorCallStatement and blockBody are optional, but the opening and closing braces must be supplied. The constructor call statement allows another constructor of the class or its superclass to be invoked before the constructor's block body. It is written as follows: this(argumentList); super(argumentList); The first form results in a constructor for the current class being invoked with the specified arguments. The second form results in the constructor of the class's superclass being invoked. The argument list consists of expressions that evaluate to the allowed values of a particular constructor. If no constructor call statement is specified, a default super() constructor is invoked before the constructor block body. Access Method Declarations Access methods are methods used to perform operations on the data contained in an object or on static class variables. They are written as follows: methodModifiers returnType methodNameAndParameters throwsClause methodBody methodNameAndParameters is the same as for constructor declarations. Access method names are different from their class names. The throws clause is also the same as for constructor declarations. The method body differs from the constructor body in that it does not allow a constructor call statement. The modifiers allowed for a method include the public, protected, and private modifiers defined for constructors as well as the final, static, abstract, native, and synchronized modifiers. The final modifier identifies a method that cannot be overridden. The static modifier identifies a class method. Class methods are allowed to access static class variables only. Static methods are final. An abstract method is used to identify a method that cannot be invoked and must be overridden by any non-abstract subclasses of the class in which it is declared. An abstract method does not have a method body. Instead, it has a semicolon (;). A native method is a method written in a language other than Java. It is like an abstract method in that its body is replaced by a semicolon. A synchronized method is a method that must acquire a lock on an object or on a class before it can be executed. Static Initializers A static initializer is a block of code that is used to initialize the static variables of a class. It is written as follows: static block Static initializers can only access static class variables. They are executed in the order in which they appear in a class declaration. Interfaces An interface specifies a collection of abstract methods that must be overridden by classes that implement the interface. Interfaces are declared as follows: interfaceModifiers interface interfaceName extendsClause interfaceBody The interface modifiers are public and abstract. public interfaces can be accessed in other packages. All interfaces are abstract. The abstract modifier is superfluous. The optional extends clause is used to identify any interfaces that are extended by an interface. It is written as follows: extends interfaceNames The interface names are separated by commas. An interface includes all the methods of all interfaces that it extends. The interface body consists of zero or more variable and abstract method declarations. They are enclosed within braces ({ and }). Variables declared within an interface must be static and final. The static and final modifiers need not be displayed. Variables declared in a public interface are public. The public keyword need not be specified. Methods declared within an interface are abstract. The abstract keyword need not be specified. Blocks and Block Bodies Blocks consist of sequences of local variable declarations and statements. They are written as follows: { blockBody } The blockBody is a sequence of local variable declarations or statements. A block can also consist of a single statement without the enclosing braces. Local Variable Declarations Local variables are declared in the same manner as field declarations are, except that local variables do not include modifiers. They are accessible within the block in which they are declared. The this and super variables are predefined. They refer to the current object for which a method is invoked and the superclass of the current object being invoked. Statements The programming statements provided by Java are described in the following subsections. Empty Statement The empty statement performs no processing. It consists of a single semicolon (;). Block Statement A block statement consists of a sequence of statements and local variable declarations that are treated as a single statement block. The statements are enclosed within braces ({ and }). Method Invocation A method invocation invokes a method for an object or a class. Method invocations may be used within an expression or as a separate statement. To be used as a separate statement, the method being invoked must be declared with a void return value. Method invocation statements take the following forms: objectName.methodName(argumentList); className.methodName(argumentList); The argumentList consists of a comma-separated list of zero or more expressions that are consistent with the method's parameters. Allocation Statements When an object is allocated, it is typically assigned to a variable. However, it is not required to be assigned when it is allocated. An allocation statement is of the following form: new constructor(argumentList); The new operator is used to allocate an object of the class specified by the constructor. The constructor is then invoked to initialize the object using the arguments specified in the argument list. Assignment Statements The assignment statement assigns an object or value to a variable. Its general form is variableName = expression; where expression yields a value that is consistent with the variable's type. Other assignment operators may be used in addition to the = operator. Refer to the section titled "Operators" later in this chapter. The if Statement The if statement is used to select among alternative paths of execution. It is written in the following two forms: if ( booleanExpression ) statement if ( booleanExpression ) statement1 else statement2 In the first form, statement is executed only if the boolean expression is true. In the second form, statement1 is executed if the boolean expression is true, and statement2 is executed if the boolean expression is false. Statement Labels A statement can be labeled by prefixing an identifier to the statement as follows: label: statement The label can be a name or an integer. The switch Statement The switch statement is similar to the if statement in that it enables a selection from alternative paths of execution. It is written as follows: switch (expression) caseBlock expression must evaluate to a byte, char, short, or int value. Control is transferred to the next statement in the block that is labeled with a value that matches the expression. The caseBlock contains a sequence of case-labeled statements. These statements are written as follows: case value: statement An optional default-value statement may also appear in the case block. It is written as follows: default: statement If no value matches the expression and a default-valued statement is provided, control is transferred to this statement. If there is no default-value statement, the next statement following the switch statement is executed. The break Statement The break statement is used to transfer control to a labeled statement or out-of-statement block. It takes the following forms: break; break label; The first form transfers control to the first statement following the current statement block. The second form transfers control to the statement with the identified label. The for Statement The for statement is used to iteratively execute a statement. It takes the following form: for (initializationStatement booleanExpression ; incrementStatement)    iteratedStatement The initialization statement is executed at the beginning of the for statement, and then the boolean expression is tested. If the expression is true, the iterated statement is executed. The increment statement is executed after the iterated statement, and then the boolean expression is retested. The iterated statement-increment statement loop continues until the boolean expression evaluates to false. The while Statement The while statement is used to execute a statement while a boolean expression is true. It is written as follows: while (booleanExpression) iteratedStatement; The boolean expression is evaluated; if it is true the iterated statement is executed. It continues to execute until the boolean expression is false. The do Statement The do statement, like the while statement, is used to execute a statement until a boolean expression becomes false. The only difference is that the expression is tested after the statement is executed. The do statement is written as follows: do iteratedStatement while (booleanExpression); The continue Statement The continue statement is used to continue execution of a loop (for, do, or while) without completing execution of the iterated statement. The continue statement may take an optional label. It is written as follows: continue label; If a label is supplied, the loop continues at the labeled loop. The synchronized Statement The synchronized statement is used to execute a statement after acquiring a lock on an object. It is written as follows: synchronized ( expression ) statement The expression yields the object for which the lock must be acquired. The try Statement The try statement executes a block of statements while setting up exception handlers. If an exception occurs the appropriate handler, if any, is executed to handle the exception. A finally clause may also be specified to perform absolutely required processing. The try statement is written as follows: try block catchClauses finallyClause At least one catch clause or a finally clause must be provided. The format of the catch clause is as follows: catch (exceptionDeclaration) block If an exception is thrown within the block executed by the try statement and it can be assigned to the type of exception declared in the catch clause, the block of the catch clause is executed. The finally clause, if it is provided, is always executed regardless of whether an exception is generated. The return Statement The return statement is used to return an object or a value as the result of a method's invocation. It is written as follows: return expression; The value of the expression must match the return value identified in the method's declaration. Operators Java defines arithmetic, relational, logical, bit-manipulation, caste, class, selection, and assignment operators. Table 11.2 summarizes these operators. Table 11.2. Java operators. Operator Type OperatorDescription Example Arithmetic + - * / % Addition Subtraction Multiplication Division Modulus a + b a - b a * b a / b a % b Relational > < >= <= != == Greater than Less than Greater than or equal Less than or equal Not equal Equal a > b a < b a >= b a <= b a != b a == b Logical ! && || Not AND OR !a a && b a || b Bit-manipulation ~ & | ^ << >> >>> Complement AND OR Exclusive OR Left shift Right shift Zero-filled right shift ~a a & b a | b a ^ b a << b a >> B a >>> b Assignment = ++ -- += -= *= /= %= |= &= ^= <<= >>= >>>= Assignment Increment and assign Decrement and assign Add and assign Subtract and assign Multiply and assign Divide and assign Take modulus and assign OR and assign AND and assign XOR and assign Left shift and assign Right shift and assign Zero-filled left shift and assign a = b a++ a-- a += b a -= b a *= b a /= b a %= b a |= b a &= b a ^= b a <<= b a >>= b a >>>= b Caste(type) Convert to type(char) b Instanceinstanceof Is instance of class? a instanceof b Allocationnew Create a new object of a class new A() Selection? : If...Then selection a ? b : c Summary This chapter provides a summary of the Java language. It reviews the language-specific material covered in Chapters 4 through 10. Part III, "Using the Java API," introduces the Java API. Contact reference@developer.com with questions or comments. Copyright 1998 EarthWeb Inc., All rights reserved. PLEASE READ THE ACCEPTABLE USAGE STATEMENT. Copyright 1998 Macmillan Computer Publishing. All rights reserved.

Wyszukiwarka

Podobne podstrony:
ch11 12 szeregi pot
ch11 12 zesp
ch11 12 macierze
ch11 12 rr uzm sta I rz
ch11 12 wiele zm
ch11 12 wiele zm
ch11 12 rr uklady
ch11 12 rr zm rozdz
ch11 12 pochodne
ch11 12 geoman2
ch11 12 pochodne wyzszych rz
248 12
Biuletyn 01 12 2014
12 control statements

więcej podobnych podstron