Declaring
and assigning values to variables
Java is called a 'strongly typed' language
because the Java compiler will not allow a variable to be referred to in
a program unless it has been declared. In addition, values cannot
be assigned to variables if the value and variable have different types.
A variable declaration is a statement that defines the identifier (name)
and type of a variable.
Examples of variable declarations include:
int
numberOfRecords;
double temperature;
char firstInitial;
Note that each of these has a type
(int,
double, char)
and an identifier (numberOfRecords,
temperature, firstInitial).
It is also possible to give a variable
an initial value (which can be overwritten with a different value elsewhere
in the program). This is done by using the assignment operator = after
the identifer, and provide the initial value:
int
numberOfRecords = 20;
double temperature
= 0;
char firstInitial
= 'm';
As you might expect, the Java compiler
will complain if you try to assign an initial value that is not compatible
with the variables declared type. For example, compiling the program below
results in an error message:
class
TypeError
{
public static
void main( String args[] )
{
int age = 0.05;
}
}
the output from the compiler was:
A:\Unit3\TypeError.java:15: possible loss of precision
found : double
required: int
int age = 0.05;
^
1 error
This error message occurs because,
of course, a real value of 0.05 cannot be stored inside a variable of type
int. Notice how the compiler has assumed that 0.05 is of type double automatically
(rather than of type float).
What is interesting about this error
message is that is tells us one way we could solve the type incompatibility
problem! Being offered a solution, and in fact receiving an informative
error message is, unfortunately, not always the case with Java. The solution
offered is:
Explicit cast needed to convert double
to int.
It is possible to covert a value from
one type to another by a technique called casting.
.Back
to top
.
RITSEC - Global Campus
Copyright © 1999 RITSEC- Middlesex
University. All rights reserved.
webmaster@globalcampus.com.eg
|