Interview Questions of Java-Variable
Q1. What is the difference between instance, local, and static variables in Java?
Solution:
Instance Variable: Belongs to an instance of the class. Each object has its own copy.
Local Variable: Declared within a method or block. Accessible only within that method or block.
Static Variable: Belongs to the class rather than any instance. Shared among all instances.
Q2. Can you declare and initialize a variable at the same time?
Solution: Yes, in Java you can declare and initialize a variable simultaneously.
Q3. What is the default value of an instance variable in Java?
Solution: Instance variables have default values depending on their data type. For example, int defaults to 0, boolean to false, and object references to null.
Q4. Can local variables have default values?
Solution: No, local variables do not have default values. They must be initialized before use.
Q5. How can you access a static variable in Java?
Solution: Static variables can be accessed directly using the class name without creating an instance.
Local Variable: Declared within a method or block. Accessible only within that method or block.
Static Variable: Belongs to the class rather than any instance. Shared among all instances.
Q2. Can you declare and initialize a variable at the same time?
Solution: Yes, in Java you can declare and initialize a variable simultaneously.
int a = 20;
String s = "Hello";
Q3. What is the default value of an instance variable in Java?
Solution: Instance variables have default values depending on their data type. For example, int defaults to 0, boolean to false, and object references to null.
Q4. Can local variables have default values?
Solution: No, local variables do not have default values. They must be initialized before use.
Q5. How can you access a static variable in Java?
Solution: Static variables can be accessed directly using the class name without creating an instance.
ClassName.variableName;