A class variable in Java is one whose scope is the complete class itself whereas a local variable is one whose scope is confined to the method enclosing it.
Generally, the two have the same name. The class variable is indicated by using the keyword 'this'. 'this' indicates that the variable being referred to belongs to this instance of the class.
An example of such an assignment would be:
class Hello{ (1)
String text = "Hello"; (2)
/*
*@This method sets the value of the String in the class
*/
public void setString(String text){ (3)
this.text = text; //Assign the value of the parameter String to the class variable. (4)
}
}
As is self evident, statement (4) will assign the value of a local variable to a class variable having the same name but differentiated by 'this' keyword.
There are different opinions on whether to use the same name for both variables. Some recommend using different names so as to avoid unambiguity. However, it is always a good practice to use the same name so as to not get too many variable names in the code. And since Java does provide a keyword 'this', it's always good to use it.
The only caution to be exercised is to be thorough with the concept of the 'this' keyword.