Apply for Zend Framework Certification Training

Java



< Method Overriding in Java – Short Notes Last >



Static Methods in Java
A static method in Java is a method that belongs to the class rather than to an object (instance) of the class.
It is declared using the static keyword.
Important Characteristics
Static methods belong to the class, not individual objects.
They can be called without creating an object.
They are generally accessed using the class name.
A static method can directly access static variables.
A static method cannot directly access non-static instance variables or methods.
The main() method in Java is static.
Static methods are associated with the class and are available once the class is loaded.

Example
class StaticMethods{
    String printmyname(String myname){
        return "My name is "+myname;
    }
    static String printmyaddress(String myaddress){
        return "I put up at "+ myaddress;
    }
}
public class static_method {
    public static void main(String[] args){
        StaticMethods sm= new StaticMethods();
        System.out.println(sm.printmyname("Rajesh"));
        System.out.println(StaticMethods.printmyaddress("Chandigarh royal city"));

    }
}


Static Variable in Java
A static variable is a variable that belongs to the class rather than to individual objects.
It is declared using the static keyword.


Why Use a Static Variable?
Suppose 100 students belong to the same college.
Without static, every object would have its own copy:

Example
class StaticVaraible{
    static int maxmarks=100;
    int marksobtained = 75;
}
public class java_static_and_nonstatic_variable {
    public static void main(String[] args) {
        StaticVaraible sv = new StaticVaraible();
        System.out.println("Maximum marks is : "+sv.marksobtained);
        System.out.println("Marks obtained is : "+StaticVaraible.maxmarks);
    }
}

 

< Method Overriding in Java – Short Notes Last >



Ask a question



  • Question:
    {{questionlistdata.blog_question_description}}
    • Answer:
      {{answer.blog_answer_description  }}
    Replay to Question


Back to Top