Global Variables vs Local Variables
Global Variables vs Local Variables. In this article we will look into what is a global variable and what is a local variable in Java
Global Variable
- Global Variable Is a variable that can be share and access by all methods (function) . In Java they called it methods instead of function.
- Global Variable reside inside a Class.
Local Variable
- Can only used or access by a Single method
- Reside inside the method itself
Both Global and Local variable can be used simultaneously to pass data from one method to the other.
Refer the Code below
- At the Code below i declare a global variable “Globalinteger”
- I also declare a local variable inside Main
- I created a method called “printmethod()”
- In the printmethod() i declared a parameter called “inputValue”
- I passed the “inputValue” data into the “Globalinteger”
- At Main i called the method “printmethod();
- I pass a value”200″ into printmethod(200);
- The result it print out the value 200.
Check out the Source Code Below
package firstproject; public class variables { static int Globalinteger; public static void main(String[] args) { int localinteger =400; System.out.println(localinteger); System.out.println(printmethod(200)); } public static int printmethod(int inputValue){ Globalinteger = inputValue; return Globalinteger; } }
Learn about Java Variables here
Leave a Reply