Local Variables in Construct versus in Method Body

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
2 replies · 2K views
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   Reactions: 1 person
yes that solved it
thanks