Java Lesson 3 – Variables
Welcome to the third Java lesson in the series. This time I want to introduce the idea of variables. Variables are a universal concept in all programming languages. The basic idea of a variable is a way for your program to remember information for later use. A good way to think about it is that it is a lot like coming across a dollar on the floor, then saving it in some kind of jar. At any time, you can look in that jar to see how much money you have.
There are different kinds of variables. In Java, before you make a variable you need to specify the kind of information you are saving. Here is a table with the different data types.
Java Data Types
Name Use Example
int Holds integers; whole positive and negative numbers. 1, 129, -50, -1000
double Holds real numbers with decimal values. 5.3, -10.2, 204.6
float Holds small ints or doubles, but must include some form of decimal. 10.00, -3.00, 1.10, -33.04
char Holds a single character surrounded in single quotes. ‘A’, ‘c’, ‘w’, ‘X’
String Holds words, phrases, and sentences in double quotes. “Hello World!”, “3, 2, 1 GO”, “Yeehaw”
Example
Here’s an example program to demonstrate.
public class VariableExample
{
public static void main(String[] args)
{
int score = 1;
double change = 10.2;
float speed = -1.00;
char middleInitial = ‘A’;
String message = “Variables rule!”;
System.out.println(s);
}
}
When we declare variables, we first specify the variable type, then the reference name we want to call it. You don’t need to specify the variables contents when you declare it, but to set a variable to something, use an equals sign. Notice how in the System.out.println() I used s instead of a raw string.