Last Updated: 04 November, 2023
A variable is a data container that contains the data while the Java program is executed. A variable is assigned a single data type, such as String, Integer, Boolean, Float, etc. The data type defines the nature of the data value. A variable is the name of a memory location.
The variable name is a combination of two words: "vary" and "able" which means its value can be changed. Multiple times, different values can be assigned to the same variable.
All Java variables must be identified with unique names. These unique names are called Identifiers.
If we declare a variable inside a method, constructor, or block, that variable is known as a local variable in Java. A local variable is only accessible inside the method; outside the method, there is no identity for the local variable. A local variable cannot be static.
If we declare a non-static variable outside the method, constructor, and block, that variable is known as the instance variable in Java. Instance variables belong to the instance of the class. Instance variables are initialized while creating the object of the class and are accessed by the object only.
A variable declared with the static keyword is known as a static variable in Java. Static variables are initialized when a class is loaded into memory. Static variables are common for all the objects of the class, and they are accessed by the class name, which is why they are also known as class variables. Static variables cannot be declared as local variables.
While declaring a variable in Java, we must follow the below rules and conventions related to the naming of variables.
Variable names in Java are case-sensitive.
For example: employeeId, EMPLOYEEID, EmployeeId
A variable name should start with a letter (A to Z or a to z) and two special characters like a dollar sign ($) or an underscore (_).
For example: mentor, Mentor, $mentor, _myVar
After the first character in a Java variable name, the name can also contain numbers (in addition to letters, the $, and the _ character).
For example: mentor1, mentor_1
A keyword or reserved word cannot be used as a variable name.
For example: int, char, if, while, for, etc.
A variable must not contain white spaces or special characters like the astric sign (*) etc.
For example: java mentor, java*mentor
To declare a variable, we specify the data type and the variable name.
Syntax: data_type variable_name;
Example: String name;
To initialize a variable, according to the data type, we assign a specific value to the variable.
syntax: variable_name=value;
Example: company_url="javabytechie.com";
Let's see the below example for better clarity on variables.
Example: How to declare, initialize, reinitialize, assign variables in Java
Output
Student Name : John
School Name : ABC School
Total Marks: 253
That's all guys, hope this Java article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com