Final Instance Variables QuizJ8 Home « Final Instance Variables Quiz

Java Objects & Classes Quiz 9

The quiz below tests your knowledge of the material learnt in Objects & Classes - Lesson 9 - Final Instance Variables.

Question 1 : What will be output from this code snippet?

public class FinalInstanceVar {
    final int i;
    FinalInstanceVar() {
        System.out.println(this.i);
    }
}
- The code snippet will not compile as final instance variables must be initialized before use.
Question 2 : An instance variable that is marked as final cannot be changed once it has been assigned a value?
- An instance variable that is marked as final CANNOT be changed once it has been assigned a value, in fact this will cause a compiler error.
Question 3 : What will be output from this code snippet?

public class FinalInstanceVar {
    final int i = 678;
    FinalInstanceVar() {
        System.out.println(this.i);
    }
    public static void main (String[] args) {
        FinalInstanceVar fiv = new FinalInstanceVar();
    }
}
- Code snippet will output 678.
Question 4 : An instance variable that is marked as final can be assigned a value from anywhere?
- An instance variable that is marked as final can only be assigned a value when defined or in its constructor.
Question 5 : What will be output from this code snippet?

public class FinalInstanceVar {
    final int i = 1;
    FinalInstanceVar() {
        this.i = 2);
        System.out.println(this.i);
    }
}
- When using the final access modifier once assigned a value can never be changed or you get a compiler error as in this case.
Question 6 : An instance variable that is marked as final must be assigned a value before first use?
- An instance variable that is marked as final MUST be assigned a value before first use or you get a compiler error.
Question 7 : What will be output from this code snippet?

public class FinalInstanceVar {
    final int i;
    FinalInstanceVar(int i) {
        this.i = i);
        System.out.println(this.i);
    }
    public static void main (String[] args) {
        FinalInstanceVar fiv = new FinalInstanceVar(1234);
    }
}
- The code snippet runs fine and outputs 1234.
Quiz Progress Bar Please select an answer


What's Next?

In the next quiz we test your knowledge of constructors basics and how we use them to instantiate objects of our classes.