03.Java Variables and Literals
03.Java Variables and Literals
In this tutorial, we will learn about Java variables and literals with the help of
examples.
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.
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;
The value of a variable can be changed in the program, hence the name variable.
For example,
... .. ...
speedLimit = 90;
Don't worry about it for now. Just remember that we can't do something like this:
... .. ...
float speedLimit;
To learn more, visit: Can I change declaration type for a variable in Java?
System.out.println(AGE); // prints 25
Here, is 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 .
• Local Variables
• Parameters
If you are interested to learn more about it now, visit Java Variable Types.
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';
1. Boolean Literals
In Java, boolean literals are used to initialize boolean data types. They can store
two values: true and false. For example,
boolean flag1 = false;
boolean flag2 = true;
2. Integer Literals
1. binary (base 2)
3. octal (base 8)
For example:
// binary
int binaryNumber = 0b10010;
// octal
int octalNumber = 027;
// decimal
int decNumber = 34;
// hexadecimal
int hexNumber = 0x2F; // 0x represents hexadecimal
// binary
int binNumber = 0b10010; // 0b represents binary
In Java, binary starts with 0b, octal starts with 0, and hexadecimal starts with 0x.
Note: Integer literals are used to initialize variables of integer types
like byte , short , int , and long .
3. Floating-point Literals
class Main {
public static void main(String[] args) {
// 3.445*10^2
double myDoubleScientific = 3.445e2;
Note: The floating-point literals are used to initialize float and double type
variables.
4. Character Literals
Character literals are unicode character enclosed inside single quotes. For example,
char letter = 'a';
5. String literals