|
Example:
3.14159265358979
1776
|
|
|
|
|
public class Exercise3
{
public static void main(String[] args)
{
int a;
float b;
a = 1L; // What is wrong ?
b = 1.0; // What is wrong ?
}
}
|
How to run the program:
|
Here is the compile errors:
Exercise3.java:10: possible loss of precision found : long required: int a = 1L; // What is wrong ? ^ Exercise3.java:12: possible loss of precision found : double required: float b = 1.0; // What is wrong ? ^ 2 errors |
Example: strictly speaking, the following assignment statements are not allowed:
public class Demo1
{
public static void main(String[] args)
{
byte a;
short b;
a = 1; // Assigns an int value (1) to a byte variable (a)
b = 1; // Assigns an int value (1) to a short variable (b)
}
}
|
Strictly speaking, you need to use casting operators:
public class Demo1
{
public static void main(String[] args)
{
byte a;
short b;
a = (byte) 1; // Converts an int value (1) to a byte value
b = (short) 1; // Converts an int value (1) to a short value
}
}
|
The designers of the Java language deem this to be inconvenient and introduced a convenience conversion rule into the Java language
|
Example:
|
How to run the program:
|
|
Later on in the program, we can use the name in place of the actual constant
final datatype CONSTANT_NAME = value ;
|
Explanation:
|
public class AreaOfCircle2
{
public static void main(String[] args)
{
double r; // variable containing the radius
double area; // variable containing the area
final double myPi = 3.14159265358979;
r = 4; // Give the radius
area = myPi * r * r; // Compute the area of the circle
System.out.print("The radius = ");
System.out.println(r);
System.out.print("The area = ");
System.out.println(area);
}
}
|
How to run the program:
|