Java Variables

Posted in Variables and Data Types By Raj On November 21, 2017


A variable is a small amount of memory which contains a value, every variable must have a data type,  usually what will happen When you define int age = 20 is, in the stack memory a small amount of memory will be allocated to store the number 20, here

  • the variable name age specifies the name of the memory
  • the size of the memory will be depended on data type which is used while defining a variable

Variable Definition :

<data type> <variable name> = <initialization>

Java Variables

Primarily, there are three types of variables available

  • Instance variables
  • Local variables
  • Static variables

Instance variable

  • The variables which are defined at class level are instance variable’s
  • You can access these with class name like static variables, you need to create an object 
  • Every object will have its own set of instance variables
  • You need to specify access specifier’s otherwise it will take default specifier

Local variables

  • The variables which are defined inside a method are called local variable
  • You must initialize local variable otherwise you will get compile time error 
  • The local variables are accessible within the block or method

Static variable

  • The static variables are created only once and the objects which are created using that class can have access to it

Example: Instance variables

Example: Local variables

Example: Static variables