Questions & Answers on Variables and Blocks

Block and Variable questions and answers will help you to clear concept and increase your knowledge on the previously discussed chapters. These questions can be asked in any interviews, college vivas etc. I hope you will learn something out of these questions and answers.

  1. What are local, static, instance variables in Java?
  • local- variables declared within a block, constructor or method.
  • static- variables declared within a class but outside of constructor, method and block with a static keyword.
  • Instance- variables present outside of any block without using any static keyword.

2. How to declare a constant in Java and what's the restriction for constant?

When a variable declared with the final keyword is called constant.

The restriction is that final variable should be initialized at the time of declaration.

3. What is the procedure for calling static, local and non-static variable?

Static: variable can be called using the class name, object name or directly in same class.
Local: variables are called directly.
Non-static: variables called by object name.

4. What are the different variables in Java?

Static, non-static, final, local, transient, volatile.

5. What are the different blocks in Java?

static and non-static.

6. What's static block?

Block declared using static keyword.

7. What's non-static block?

Block declared without static keyword.

8. If a variable is declared private where can it be accessed?

Within the same class.

9. Execution of non-static variables depends on whom?


10. When does a non-static block gets executed?

Before the calling of constructor by a user.

11. When is a static block executed?

Before the main method.

12. How many times can the blocks be executed?

Static: Once

Non-Static: Depends on User.

13. In case of a variable which special character is allowed?

_ (underscore)

14. When is variable declaration an error?

when it is not initialized.

15. How can static variables be accessed?

by class name, object name, and directly within the same class.

16. Where can local variables be accessed?

Within the same class where it is declared.

17. What is the purpose of declaring a variable as final?

When the value of the variable will not be changed throughout the entire program then it is declared as final.

18. Can you access a non-static variable from a static context?