CONVERSIONS AND PROMOTIONS
Assignment Conversion
5.2
5.2   Assignment Conversion
Assignment conversion
 occurs when the value of an expression is assigned
( 15.25) to a variable: the type of the expression must be converted to the type of
the variable. Assignment contexts allow the use of an identity conversion ( 5.1.1),
a widening primitive conversion ( 5.1.2), or a widening reference conversion
( 5.1.4). In addition, a narrowing primitive conversion may be used if all of the
following conditions are satisfied:
The expression is a constant expression of type
int
.
The type of the variable is
byte
,
short
, or
char
.
The value of the expression (which is known at compile time, because it is a
constant expression) is representable in the type of the variable.
If the type of the expression cannot be converted to the type of the variable by a
conversion permitted in an assignment context, then a compile time error occurs.
If the type of an expression can be converted to the type a variable by assign 
ment conversion, we say the expression (or its value) is
assignable to
 the variable
or, equivalently, that the type of the expression is
assignment compatible with
 the
type of the variable.
An assignment conversion never causes an exception. (Note, however, that an
assignment may result in an exception in a special case involving array elements
 see  10.10 and  15.25.1.)
The compile time narrowing of constants means that code such as:
byte theAnswer = 42;
is allowed. Without the narrowing, the fact that the integer literal
42
 has type
int
would mean that a cast to
byte
 would be required:
byte theAnswer = (byte)42;
//
cast is permitted but not required
A value of primitive type must not be assigned to a variable of reference type;
an attempt to do so will result in a compile time error. A value of type
boolean
can be assigned only to a variable of type
boolean
.
The following test program contains examples of assignment conversion of
primitive values:
class Test {
public static void main(String[] args) {
short s = 12;
//
narrow
12
 to
short
float f = s;
//
widen
short
 to
float
System.out.println("f=" + f);
61






footer




 

 

 

 

 Home | About Us | Network | Services | Support | FAQ | Control Panel | Order Online | Sitemap | Contact

java hosting

 

Our partners: PHP: Hypertext Preprocessor Best Web Hosting Java Web Hosting Inexpensive Web Hosting  Jsp Web Hosting

Cheapest Web Hosting Jsp Hosting Cheap Hosting

Visionwebhosting.net Business web hosting division of Web Design Plus. All rights reserved