1

I'm kind of confused about the outputs.

This is the first program.

class A {
    private int price;
    private String name;

    public int getPrice() {
        return price;
    }
    public String getName() {
        return name;
    }
}

class B {
    public static void main(String[] args) {
        A a = new A();
        System.out.println(a.getName());
        System.out.println(a.getPrice());
    }
}

This program compile without error. And the variables have values.

output -

 null
 0

Second program is,

class B {
    public void value() {
        int x;
        System.out.println(x);
    }
}

This program won't even compile.

B.java:4: error: variable x might not have been initialized

The question is why these variables act different? What is the reason. This may be a very simple question. But kindly explain me.

Thanks.

  • int is a primitve value while String is a reference. – user Jun 22 '15 at 18:51
  • [This answer](http://stackoverflow.com/a/30820127/335858) is for C#, but the same idea applies to Java: use of uninitialized local is probably a bug, and it is easy to detect; use of uninitialized member is also probably a bug, but it's so hard to detect that it's not worth the effort. – Sergey Kalinichenko Jun 22 '15 at 18:52

1 Answers1

8

Instance variables are declared inside a class. not within a method.

class A {
   private int price; //instance variable
   private String name; //instance variable
}

And instance variables always get a default value( integers 0, floating points 0.0, booleans false, String / references null).

Local variables are declared within a method.

class B {
   public void value() {
       int x; // local variable
    }
}

Local variables must be initialized before use.

 class B {
           public void value() {
               int x = 2; // initialize before use it.
               System.out.println(x);
            }
        }
Dhanuka
  • 2,826
  • 5
  • 27
  • 38