❮ Previous Next ❯

Java static Variable

Suppose there are 1000 students in SILAN Engineering College, now all instance data members will get memory each time when object is created. All student have its unique regdno and name so instance data member is good. Here, the property cname(college name) refers to the common property of all objects. If we make it static, this field will get memory only once.




Example;
package java8s;

class Student
{
      int regdno;
      String name;
      static String cname="SILAN";
     
      Student(int regdno, String name)
      {
            this.regdno=regdno;
            this.name=name;
      }
     
      void show()
      {
            System.out.println(regdno+""+name);
            System.out.println(cname);
      }
}

public class StaticExample1 {

      public static void main(String[] args) {
           
            Student s1=new Student(101,"Sidhant");
            Student s2=new Student(102,"Sonali");
            s1.show();
            s2.show();

      }

}

Output


static variable
❮ Previous Next ❯




Warning: include(../footer1.php): failed to open stream: No such file or directory in /home/java8s/public_html/java/static-Variable.php on line 151

Warning: include(../footer1.php): failed to open stream: No such file or directory in /home/java8s/public_html/java/static-Variable.php on line 151

Warning: include(): Failed opening '../footer1.php' for inclusion (include_path='.:/opt/cpanel/ea-php56/root/usr/share/pear') in /home/java8s/public_html/java/static-Variable.php on line 151