Transcript Chapter 4

Chapter 4
Language Fundamentals
1
Identifiers
• Program parts such as packages, classes,
and class members have names, which are
formally known as identifiers.
• Java, like all languages, has rules that
govern identifiers.
• The compiler generates errors on invalid
identifiers.
2
Identifiers
• A valid identifier must begin with a letter,
an underscore (_), or a dollar sign ($).
• The remaining characters must be letters,
numerals, underscores, or dollar signs.
• Because compiler-generated identifiers
typically include the dollar sign, the
programmer typically does not use this
symbol.
3
Variables
• A variable is a named storage cell that can
hold a value of a particular type.
• A variable must be declared before used. A
declaration provides the name, which must
be a valid identifier, and the data type
together with any attributes such as
public. A sample is
int n; // n is the name, int the type
4
Variables
• Variables occur as class fields and as local
variables in constructors and methods.
• Fields have default values. For example,
integer fields default to 0, floating-point
fields to 0.0, and Boolean fields to false.
– Object references default to the special value
null.
5
Local variables
• Local variables, unlike fields, do not have
default values.
• A local variable’s value must be set before
using the variable, for example, in a
function call or as the source of an
assignment operation.
• A variable can be declared final to mark
the variable as a constant.
6
Constructors and methods
• All Java functions are encapsulated as either
constructors or methods.
• A constructor has the same name as its
encapsulating class and no return type or
void in place of a return type. For
instance, a Date constructor would have
the name Date.
7
Constructors and methods
• Constructors are used with the new operator
to construct instances of a class. The
statement
Date today = new Date();
illustrates.
• Constructors are typically overloaded; that
is, a class typically has several constructors.
8
Constructors and methods
• A method does not have the same name as
its encapsulating class and has either a
return type or void in place of a return
type.
• Methods define the operations appropriate
to a class and its instances.
9
Constructors and methods
• A constructor cannot be static, but a
method can be static.
• Constructors and methods can be
parameterized. The parameter names and
data types must be provided.
• Methods, like constructors, can be
overloaded but must be distinguished by
their names and/or parameter types.
10
Primitive types
• Java has standard class types such as Date
and standard nonclass or primitive types
such as int and double.
• Integer types have fixed bit sizes and
ranges. For instance, a byte is 8 bits, its
minimum value is -128, and its maximum
value is +127.
11
Integer types
• The integer types (with bit sizes in
parentheses) are byte (8), short (16),
int (32), and long (64).
• All integer types are signed and have 2’s
complement internal representation.
• An integer constant such as 12 is of type
int, whereas 12L and 12l are of type
long.
12
Integer types
• A decimal constant must not begin with a 0.
An octal constant begins with a 0 and a
hexadecimal constant begins with 0x or 0X.
• The java.math package has a
BigInteger class for arbitrary-precision
integer arithmetic.
13
Floating-point types
• The floating-point types are float (32
bits) and double (64 bits).
• A floating-point constant such as 3.14 is of
type double, whereas 3.14F and 3.14f
are of type float.
• The floating-point types follow the IEEE
754 floating-point standard.
14
Cast operations
• The code segment
float f = 3.14; //*** ERROR
is in error because it tries to assign a
double value to a float variable. The
problem can be corrected in several ways,
including a cast operation
float f = (float) 3.14; // ok
15
Cast operations
• In a cast operation, the target type is
enclosed in parentheses.
• Java imposes restrictions on casts. For
example, a boolean value such as true
cannot be cast to any other type, and no
nonboolean value can be cast to boolean.
• Casts should be used with great caution.
16
Arithmetic operators
• Java supports the usual arithmetic
operations: addition (+), subtraction (-),
multiplication (*), division (/), and
remainder (%).
• The arithmetic operators apply to integer
and floating-point operands.
• Java also provides bit and shift operators for
integers.
17
Assignment operators
• The symbol = is the basic assignment
operator.
• Java also provides special assignment
operators such as +=, *=, and the like.
– The code segment
int x = 4;
x *= 6; // x is 24
illustrates.
18
Character type
• The char is based on 16-bit Unicode
characters.
• Character literals are placed in single
quotes. For instance, ‘A’ is a character
literal that could be assigned to a char
variable.
• Special characters such as ‘\n’ (newline)
begin with a backslash.
19
Character type
• Arithmetic and relational operations can be
performed on characters. The code segment
char c1 = ‘A’,
char c2 = c1 + 1; // ‘B’
if ( c2 > c1 )
// true
...
illustrates.
20
Boolean type
• The boolean type has two values, true
and false.
• Boolean values are not integer values.
• Boolean values cannot be cast.
• Boolean expressions are used in if
statements, loops, and relational
expressions.
21
Relational operators
• Java has the standard relational operators
for comparing values: greater than (>), less
than (<), greater than or equal to (>=), less
than or equal to (<=), equals (==), and not
equals (!=).
• The equality operator should be used with
caution on floating-point values and object
references.
22
Logical operators
• Java has the standard logical operators: and
(&&), inclusive-or (||), and not (!).
• Evaluation of a logical-and expression
terminates with a value of false at the
first false subexpression.
• Evaluation of a logical-or expression
terminates with a value of true at the first
true subexpression.
23
Logical operators
• Logical expressions evaluate left to right.
• The bit operators & and |behave as logical
operators if their operands are booleans
instead of integers.
24
instanceof operator
• This operator tests whether an object
instantiates a class. The code segment
Date d = new Date();
if ( d instanceof Object ) // false
...
else if ( d instanceof Date ) // true
...
illustrates.
25
Arrays
• Arrays of primitive and class types are
supported.
• Arrays are fixed size.
• Arrays constructed with new
int[ ] nums = new int[ 100 ];
have their elements initialized to the
appropriate default value (e.g., 0 for
numbers and false for Booleans).
26
Arrays
• Arrays can be initialized in their
declarations. The code segment
int[ ] nums = { 1, 2, 3 };
illustrates.
• “Multidimensional” arrays are supported:
int[ ][ ] nums = new int[ 2 ][ 4 ];
27
Arrays
• All arrays have a convenient length
member:
int[ ] nums1 = new int[ 10 ];
int n1 = nums1.length; // 10
int[ ][ ] nums2 = new int[ 2 ][ 4 ];
int n2 = nums2.length; // 2
int n3 = nums2[ 0 ].length // 4
28
Arrays
• A “multidimensional” array is really an
array of arrays. For instance,
int[ ][ ] nums = new int[ 2 ][ 4 ];
is an array of two elements, each of which
is an array of four ints.
29
Arrays
• The Java compiler does not perform bounds
checking on array accesses:
int[ ] nums = new int[ 10 ];
nums[ -1 ] = 999; // compiles
• The Java runtime throws an exception if an
array index is out of bounds.
30
Blocks
• A block is sequence of instructions enclosed
in curly braces.
• Variables declared inside a block have block
scope; that is, such variables are visible
only within their containing block.
• Name conflicts among local variables are
not allowed; hence, local variables with the
same name must occur in different blocks.
31
Loops
• Java provides three loop constructs:
while, do while, and for.
• The while and do while are suited for
conditional loops, and the for loop is
suited for counted loops.
• Any loop construct can be rewritten in
principle with one of the other loop
constructs.
32
Loops
• The while loop
int i = 0;
final int n = 100;
while ( i < n ){
System.out.println( i );
i = i + 1;
}
prints 0,1,…,99.
33
Loops
• The do while loop
int i = 0;
final int n = 100;
do {
System.out.println( i );
i = i + 1;
} while ( i < n; }
prints 0,1,…,99.
34
Loops
• The for loop
final int n = 100;
for ( int i = 0; i < n; i++ )
System.out.println( i );
prints 0,1,…,99.
• In a for loop, the three clauses are the
initialization, the loop condition, and the
post-body expression.
35
Exceptions
• An exception is an unexpected condition
that arises during a program’s execution.
– For instance, a program might inadvertently
divide an integer by zero, which would cause or
“throw” an exception.
• Exception handling is a mechanism for
handling exceptions.
36
Exceptions
• The runtime environment implicitly throws
an exception whenever a program violates
some condition such as trying to open a
nonexistent file or dividing an integer by
zero.
• A program can explicitly throw an
exception with the throw statement.
37
Exceptions
• Code that might throw exceptions is placed
in a try block:
try {
FileInputStream in =
new FileInputStream( “in.dat” );
//*** remaining code
}
catch( IOException e ) { /*...*/ }
38
Exceptions
• A try block is followed by one or more
catch blocks, which represent the
exception handlers, or by a finally
block, whose code executes regardless of
whether an exception is thrown in the
corresponding try block.
39
Exceptions
• Exceptions provide a concise, disciplined
mechanism for handling unexpected
conditions during a program’s execution.
• Constructors and methods in the standard
classes rely heavily upon exception
handling.
40