Java Reference
In-Depth Information
Similarly, assignments of integer type variables to floating-point type variables are
also allowed. For example, the following is permitted:
int intVariable;
intVariable = 42;
double doubleVariable;
doubleVariable = intVariable;
More generally, you can assign a value of any type in the following list to a variable
of any type that appears further down in the list:
byte —> short —> int —> long —> float —> double
For example, you can assign a value of type int to a variable of type long , float , or
double (or of course to a variable of type int ), but you cannot assign a value of type
int to a variable of type byte or short . Note that this is not an arbitrary ordering of
the types. As you move down the list from left to right, the range of allowed values for
the types becomes larger.
You can assign a value of type char to a variable of type int or to any of the
numeric types that follow int in our list of types (but not to those that precede int ).
However, in most cases it is not wise to assign a character to an int variable, because
the result could be confusing. 3
If you want to assign a value of type double to a variable of type int , then you must
change the type of the value by using a type cast , as explained in the subsection later in
this chapter entitled “Type Casting.”
In many languages other than Java, you can assign integers to variables of type
boolean and assign boolean values to integer variables. You cannot do that in Java. In
Java, the boolean values true and false are not integers nor will they be automatically
converted to integers. (In fact, it is not even legal to do an explicit type cast from the
type boolean to the type int or vice versa. Explicit type casts are discussed later in this
chapter in the subsection “Type Casting.” )
integers and
booleans
Constants
Constants or literals are names for one specific value. For example, 2 and 3.1459
are two constants. We prefer the name constants because it contrasts nicely with the
word variables . Constants do not change value; variables can change their values.
constants
literals
3 Readers who have used certain other languages, such as C or C ++ , may be surprised to learn that you
cannot assign a value of type char to a variable of type byte . This is because Java uses the Unicode
character set rather than the ASCII character set, and so Java reserves two bytes of memory for each
value of type char , but naturally only reserves one byte of memory for values of type byte . This is
one of the few cases where you might notice that Java uses the Unicode character set. Indeed, if you
convert from an int to a char or vice versa, you can expect to get the usual correspondence of ASCII
numbers and characters. It is also true that you cannot assign a value of type char to a variable of type
short , even though they both use two bytes of memory.
 
Search WWH ::




Custom Search