Prev Next

Java / Class Variables (Static Variables)

1. How do I define a constant?

Posted on Apr 1, 2016 by Senthil Kumar.

The variable should be declared with static and final modifiers. static ensures that only one variable exists for all instances of the class and final makes its value not changeable once initialized. static final int MAX_HEIGHT = 50;

Read full answer

2. What are static variables?

Static variables are class level variable where all instances of the class refer same variable. When an instance update its value, all the other objects will see the new value.

Read full answer

3. Explain static keyword in Java.

The static keyword can be applied to, static variables, static methods, static block, static inner class, and interface static method (introduced in Java 8).

Read full answer

4. What is a static class in Java?

A Class can be made static only if it is a nested class (class within a class). The nested static class can be accessed without having an object of outer class. It can access static data members of outer class including private. Static nested class cannot access non-static data member or method. ...

Read full answer

5. What is a static block?

A static block, is a block of code inside a Java class that will be executed when a class is first loaded into the JVM. Mostly the static block will be used for initializing the variables. Static block will be called only one while loading and it cannot have any return type also not have 'this' o...

Read full answer

6. Can we have multiple static blocks in a Java Class?

Yes, a Java class can have more than one static block. It will be executed in the same order as it appears.

Read full answer

7. Can Interface in Java have static methods?

Yes, since Java 8, interfaces can have static methods.

Read full answer

8. Can we overload static methods in java?

Yes, we can overload static methods in java.

Read full answer

9. Can we override static methods in java?

No, we can not override static methods in java.

Read full answer

10. Can we invoke a superclass static method from the subclass?

Yes. We can invoke it using the superclass name or subclass name.

Read full answer

11. Can we serialize static variables?

No,Static variables are shared variables and don't correspond to a specific object.

Read full answer

12. What is a static import?

Static imports allow us to import all static fields and methods of the class, you can access them without class name reference. static import is introduced in Java 5. import static java . lang . System . out; import static java . lang . Math .* ; class WithStaticImports { public static void main(...

Read full answer

13. Can we execute a program without main () method?

Yes, it is possible in previous versions of Java, not since JDK 1.7 using static block.

Read full answer

«
»

Comments & Discussions