-6
public class A {
static void print(){
    int i=10;
    System.out.println("i="+i);
}
void show(){
    int j=20;
    System.out.println("j= "+j);
}
public static void main(String[] args) {
    int f=87;
    A a =new A();
    print();
    a.show();
    System.out.println(a.f); //compile error.
}

}

Can someone explain why i and j can be printed but f is giving compile error when i,j and f are local variables inside a method ? Thank you all for the initial replies.

Yathish
  • 9
  • 4

3 Answers3

4

f is a local variable within the main method, it is not a class-level variable in A.

Gaël J
  • 11,274
  • 4
  • 17
  • 32
Stultuske
  • 9,296
  • 1
  • 25
  • 37
  • public class A { static void print(){ int i=10; System.out.println("i="+i); } void show(){ int j=20; System.out.println("j= "+j); } public static void main(String[] args) { int f=87; A a =new A(); print(); a.show(); //System.out.println(a.f); //compile error. } }Above i and j are also local variables within method right.It can be printed.Just not clear why in main method it can't be printed ?.Thank you. – Yathish Dec 27 '15 at 10:23
  • Yes, I know, and the reason for that is explained in my answer to which you are replying. – Stultuske Dec 27 '15 at 10:24
1

Like other people answered f is local. To access it in class level do like this:

public class A {

    private int f;

    public A(int _f) {
        f = _f;
    }

    public int getF() {
        return f;
    }

    public static void main(String[] args) {
        int ff = 87;
        A a = new A(ff);
        System.out.println(a.getF());
    }
}
Guy
  • 46,488
  • 10
  • 44
  • 88
0

You seem to be thinking f is a class level (static) variable in the A class. This is flawed; it is a local variable in your main function. To access it inside that method and print it just type f since it is in your method.

Mario Ishac
  • 5,060
  • 3
  • 21
  • 52