Home
Calculator
Algebra
Fun Games
Geometry
Interactive
Trigonometry
Good Links
Home
Calculator
Algebra
Fun Games
Geometry
Interactive
Trigonometry
Good Links

Variable Scope in Java

Variable declaration in class vs. method

Example of variable scope code

Run the Java code example below and you will run into no problems. As you can see the highestScopeStr can be accessed in the main method, the ScopeTest() constructor (using the keyword 'this').
public class ScopeTest {
	String highestScopeStr ="high scope";
	
	ScopeTest(){
		String mediumScopeStr="medium level";
		System.out.println("mediumScopeStr from withint ScopeTest"+ mediumScopeStr);
		System.out.println("this.highestScopeStr "+ this.highestScopeStr);
		
	}
	
	public static void main(String[] args){
		ScopeTest st = new ScopeTest();
		System.out.println("st.highestScopeStr "+ st.highestScopeStr);
		//System.out.println("mediumScopeStr main  "+ mediumScopeStr);	
	}
	
}
Output:
mediumScopeStr from withint ScopeTestmedium level
this.highestScopeStr high scope
st.highestScopeStr high scope
Now let's uncomment the one line above and see what happens
public class ScopeTest {
	String highestScopeStr ="high scope";
	
	ScopeTest(){
		String mediumScopeStr="medium level";
		System.out.println("mediumScopeStr from withint ScopeTest"+ mediumScopeStr);
		System.out.println("this.highestScopeStr "+ this.highestScopeStr);	
	}
	
	public static void main(String[] args){
		ScopeTest st = new ScopeTest();
		System.out.println("st.highestScopeStr "+ st.highestScopeStr);
		
		   System.out.println("mediumScopeStr main  "+ mediumScopeStr);
	}
}
 Output
 Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	mediumScopeStr cannot be resolved