Different Variables In Java

Different Types of Variables in Java: Based on our usage there are three different types of variables. They are

1.Local Variables

2.Instance Variables or global variables.

3.Static Variable.

1.Local variable : A variable declared within a method is called as local variable. Local variable life span is active until it is within the method.

Local Variable Example in Java


OUTPUT :

java local variable example

In the above program age is an local variable, which scope lies within method1. If we try to access the age without accessing the method. Java compiler will throw an syntactical error. Because we need to create an object of that class and access the methods which contains variables.

2.Global variables or instance variables : A variable declared within a class but outside the method, constructor, block is called as Global variables.

Global Variable Example in Java


OUTPUT :
java global variable example

The value is 0 because the default value of integer is zero. Since we did not declare the variable with any value we are getting zero. However after declaration we are getting 20.

3.Static Variable : A static variable is declared with the keyword as static and its within class level however outside a method, constructor, block.

We can access the variables without creating an object. Using classname with variablename we can access the variables.

Static Variable Example in Java

OUTPUT :

Leave a Comment

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