Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Basics Perfecting the Prototype Censoring Words - Looping Until the Value Passes

Mariya Shklyar
Mariya Shklyar
1,022 Points

Can't understand how to fix "the bug".

Started to get lost around 3:15, when Craig says something like "Declare variable outside code. " and then, "Remove declaration because we want to talk about the same variable". Totally confused here. Please help. (I am a novice, so please use as many "human" words as possible).

1 Answer

Simon Coates
Simon Coates
28,694 Points

a variables has scope. It's duration and availability is within the {}, in which it is defined. Moving the declaration outside that {} meant that it was more broadly available. Making the variable available in the outer scope means that it can be used by the inner scope. As it already exists, it doesn't need to be declared by the lesser {}.

here's a demo:

class Main {
  public static void main(String[] args) {
    String y = "I am a string in an outer scope";//i persist until the function ends.

    //create a new inner scope using {}
    {
        //variables here exist and are visible within the nearest enclosing {}
        String x = "i am a string";
        System.out.println(""+x);
        System.out.println(""+y);
    }
    //System.out.println(""+x); //can't include this line. x is only available inside the inner {}
  }
}