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
}
}
Sur cette page du site, vous pouvez voir la vidéo en ligne Static & Instance Variable in Java durée heure minute seconde en bonne qualité , qui a été Téléchargé par l'utilisateur JavaTwist 25 mai 2022, Partagez le lien avec vos amis et connaissances, sur youtube cette vidéo a déjà été regardée 9 fois et il a aimé 0 téléspectateurs. Bon visionnage!