+ 1

Why is 1 the answer here?

Could anyone explain why the output of this is 1? public class A{ int i; public A(){i++} public void count(){ System.out.print(i); } } public class Program{ public class void main(String[] args){ A obj1 = new A(); A obj2 = new A(); obj2.count(); } } I would expect an error, as i is declared but not initialised anywhere. So value of i would be undefined. Then in the constructor of A, when we try to do i++, that is i = i +1 = undefined + 1. As far as I know doing arithmetic on undefined results in an error. Am I wrong here? And why?

28th Jul 2019, 8:41 AM
Mate Krisztian
Mate Krisztian - avatar
2 Antworten
+ 1
Ok, the irony of finding the answer yourself straight away after you post the question is present here. As it turns out, declared but not initialised variables will get a default value in java. The default value for int is 0. Then because i is an instance variable, separate for each objects: initial value for i after creation of obj2 is 0 (similarly to obj1) and only the instace variable of obj2 is increases by .count() method. so obj2.i is 1 http://www.c4learn.com/java/java-default-values/
28th Jul 2019, 9:07 AM
Mate Krisztian
Mate Krisztian - avatar
+ 1
C, C++ and Java (as far I know) don't have the integer value undefined. Undefined values are usually set to zero. That's all...
28th Jul 2019, 9:11 AM
Aaron Eberhardt
Aaron Eberhardt - avatar