Back-End/Java_1

[Java] Static_2

리딩리드 2016. 7. 26. 18:22

Static_2

- The static keyword in java is used for memory management mainly

- It makes your program memory efficient


1) Static variable

- The static variable can be used to refer the common property of all objects 

- The static variable gets memory only once in class area at the time of class loading


1_1. Understanding problem without static variable


- Suppose there are 500 students in my college

- All instance data members will get memory each time when object is created

- If we make it static, college field will get memory only once


1_2. Example

 

1_3. Program Counter

1) Without static variable

 

- Since instance variable gets the memory at the time of object creation, each object will have the copy of the instance variable

- If it is incremented, it won't reflect to other objects

2) static variable

 

2) Static method

- A static method belongs to the class rather than object of class

- A static method can be invoked without the need for creating an instance of a class

- static method can access static data member and can change the value of it


2_1. Example

1) change

 

2) Calculate

 


3) Restriction

- 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

 


 4) Why java main method is static?

Object is not required to call static method

- If it were non-static method, jvm create object first then call main() that will lead the problem of extra memory allocation


5) Java static block

- Is used to initialize the static data member

- It it executed before main method at the time of classloading

 


6) Can we execute a program without main() method?

- One of the way is static block but not in JDK 1.7