Classnotes | JAVA01 | RecentChanges | Preferences A variable is like a place holder for some value. Variables are very much like the variables used in Mathematics, however, they can store many different types of data in addition to numbers.
Before using a variable, you should define the variable. You define it with an initial declaration. It is typically a good idea to als set a default value to a variable, for example, if we had an integer variable called "apples" with a default value of '28', we would set this default thusly:
int apples = 28;
There are several different data types which you can use in Java (we will only cover a handful of the most common):
int
'int' specifies that a variable will be an integer (which is a non-decimal number, eg 1, 2, 3, 56, 99, 1283). Java allows integers to range from -2.14 billion to 2.14 billion.
int foo;
float
'float' specifies that a variable will be a floating-point number, or a decimal number (eg, 1.233, 3.88, 1823.822).
float bar;
char
'char' specifies that a variable will be a character (a single character, any character value, eg 'a', 'J', '2', '*').
char key;
String
'String' specifies that a variable will contain a sequence of characters (eg "Fred", "Sam", "Space Ghost", "Wilmington, North Dakota").
String something;
boolean
A boolean type is a variable that can either be 'true' or 'false'.
boolean gameOver;
Naming your variables
Variable names in Java can begin with a letter, underscore character (_), or a dollar sign ($). The rest of the name can be any letters or numbers, but you cannot use blank spaces or mathematical operator (such as "+" or "-" or "/"). You can give your variables any name you like under those rules, but you should pick variable names that are meaningful and strive for consistency.
For example, 'a' might be a fine name for a small incrimental variable, but not so great if 'a' signifies something larger and more complicated.
Some example valid variable names:
int howManyApples = 20;
float pi = 3.1415;
String emp_of_rome = "Julius Caesar";
Some poorly chosen variable names:
int hmn = 20; //hmn is how many apples
float TheValueOfPI_RelatedToCircumferenceOfCircle = 3.1415;
String julius_caeser = "Julius Caesar";
Some invalid variable names:
int how many apples = 20;
float pi-pi = 3.1415;
String emp+of+rome = "Julius Caesar";
println with variables
You can use System.out.println with variables instead of the text string used in the previous example. For example, if I had an int with a value of '25', I could use it in my println like this:
int val = 25;
System.out.println("The value is " + val);