Variables in java


In this tutorial, we will see introduction to variables, declaration, and types.


Variables in java is used to store values of elements while the program is executed.

Java variables are nothing but memory location. It stores the values which can be manipulated by program. Variables in java are strongly typed hence they all must have a datatype followed by an identifier.

Each variable has the specific data type which defines size and layout of the variable’s memory.

Declaring a variable

We can declare a variable as below:

Here is the example:
variable declaration

💡 Did you know?

value is optional while declaring variables. You can declare variable and assign value to it later in program.

Variable has a name that is used to identify it. The name of the variable is known as the variable’s identifier.

There are some naming conventions that you need to follow while declaring a variable.

  • You can use A to Z or a to z
  • You can use 0 to 9
  • You can use special symbol$ and _ to declare a variable
  • You can not start a variable name with number
  • You can not have spaces in variable name.
  • You can not use reserved keywords in variable name
  • Varibles names are case sensitive.


You can declare variables in groups as well.

Assigning a value to variable

Each variable holds some data which it describes. We use = operator to assign value to a variable.

Compiler will give compile type error if value is not matched with datatype.
For example:
You can not assign String literal to int data type.

Types of variables

There are three kinds of variables in java.

Local variable

A Variable which is declared inside a method can be termed as Local Variable. It is mandatory to initialize local variable otherwise Compiler will complain about it.

Instance variable

A Variable which is declared at class level can be termed as Instance variable. It is not mandatory to initializeInstance variable.

All instance variable will be by default initialized by JVM.

Static variable

A Variable which is declared as static is known as Static variable. Static variables are class level variables.

Let’s understand it with the help of simple program:

When you run above program, you will get below output:

Instance variable: 0
Static variable: 20
Method local variable: 10

That’s all about Variables in java.


Add Comment