Variable in Java with Examples
A variable is a name assigned to a memory to allocate space for storing a data value in a program. Each variable in Java is of a specific type.
Java is a statically-typed programming language, meaning that a variable must always be declared before it is used. Declaring of a variable involves stating the variable's type and name.
Example
String name;
byte diceNumber;
short age;
int rollNumber;
float fee;
double amount;
Here, name, diceNumber, age, rollNumber, fee, and amount are variables while String, byte, short, int, float, and double are their data types.
A variable can also be declared with access modifiers.
Example
public String name;
private int age;
Here, public and private are access modifiers.
Types of variables in Java
Variables in Java are of three types:
- Instance variable
- Static/Class variable
- Local variable
Instance variable
An Instance variable is a variable that is declared inside a class and outside of any method and constructor. An instance variable is declared without the static keyword, therefore it is also called non-static variable. The instance variables are visible to all methods, constructors, and blocks in the class where they are declared.
An instance variable can only be called through objects.
Example
public class Student {
/* Declaring instance variables or non-static variables
*with private access visibility */
private String name;
private int rollNumber;
}
Static/Class variable
A static variable is declared with the static keyword. Static variables are also called Class variables. A static variable is declared inside a class but outside of any constructor and method.
Static variables are usually used for declaring constants. Constants are variables with a fixed value. Constants value cannot be changed after it has been assigned.
Static variables belong to class and not objects. Therefore we do not need any object to access static variables in Java. Generally, public variables can be accessed from everywhere, and private variables can only be accessed from within the class where it is declared.
A static variable is initialized only once and only a single copy of such variable is created and shared at class level, however many times it is called in a program.
In Java, static variables are declared using the uppercase letters.
Example
public class Student {
public static String NAME = "abc";
private static int ROLL_NO = 11;
}
To access the static variable in another class, we only need to use the class reference name followed by a dot . or period and static variable name.
Here is an example of accessing the static variable of the Student class in another School class. The static variable with the private modifier is not accessible from other classes.
public class School {
public void printStudentDetail() {
/* We do not have to create an object of Student class for
* accessing static variables. We use a reference of class Student
* followed by a dot and static variable. */
String studentName = Student.NAME;
//Printing student's name in console
System.out.println("Student's name is " + studentName);
}
}
Local variable
A local variable is declared within the body of a method, constructors or blocks. We can use the local variable only within that method where it is declared. Other methods in the same class aren’t even aware that the variable of one method exists.
A default value is never assigned to an uninitialized local variable by the compiler. Therefore, a local variable must always be assigned a value before it is used otherwise accessing an uninitialized local variable will result in a compile-time error.
Example
public class Actor {
public static void main(String[] args) {
//Declaring local variable.
String name = "abc";
//Printing local variable in console.
System.out.println("Actor's name is " + name);
}
}
We can also declare local variables within blocks of code marked by braces.
Note: Local variables cannot have access modifiers.
Example
public class Employee {
public static void main(String[] args) {
//Declaring local variables
double salary = 1000;
double totalSalary = 0;
if(salary == 1000) {
//Declaring local variable within blocks of code.
double bonusAmount = 5000;
totalSalary = salary + bonusAmount
}
//Printing local variable
System.out.println("Total salary is " + totalSalary);
}
}
Output
Variable Naming Conventions
The best variable naming convention is to choose a variable name that will tell the reader what the variable is for and what the variable is representing in the program. For example: if you wish to store a roll number on Student, a variable name such as rollNo would be easier to remember than a variable name such as var2.
There are rules and conventions related to the naming of variables in Java. The rules are:
- Java variable names are case sensitive. The variable name hello is not the same as Hello or HELLO.
- Java variable names must start with a letter or underscore _ or a dollar sign $ character. After the first character in a variable name, the name can also contain numbers from 0 to 9 (in addition to letters, the dollar sign $, and the underscore _ character). No special characters are allowed.
- We cannot use reserved keywords as variables name in Java. For example: the words String or while are reserved words in Java. Therefore, you cannot String or while as a variable name.
- All uppercase letters are used to identify constant variables.
Here are some examples of valid and invalid variable names:
Valid Variable Names | Invalid Variable Names |
---|---|
name | #name |
name2 | 2name |
_name21 | 21_name |
NAME | ()NAME |
Name | -Name |
first_name | first_name() |
$lastName | @lastName |