4 Static in Java
4 Static in Java
CSA6003T
BHAWANA BOTHARA
ASSISTANT PROFESSOR
LEARNING OBJECTIVES
• The static keyword in Java is used for memory management mainly. We can
apply static keyword with variables, methods, blocks and nested classes. The
static keyword belongs to the class than an instance of the class.
THE STATIC CAN BE:
• There are two main restrictions for the static method. They are:
• The static method can not use non static data member or call non-static method directly.
• this and super cannot be used in static context.
public class MathUtils {
• Overuse of static methods and variables can lead to code that is difficult to
maintain and test.
• Static methods cannot be overridden.
• Static methods cannot access instance variables directly.
• Misunderstanding the lifecycle and scope of static members.
REVIEW AND SUMMARY
• The static keyword is used for memory management and belongs to the
class.Static variables and methods can be accessed without creating an
instance.Static blocks are used for static initialization.Understand the
differences between static and non-static members.Be mindful of common
pitfalls associated with static usage.
ASSESSMENT
1. What is true about static variables?
a) They are shared among all instances of a class.
b) They are created with each new instance.
c) They can be accessed only through objects.
d) None of the above.