Scroll to top

Variables in Java

Introduction

In Java, objects store their states in variables. Variables are used as containers to hold values (int, long, string…) during the life cycle of an application.

Variable Definition

To define a variable, we need to assign a data type for that variable. A data type defines the kind of value this variable can hold (int, long or String etc.).

Example of variable definition

	public final int var ;
public :  Access Modifier applied to variable
final    :  Non Access Modifier applied to this variable
int       :  Datatype. It defines kind of value this variable can hold (int in this case)
var      :   Name of the variable

Variable Initialization

Now that we are done defining a variable, we can initialize the above variable by assigning a value to it . In this case, we assign the variable an integer value.

	public final int var = 9;

Variables Types in Java

Variables in Java can be defined anywhere in the code (inside a class, inside a method or as a method argument) and can have different modifiers. Depending on these conditions variables in Java can be divided into four categories.

  • Instance Variable
  • Static Variable
  • Local Variable
  • Method Parameter

Instance Variable(Non Static Fields)

Instance variables are used by objects to store their states. Variables which are defined without the STATIC keyword and are outside any method declaration are object-specific and are known as Instance Variables. Such variables are called instance variables because their values are instance specific and values of these variables are not shared among instances. For more details go to Instance Variable topic.

Class Variable(Static Fields)

 Variables which are declared with a STATIC keyword inside a Class (outside any Method) are known as Class variable / Static variable. They are known as Class level variables because values of these variables are not specific to any instance but are common to all instances of a class. Such variables will be shared by all instances of an Object. For more d

Local Variables(Method Local)

When a variable is declared inside a Method it is known as Method Local Variable. The scope of local variables is only inside the Method, which means local variables cannot be accessed outside that Method.  There are some restrictions on access modifier that can be applied to local variables. To know more about access modifier CLICK HERE. For more detail go to Local Variable article.

Parameters

Java method parameter and argument  are variables that are passed in Methods. For example, String args[] variables in the main Method is a parameter.

package com.jbt;

/*
 * Here we will discuss about different type of Variables available in Java
 */
public class VariablesInJava {

	public static void main(String args[]) {
		System.out.println("Hello");
	}
}

Author avatar
JBT
https://javabeginnerstutorial.com/

93 comments

  1. siva

    Why there is no navigation provided for next chapters in every page

  2. siva

    Why there is no navigation provided for next chapters in every page

  3. Zahangir Alam

    “Why there is no navigation provided for next chapters in every page”- Right. It is very necessary to follow the tutorials….

    • Vivekanand Gautam

      Right NAV is already provided. Same can be used for navigation from one topic to another. Meanwhile your point is taken and will try to resolve this problem with next template for my blog.

      Thanks

  4. Zahangir Alam

    “Why there is no navigation provided for next chapters in every page”- Right. It is very necessary to follow the tutorials….

    • Vivekanand Gautam

      Right NAV is already provided. Same can be used for navigation from one topic to another. Meanwhile your point is taken and will try to resolve this problem with next template for my blog.

      Thanks

  5. senthilkumar

    nice program and tips…..

  6. senthilkumar

    nice program and tips…..

  7. Jeevan

    Dear Mr. Gautam,

    1. Could you please take an example when should we use final ?
    2. In this example where are the parameters?

    
    package com.jbt;
    public class VariablesInJava {
     
        public static void main(String args[]) {
            System.out.println("Hello");
        }
    }
    
    Shouldn't be like this? (Excuse me for asking silly questions)
    
    package com.jbt;
    public class VariablesInJava {
     
        public static void main(username) {
            System.out.println(username);
        }
    }
    • Vivekanand Gautam

      Hi Jeevan,

      Que 1: Final keyword is used to make sure that once value assigned to a variable doesn’t get changed(If used with Variable).

      Final int i=10;

      i=20; // Here compiler will give you error. As i can not be assigned this value as i is Final.

      Que 2 : Here method(Main) you are referring is not a normal method. It is a Special method used by JVM as starting point for application. Moment you change the signature as you are doing by replacing “String []” with “username”. It will become a normal method in a class. I am not sure exactly what do you mean by parameter.

      Thanks

  8. Jeevan

    Dear Mr. Gautam,

    1. Could you please take an example when should we use final ?
    2. In this example where are the parameters?

    
    package com.jbt;
    public class VariablesInJava {
     
        public static void main(String args[]) {
            System.out.println("Hello");
        }
    }
    
    Shouldn't be like this? (Excuse me for asking silly questions)
    
    package com.jbt;
    public class VariablesInJava {
     
        public static void main(username) {
            System.out.println(username);
        }
    }
    • Vivekanand Gautam

      Hi Jeevan,

      Que 1: Final keyword is used to make sure that once value assigned to a variable doesn’t get changed(If used with Variable).

      Final int i=10;

      i=20; // Here compiler will give you error. As i can not be assigned this value as i is Final.

      Que 2 : Here method(Main) you are referring is not a normal method. It is a Special method used by JVM as starting point for application. Moment you change the signature as you are doing by replacing “String []” with “username”. It will become a normal method in a class. I am not sure exactly what do you mean by parameter.

      Thanks

  9. nantha kumar

    dear gautham sir .i’m the beginner in core java.
    so could you show me the basic pakages like What is swing? and related this please.
    i’m already search many times but none of the sites give me the perfect answers what i expected….

    another one query,
    show me tree diagrams for java and their subdivides , if any.

  10. nantha kumar

    dear gautham sir .i’m the beginner in core java.
    so could you show me the basic pakages like What is swing? and related this please.
    i’m already search many times but none of the sites give me the perfect answers what i expected….

    another one query,
    show me tree diagrams for java and their subdivides , if any.

  11. Prince

    Hello Guys,

    navigation is available. please see on left and right side. are you guys are able to see there is a arrow both side in between page. on mouse hover you will see next and previous page link.

  12. Prince

    Hello Guys,

    navigation is available. please see on left and right side. are you guys are able to see there is a arrow both side in between page. on mouse hover you will see next and previous page link.

  13. Darshan Mutha

    Sir, I’m also core java beginner… will you please post the necessary information regarding collection frameworks….

  14. Darshan Mutha

    Sir, I’m also core java beginner… will you please post the necessary information regarding collection frameworks….

  15. Shwetha

    Please provide navigation to the next page..

    • Vivekanand Gautam

      Hi Shwetha,

      On right nav you will get link to different topic in same category. Also below every article there is a link to next and Previous page. Which can be useful if you want to navigate to other Article.

      Thanks

  16. Shwetha

    Please provide navigation to the next page..

    • Vivekanand Gautam

      Hi Shwetha,

      On right nav you will get link to different topic in same category. Also below every article there is a link to next and Previous page. Which can be useful if you want to navigate to other Article.

      Thanks

  17. Deepak

    Hi Mr.Vivek
    I am Beginner to core java… Basically I am having knowledge about .NET… Here in my work location they asked me to work in JAVA and android.. So plz help me to develop myself by sending me a mail like simple sample programs to my mail……

  18. Deepak

    Hi Mr.Vivek
    I am Beginner to core java… Basically I am having knowledge about .NET… Here in my work location they asked me to work in JAVA and android.. So plz help me to develop myself by sending me a mail like simple sample programs to my mail……

  19. Raj

    Very informative article.

    Few spelling mistakes:
    Under “Instance Variable(Non Static Fields)” section.

    …. used by Objects to store “there” states… There should be “their” instead of there.

    Thanks.

  20. Raj

    Very informative article.

    Few spelling mistakes:
    Under “Instance Variable(Non Static Fields)” section.

    …. used by Objects to store “there” states… There should be “their” instead of there.

    Thanks.

  21. srisiva

    very useful website

  22. srisiva

    very useful website

  23. surya

    Hello Vivekanand Gautam Sir,

    your blogs are very well formed..and easy to understand.i want to know that what is most important thing in java to learn ..means in which topic have to focus to cover java as soon as possible…i am seeing first time java programming…and want to cover java quickly..please guide me how to start study about java….

  24. surya

    Hello Vivekanand Gautam Sir,

    your blogs are very well formed..and easy to understand.i want to know that what is most important thing in java to learn ..means in which topic have to focus to cover java as soon as possible…i am seeing first time java programming…and want to cover java quickly..please guide me how to start study about java….

  25. ayushi

    hello
    gautam sir,
    I m also a beginner in a core java.
    could you please help me out with the swing section.
    as i have to give interview next week.

  26. ayushi

    hello
    gautam sir,
    I m also a beginner in a core java.
    could you please help me out with the swing section.
    as i have to give interview next week.

  27. swetha

    dear gautham sir .i’m the beginner in core java.
    so could you show me the basic pakages like What is swing? and related this please.
    i’m already search many times but none of the sites give me the perfect answers what i expected….

    another one query,
    show me tree diagrams for java and their subdivides , if any.

    and please tell me what is heap memory and garbage collector

  28. swetha

    dear gautham sir .i’m the beginner in core java.
    so could you show me the basic pakages like What is swing? and related this please.
    i’m already search many times but none of the sites give me the perfect answers what i expected….

    another one query,
    show me tree diagrams for java and their subdivides , if any.

    and please tell me what is heap memory and garbage collector

  29. sumit kumar

    Hello gautam sir,
    i am also a beginner in core java.
    sir provide package for topic applets And swing with example in Netbeans IDE.

  30. sumit kumar

    Hello gautam sir,
    i am also a beginner in core java.
    sir provide package for topic applets And swing with example in Netbeans IDE.

  31. karthick Ramamoorthy

    Hi
    Why don’t you give some simple example, as this chapter deals with variable why we want to use objects ,and iam at the bottom level of java just started to learn very basic so it would be better if the examples overs only exact topic.

  32. karthick Ramamoorthy

    Hi
    Why don’t you give some simple example, as this chapter deals with variable why we want to use objects ,and iam at the bottom level of java just started to learn very basic so it would be better if the examples overs only exact topic.

  33. viany

    i am java beginner dont have subject in java plz help

  34. viany

    i am java beginner dont have subject in java plz help

  35. Bhavesh Rathod

    final String localVariable = “Initial Value”;
    System.out.println(localVariable);

    this line may be not working.
    I ran the same code which you mention but it is not print the localvariable value

  36. Bhavesh Rathod

    final String localVariable = “Initial Value”;
    System.out.println(localVariable);

    this line may be not working.
    I ran the same code which you mention but it is not print the localvariable value

  37. anubha

    dear gautham sir .i’m the beginner in core java.
    so could you show me the basic pakages like What is swing? and related this please.
    i’m already search many times but none of the sites give me the perfect answers what i expected….

    another one query,
    show me tree diagrams for java and their subdivides , if any.

  38. anubha

    dear gautham sir .i’m the beginner in core java.
    so could you show me the basic pakages like What is swing? and related this please.
    i’m already search many times but none of the sites give me the perfect answers what i expected….

    another one query,
    show me tree diagrams for java and their subdivides , if any.

  39. Anantha

    Hi, Your post is nice and very useful to start java.having one doubt. Method parameter also come under local variable right? Variable also declared in block.({}).can you please explian these two?.

  40. Anantha

    Hi, Your post is nice and very useful to start java.having one doubt. Method parameter also come under local variable right? Variable also declared in block.({}).can you please explian these two?.

  41. sanapathi ramesh

    Hi sir,

    can you tell me why can not use public keyword inside method infront of local variables..

    • Vivekanand Gautam

      It is not allowed because there is no point in using the same. public means it should be available to everything in JVM. But Local Variable can not be made available to anything outside Method. Hence it is not allowed to use public keyword.

      Regards

  42. sanapathi ramesh

    Hi sir,

    can you tell me why can not use public keyword inside method infront of local variables..

    • Vivekanand Gautam

      It is not allowed because there is no point in using the same. public means it should be available to everything in JVM. But Local Variable can not be made available to anything outside Method. Hence it is not allowed to use public keyword.

      Regards

  43. Balan

    I am new to java. Yet, I felt I should make some suggestions. This lesson could be preceded by a brief write up on the structure of java programmes – say, package>import statements>Classes, including Public Class>methods and main method.

    The examples for both Instance Variables and Class Variables appear similar. One has to read it twice. The relevant portions could have been highlighted differently for the two examples.

    You have said Instance Variables are Instance specific. The obj could have been followed by say obj2 and then whether the variable could have been used by both or not could have been explained ( I am not clear myself as I am learn this area more).

  44. Balan

    I am new to java. Yet, I felt I should make some suggestions. This lesson could be preceded by a brief write up on the structure of java programmes – say, package>import statements>Classes, including Public Class>methods and main method.

    The examples for both Instance Variables and Class Variables appear similar. One has to read it twice. The relevant portions could have been highlighted differently for the two examples.

    You have said Instance Variables are Instance specific. The obj could have been followed by say obj2 and then whether the variable could have been used by both or not could have been explained ( I am not clear myself as I am learn this area more).

  45. Shekhar

    Good effort done for the java beginners……Thanks

  46. Shekhar

    Good effort done for the java beginners……Thanks

  47. tamil

    super sir…

    .i’m the beginner in core java.

    show me tree diagrams for java and their subdivides .

    • Vivekanand Gautam

      Hi Tamil,

      Link :

      Either you can access above link or you can go to FB page and check in photo section. you will find the diagram
      for different subbdivides.

      Hope it help,

      Thanks

  48. tamil

    super sir…

    .i’m the beginner in core java.

    show me tree diagrams for java and their subdivides .

    • Vivekanand Gautam

      Hi Tamil,

      Link :

      Either you can access above link or you can go to FB page and check in photo section. you will find the diagram
      for different subbdivides.

      Hope it help,

      Thanks

  49. sakshi sharma

    hii sir,
    can you help in collection framework and gernic data type. actually I studied these topics but I didnt get basic usage whr we can use these topic .

  50. sakshi sharma

    hii sir,
    can you help in collection framework and gernic data type. actually I studied these topics but I didnt get basic usage whr we can use these topic .

  51. rams

    Hi Sir, very interesting I am new to programming, can you send the learning tree to place in the industry.

  52. rams

    Hi Sir, very interesting I am new to programming, can you send the learning tree to place in the industry.

  53. keerthi

    Hi Sir, very interesting I am new to programming, can you send the learning tree to place in the industry.

  54. keerthi

    Hi Sir, very interesting I am new to programming, can you send the learning tree to place in the industry.

  55. Shashikala

    when I click a button “My computer window should appear” can you please help me writing code for this
    Thanks in advance

  56. Shashikala

    when I click a button “My computer window should appear” can you please help me writing code for this
    Thanks in advance

  57. toni

    can you explain for me about “public final static int a”, please ?

  58. toni

    can you explain for me about “public final static int a”, please ?

  59. Manvendra V Singh

    Hi ,

    You have mentioned that- “Instance variable can only be accessed by Object of the class only as below.” in first example. But it is NOT correct. A method can use instance variable of it’s own class without using it’s object.

    For Example –
    class Employee {

    public Employee(String n, double s){
    name=n;
    salary=s;
    }

    public void print(){
    System.out.println(“Name = “+name+”Salary = “+salary);
    }
    private String name;
    private double salary;

    }

    • When we talk about accessing anything we talk about accessing it from outside of the class. Any method can access any variable irrespective of Access Modifier. There is no point in discussing that behavior. Hope it clarifies.

  60. Manvendra V Singh

    Hi ,

    You have mentioned that- “Instance variable can only be accessed by Object of the class only as below.” in first example. But it is NOT correct. A method can use instance variable of it’s own class without using it’s object.

    For Example –
    class Employee {

    public Employee(String n, double s){
    name=n;
    salary=s;
    }

    public void print(){
    System.out.println(“Name = “+name+”Salary = “+salary);
    }
    private String name;
    private double salary;

    }

    • When we talk about accessing anything we talk about accessing it from outside of the class. Any method can access any variable irrespective of Access Modifier. There is no point in discussing that behavior. Hope it clarifies.

  61. Vartika

    Hello Sir, I want to learn java coding and clear my basic concepts. Can I have the tutorial in pdf format . ?

  62. Vartika

    Hello Sir, I want to learn java coding and clear my basic concepts. Can I have the tutorial in pdf format . ?

  63. Mohammad Yakubpasha

    Hi Sir,
    This tutorial is very good, could you please share Total Java course in pdf format.
    Thank you

Post a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.