0
public class Test{
int i;
Test(){
    System.out.println(i);
}
public static void main(String[] args){
    Test obj=new Test();
    }
}

Output=0

P.S: I am naive in Java so this question could be very silly. I am expecting your support. Thanks

6
  • That's how Java is defined. Read the JLR -- the Java Language Reference -- for the details. Commented Mar 23, 2016 at 21:22
  • The default value of an int is 0 Commented Mar 23, 2016 at 21:22
  • When you declare an int as a "field" (class variable), It initialize automatically with value "0", but when belongs to other method, is "null" Commented Mar 23, 2016 at 21:50
  • @Abdelhak Instance variable belongs to Object and static variable belongs to class. In the above case variable i belongs to whom since there is no object and i is not a static variable. Commented Mar 23, 2016 at 22:21
  • Are you sure this program has any output? I would not expect it to. Commented Mar 23, 2016 at 22:41

2 Answers 2

1

Static/Instance fields which are not initialized will be set to a default value by the compiler.

The table bellow indicates the default value for data types:

+--------------------------+----------------------------+
|        Data Type         | Default Value (for fields) |
+--------------------------+----------------------------+
| byte                     | 0                          |
| short                    | 0                          |
| int                      | 0                          |
| long                     | 0L                         |
| float                    | 0.0f                       |
| double                   | 0.0d                       |
| char                     | '\u0000'                   |
| String (or any object)   | null                       |
| boolean                  | false                      |
+--------------------------+----------------------------+

For more information, you can see the doc here

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

Comments

1

See, every Instance-Variable or Class-Variable initialized by it's default value

In case instance-variable is some Reference type then it will be always assigned with it's default value by null

So, here in your case int is primitive type whose default value is 0(zero) that's the reason you get 0 in out-put.

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.