Variables in java

A java variable is a reserved space of computer memory where a data value can be stored. You can assign a specific name to each of these memory locations however should follow the naming conventions. 

Usually, a java program begins with the variable declaration since variables store the information that is required by your java program to perform its task. The information or data can be anything like simple texts or codes or numbers or even simple predefined calculations. Hence the variables that store data have specific data types which you will learn in detail in the next tutorial -Data types in Java.

Example: Variables in a program

public class Student {

 public static void main(String[] args) {
 String name;
 int age;



In the above code, the name is a variable of string data type and age is another variable of integer data type. 

How to name variables in Java

Though 'Java' has provided the freedom of using variable names according to your wish and convenience, there are certain rules you must abide by. 

  1. Variable names can be a combination of alphabets(A,a,B,b), numbers(0,1,2) and underscore(_) only. 
  2. Variables must start with a letter or some compilers support underscore(_) or a dollar sign($). But it can't begin with a number.
  3. Since Java is a case-sensitive language both uppercase (NUM) and lowercase (num) letters are treated differently.
  4. Special characters(/,;,:)and symbols(#,@) are not allowed while naming a variable.
  5. The variable name must be different from reserved keywords. This means reserved keywords like int, float, etc can’t be used for naming variables.
  6.  No whitespace is allowed. 
  7. Last but not least it is safer to use variable names that are short, simple, and meaningful ( not more than 31 characters). 

Following the below table gives you the idea of valid and invalid variable names.

age, _age, $age 17age
num, NUM int, float, for, while
stud1, stud_2 Stud#, Stud@2, Stud  1

Apart from these, Java has few naming conventions that are not necessary to follow but are practiced by many java developers to keep the proficiency of the java code. Following these conventions result in code readability. So the few naming conventions are listed below:

  1. Always write variable names in lowercase like age, name, etc.
  2. If the variable name consists of more than one word, capitalize the first letter of each subsequent word, i.e, studName,studAge,studFatherName, etc.
  3. Variables that store constant values (static final fields) are always named in uppercase letters with an underscore between each word. Eg: EXCHANGE_RATE.

How to declare a variable in Java

Like in other programming languages, in java also all the variables which are going to be used in the program must be declared first. It is because of the two reasons

  1. The compiler must know how much space to be reserved for the variable for proper functioning. The allocated space must be sufficient and not extra-large causing misuse of memory. 
  2. The compiler must recognize the data whether it is a number or alphabet and that is why 'type' must be declared. Except this, a meaningful name (called identifier)should be given to it for ease of operation. 

Variable declaration syntax involves two important parts as shown below, one is the data type and the other is the variable name. Variable declarations should always end with a semicolon unless the compiler will raise a termination error. Also, java provides the freedom to declare multiple variables in a single line if they possess the same datatype.

Syntax :

datatype variable_name;

For instance,

int num1; 
int num 2; 
float f1,f2;

Here, int means the integer numbers, float means a fractional number. int and float are data types and num1, num2, f1, f2 are identifiers(variable names). A variable once declared with a specific data type will only take values of that particular data type. Here num can take only integral values, if we try to store any other values like character to num then it will raise an error.

How to initialize a variable in Java

After the declaration is done, you are free to use the allocated space (i.e. variable) as per your requirement. This declared variable initially contains garbage values which are the undefined values. If you wish to assign some values initially you can do that with the help of the assignment operator ‘=’. Variable initialization can be performed at the time of declaration itself or you can assign the value later.


datatype variable_name = value;

Some examples of variable initialization are illustrated  below:

int num1 = 4; 
float f1 ;
f1 = 2.5;

A variable always allocates the latest value in its space unless it is declared with the keyword final. See below example,

public class Student {

    public static void main(String[] args) {
        String name = "TOM";
        int age = 17;
        age = 20;

        System.out.println("Name:" + name);
        System.out.println("Age:" + age);





In the above example, initially, the variable age stores the value 17 but as it goes it encounters that the age is assigned with a new value 20. So the new value 20 overwrites the previous value 17 since the variable is not declared with the keyword final. Hence it displayed age as 20.

If you declare the variable as final and attempt to assign it with another value, the result will be an error.

How to display variables

Now to display the variables in java we can use the println() method. Let’s understand this with the help of an example:

public class Sum {

    public static void main(String[] args) {
        int num1 = 4;
        int num2 = 5;
        System.out.println("First number is : " + num1);
        System.out.println("Second number is : " + num2);

        int sum = num1 + num2;
        System.out.println("Sum is " + sum);


Here variables num1 and num2 store the integer value 4 and 5 respectively. The variable sum contains the added value of num1 and num2. Using the println() method, the values stored in the variables are displayed. To club the text with variables we can make use of the  + character.


First number is : 4
Second number is : 5
Sum is 9

Types of variables in java

Java describes 4 types of variables. They are listed below:

  1. Local Variable
  2. Instance Variable (Non- Static Field Variables)
  3. Class Variable(Static Field Variables)
  4. Parameters

Local Variable

A local variable is a variable that is defined inside a method or constructor or a block of code. The scope of the variable is limited to that method or block of code. Hence we can say this type of variable has local scope only which means the variable is created upon entering the code block or being called by the method and destroyed when it exits that code block or returning the method.

Example: illustrates local variable

void method()
      int num = 5;   // Local Variable 

Here,  variable num is bound to the function method().

Instance Variables

Instance variables are variables that are defined inside a class but outside a method or constructor or code block and are not being prefixed with the keyword static. That means instance variables are non-static field variables

An instance variable belongs to an object which in turn is an instance of a class thus we can say in other words that “An instance variable is an instance of the class”. An instance variable gets created whenever an object of a class is created with the use of keyword new. That means instance variables are unique to their objects.

Example: How instances variables are created

Class Employee{
String employee_Name;
int employee_Id;


In the above example, two instances (emp 1 and emp2) of class Employee got created.

Static Variables

A variable is said to be static if it is prefixed with the keyword static. Static variables in java are defined inside a class but outside a method or code block. Static variables are also called class variables as they belong to the class and not the objects(instance). Hence static variables are common to all instances of the class irrespective of the number of instantiations. In other words, the variables declared as static are shared among all the objects of the class. The below code snippet will illustrate the working of static variables.

Example: Use of Static Variable

Class Employee{
String employee_Name;
int employee_Id;
static String company_Name= “ABC”; //Static 


Parameters are variables associated with methods. When a method is called, parameters are used to pass the information to the method. The scope of the parameter lies inside the method that declares the parameter. 

Example: illustrating the use of parameters

public class ParamEx {

    static void MethodDisp(String fname) {
        System.out.println("Hai " + fname + " Welcome to LearneTutorials!!!");

    public static void main(String[] args) {



This example, ParamEx is a class with a method named  MethodDisp().  The purpose of this method is to display the message “ Hai (name) Welcome to Learnetutorials!!!”. Here the name is passed as a string parameter fname to the MethodDisp() on the method call. 

Don’t bother yourself now about parameters. Definitely, you will learn in future tutorials. As of now just keep in mind variables can show up in the form of parameters also.