In the previous tutorial you learnt about Java comments. Now, let's learn about variables and literals in Java.
Java Variables
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). Learn more about Java identifiers.
Create Variables in Java
Here's how we create a variable in Java,
int speedLimit = 80;
Here, speedLimit is a variable of int data type and we have assigned value 80 to it.
The int data type suggests that the variable can only hold integers. To learn more, visit Java data types.
In the example, we have assigned value to the variable during declaration. However, it's not mandatory.
You can declare variables and assign variables separately. For example,
int speedLimit;
speedLimit = 80;
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, hence the name variable. For example,
int speedLimit = 80; ... .. ... speedLimit = 90;
Here, initially, the value of speedLimit is 80. Later, we changed it to 90.
However, we cannot change the data type of a variable in Java within the same scope.
What is the variable scope?
Don't worry about it for now. Just remember that we can't do something like this:
int speedLimit = 80; ... .. ... float speedLimit;
To learn more, visit: Can I change declaration type for a variable in Java?
Java programming language has its own set of rules and conventions for naming variables. Here's what you need to know:
1. Java is case sensitive. Hence, age and AGE are two different variables. For example,
int age = 24;
int AGE = 25;
System.out.println(age); // prints 24
System.out.println(AGE); // prints 25
2. Variables must start with either a letter or an underscore, _ or a dollar, $ sign. For example,
int age; // valid name and good practice
int _age; // valid but bad practice
int $age; // valid but bad practice
3. Variable names cannot start with numbers. For example,
int 1age; // invalid variables
4. Variable names can't use whitespace. For example,
int my age; // invalid variables
Here, we need to use variable names having more than one word, use all lowercase letters for the first word and capitalize the first letter of each subsequent word. For example, myAge.
5. When creating variables, choose a name that makes sense. For example, score, number, level makes more sense than variable names such as s, n, and l.
6. If you choose one-word variable names, use all lowercase letters. For example, it's better to use speed rather than SPEED, or sPEED.
Java literals
Literals are data used for representing fixed values. They can be used directly in the code. For example,
int a = 1;
float b = 2.5;
char c = 'F';
Here, 1
, 2.5
, and 'F'
are literals.
There are different types of literals in Java. let's discuss some of the commonly used types in detail.