0
class Test {
    static int p;
    Test(int x) {
        p=x;
    }
}

class Mtest
{
    public static void main(String args[])
    {
        Test c[] = new Test [100];
        for(int i=0; i<5; i++) {
            c[i]=new Test(i);
        }

        for (int i=0; i<5;i++) {
            System.out.println(c[i].p);         
        }
}

OUTPUT: 4 4 4 4 4

What kind of sorcery is this? shouldnt it give me 0,1,2,3,4??

1
  • 3
    Remove the static keyword from declaration of p, and see the magic. Commented Jan 20, 2014 at 19:01

4 Answers 4

4

You are using static field

static int p;

which is shared across class (not per instance)

if you want it per Object, remove static from declaration

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

1 Comment

There is only one p variable so it can have only one value, the last one.
0

Because p is static, i.e. field of the class, not of an object. So p is shared between all instances of class test. You should remove static from field declaration to achieve your result expectations.

Comments

0

You declared p as static. Remove it and it should word fine. Plus format your code following the java guidelines, it makes it much more readable.

Comments

0

Change static int p; to int p -> You're using class variables instead of instance variables.

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.