Advertisement
Shailrshah

The Static Keyword

Dec 18th, 2013
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.38 KB | None | 0 0
  1. ///A static variable is used when it is known that all objects of a class will have the same value for an attribute, such as the name of a college of a set of students from TSEC. It gets memory only once in class area at the time of class loading.
  2. //A static method belongs to a class, not an object of the class. So, it can be invoked without an object. It can access and modify static data.
  3. //A static block/initializer is a block of code which is initialized when class is loaded. It can be called a class constructor.
  4. class Student{
  5.         static{System.out.println("Hello Student!");} //static block
  6.         int roll_no;
  7.         String name;
  8.         static String college = "TSEC"; //static variable
  9.  
  10.         Student(int roll_no, String name){
  11.                 this.roll_no = roll_no;
  12.                 this.name = name;
  13.         }
  14. }
  15. class testHello{
  16.         public static void main(String args[]){ //static method
  17.                 Student s1 = new Student(103, "Shail");
  18.                 Student s2 = new Student(105, "Alice");
  19.                 System.out.println("Name: "+s1.name+"\nRoll No: "+s1.roll_no+"\nCollege: "+s1.college);
  20.                 System.out.println("Name: "+s2.name+"\nRoll No: "+s2.roll_no+"\nCollege: "+s2.college);
  21.         }  
  22. }
  23. /*Output:-
  24. C:\Java>java testHello
  25. Hello Student!
  26. Name: Shail
  27. Roll No: 103
  28. College: TSEC
  29. Name: Alice
  30. Roll No: 105
  31. College: TSEC
  32. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement