Variables and data types are important concepts in every programming language. In this article, we will explore variables and data types in Java.
Variable
A variable is a container used to store data in memory. In the real world, we use different types of containers to store various things. The data we store can be of various types. It can be a number, a character, a word, or a boolean value, either true or false. Here are the data types in the picture.
Data Types
Data types are the types of data. In Java, there are numerous types of data. Some of them are:
- int: Whole numbers from -2,147,483,648 to 2,147,483,647
- float: Floating point numbers eg: 3.14
- long: Whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
- double: A double is a 64-bit (8-byte) floating-point number that can store up to 15-16 decimal digits.
- boolean: A boolean type, true or false
- char: A single character or letter
Declaring variables
In Java, we can declare variables by using the following method:
dataType variableName = value;
So, if we want to store a variable called age. So the code will be :
int age = 21;
Let’s create some more variables.
class MyClass {
public static void main(String[] args) {
int age = 21;
String name = "Mahmud";
float pi = 3.146;
char letter = 'm';
boolean isMarried = false;
}
}
Here we have created a few variables of different types. We have created a variable called name
of the String
data type to store a word. Note that the String
keyword starts with a capital S. We’ve also created a variable of float
type to store the value of pi which is a floating point number.
Boolean is a data type where there are only two values, true
or false
. We’ve declared a boolean
variable called isMarried
and assigned its value to false.
Constant
We can create a constant using the final
keyword. Here is an example:
final int constantNumber = 16;
Now, we cannot change the value of constantNumber
because it’s a constant. If we try to assign a new value it will generate an error.
Conclusion
In this article, I discussed different data types and how to create variables using those types in Java.
Top comments (0)