Given the code below:
class Demo {                    
    static String s = "123";    
    static void m1(String s) {
        this.s = s;             
    }
    void m2(String s) {
        this.s = s;              
    }
}
class Hello {
    public static void main(String args) {
        Demo.m1("456");          
        Demo d = new Demo();       
        d.m2("789");         
    }
 }
I would like to know what is the difference between using an instance variable and a static variable regarding object creation:
- Given that string is immutable and variable s is static, how many objects are created for variable - s?
- Is a new object created when a static method such as - m1()is called?
- Is a new object created when an instance method such as - m2()is called?
Edited:
I had a wrong assumption about static keyword. Now I am clear about it.
- static is a keyword.
- It is used for declaring the members of the class.
- static members belong to class.
- Instance variables cannot be used in static context.
- this keyword cannot be used in static context.
- static members can be accessed without creating an object.
- Static variables come to life when class is loaded into the memory.
- this keyword can be used only to access instance members.
- this keyword is used to access the members of the class within the same class.
Thanks for helping. Below is the edited code:
class Demo {                    
    static String s= "123";  //Static variable
    String s1 ="abc"; // Instance variable  
    static void m1(String s) {
        Demo.s = s; //Accessing an static variable       
    }
    void m2(String s,String s1) {
        Demo.s = s; 
        this.s1 = s1;//Accessing an instance variable           
    }
}
class Hello {
    public static void main(String args[]) {
        Demo.m1("456");          
        Demo d = new Demo();       
        d.m2("789","xyz");         
    }
}
 
     
     
     
    