Java Basics – local and global variables

Java does not have a global variable, but variables for the whole class known as fields. For all other values that are within a block, or within a method it is a local variable.

Question is when to use?

Class fields : can be used if this variable is always accessed by different methods and other classes. Just be careful its value may not be thread safe. Constant variables should also be declares as class fields.

Example:

public class test(){

 //this is a class field.

 int a = 1;

}

Local variable: variables that are used within method scope only. The variables is created once the method is called, then it is destroyed when the method exits.

Example:

public class test(){

 public void doSomething(){

  //this is a local variable

  int a = 1;

 }

}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s