
Variable in JAVA
A variable is a data name that is used for storing a data value. The value of the variable may be changed during the program execution.
Example: – int number = 8;
Here ‘int’ is a data type, ‘number’ is a variable name and 8 is a value that it stores.
Rules for declaring a variable name
If the following conditions are satisfied the syntax of the variable is correct:
- A variable must begin with a character without any space.
- It must not begin with a digit.
- It shouldn’t be a keyword.
- Java variable name is case sensitive.
- It doesn’t allow white space and commas.
- After the above conditions are satisfied then it can contain alphabets, ‘&’ character, ‘_‘ character, and digits also.
Constant in JAVA
Constant is also a variable name but its value cannot be changed during program execution. If once we can assign a value to it then it cannot be changed. Simply we just need a ‘final’ keyword to declare a variable as a constant.
Example:- final double pi = 3.14;
Here ‘final’ is a keyword, ‘double’ is a data type, ‘pi’ is a variable name and 3.14 is a value that it stores.
Literals in JAVA
It is a constant value that can be assigned to the variable called a literal. Literal is a unique value to assign the variable. It is a representation of fixed value.
Example:- int a = 3;
float b = 4.9f;
char c = ‘A’;
Here ‘3’, ‘4.9’, ‘A’ are the literals.
There are mainly different types of literal available in Java i.e.:
- Integer Literal
- Floating point Literal
- Boolean Literal
- Character Literal
Integer literals
It is a numeric value that is assigned as a number. But it doesn’t contain any fractional or exponential part.
Example: – int a = 36;
Floating point Literal
These are the numeric literals that have in fractional format or exponential format.
Example: – float f = 7.6f;
double d = 56.9;
Boolean Literal
Boolean literals are used to initialize data with boolean value and boolean data type. It can store only the value ‘true’ or ‘false’.
Example:- boolean b = true;
boolean c = false;
Charachter Literals
These are the characters that are Unicode and these are enclosed within a single quote.
Example: – char e = ‘A’;
So this is all about the variables, constants & literals in Java. These are very useful concepts that are used in a java program. I hope this will help you. In the next upcoming post we will discuss another new topic of java, so wait for this will meet in the next post. Thank you.
1 thought on “Variable, Constant & Literals in JAVA”