Local Variables in Construct versus in Method Body

AI Thread Summary
Local variable declarations in Java must adhere to specific rules, particularly regarding reserved keywords. The discussion highlights a compiler error in Eclipse when attempting to declare a variable named "final" inside an if statement, which is not allowed since "final" is a reserved keyword in Java. It clarifies that local variables can be declared within a block but only exist within that block's scope. The confusion arose from a misunderstanding of local variable declaration rules. Ultimately, the issue was resolved by recognizing the restriction on using reserved words as variable names.
friendbobbiny
Messages
49
Reaction score
2
I've posted a method below.

I'm experimenting with local variable declarations in java. Actually, a compiler error in eclipse has made me reconsider what I understand about local variables. Why can't the local variable, String final, be created inside my if statement? Why, instead, would Eclipse recognize final if it were declared before the if statement.

In the previous two questions, I questioned the rationale behind a rule. Is my understanding of the rule even correct? My memory suggests otherwise -- declaring local variables in a construct should be possible.

If it makes any difference, although I doubt it, I created the method under a class that inherits another class.

public String getShortDate(){
String need = "0";
String temporary;
if( getMonth() < 10){
temporary = String.valueOf(getMonth());
String final = need + temporary;
int month = Integer.parseInt(final);
}
 
Physics news on Phys.org
You can declare a variable inside the { ... } block after an if statement, but the variable only exists inside that block, not for the rest of the function.

But "final" is a reserved keyword in Java. You can't declare a variable called "final" anywhere in a Java program, just like you can't declare a variable called "if" or "int".

Here's a complete list of the reserved words. If you are just starting to learn Java, don't worry about what they all mean - just don't try to use them as variable names! http://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html
 
Last edited:
  • Like
Likes 1 person
yes that solved it
thanks
 

Similar threads

Replies
3
Views
1K
Replies
3
Views
2K
Replies
2
Views
1K
Replies
12
Views
3K
Replies
1
Views
2K
Replies
1
Views
1K
Replies
3
Views
2K
Back
Top