Find the output of Java programs | final Keyword | Set 1: Enhance the knowledge of Java final Keyword concepts by solving and finding the output of some Java programs.
Question 1:
public class Main {
final static int X = 10;
public static void main(String[] args) {
int Z;
int Y;
X = 20;
Y = 30;
Z = X + Y;
System.out.println(Z);
}
}
Question 2:
public class FinalEx {
final int X;
FinalEx() {
X = 10;
}
public static void main(String[] args) {
int Z = 0;
int Y = 20;
FinalEx F = new FinalEx();
Z = F.X + Y;
System.out.println(Z);
}
}
Question 3:
public class FinalEx {
final static int X;
public static void main(String[] args) {
int Z;
int Y = 20;
Z = X + Y;
System.out.println(Z);
}
}
Question 4:
public class FinalEx {
final int X;
final FinalEx() {
X = 10;
}
public static void main(String[] args) {
int Z;
int Y = 20;
FinalEx F = new FinalEx();
Z = F.X + Y;
System.out.println(Z);
}
}
Question 5:
final class Sample {
static void sayHello() {
System.out.println("Hello World");
}
}
public class Main: Sample {
public static void main(String[] args) {
sayHello();
}
}
Answer Question 1:
Output:
Explanation:
The above program will generate syntax error because here we created a variable X initialized with 10. And we changed the value of X in the main() function but we cannot change the value of the final variable because the final keyword is used to create constants in Java.
Answer Question 2:
Output:
Explanation:
In the above program, we created a class FinalEx that contains a data member X using the final, and we initialized X with 10 in the constructor.
Now look to the main() method, here we created two local variables Y and Z initialized with 0 and 20 respectively, and we created the object of FinalEx class.
Now look to the below expression,
Z = F.X + Y; Z = 10 + 20; Z = 30;
And then finally we print the value of Z on the console screen.
Answer Question 3:
Output:
Explanation:
The above program will generate syntax error because we cannot create an uninitialized final variable in Java.
Answer Question 4:
Output:
Explanation:
The above program will generate syntax error because we cannot use the final keyword with the constructor of the class.
Answer Question 5:
Output:
Explanation:
The above program will generate syntax error because here we use a colon ":" operator to inherit Sample class into Main. We need to use the extends keyword for inheritance in Java.
need an explanation for this answer? contact us directly to get an explanation for this answer