Java Reference
In-Depth Information
Self-Test Exercises
10. Which of the following may be used as variable names in Java?
rate1, 1stPlayer, myprogram.java, long,
TimeLimit, numberOfWindows
11. Can a Java program have two different variables named number and Number ?
12. Give the declaration for two variables called feet and inches . Both variables are
of type int and both are to be initialized to zero in the declaration.
13. Give the declaration for two variables called count and distance . count is of type
int and is initialized to zero. distance is of type double and is initialized to 1.5 .
14. Write a Java assignment statement that will set the value of the variable distance
to the value of the variable time multiplied by 80 . All variables are of type int .
15. Write a Java assignment statement that will set the value of the variable interest
to the value of the variable balance multiplied by the value of the variable rate .
The variables are of type double .
16. What is the output produced by the following lines of program code?
char a, b;
a = 'b';
System.out.println(a);
b = 'c';
System.out.println(b);
a = b;
System.out.println(a);
Assignment Compatibility
As a general rule, you cannot store a value of one type in a variable of another type.
For example, the compilers will object to the following:
int intVariable;
intVariable = 2.99;
The problem is a type mismatch. The constant 2.99 is of type double and the variable
intVariable is of type int .
There are some special cases where it is permitted to assign a value of one type to a
variable of another type. It is acceptable to assign a value of an integer type, such as
int , to a variable of a floating-point type, such as the type double . For example, the
following is both legal and acceptable style:
assigning
int values
to double
variables
double doubleVariable;
doubleVariable = 2;
The preceding will set the value of the variable named doubleVariable equal to 2.0 .
Search WWH ::




Custom Search