What Is Variables In Java

In this article we learn what is variables in java and types of variables in java with examples.

Variables In Java (Java Variables)

Variables in java is a name of memory location that holds the data value of a particular data type.

A variable in Java is a kind of container that contains the value during program execution.

Syntax of variables

datatype variableName=Value ;

Types of Variables In Java

There are two types of variables:

  1. Local Variables
  2. Global Variables

1. Local Variables In Java

What Is Local Variable?

  1. Variable is a container which holds the value
  2. Variable is name of memory location
  3. Variable always declare with data type.
  4. Variable which is present inside the method is called local variable.

Why We Use Local Variable?

  1. To store the value, we use variable.
  2. To maintain the scope of value within the method, we use local variable.
  3. To maintain the heap memory, we use local variable.

When We Use Local Variable?

  1. When we want to store the value at method level, we use local variable.
  2. When we don’t want to give scope of value outside the method, we use local variable.

How We Use Local Variable?

  1. Local variable always declare inside the method
  2. Syntax of variable: data_type variable_name = value;

Example of Local Variable:

public class Trials {

void method() {

int n = 90; // local variable

System.out.println(n);

}

public static void main(String args[]) {

Trials obj = new Trials();

obj.method();

}

}// end of class”

2. Global Variables In Java

What Is Global Variable?

  1. Variable is a container which holds the value
  2. Variable is name of memory location
  3. Variable always declare with data type.
  4. Variable which is present outside the method is called global variable.
  5. Global variable also known as instance variable.

Why We Use Global Variable?

  1. To store the value, we use variable.
  2. To maintain the scope of value at class level, we use global variable.

When We Use Global Variable?

  1. When we want to store the value at class level, we use local variable.
  2. When we want to give scope of value outside the method, we use global variable.

How We Use Global Variable?

  1. Global variable always declare outside the method but inside the class.
  2. Syntax of variable : data_type variable_name = value;

Example of Global Variable:

public class Trials {

int n = 90;  // global variable

void method() {

System.out.println(n);

}

public static void main(String args[]) {

Trials obj = new Trials();

obj.method();

}

}// end of class

Other Popular Articles

What Is Main Method, Print Method and Output In Java?

Leave a Comment