Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ///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.
- //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.
- //A static block/initializer is a block of code which is initialized when class is loaded. It can be called a class constructor.
- class Student{
- static{System.out.println("Hello Student!");} //static block
- int roll_no;
- String name;
- static String college = "TSEC"; //static variable
- Student(int roll_no, String name){
- this.roll_no = roll_no;
- this.name = name;
- }
- }
- class testHello{
- public static void main(String args[]){ //static method
- Student s1 = new Student(103, "Shail");
- Student s2 = new Student(105, "Alice");
- System.out.println("Name: "+s1.name+"\nRoll No: "+s1.roll_no+"\nCollege: "+s1.college);
- System.out.println("Name: "+s2.name+"\nRoll No: "+s2.roll_no+"\nCollege: "+s2.college);
- }
- }
- /*Output:-
- C:\Java>java testHello
- Hello Student!
- Name: Shail
- Roll No: 103
- College: TSEC
- Name: Alice
- Roll No: 105
- College: TSEC
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement