You can store a value in a variable at the same time that you create the variable in a Java program. You also can put a value in the variable at any time later in the program.
To set a starting value for a variable upon its creation, use the equal sign (=
). Here’s an example of creating a double floating-point variable called pi
with the starting value of 3.14:
double pi = 3.14;
All variables that store numbers can be set up in a similar fashion. If you’re setting up a character or a string variable, quotation marks must be placed around the value as described earlier in this hour.
You also can set one variable equal to the value of another variable if they both are of the same type. Consider the following example:
int mileage = 300;
int totalMileage = mileage;
If you do not give a variable a starting value, you must give it a value before you use it in another statement. If you don’t, when your program is compiled, you might get an error stating that the variable “may not have been initialized.”
First, an integer variable called mileage
is created with a starting value of 300. Next, an integer variable called totalMileage
is created with the same value as mileage
. Both variables have the starting value of 300. In future hours, you learn how to convert one variable’s value to the type of another variable.
As you’ve learned, Java has similar numeric variables that hold values of different sizes. Both int
and long
hold integers, but long
holds a larger range of possible values. Both float
and double
carry floating-point numbers, but double
is bigger.
You can append a letter to a numeric value to indicate the value’s type, as in this statement:
float pi = 3.14F;
The F after the value 3.14 indicates that it’s a float
value. If the letter is omitted, Java assumes that 3.14 is a double
value. The letter L is used for long
integers and D for double
floating-point values.
Another naming convention in Java is to capitalize the names of variables that do not change in value. These variables are called constants. The following creates three constants:
final int TOUCHDOWN = 6;
final int FIELDGOAL = 3;
final int PAT = 1;
Because constants never change in value, you might wonder why one ever should be used—you can just use the value assigned to the constant instead. One advantage of using constants is that they make a program easier to understand.
In the preceding three statements, the name of the constant was capitalized. This is not required in Java, but it has become a standard convention among programmers to distinguish constants from other variables.
3.142.114.199