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
}
}
In questa pagina del sito puoi guardare il video online Static & Instance Variable in Java della durata di ore minuti seconda in buona qualità , che l'utente ha caricato JavaTwist 25 maggio 2022, condividi il link con amici e conoscenti, su youtube questo video è già stato visto 9 volte e gli è piaciuto 0 spettatori. Buona visione!