-1

I created my class (exending Activity) with an attribute int a.
The attribute is automatically initialized to 0 in the method onCreate().

Is it normal?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Bazouk55555
  • 557
  • 6
  • 24
  • 1
    if you do not assign some value to `int` attribute, it is initialized at construction time to value `0` by default. Activity's life-cycle method `onCreate(...)` is invoked later, so if you are not assigning some value in `onCreate(...)`, the default value is used. – matoni Aug 28 '17 at 17:07

3 Answers3

2

This is normal. You see, "int" is a primitive type. It is not an object, and so, it cannot hold a "null" value. If you want your variable to be null at onCreate(), you must change its type to the Object representation of it. The "Integer" class represents the primitive type "int".

Ortiz
  • 294
  • 1
  • 4
  • 14
1

in the method onCreate().

No, it's not initialized in onCreate(). It's initialized when object of your class is instantiated.

0

Yes it is. Variable of int is primitive type can only hold numeric values and unless you initialize it other way it will be assigned 0 (contrary to i.e. Integer which can also be null).

See docs:

https://docs.oracle.com/javase/tutorial/java/javaOO/index.html https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
1

From Official Java Tutorial:

Fields that are declared but not initialized will be set to a reasonable default by the compiler.

Check default values for each data type: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

Akshar Patel
  • 8,998
  • 6
  • 35
  • 50