Global, Local, Static variables

지니🧸·2023년 4월 14일
0

Java

목록 보기
9/13

Local variable

  • declared inside the body of the method
  • can be only used within that method
  • other methods in class aren't aware of variables' existence
  • can't be declared as static

Instance variable

  • declared inside the class but outside the body of method
  • can't be declared as static

Static variable

  • declared as static
  • can't be local
  • only variables that static methods can access
    • static methods can access only static type data

You can create a single copy of the static variable and share it among all instances of the class. Also, memory allocation for static variables only occur once when the class is loaded in the memory.

Regular static variables are deemed as against object-oriented programming nature of Java, which recommends each object to have its own state represeted by an instance variable, because a static variable represents the state across instances. However, a final static variable, which is technically a constant, is not so against the OOP nature of Java.

Others

Global variable

Global variables in C: accessible in any function of the program & persists until the program comes to an end

  • OS stores global variables in Data area (not stack/heap)
  • initialized to 0 by default

Java does not have global variables because it is an Object Oriented Programming language. All variables in Java should either be local or a member of a class.


References

profile
우당탕탕

0개의 댓글