Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

There is two variable 'a' and 'b' which is not initialised. 'a' variable is of class Example1 and 'b' variable of class Main

Tags:

java

oop

There are two variables, a and b, which are not initialized. a variable is of class Example1 and b variable of class Main. As we know if we not initialized any variable in java then it take default value. But when I want to print variable of Main class it show error of initialization. But when I call the Example1 class variable then it executed successfully and gives default value.

What is the exact reason behind it?

class Example1 {
    int a;
}
public class Main
{
    public static void main(String[] args) {
        int b;
        Example1 e = new Example1();
        System.out.println(e.a);        // output: 0
        System.out.println(b);          // error: variable a might not have been initialized
        
    }
}
like image 827
Amol Kumar Pandey Avatar asked Sep 12 '25 19:09

Amol Kumar Pandey


1 Answers

When you write:

int b; // this is declaration

int b; is a local variable. Method local variables need to be initialized before using them. And this is why you've got an error.

When you write

 int b = 0; // this is initialization

When you write:

  Example1 e = new Example1();  // This is an initialization

Primitive default value is zero when declared as class members.

like image 138
StepUp Avatar answered Sep 14 '25 09:09

StepUp