Static & Instance Variable in Java

Published: 25 May 2022
on channel: 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




}
}


On this page of the site you can watch the video online Static & Instance Variable in Java with a duration of hours minute second in good quality, which was uploaded by the user JavaTwist 25 May 2022, share the link with friends and acquaintances, this video has already been watched 9 times on youtube and it was liked by 0 viewers. Enjoy your viewing!