how default constructor in java gets called?

89 views Asked by At
public class Hello {

  int i;
  char ch;
   Hello(int x){
    i=x;

   }
    Hello(char c){
     ch=c;
     }  

   public static void main(String[] args) {
  Hello h=new Hello(1);
   System.out.printf("value of i  is %d"+"value of ch is %c",h.i,h.ch);
   //Hello h=new Hello('T');
   //System.out.printf("value of i  is %d"+"value of ch is %c",h.i,h.ch);
    }

O/p is :value of i is 1value of ch is

my question is why ch value is not initialized ?? while if the other case O/p is:value of i is 0 value of ch is T why in this case i is initialized.??

4

There are 4 answers

2
MSD On BEST ANSWER

As per this the default value for int is 0 and for char is '\u0000' (which is nothing but null) and that is what you are seeing.

0
biddyfiddy On

Java initializes an int to 0 and a char to the null character by default. Thus, System.out.println will make it seem as though there is no output for ch, but it technically has been initialized. In the first case, the second constructor is not run because Hello is created by passing in an int parameter, which calls the first constructor, and as a result ch is not set to anything. The commented code behaves in the same manner, but since i is initialized to 0 by default, System.out.println shows value of i is 0 value of ch is T

0
fcman On

In Java, the default value of the int primitive type is 0 while the default char is '\u0000', the null character. Which is why you aren't getting anything recognizable out of your int constructor for the value of ch.

2
OhBeWise On

You have two constructors for your class, one takes in an int and the other a char. Whichever you use to initialize an instance of your class, the other variable will use it's default value.

  • Type int defaults to 0.
  • Type char defaults to \u0000, the null character, as discussed here.

Therefore, when you call:

Hello h=new Hello(1);

your results are effectively:

h.i = 1;
h.ch = '\u0000';

While calling:

Hello h=new Hello('T');

effectively results in:

h.i = 0;
h.ch = 'T';