Java variables are essential when programming. At the core of variables, is the ability to store information in a java program. Variables can store many different types of information. Some of the most basic types are integers (int), doubles or floating point (double), characters (char) and String (String). After reading this post, you should have a very solid understanding of how to use variables in Java.
All java variables need at least two things to be created. The type, which tells Java what kind of information you are storing and the name of the variable. The name is how you would access this information later in the program.
To start off, lets create a basic java file that we will use to get a better understanding of variables. If you haven't done so yet, please visit my posts on getting java set up to operate: Using Java with The Command Prompt and Our First Program.
Fire up notepad or Notepad++. At this point, my screen shots will be coming from the latter, Notepad++.
Create a new text file in your editor and save it as Variables.java. I place mine in the C:\Java directory. The first thing we will do with our file is create the basic layout.
public class Variables
{
// This method is where we will play
public static void main(String[] args)
{
// TODO: Play with variables.
}
}
Next we will start by creating an integer variable, used to hold an integer number for out program. Let's name our integer number.
public class Variables
{
// This method is where we will play
public static void main(String[] args)
{
// TODO: Play with variables.
int number;
}
}
Here is a picture and explanation of what the different words mean. Notice that our type represents the type of information being stored in this case, we are storing a whole number. The name of the variable is how we will access our variable in the future. We can change, print, read and compare our integer using the "number" reference (or name) later in our program.
Now let's create a number that stores a value that has a decimal. This could be known as a floating point number or fraction. At the end of our previous line, lets enter a new line and create a double.
public class Variables
{
// This method is where we will play
public static void main(String args)
{
// TODO: Play with variables.
int number;
double decimalNumber;
}
}
Notice that at this point we have two variables defined. Now we must learn how to use these variables.