Static & Instance Variable in Java

Veröffentlicht am: 25 Mai 2022
auf dem Kanal: JavaTwist
9
0

Static variable and Instance variable in Java:
A static variable is shared by all instances of the class, while an instance variable is unique to each instance of the class

A static variable is created only once when the classloader loads the class.

Syntax: static int x;

An instance variable is a property of an instance.

An instance variable is created everytime an instance is created.

Syntax: int x;



Example Code:

package p1;
class A{


int x=200; //instance variable


static int y=300;//static variable

}


public class B {

public static void main(String[] args) {
A a = new A();
A a1= new A();


System.out.println("The instance variable of object a is: " + a.x);//200
System.out.println("The instance variable of object a1 is: " +a1.x);//200


a1.x=500;
System.out.println("The changed value of instance variable of object a1 is: "+a1.x);//500


System.out.println("The static variable value of object a is: " + a.y);//300
System.out.println(" The static variable of object a1 is: " + a1.y);//300


a1.y=600;


System.out.println("Static variable values of object a and a1 is : "+ a1.y +" "+ a.y);//600 600




}
}
Static variable and Instance variable in Java:


A static variable is shared by all instances of the class, while an instance variable is unique to each instance of the class


A static variable is created only once when the classloader loads the class.


Syntax: static int x;


An instance variable is a property of an instance.


An instance variable is created everytime an instance is created.


Syntax: int x;


Example Code:
package p1;




class A{

int x=200; //instance variable


static int y=300;//static variable

}


public class B {

public static void main(String[] args) {
A a = new A();
A a1= new A();


System.out.println("The instance variable of object a is: " + a.x);//200
System.out.println("The instance variable of object a1 is: " +a1.x);//200


a1.x=500;
System.out.println("The changed value of instance variable of object a1 is: "+a1.x);//500


System.out.println("The static variable value of object a is: " + a.y);//300
System.out.println(" The static variable of object a1 is: " + a1.y);//300


a1.y=600;


System.out.println("Static varible values of object a and a1 is "+ a1.y +" "+ a.y);//600 600




}
}


Auf dieser Seite können Sie das Online-Video Static & Instance Variable in Java mit der Dauer stunde minuten sekunde in guter Qualität ansehen, das der Benutzer JavaTwist 25 Mai 2022 hochgeladen hat, den Link mit Freunden und Bekannten teilen, dieses Video wurde auf Youtube bereits 9 Mal angesehen und es wurde von 0 den Zuschauern gefallen. Viel Spaß beim Betrachtenden Zuschauern gefallen!