Monday 30 December 2019

Static Method in Java tccicomputercoaching.com

The static keyword in Java is used for memory management mainly. If you apply static keyword with any method, it is known as static method.


All the instance of the class share the same copy of the variable, a static variable can be accessed directly by calling “<<ClassName>>.<<VariableName>>” without need to create instance for the class.

class Student{
int rollno;
String name;
static String college = "ITS";
//static method to change the value of static variable
static void change(){
college = "BBDIT";
}

//constructor to initialize the variable
Student(int r, String n){
rollno = r;
name = n;
}

//method to display values
void display(){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to create and display the values of object
public class TestStaticMethod{
public static void main(String args[]){
Student.change();//calling change method

//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
s1.display();
s2.display();
s3.display();
}
}

Test it Now

Output:111 Karan BBDIT

222 Aryan BBDIT

333 Sonoo BBDIT

To learn more about Java at TCCI.

call us@9825618292.

visit us@tccicomputercoaching.com

No comments:

Post a Comment