0

How do i print the value of variable which is defined inside another method?

This might be a dumb question but please help me out as i am just a beginner in programming

public class XVariable {
    int c = 10; //instance variable

void read() {
    int b = 5;
    //System.out.println(b);
}

public static void main(String[] args) {
    XVariable d = new XVariable();
    System.out.println(d.c);
    System.out.println("How to print value of b here? ");
    //d.read();
}
}
2
  • 2
    You can't print the value of b since it is only accessible in that read method. I suggest you read about Java variable scopes. Try this website so that you can understand -> javawithus.com/tutorial/scope-and-lifetime-of-variables Commented Jul 4, 2019 at 8:46
  • Integer read() { return 5; //System.out.println(b); } Commented Jul 4, 2019 at 8:48

3 Answers 3

3

You can't. b is a local variable. It only exists while read is executing, and if read executes multiple times (e.g. in multiple threads, or via recursive calls) each execution of read has its own separate variable.

You might want to consider returning the value from the method, or potentially using a field instead - it depends on what your real-world use case is.

The Java tutorial section on variables has more information on the various kinds of variables.

Sign up to request clarification or add additional context in comments.

1 Comment

Maybe it's about time for Java in Depth :)
1

You need to return value from your read() methods.

public class XVariable {
    int c = 10; //instance variable

int read() {
    int b = 5;
    return b;
}

public static void main(String[] args) {
    XVariable d = new XVariable();
    System.out.println(d.c);
    System.out.println(read());
    //d.read();
}
}

Comments

0

Return b from the read method and print it

public class XVariable {
    int c = 10; //instance variable

    int read() {
        int b = 5;
       return b;
    }

    public static void main(String[] args) {
        XVariable d = new XVariable();
        System.out.println(d.c);
        System.out.println(d.read());
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.