-1

Here is my code:

class Xyz{
   public static void main(String args[])
   {
      first fobj = new first(10);
      for(int i=0;i<5;i++){
         fobj.add();
         System.out.printf("%s",fobj);
      }
   }
}

class first{
   public int sum=0;
   public final int num;
   first(int x){
      num=x;
   }

   public void add(){
      sum+=num;
   }

   public String toString()
   {
      return String.format("sum = %d" ,sum);
   }
}


output:
sum=10
sum=20
sum=30
sum=40
sum=50

In the class first I didn't initialize a variable named "sum" but I still get output. Can someone explain that to me? asgfafgalsdfkjsaflkasflaskfalskfajlskfaskfaslkjflaskfaslkflasjkf.

3 Answers3

2

Instance members are automatically initialized to default values, JLS-4.12.5 Initial Values of Variables

Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10):

...

For type `int`, the default value is zero, that is, 0. 
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

Class and instance data members are automatically defaulted to the all-bits-off value for their type (0 in the case of int), even if you don't do it explicitly. Since sum is an instance data member, it's implicitly defaulted to 0.

This is covered by §4.12.5 of the Java Language Specification:

Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10.2):

  • For type byte, the default value is zero, that is, the value of (byte)0.
  • For type short, the default value is zero, that is, the value of (short)0.
  • For type int, the default value is zero, that is, 0.
  • For type long, the default value is zero, that is, 0L.
  • For type float, the default value is positive zero, that is, 0.0f.
  • For type double, the default value is positive zero, that is, 0.0d.
  • For type char, the default value is the null character, that is, '\u0000'.
  • For type boolean, the default value is false.
  • For all reference types (§4.3), the default value is null.
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

In Java, all the member variables are automatically initialized to their default values at the time of object creation even if you don't do it yourself. Default value of int is 0.

KodingKid
  • 971
  • 9
  • 14