Preloader
Java
  • Estimated reading time: 1 Minute

Local variable is accessed from within inner class, needs to be declared final (java)

This issue is very common when you try to use a variable which needs to be accessed from another class !  Sometimes, you don't notice when this will happen, for example using a threadPool on cordova will need an inner class to be executed :

String password = "qweqwe";
String config = "MyObject";

cordova.getThreadPool().execute(new Runnable() { // we are executing a nested class !
	public void run() {
		try {
                        Session session = new Session();
			session.setConfig(config);
			session.setPassword(password);
				 		
		} catch (Exception e) {
			error(e.getMessage().toString());
			e.printStackTrace();  
		}
	}
});

The previous code will throw an exception because you are accesing config and password and it's not a final variable.

This issue can be easily fixed declaring the variable with problem as final.

// Note that you can declare final any kind of variable like objects, classes, numbers etc ...

final String password = "qweqwe";
final String config = "MyObject";

cordova.getThreadPool().execute(new Runnable() { // we are executing a nested class !
	public void run() {
		try {
                        Session session = new Session();
			session.setConfig(config);
			session.setPassword(password);
				 		
		} catch (Exception e) {
			error(e.getMessage().toString());
			e.printStackTrace();  
		}
	}
});

Although the solution is easy, if you don't know how to solve it ,it can be a really headache sometimes.

Share:
Carlos Delgado

Carlos Delgado

Senior Software Engineer at Corvix. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Related articles
Weekly trending
How Cloud-Based Tools Are Changing Video Production Collaboration
14 Sep, 2026
  • Estimated reading time: 7 Minutes
Top 10 Trusted iOS App Development Companies
14 Sep, 2026
  • Estimated reading time: 4 Minutes
How Technology Is Making China Supplier Management More Efficient
14 Sep, 2026
  • Estimated reading time: 6 Minutes
DeFAI Development: How to Build AI-Powered DeFi Solutions
14 Sep, 2026
  • Estimated reading time: 6 Minutes
Our Sponsors

Our blog is proudly supported by industry-leading sponsors.