Can You Change a Static Variable in Java

Static Variable in Coffee | Generally, when we create a class, we don't know annihilation until we create an object of that course using the new keyword.

Once the object of class is created, information storage is created and methods get available.

Sometimes, we need a method that is not associated with any particular object of the class and tin phone call even if no objects are created.

For this purpose, we can fulfill both needs with the assistance of static keyword in Java.

When nosotros declare a fellow member as static, it means that it is not tied to whatever particular object of that course. Information technology tin be accessed earlier whatsoever objects of its form are created and without reference to any object.

We tin can declare methods, variables, and blocks to exist static. The about common case of a static member inside a course is primary( ) method.

main( ) method is declared every bit static because information technology must be chosen before any objects be.

In this tutorial, we volition comprehend the post-obit topics 1 by ane based on the static keyword in coffee.

  • Static keyword in Coffee
  • Features of static keyword
  • Utilize of static keyword
  • Static variable (Course variable) in Java
  • How to access static variable
  • Static variable initialization
  • Utilise of static variable
  • Tin can we access instance members from the static area directly?
  • Tin we admission static variables from case and static methods?
  • How to access static variables in Coffee from another course?
  • Difference between Static variable and Instance variable.

Static Keyword in Java


In Java, static is a keyword that is used for retention management mainly. Static means single copy storage for variables or methods. The members that are declared with the static keyword inside a course are called static members in java.

These members can be accessed even if no instance of the course exists considering static members are non tied to a detail instance. They are shared across all instances of the class.

Features of Static Keyword in Coffee


There are several important features of static keyword in java that must continue in mind. They are as follows:

1. Static keyword in Java can be applied with variables, methods, inner classes, and blocks.

2. We cannot declare a class with static keyword but the inner class can exist declared as static.

3. It belongs to the class than an instance of the class.

iv. I basic dominion of working with static keyword is that we cannot directly call instance members within the static area because the static members are linked with the form.

v. Static members get memory once when the class is loaded into the retentiveness. Merely instance members get the retentivity after the object cosmos of the class.

Therefore, when we phone call an instance member within the static area, it means that when a class is loaded into the retention, the static fellow member likewise loaded into the memory.

After loading, it will look the instance member in its class that is non in existence because nosotros have not created any object till now. Hence, there is ambivalence.

For example:

public class SaticTest   {    private int a = 10; // Instance field.  public static void main(String[] args)  {     int b = a; // error: won't compile.   }  }

Here, main method is static. So, we cannot admission the instance variable a. However, we tin can access static methods or fields from the instance method.

Employ of Static Keyword in Java


There are mainly two uses of java static keyword that are as follows:

ane. The main purpose of using static keyword is that we tin can access the data, method, or cake of the class without whatsoever object cosmos. Let's understand it with a elementary example.

As you know that the main method is static in Java because the object is not required to call the static method. If it is a non-static method then JVM will create an object beginning and and so it will telephone call the main() method which creates the trouble of an extra memory location.

2. It is used to make the programs more than retentivity efficient.

Static Variable (Class variable) in Java with Example


If nosotros declare whatsoever instance variable with a static modifier, it is known as static variable in java. A static variable is too known equally class variable in coffee. It stores the value for a variable in a mutual memory location.

The static variable can be alleged in coffee program as follows:

Access_ modifier  static variable_name;  For example: one. static int num;  // Default access modifier.    2. private static int age; // Private admission modifier.

When nosotros declare an case variable in java, a dissever re-create volition exist created for every object. Merely in the case of a static variable, a single copy is created at the form level and shared by all objects of that class.

Key point: A local variable cannot exist declared as static. JVM will display modifier error at compile time.

How to access Static variable in Java?


In that location are 2 ways to access a static variable in Java. They are as follows:
1. A static variable can be accessed within any other class using the class name. The general syntax to access a static variable is every bit follows:

A.ten; // A is the class name and "x " is a static variable alleged in that class.

2. Static variables can besides be accessed past the object reference but an instance variable can simply be accessed past the object reference. For case, We have a grade named Student. We tin create the object of the Educatee class like this:

Educatee s = new Student();   s.x;

Let u.s.a. have an example program where we will declare a variable as static and admission it by using class name and object reference variable.

Program source code i:

package staticVariable;  public class Student  {  // Declare a static variable id having data type int and assign it the value 20.    static int id = 20;  public static void principal(String[] args)   {  // Create an object of the class Student.      Student south = new Student(); // Call static variable using object reference variable south and store information technology by variable 10 with information blazon int.       int 10 = s.id; // Impress on the console.      System.out.println(10); // Now Phone call static variable id using the grade name.      System.out.println(Student.id);    }  }
Output:         20         20

As you tin can meet in the above program, we printed the value of id past using object reference and form name.

Static Variable Initialization


There are the following of import points to go on in mind about static variable initialization in Coffee. They are:

1. When a course is loaded into the memory at runtime, the static variable is created and initialized into the common retentiveness location only once. In other words, it gets loaded into the memory at the time of class loading.

ii. Static variables in a class are initialized before the creation of any case of that class.

3. Static variables in a course are initialized before the execution of any static method of the class. Therefore, we cannot change the initialized value of the static variable inside the static method.

4. If any object changes the value of the static variable, information technology volition retain its value and increments past i for every object creation.

Permit's create a program where nosotros volition initialize a static variable ten is equal to 0 and increment static variable by 1 for each object creation. Expect at the source lawmaking to empathise better.

Programme source code 2:

package staticVariable;  public class Counter  {    static int x = 0; // Information technology will get memory but once and retain its value.    Counter()    {       x++; // Information technology will increase the static variable past 1 for each object cosmos.    }  void display()  {     Arrangement.out.println(x);  }  public static void main(String[] args)  {      Counter c1 = new Counter();       c1.brandish();      Counter c2 = new Counter();       c2.display();      Counter c3 = new Counter();       c3.brandish();    }  }
Output:          1          2          iii

The flow of execution of the above program is shown in the below effigy.
Static variable in Java

Caption:

1. When the above lawmaking will exist executed, the static variable 10 will set to nothing when the class is offset loaded in the memory by JVM earlier any counter instances are created.

When a counter instance is created, the counter constructor executes and increments the static variable past 1 and upshot is 1.

ii. When the second object is created, counter constructor again executes and increments the static variable past 1. At present, result is two.

3. Similarly, when the third object is created, the result will be 3.

Now imagine what would happen in the above programme if x is an instance variable i.e. non-static variable and creating three counter objects in the main() method, then the upshot will exist as follows:

Output:              1              i               1        

Uses of Static variable in Java with Example


The most common use of a static variable in a course is to agree predefined constant or unchanging values that are the aforementioned for all the instances of the class and will never modify during the execution of the program.

Let'due south understand the concept with the aid of an example programme.

Program source code 3:

package staticVariable;  public class Employee  {  // Declare instance variables.     String proper noun;     int id;  // Declare a static variable companyName with data type String and assign value IBM which is common for all the objects.      static Cord companyName = "IBM";   // Declare a two-parameter constructor with parameters named n and i.       Employee(Cord northward, int i)       {         name = north;         id = i;       }  // Declare an instance method display and print the output on the console.      void display()      {         System.out.println("Proper noun: "+name+ " " +"Id = "+id+ " " +"Visitor Name:"+ " " +companyName);      }  public static void primary(Cord[] args)  {  // Create the first object of the course and pass the two arguments with blazon string and int.      Employee east = new Employee("Shubh", 123);  // Phone call the brandish method using reference variable due east.       east.display();  // Similarly, create the second object of the class and pass the 2 arguments.       Employee e1 = new Employee("Deep", 321);       e1.display();     }  }
Output:         Name: Shubh         Id = 123         Company Name: IBM         Proper noun: Deep         Id = 321         Visitor Proper name: IBM

In this instance, companyName refers to the "mutual property" of all objects because companyName is a static variable and it will become retentivity merely once in a mutual memory location.

Can we access instance members from static area directly?


Instance members (not-static members) can be accessed only from case area directly. But nosotros cannot admission it from the static area directly.

In other words, nosotros cannot telephone call instance member from the static member because a static variable stores values into the memory before the object creation whereas an instance variable stores into the memory later the object creation.

Then, when we access case members by static members as they are non present in the memory, information technology volition give the compile-fourth dimension mistake.

Can we admission static variables from instance and static methods?


Aye, static members (static variables) can be accessed from both instance and static area (i.e. example and static methods) directly using the form proper name or without the class name. But outside the class, we can phone call only using class proper name.

Let'south make a program where nosotros volition admission a static variable from both instance and static methods.

Program source code 4:

package staticVariable;  public form Exam  {  // Case area.     int a = x; //Instance variable.      static int b = 30; // Static variable  // Declare an instance method.      void m1()      {  // We can call example variable directly from instance expanse without any object reference variable.       System.out.println(a); // Call static variable directly from instance area.       System.out.println(b);      }  static void m2()  {  // Static area.  // We cannot call instance fellow member from static expanse.      Organization.out.println(a); // Hither, compile time error considering at this fourth dimension, the object of the class is not created. then we cannot call the case variable using object reference variable.   }  public static void main(String[] args)  {    // Static area.       Test t = new Test(); // Object creation.        t.m1(); // Here, nosotros can call case member using object reference variable t in the static expanse.       Arrangement.out.println(t.a);        m2();     }  }
Output:          10          30          x          Compile time mistake

How to access static variable in Java from another class?


We tin can access a static variable in Coffee by using grade proper name from another class. Let'due south have an example program related to this concept.

In this example, we will declare static variables in a class Calculation and call them in another class CalculationTest using the class proper name.

After that, we will perform a uncomplicated improver and subtraction operation and print output on the console.

Plan source code five:

packet staticVariable;  public grade Calculation  {    static int ten = 20;    static int y = thirty;  } public grade CalculationTest  {   void addition()   {  // Call S.V. using class name.      int a = Adding.ten; // Since the returning value is an integer, we will store it by using a variable a of type int.      int b = Calculation.y;      int c = a + b;      System.out.println(c);   }  void subtraction()  {    int p = Calculation.x;    int q = Adding.y;    int r = p - q;    Organisation.out.println(r);  }  public static void main(Cord[] args)  {     CalculationTest CT = new CalculationTest();      ct.addition();      ct.subtraction();   }  }
Output:         l        -x

How to modify value of static variable?


We can modify the value of the static variable in java past using a constructor and static block just non inside a static method.

Let's make a program and change the value of static variables from constructor, static block, static, and instance methods.

Program source code 6:

package staticVariable;  public class Demo  {     static int a = twenty;     static int b = 50;     static int c = 100;  Demo()  {    a = three; // Inverse value of variable.   }  static  {    b = ten;  }  void m1()   {      Organisation.out.println(a);      System.out.println(b);      System.out.println(c); // Information technology volition print 100.   }  static void m2()  {    c = 200;   }  void m3()  {     c = 200;  }  public static void master(Cord[] args)  {     Demo d = new Demo();     d.m1();   }  }
Output:         3         ten         100

Advantage of Static variable in Java


Class variable makes program memory efficient. That is, it saves memory. All static variables are stored in PermGen space of the heap retentiveness.

Difference between Static variable and Instance variable


There are the following differences betwixt static variable (course variable) and case variable.

ane. A static variable is as well known every bit form variable whereas, instance variable is also known as non-static variable.

2. Class variable can be accessed within a static block, instance block, static method, instance method, and method of the inner class whereas, instance variable can be accessed within the case block, instance method, and method of the inner class.

3. Class variable is always resolved during compile time whereas, instance variable is resolved during the runtime.

four. Information technology is not serialized in Coffee whereas, instance variable is serialized in Java.


Primal Points:

1. Static variable (also known as class variable) in Java is simply like another variable but it is mutual to all instances of the course.

2. It tin be accessed and modified by any other objects of grade.

3. A static variable can exist directly accessed by class proper name within static and non-static methods of the class.

four. It can exist used with public and final modifiers to make constant value.
Thanks for reading!!!
Next ⇒ Static method in Java

⇐ Prev Next ⇒

wootonsirle1977.blogspot.com

Source: https://www.scientecheasy.com/2020/06/java-static-variable.html/

0 Response to "Can You Change a Static Variable in Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel