When programming in Java, it is essential to understand the basics of storing and using information that is stored in variables. In this post, we dig a little more into detail about using Java variables. If you are just happening onto this post, please read the pre-cursor to this as we learned how and why to create Java variables. You can find that post here: Java Variables.
Java allows you to store variables at different times during programming. The first place you might store information into a variable is at the time you declare it. Declaration happens when you are assigning a type to a name (i.e. int number;). When you are assigning a value to a variable, you use the '=' equals sign with the assigned value coming after the name of the variable. You can do this when initializing your variable, or you can do it anytime after you have declared your variable (assigned a type to a name, int number;). Below are examples of how you can accomplish this.
Assigning value to a variable at initialization:
public class Variables
{
// This method is where we will play
public static void main(String[] args)
{
// TODO: Variables assigned at
// initialization.
int number = 2;
double decimalNumber = 4.55;
}
}
Assign a value to the variable after initialization:
public class Variables
{
// This method is where we will play
public static void main(String[] args)
{
// TODO: Variables assigned at
// initialization.
int number;
number = 2;
double decimalNumber;
decimalNumber = 4.55;
}
}
Note: You can not use a variable before it has been initialized to a type. This will result in a compiler error.
When using variables in java, you can assign variables different values along the way. In this post we have described and demonstrated assigning variables at initialization time as well as after initialization.