1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Local Variables in Construct versus in Method Body

  1. Aug 18, 2014 #1
    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);
    }
     
  2. jcsd
  3. Aug 18, 2014 #2

    AlephZero

    User Avatar
    Science Advisor
    Homework Helper

    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: Aug 18, 2014
  4. Aug 18, 2014 #3
    yes that solved it
    thanks
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted



Similar Discussions: Local Variables in Construct versus in Method Body
Loading...