Global Variables vs Local Variables

Global Variables vs Local Variables

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

  1. At the Code below i declare a global variable “Globalinteger”
  2. I also declare a local variable inside Main
  3. I created a method called “printmethod()”
  4. In the printmethod() i declared a parameter called “inputValue”
  5. I passed the “inputValue” data into the “Globalinteger”
  6. At Main i called the method “printmethod();
  7. I pass a value”200″ into printmethod(200);
  8. 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

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

eleven − eleven =