Static Keyword
In Java, static keyword is mainly used for memory management. It can be used with variables, methods, blocks and nested classes. It is a keyword which is used to share the same variable or method of a given class. Basically, static is used for a constant variable or a method that is same for every instance of a class.
Let's See How to Use Static Keyword.
import java.util.*; //predefine class
class Account
{
public double principle;
public double balance,totalBalance;
public static float sIntrest=5.5f; //declartionm variable in float and Static and we can use and initialize of static variable anywhere in file by variable location
public void simpleIntrest(double p,int t)
{
totalBalance=(p*sIntrest*t)/100;
System.out.println("intrest is : " +totalBalance);
}
}
public class StaticUse
{
public static void main(String [] args)
{
Account a1=new Account(); //with static variable we can save memory
Account a2=new Account(); //coz if we r create many time object of a class but static variable take memory one time when we create it.
// Account.cIntrest=5.5f; //u can initialize like this
System.out.println("Enter amount of principle : ");
Scanner sc = new Scanner(System.in); //Read value By User
double principle=sc.nextInt();
a1.simpleIntrest(principle,10);
a2.simpleIntrest(200,5);
}
}
Post a Comment