19.7k views
0 votes
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

User GatesDA
by
5.2k points

1 Answer

7 votes

Answer:

Final variable x is not initialized.

Step-by-step explanation:

In this JAVA code we have a final variable named x.The thing with final variable is that they act like constants in C++.Once initialized cannot be changed after that and we have to initialize them at the time of declaration.

In JAVA if we do not initialize the final variable the compiler will throw compile time error.Final variables are only initialized once.

User Penny Liu
by
4.7k points