Index
Java Variables
Definition
A variable is a location in memory (storage area) to hold data.
To indicate the storage area, each variable should be given a unique name (identifier).
Info
There are 4 types of variables in Java programming language:
- Instance Variables (Non-Static Fields)
- Class Variables (Static Fields)
- Local Variables
- Parameters
If you are interested to learn more about it now, visit Java Variable Types.
Create Variables in Java
Here’s how we create a variable in Java:
type variable
The int data type suggests that the variable can only hold integers. To learn more, visit Java built-in data types
You can also declare variables and assign variables separately:
Note
Java is a statically-typed language. It means that all variables must be declared before they can be used.
Change values of variables
The value of a variable can be changed in the program. For example,
However, we cannot change the data type of a variable in Java within the same scope:
Error: variable s is already defined in method ...
Unmutable Variables
Rules for Naming Variables in Java
Java programming language has its own set of rules and conventions for naming variables. Here’s what you need to know:
-
Java is case sensitive. Hence, age and AGE are two different variables. For example,
-
Variables must start with either a letter or an underscore, _ or a $.
-
Variable names cannot start with numbers.
-
Variable names can’t use white space.
Naming conventions
If you choose one-word variable names, use all lowercase letters.
Java uses the Camel case notation, if we need to use variable names having more than one word, use all lowercase letters for the first word and capitalise the first letter of each subsequent word.
Examples: myAge, speedLimit