What is wrong with the following code How should it be fixed

What is wrong with the following code? How should it be fixed?

1 public class H2ClassH {
2   final int x;
3
4   int H2ClassH () {
5     if (x == 7) return 1;
6     return 2;
7   } // end
8 } // end class H2ClassH

Solution

Answer:. we have to initialize final variable at the time of declaration

1 public class H2ClassH {
2   final int x;//final int x=6;
3
4   int H2ClassH () {
5     if (x == 7) return 1;
6     return 2;
7   } // end
8 } // end class H2ClassH

Note: Java discourage to use same method name as class name, but above code still work

Thanks a lot

What is wrong with the following code? How should it be fixed? 1 public class H2ClassH { 2 final int x; 3 4 int H2ClassH () { 5 if (x == 7) return 1; 6 return 2

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site