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 Objects (Retired) Meet Objects Privacy and Methods

Wait I don't get in. What is scope and return ?

I don't understand anything from this scope concept, I also cant understand what return means. Can someone plese help me

1 Answer

Simon Coates
Simon Coates
28,694 Points

scope is the section of code in which a variable is able to be accessed. In java it is usually defined by the {} in which the variable is defined. The return statement is able to be used to return a value from a method (eg. return true;), or - when the function is defined as void - just end the function by returning control to the calling code (eg. return;). I posted a small demonstration of scope a while back at https://teamtreehouse.com/community/cant-understand-how-to-fix-the-bug

Simon Coates
Simon Coates
28,694 Points
class Main {

  private String classScope = "I am available through this class";

  private String returnSomething(){
    String x = "a string - thus object type"; //x can only reference in this method,
    return x;
  }

  public void run() {
      System.out.println(classScope);
      String functionScope = "I am available through this function";
      System.out.println(functionScope);
      if(true){
        System.out.println(classScope);
        System.out.println(functionScope);
        String ifScope = "I exist inside my enclosing {}";
        System.out.println(ifScope);
      }
      //System.out.println(ifScope); //ifScope doesn't exist here.
      System.out.println(returnSomething());
  }
  public static void main(String[] args){
    Main m = new Main();
    m.run();
  }
}
Alex Popian
Alex Popian
977 Points

How do you add code to your comment?

Simon Coates
Simon Coates
28,694 Points

to format text as code, use three backticks on the line before the code and three on the line after the code. When you write a comment, i think there should be a link for the "Markdown Cheatsheet". This explains syntax you can embed in answers or comments.

Alex Popian
Alex Popian
977 Points

Thank you and you are right about the Markdown Cheatsheet!