Static are the members or variables which are defined independently of any object of that class. Static members are the members that can be used by itself, without reference to a specific instance. We can declare both methods and variables to be static. The variables declared as static are global variables. When objects of the class are declared, no copy of a static variable is made. Instead, all instances of the class share the same static variable.
Methods declared as static have several restrictions:
1. They can only call other static methods.
2. They must only access static data.
3. They cannot refer to this or super.
If we need to do computation in order to initialize the static variables, we can declare a static block which gets executed exactly once, when the class is first loaded.
import java.io.*; class StudentDetail { static int SrNo=1; int RollNo,sci,math; String Sname; void Setdata() throws IOException { BufferedReader bf=new BufferedReader(new InputStreamReader(System.in)); String str; int RollNo = SrNo; System.out.println("Enter Name of a Student : "); Sname=bf.readLine(); System.out.println("Enter Science Marks "); str=bf.readLine(); sci=Integer.parseInt(str); System.out.println("Enter Math Marks "); str=bf.readLine(); math=Integer.parseInt(str); SrNo++; } void ShowDetail() { System.out.println("Roll Number :"+ RollNo); System.out.println("Name : "+Sname); System.out.println("Science :"+sci); System.out.println("Math :"+math); } } class StaticVariable { public static void main(String args[]) { int i; try { StudentDetail STD[]=new StudentDetail[3]; System.out.println("Enter the Details of Three Students"); for(i=0;i<=2;i++) { STD[i]= new StudentDetail(); STD[i].Setdata(); } System.out.println("The Details of Three Students Entered are :"); for(i=0;i<=2;i++) { STD[i].ShowDetail(); } } catch(IOException e){} } };