Skip to main content

Posts

Showing posts with the label Class variables

How to initialize variables in Java?

Initializing your variables to proper value is must because it pays you better to initialize your variables properly while declaring them. If you don't initialize the variables then either they will cause compiler error or will be initialized with default values. Getting a compiler error for uninitialized variable is better because it will result in making you properly initialize your variable but if you are careless then you may initialize your variables to null to avoid the compiler error. The variables which will result in compiler error are method local and final variables. The problem with null initialized variables is that they will cause NullPointerException if you forget to initialize them even by the time you try to access them. The biggest issue here is that the JVM does not point out the variable which is Null. You need to debug your Java application to be able to find the variable which caused NullPointerException.

What are class variables in Java?

The class variables must have the keyword static as the modifier and are declared inside a class body but outside of any method bodies. Only one copy of class variables are created from the point the class is loaded into the JVM until the the class is unloaded, regardless of the number of object instances that are created from that class. If one object instance of that class changes the value of a class variable then all the other instances see the same changed value. You access a class variable directly through the class or through an object instance. Accessing a class variable through the class by specifying the name of the class, followed by a dot, followed by the name of the variable . Class variables can be initialized by an assignment statement . Unassigned declaration of  class variables will get the default value as instance variables. Class variables are  not serialized. Static method can access static variables and can't access in...