A variable is a container that stores a meaningful value that can be used throughout a program. For example, in a program that calculates tax on items you can have a few variables - one variable that stores the regular price of an item and another variable that stores the total price of an item after the tax is calculated on it. Variables store this information in a computer's memory and the value of a variable can change all through out a program.
One variable in your program can store numeric data while another variable can store text data. Java has special keywords to signify what type of data each variable stores. Use these keywords when declaring your variables to set the data type of the variable.
Java data types
||Type of data the variable will store
||Size in memory
||byte size integer
||a single character
||double precision floating point decimal number
||single precision floating point decimal number
||a whole number
||a whole number (used for long numbers)
||a whole number (used for short numbers)
Rules that must be followed when naming variables or errors will be generated and your program will not work:
- No spaces in variable names
- No special symbols in variable names such as !@#%^&*
- Variable names can only contain letters, numbers, and the underscore ( _ ) symbol
- Variable names can not start with numbers, only letters or the underscore ( _ ) symbol (but variable names can contain numbers)
Recommended practices (make working with variables easier and help clear up ambiguity in code):
- Make sure that the variable name is descriptive of what it stores - For example, if you have a variable which stores a value specifying the amount of chairs in a room, name it "numChairs".
- Make sure the variable name is of appropriate length - Should be long enough to be descriptive, but not too long.
Also keep in mind:
- Distinguish between uppercase and lowercase - Java is a case sensitive language which means that the variables varOne, VarOne, and VARONE are three separate variables!
- When referring to existing variables, be careful about spelling - If you try to reference an existing variable and make a spelling mistake, an error will be generated.
Variables are printed by including the variable name in a System.out.print() or System.out.println() method. When printing the value of a variable, the variable name should NOT be included in double quotes. You can also print variables together with regular text. To do this, use the + symbol to join the text and variable values.