Variable

Variable

  • It is an entity that may vary during execution of program called as variable.
  • Variable is a name which is associated with a value that can be changed.

Guidelines for declaring variables

Note- Variable is declared followed by semi-colon (;)

There are two types of variable as

  • Global variable
  • Local variable

Global variable

  • It is defined outside of method but inside the class called global variable.
  • It is called as instance variable.
  • How to declare and initialize the global variable?
  • In this example, we have declared x variable as globally, outside of the method.
  • It is initialized automatically by JVM and default value is 0.
  • Global variables are stored in heap area.
  • Each instance (objects) of class has its own copy of instance variable.
  • Scope is anywhere in the class.

Note- Static keyword is applied to global variable and it will become a static variable.

Local variable

  • It is declared inside method body called as local variable.
  • It is also declared in constructor or block.
  • How to declare & Initialize the local variable?
  • Scope is within the method, constructor and block only.
  • Local variable is also declared in constructor.
  • It does not initialized automatically.
  • Local variables are stored in stack area.

How to print the value of local variable

  • In this example, we are printing the value of variable by using two ways.
  • 1. System.out.print(x); // Here passing variable x.

    2. System.out.println (“Value of X is=”+x); // Here we are writing message in double quotes then passing variable x. Both statements indicates that output is 0.

  • If you are trying to use local variable without initialization then we will get compile time error.

Note- Static keyword is not applied to local variable.

How to print the value of Global variable

How to access the global variable outside of class.

  • Step-1 Create another class.
  • Step-2 Create the object of that class.
  • Step-3 Call the variable

public class GlobalDemo {

int x ; //declaration of global variable

int y=10; //initalization of global variable

public static void main(String[] args) {

GlobalDemo globalDemo= new GlobalDemo(); //this is the way to create the object of class-globalDemo this is the object name

//how to print the value of variable- objectname.variablename

System.out.println("value of y variable is>>"+globalDemo.y);

}

}

public class Test {

public static void main(String[] args) {

GlobalDemo globalDemo= new GlobalDemo();

System.out.println(globalDemo.y);

}

}

Output

value of y variable is>>10

Example- Declaring variable for different data types

int a;

byte b;

short s;

long l;

float f;

boolean b1;

char ch='v';

Example- Initialize variable for different data types

int a=5000;

byte b=50;

short s=500;

long l=50000;

float f=2.5f;

boolean b1=false;

char ch='v';