top of page

Subscribe to Wisdom

Thanks for Subscribing!

  • Writer's picturePuru Uttam

Global v/s Local Variables - Java

Variable : In programming, a variable is the name assigned to a memory location where values are stored. It is used to store data that may be changed and referenced.


There are basically 2 scopes of a variable i.e. Global & Local .

Now what is the difference between these 2 scopes of variable?

So here is the answer to that question.



//exmaple
int a;
String b;
long d;


Global variables:

  • As the name suggests, Global variables are those variables which are declared outside the method or function or block and can be accessed globally in that program.

  • Scope of them are within the program.

  • These are stored in the fixed data segment of memory which is decided by the compiler.

  • We can't declare anymore variables with same name inside the class.

  • These can be accessed by all the methods or functions of a class.

  • These variables are destroyed with complete execution of a program till that they remain in the program.

  • Change in their values or data can affect all the functions of a class where they are used.

  • Data can be shared among various functions of a class by using them.

  • They use memory till the execution of a complete program.

  • Zero is stored by default when not initialized.


//Global Variables are iQ and problemSolvingSkills, as they are defined at class level not in any function, but there value can be used anywhere in the functions.

class Developers
{
int iQ =120;
int problemSolvingSkills=100;

public int makeDeveloper(){
return iQ + problemSolvingSkills;
}
}


Local variables:

  • Local variables are the variables which are declared within the method.

  • Scope of them are limited within the method in which they are declared.

  • These are stored in the stack in memory.

  • We can declare as many variables with same name but inside different methods or functions.

  • These can be accessed by the method or function of a class in which it is declared which means no other function can access these variables..

  • These variables are destroyed after the complete execution of a function.

  • Change in their values or data only affect the particular function of a class in which they are used, not all the functions are affected .

  • Data can't be shared among various functions of a class by using them due to their limited scope.

  • They use memory for a limited time as they don't have to wait for the execution of a complete program.

  • A garbage value is stored when not initialized.


//Local variables are salary and bonus as their scope is limited to the method getTotalSalary().

class Employee
{
public int getTotalSalary(){
int salary =10000;
int bonus=100;
return salary + bonus;
}
}




Recent Posts

See All

Comments


Modern Digital Watch
bottom of page