tags:

views:

60

answers:

5

Why doesn't the following program return 0, since I am accessing p from a new A(), which has not had main called on it?

 public class A {

         public static int p = 0;

         public static void main(String[] args) {

                p = Integer.parseInt(args[0]);
                new B().go();

            }

        }


       class B {
            public void go() {
                System.out.println(new A().p);
            }
        }
A: 

That shouldn't even compile, since you're trying to assign an instance member from a static method.

Matti Virkkunen
+2  A: 
OscarRyz
good call. In the original code p is static. That probably resolves the issue.
George
I'd delete this question, but I can't.
George
@George: If you run it with `0` as argument, it prints `0` ;)
Felix Kling
the code i compiled had "static"
George
In that case.. mhhh nevermind :P You can always mark my answer as accepted and I'll in turn vote to close it.
OscarRyz
Thank you. So the key is the word "static" (which, ironically, is the one word that I must've erased when I pasted the code!)
George
Yeap. I have voted to close this as "not a real question" ( the reason: "not longer relevant" is not available anymore )
OscarRyz
A: 

This program doesn't compile. The compiler won't let you access 'p' from within the main method of class A. You cant access non static variables from within a static context. Hence the compilation issue

Harsha
Even if you define the variable 'p' to be static, still there is a run time exception `Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0`
Harsha
@Harsha: Probably because you don't call the code with an argument?
Felix Kling
A: 

That won't compile as is, so I don't know how it would return anything.

Variable p cannot be accessed from a static context is what it SHOULD say.

If you set an instance of p, it should work correctly.

ps. For this one experiment I will let you have a public non-final member variable, but NEVER AGAIN!

Bill K
A: 

EDIT: this was just a guess based on the first revision of the question, which assumes p is non-static. It turns out that the intent was that it is static, so this gets the wrong end of the stick.

Despite the compiler error, I assume your intent was to initialize p from a non-static method, or on an instance of A.

The problem is then that you are creating a new instance of A in B, and not using the original instance.

To get what (I believe) you want, do something like

   public class A {

         public int p = 0;

         public static void main(String[] args) {
                A a = new A();
                a.p = Integer.parseInt(args[0]);
                new B().go(a);
         }

   }


       class B {
            public void go(A a) {
                System.out.println(a.p);
            }
        }

Note that the go() method in B takes A as a parameter. No new instance of A is created.

mdma