Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static variables, what is their life span?

Tags:

java

android

I am using static variables in my app, lots of them. My question is, when I exit the app will they be still in memory..? If yes, how can I correct this. Thanks in advance.

like image 258
Rookie Avatar asked Jun 21 '12 08:06

Rookie


People also ask

What is scope and lifetime of static variable?

A static variable stays in the memory and retains its value until the program execution ends irrespective of its scope. Scope is of four types: file, block, function and prototype scope. Lifetime is of three types: static, auto and dynamic lifetime.

What is life of static variable in Java?

A variable which is declared inside a class, outside all the blocks and is marked static is known as a class variable. The general scope of a class variable is throughout the class and the lifetime of a class variable is until the end of the program or as long as the class is loaded in memory.

What is the lifetime of a variable?

The lifetime of a variable is the time during which the variable stays in memory and is therefore accessible during program execution. The variables that are local to a method are created the moment the method is activated (exactly as formal parameters) and are destroyed when the activation of the method terminates.

Are static variables permanent?

static is a variable. The value can change, but the variable will persist throughout the execution of the program even if the variable is declared in a function.


2 Answers

For the Next Readers of this question-

As Everybody said in the answer that static variables are class variables. They remain in the memory until the class is not unload from JVM.

In Android you have seen that when we close any application then it does not close completely, It remains in the recent application stack, That you can see by long press the home button(On Most Devices).

 Android itself kicked out those recent apps when the other app needs memory

In Android, static variable unload when-

 -You force stop your app.
 -Application crashes.
 -You clear your app data.
 -Switch off your Device.
 -Android kicked out recent app  
like image 32
T_V Avatar answered Oct 23 '22 06:10

T_V


Static variable gets loaded when class is loaded by ClassLoader, and would be removed when it is Unloaded

like image 181
jmj Avatar answered Oct 23 '22 06:10

jmj