Technical SpeaksCodeForDevelopersThe official blog of Technical Speaks
Core Java

Variables in Java | Different Types of Variables in Java | Java Tutorial

By · Published · Updated · 1 min read

What is a Variable? In simple words, a variable can be defined as the container which holds the value. Also, a Variable is assigned with a data type. A variable determines the size and range of values, that can be stored within the memory.

There are three types of Variables we use in Java

1. Local Variable:

Local variables declared inside the body of the method. we use these variables only within that method. Example:

code
public class Test {

   public void localvar() {

      int num = 0;

      num = num + 7;

      System.out.println(“Final num is : ” + num);

   }

 

   public static void main(String args[]) {

      Test test = new Test();

      test.locavar();

   }

}
Output: Final num is 7
If You want to learn step by step tutorial, watch the video:

2. Instance Variable:

A variable declared inside the class but outside the body of the method, is called instance variable. Instance variables are created when an object is created with the use of the keyword ‘new’ and destroyed when the object is destroyed.

code
class Marks
     {

//These variables are instance variables.

//These variables are in a class and are not inside any function

          int engMarks;

          int mathsMarks;

          int phyMarks;

     }

class InstanceVar

     {

          public static void main(String args[])

             {

                   Marks obj = new Marks();

                    obj.engMarks = 50;

                    obj.mathsMarks = 80;

                    obj.phyMarks = 90;

                    System.out.println(“Marks for object:”);

                    System.out.println(obj.engMarks);

                    System.out.println(obj.mathsMarks);

                    System.out.println(obj.phyMarks);

}

}
Output: Marks for object: 50,80,90

3. Static Variable/Class Variable:

Static variables are also called class variables and this is much similar to the instance variables. it is declared with the static keyword in a class, but outside a method, constructor or a block.

code
class Emp {
// static variable salary

          public static double salary;

          public static String name = “Mohan”;

       }

public class EmpDemo

   {

       public static void main(String args[]) {

//accessing static variable without object

       Emp.salary = 10000;

       System.out.println(Emp.name + “‘s average salary:” + Emp.salary);

    }

 }

Output: Mohan’s average salary : 10000

Connect with us:

Written by

Saurabh Kumar

SEO Consultant and Founder of Technical Speaks

Saurabh Kumar is an SEO professional with more than 10 years of hands-on experience and a Top Rated freelancer on Upwork. He is the founder of Technical Speaks and also builds websites with Next.js and WordPress.

Comments

Leave a comment