Static methods, what for?

What are static methods for? is there something that is not possible through methods associated with instances (non-static methods) ?

There are many examples of static mehods in the Java API. For example the Math or the System class. All methods in this classes are static. So you dont have to instantiate the system class. In fact it is even not possible to instantiate the System class. System is final and all Constructors are private.
Another use for static methods is the access to private static variables.

Similar Messages

  • What is static method

    I can not understand how to use static method
    What is the difference between
    int a;
    static int a;
    what is the meaning of static??

    I would add that a static member exists for the class independently of any instances of the class.
    This means that you can refer to it at any time by using TheClass.theMember.
    This applies to the methods too, like TheClass.theMethod().

  • Re: No late binding for static methods

    Only the sale class has a showAdvertisement() method.
    When the compiler compiles that class it decides at compile time which exact method is called for each static method call (that's the big difference to non-static method calls: the exact method to be called is only decided at runtime in those cases).
    There's only one method showAdvertisement() and that is called in both cases in your code. Since that single method always calls the same static announcement() method, you will see the result you posted.

    JoachimSauer wrote:
    When the compiler compiles that class it decides at compile time which exact method is called for each static method call (that's the big difference to non-static method calls: the exact method to be called is only decided at runtime in those cases).I thought static methods were bound at classload-time. Demo:
    public class A {
        public static void f() {
            System.out.println("A.f");
    public class B extends A  {
        public static void f() {
            System.out.println("B.f");
    public class C  {
        public static void main(String[] args) {
            B.f();
    }If you run the above code, "A.f" is printed, as you would expect -- there is only one static method f defined.
    But if you uncomment the code in class B and recompile only it (not C!), then run C, you will get the output "B.f".
    If you run javap -c C you will see:
    public static void main(java.lang.String[]);
      Code:
       0:   invokestatic    #2; //Method B.f:()V
       3:   returnSo the byte code isn't binding the call to A.f at compile time. The choice is made at classload-time. That is why there are similar restrictions on hiding static methods as for overriding instance methods: [http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.4.8.3]

  • Using a non-static vector in a generic class with static methods

    I have a little problem with a class (the code is shown underneath). The problem is the Assign method. This method should return a clone (an exact copy) of the set given as an argument. When making a new instance of a GenericSet (with the Initialize method) within the Assign method, the variables of the original set and the clone have both a reference to the same vector, while there exists two instances of GenericSet. My question is how to refer the clone GenericSet's argument to a new vector instead of the existing vector of the original GenericSet. I hope you can help me. Thanks
    package genericset;
    import java.util.*;
    public class GenericSet<E>{
    private Vector v;
    public GenericSet(Vector vec) {
    v = vec;
    private <T extends Comparable> Item<T> get(int index) {
    return (Item<T>) v.get(index);
    public static <T extends Comparable> GenericSet<T> initialize() {
    return new GenericSet<T>(new Vector());
    public Vector getVector() {
    return v;
    public static <T extends Comparable> GenericSet<T> insert (GenericSet<T> z, Item<T> i){
    GenericSet<T> g = assign(z);
    Vector v = g.getVector();
    if (!member(g,i))
    v.addElement(i);
    return g;
    public static <T extends Comparable> GenericSet<T> delete(GenericSet<T> z, Item<T> i){
    GenericSet<T> g = assign(z);
    Vector v = g.getVector();
    if (member(g,i))
    v.remove(i);
    return g;
    public static <T extends Comparable> boolean member(GenericSet<T> z, Item<T> i) {
    Vector v = z.getVector();
    return v.contains(i);
    public static <T extends Comparable> boolean equal(GenericSet<T> z1, GenericSet<T> z2) {
    Vector v1 = z1.getVector();
    Vector v2 = z2.getVector();
    if((v1 == null) && (v2 != null))
    return false;
    return v1.equals(v2);
    public static <T extends Comparable> boolean empty(GenericSet<T> z) {
    return (cardinality(z) == 0);
    public static <T extends Comparable> GenericSet<T> union(GenericSet<T> z1, GenericSet<T> z2) {
    GenericSet<T> g = assign(z1);
    for(int i=0; i<cardinality(z2); i++) {
    Item<T> elem = z2.get(i);
    insert(g, elem);
    return g;
    public static <T extends Comparable> GenericSet<T> intersection(GenericSet<T> z1, GenericSet<T> z2) {
    GenericSet<T> g = initialize();
    for(int i=0; i<cardinality(z2); i++) {
    Item<T> elem = z2.get(i);
    if(member(z1, elem))
    insert(g, elem);
    return g;
    public static <T extends Comparable> GenericSet<T> difference(GenericSet<T> z1, GenericSet<T> z2) {
    GenericSet<T> g = initialize();
    for(int i=0; i<cardinality(z1); i++) {
    Item<T> elem = z1.get(i);
    if(!member(z2, elem))
    insert(g, elem);
    for(int i=0; i<cardinality(z2); i++) {
    Item<T> elem = z2.get(i);
    if(!member(z1, elem))
    insert(g, elem);
    return g;
    public static <T extends Comparable> GenericSet<T> assign(GenericSet<T> z) {
    GenericSet<T> g = initialize();
    for(int i=0; i<cardinality(z); i++) {
    Item<T> elem = z.get(i);
    insert(g, elem);
    return g;
    public static <T extends Comparable> boolean subset(GenericSet<T> z1, GenericSet<T> z2) {
    for(int i=0; i<cardinality(z1); i++) {
    Item<T> elem = z1.get(i);
    if(!member(z2, elem))
    return false;
    return true;
    public static <T extends Comparable> int cardinality(GenericSet<T> z){
    Vector v = z.getVector();
    return v.size();
    }

    The issue is not "reference a non-static interface", but simply that you cannot reference a non-static field in a static method - what value of the field ed would the static method use? Seems to me your findEditorData should look something like this:   public static EditorBean findEditorData( String username, EditorBean editorData )
          return editorData.ed.findEditor( username );
       }

  • Why do we need private static method or member class

    Dear java gurus,
    I have a question about the use of private and static key words together in a method or inner class.
    If we want to hide the method, private is enough. a private static method is sure not intended to be called outside the class. So the only usage I could see is that this private static method is to be called by another static method. For inner class, I see the definition of Entry inner class in java.util.Hashtable, it is static private. I don't know why not just define it as private. Could the static key word do anything better.
    Could anybody help me to clear this.
    Thanks,

    What don't you get? Private does one thing, andstatic does >something completely different.
    If you want to listen to music, installing an airconditioner doesn't help>
    Hi, if the private keyword is the airconditioner, do
    you think you could get music from the static keyword
    (it acts as the CD player) in the following codes:You're making no sense and you're trying to stretch the analogy too far.
    Private does one thing. If you want that thing, use private.
    Static does something completely different and unrelated. If you want that thing, use static.
    If you want both things, use private static.
    What do you not understand? How can you claim that you understand that they are different, and then ask, "Why do we need static if we have private"? That question makes no sense if you actually do understand that they're different.

  • Why is the static method in the superclass more specific?

    Why is the static method in the superclass more specific than the static method in the subclass? After all, int is a subtype of long, but Base is not a subtype of Sub.
    class Base {
        static void m(int i){ System.out.println("Base"); }
    class Sub extends Base {
        static void m(long l){ System.out.println("Sub"); }
    class Test {
        public static void main(String[] args) {
            int i = 10;
            Sub sub = new Sub();
            sub.m(i);
    }The first example compiles without error.
    Output: Base
    class Base {
        void m(int i){ System.out.println("Base"); }
    class Sub extends Base {
        void m(long l){ System.out.println("Sub"); }
    class Test {
        public static void main(String[] args) {
            int i = 10;
            Sub sub = new Sub();
            sub.m(i);
    }In the second example, both instance methods are applicable and accessible (JLS 15.12.2.1), but neither is more specific (JLS 12.2.2), so we get a compiler error as expected.
    : reference to m is ambiguous,
    both method m(int) in Base and method m(long) in Sub match
    sub.m(i);
    ^
    1 error
    Why don�t we get a compiler error for the static methods?

    Thank you for your ideas.
    ====
    OUNOS:
    I don't get Sylvia's response. This is about static methods, what are instances are needed for??Yes, the question is about static methods. I included the example with non-static methods for a comparison. According to JLS 15.12.2, both examples should cause a compiler error.
    And why you create a Sub object to call the method, and dont just call "Sub.m(..)"Yes, it would make more sense to call Sub.m(i). Let�s change it. Now, I ask the same question. Why is there no compiler error?
    ====
    DANPERKINS:
    The error in your logic stems from calling static methods on instances, as ounos pointed out. Solution: don't. You won't see any more ambiguities.A static member of a class may also be accessed via a reference to an object of that class. It is not an error. (The value of the reference can even be null.)
    Originally I was looking only at the case with non-static methods. Therefore, I used sub.m(i). Once I understood that case, I added the static modifiers. When posting my question, I wish I had also changed sub.m to Sub.m. Either way, according to JLS 15.12.2, a compiler error should occur due to ambiguous method invocation.
    ====
    SILVIAE:
    The question was not about finding an alternative approach that doesn't throw up an ambiguity. The question related to why, in the particular situations described, the ambiguity arises in only one of them.
    Yes.
    Proposing an alternative approach doesn't address the question.
    Yes.
    ====
    If anyone is really interested, here is some background to the question. Some people studying for a Sun Java certificate were investigating some subtleties of method invocations:
    http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=24&t=019182
    I remember seeing the non-static case discussed in this forum once before in a more practical context. jschell probably knows the link.

  • Serializing a static method

    is it possible to serialize a static method?
    For example
    Class foobar implements serializable
    public static void foo(){};

    If you serialize an Object and send it over a network, I believe that the program/class that is unserializing it must otherwise know (be able to create) an Object of that type. So the static method would already be available. The only other way would be with reflection, but I'm not sure if that works on serialized objects.

  • Difference between calling static method and not static method?

    Hi,
    Suppose i want to write a util method, and many class might call this method. what is better? writing the method as static method or not static method. what is the difference. what is the advantace in what case?

    writing the method as static method or not static
    method. what is the difference.The difference is the one between static and non-static. Any tutorial or the JLs will clarify the difference, no need to repeat it here.
    what is the advantace in what case?It's usually not like you have much of a choice. If you need access to an instance's attributes, you can't make it static. Otherwise, make it static.

  • No warning for 'name clash' of static methods

    The background is that I am trying to design a package which allows conversion methods to be 'plugged-in' to a class within a class hierarchy so that users can choose how objects are converted to double values. (For example, a 'city-block' conversion might be used instead of the Euclidean-distance one for class TwoD below.) I am trying to use generics to ensure that only converters specific to the appropriate class can be 'plugged-in' and also to simplify the definition of new converters.
    The issue that has arisen is a case which is not 'type-safe', in that the behaviour is not what I would expect from the type specifications, yet no warning is given. The full code is below.
    public abstract class Base {
        public abstract Converter getConverter();
        public double convert() {
            return this.getConverter().convert(this); // produces a warning
    public class OneD extends Base {
        static Converter<OneD> converter;
        int x;
        public OneD(int x) {
            this.x = x;
        public static void setConverter(Converter<OneD> c) {
            converter = c;
        public Converter getConverter() {
            return converter;
    public class TwoD extends OneD {
        static Converter<TwoD> converter;
        int y;
        public TwoD(int x, int y) {
            super(x);
            this.y = y;
        public static void setConverter(Converter<TwoD> c) {
            converter = c;
        }                                   // compiles OK with no warning
        public Converter getConverter() {
            return converter;
    public abstract class Converter<T> {
        public abstract double convert(T val);
    public class OneDConverter extends Converter<OneD> {
         public double convert(OneD val) {
            return val.x;
    public class TwoDConverter extends Converter<TwoD> {
        public double convert(TwoD val) {
            return Math.sqrt(val.x * val.x + val.y * val.y);
    public class Test {
        public static void main(String[] args) {
            OneD x1d = new OneD(1);
            TwoD x2d = new TwoD(1, 1);
            OneD.setConverter(new OneDConverter());
            TwoD.setConverter(new TwoDConverter());
            System.out.println("Convert OneD(1): " + x1d.convert() +
                               ", Convert TwoD(1, 1): " + x2d.convert());
            TwoD.setConverter(new OneDConverter());
              // wrong type of converter; should not be allowed
            System.out.println("Convert OneD(1): " + x1d.convert() +
                               ", Convert TwoD(1, 1): " + x2d.convert());
    }This produces the output:
    Convert OneD(1): 1.0, Convert TwoD(1, 1): 1.4142135623730951
    Convert OneD(1): 1.0, Convert TwoD(1, 1): 1.0The first line of this shows that the all is working OK, but in the second line we see that the wrong type of converter has been plugged-in to class TwoD, with no complaints or warnings at compile or run-time. I understand why this is so (as a result of erasure), but I am surprised that no warning is given that the static method setConverter() in class TwoD clashes with the one in OneD. Is this really type-safe behaviour? (If the two methods are made instance methods instead of static, the code does not compile because of a 'name clash' error.)
    Incidentally, an 'unchecked warning' arises because of the use of the raw class Converter in class Base, but I cannot figure out how to avoid this. The warning is right, and signals that we cannot be sure that the converter is the appropriate type for the argument. It is up to subclasses to ensure this and I cannot figure out how to guarantee that it will be so.

    public abstract class Base {
    public abstract Converter getConverter();
    public double convert() {
    return this.getConverter().convert(this); // produces a warning
    }Some of the problems you're seeing can be resolved
    by organizing your code better:
    abstract class Base<T extends Base<T>> {
        public abstract Converter<T> getConverter();
        public double convert() {
            return this.getConverter().convert(getThis());
        abstract protected T getThis();
    class OneD extends Base<OneD> {
        static Converter<OneD> converter;
        int x;
        public OneD(int x) {
            this.x = x;
        public static void setConverter(Converter<OneD> c) {
            converter = c;
        public Converter<OneD> getConverter() {
            return converter;
        protected OneD getThis() { return this; }
    class TwoD extends Base<TwoD> {
        static Converter<TwoD> converter;
        int y;
        int x;
        public TwoD(int x, int y) {
            this.x = x;
            this.y = y;
        public static void setConverter(Converter<TwoD> c) {
            converter = c;
        public Converter<TwoD> getConverter() {
            return converter;
        protected TwoD getThis() { return this; }
    abstract class Converter<T> {
        public abstract double convert(T val);
    class OneDConverter extends Converter<OneD> {
         public double convert(OneD val) {
            return val.x;
    class TwoDConverter extends Converter<TwoD> {
        public double convert(TwoD val) {
            return Math.sqrt(val.x * val.x + val.y * val.y);
    class Test {
        public static void main(String[] args) {
            OneD x1d = new OneD(1);
            TwoD x2d = new TwoD(1, 1);
            OneD.setConverter(new OneDConverter());
            TwoD.setConverter(new TwoDConverter());
            System.out.println("Convert OneD(1): " + x1d.convert() +
                               ", Convert TwoD(1, 1): " + x2d.convert());
            TwoD.setConverter(new OneDConverter());  // error
            System.out.println("Convert OneD(1): " + x1d.convert() +
                               ", Convert TwoD(1, 1): " + x2d.convert());
    }

  • JNI static method call fails for the 6th time

    Hello,
    I have a JNI Method which calls the static method which gets reference to singleton class(getReference()), JVM crashes.
    what might be the problem?
    is it due to insufficient memory or any other reason?
    Here is my code.
    eScannerClass = gEnv->FindClass("com/elvista/jscaner/EScanner");
    eScannerContructId = gEnv->GetStaticMethodID(eScannerClass,"getReference","()Lcom/elvista/jscaner/EScanner;");
    eScannerUpdateMethodId = gEnv->GetMethodID(eScannerClass,"updateScanStatus","(Lcom/elvista/jscaner/EScanEvent;)V");
    eScannerObjectRef = gEnv->NewObject(eScannerClass,eScannerContructId);Thanx for any help on this.

    Hi,
    the eScannerContructId is refering a static method, not a constructor. Therefore you must not use gEnv->NewObject, which is only allowed for constructors. Instead you have to use gEnv->CallStaticObjectMethod to call getReference().
    Martin

  • What is the use of private static method/variable?

    Hi All,
    I have read lots of books and tried lots of things but still not very clear on the
    topic above.
    When exactly do we HAVE to use private static methods?
    private implies its only for class, cannot be accessed outside.
    But then static means, it can be accessed giving classname.method.
    They seem to be contradicting each other.
    Any examples explaining the exact behaviour will be well appreciated.
    Thanks,
    Chandra Mohan

    Static doesn't really "mean" that the method/field is intended for use outside the class - that is exactly what the access modifier is for.
    Static implies that it is for use in relation to the class itself, as opposed to an instance of the class.
    One good example of a private static method would be a utility method that is (only) invoked by other (possibly public) static methods; it is not required outside the class (indeed, it might be dangerous to expose the method) but it must be called from another static method so it, in turn, must be static.
    Hope this helps.

  • What 's the advantage of static method.

    I think if a method is declared as static, the program should allocate some spaces for the method when the program start. However, I found many static method in an erp open source project. What make me confused is that it will cost many spaces.
    Perhaps they want to lose some spaces for speed???
    Can somebody answer my question.thanks!

    > I think if a method is declared as static, the
    program should allocate some spaces for the method
    when the program start. However, I found many static
    method in an erp open source project. What make me
    confused is that it will cost many spaces.
    Perhaps they want to lose some spaces for speed???
    Can somebody answer my question.thanks!
    To be sincere, I've never thought about performance cost when static methods are used. I decide to create and use them mainly whether I have the "feeling" that it will provide me benefits, in terms of designing. Yes, it's like a feeling. I am not able to explain you why or how I have this feeling, I'm not native in English language, so choosing the appropriate words to explain my ideas sometimes is hard to me. Besides. I admit that I am a little bit lazy in this moment, I don't want to search through some dictionary...;-).
    I think the more you develop your abilities and skills in java programming, the more you can feel, you can have this "feeling", and naturally you figure out in which situations using static methods is a better choice.

  • Singleton or static methods for DAO?

    Which is the preferred way of creating a DAO which has no state...Singleton or static methods for DAO? and why? What are the issues implement one over the other?

    A [url http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html]DAO is an object that abstracts different data source access mechanisms by providing a common interface, decoupling the client code from the data layer implementation, and allowing differrent data sources to be used without changing the client code.
    This is not possible with static methods- you would have to change the client code to use a different data source.
    There is a similar pattern, the facade, where an object/utility class provides the interface to a set of functionality. In the case of a facade with static methods, the facade class needs to be rewritten to use a different implementation. This is possible, but means only one implementation may exist in each version of the software. A static method facade is a tighter coupled solution to a similar problem; tight coupling occasionally makes a measurable improvement in performance, but always reduces flexibility and requires destructive editing to change its implementation.
    Pete

  • What is the purpose of Static methods inside a class?

    Hi,
    What is the purpose of Static methods inside a class?
    I want the answers apart from "A static method does not require instance of class(to access) and it can directly be accessed by the class name itself"
    My question is what is the exact purpose of a static method ?
    Unlike attributes, a separate copy of instance attributes will be created for each instance of a class where as only one copy of static attributes will be created for all instances.
    Will a separate copy of instance method be created for each instance of a class and only one copy of static methods be create?
    Points will be rewarded for all helpful answers.

    Hi Sharma,
    Static methods is used to access statics attributes of a class. We use static attributes when we want to share the same attribute with all instances of a class, in this case if you chage this attribute through the instance A this change will change will be reflected in instance B, C........etc.
    I think that your question is correct -> a separate copy of instance method will be created for each instance of a class and only one copy of static methods be create ?
    "A static method does not require instance of class(to access) and it can directly be accessed by the class name itself"
    Static Method: call method class=>method.
    Instance Method: call method instance->method.
    Take a look at this wiki pages.
    [https://wiki.sdn.sap.com/wiki/x/o5k]
    [https://wiki.sdn.sap.com/wiki/x/ZtM]
    Best regards.
    Marcelo Ramos

  • Does not contain a static 'Main' method suitable for an entry point_

    Hello
    I want to to do a project with Entiity Framework . I add a project to my solution for my domain class and it's name is 'LinkModel.DomainClasses'.  when I prees F5 there is an error like bellow.
    Could You help me to solve this? thanks alot
    ..\Documents\Training\LinkCodeFirstLast\LinkCodeFirst\LinkCodeFirst\LinkModel.DomainClasses\obj\Debug\LinkModel.DomainClasses.exe'
    does not contain a static 'Main' method suitable for an entry point

    Hi bkshn,
    This error is caused by the missing "Main" method in your project. it is the entry point of your project.
    If you want to create a EF project, you could follow the way in the aricle below.
    https://msdn.microsoft.com/en-us/data/ee712907#codefirst
    The Main method is like below.
    class Program
    static void Main(string[] args)
    using (var db = new BloggingContext())
    // Create and save a new Blog
    Console.Write("Enter a name for a new Blog: ");
    var name = Console.ReadLine();
    var blog = new Blog { Name = name };
    db.Blogs.Add(blog);
    db.SaveChanges();
    // Display all Blogs from the database
    var query = from b in db.Blogs
    orderby b.Name
    select b;
    Console.WriteLine("All blogs in the database:");
    foreach (var item in query)
    Console.WriteLine(item.Name);
    Console.WriteLine("Press any key to exit...");
    Console.ReadKey();
    And you could start to learn the EF from the following MSDN blogs.
    https://msdn.microsoft.com/en-us/data/ee712907
    If you have any other concern regarding this issue, please feel free to let me know.
    Best regards,
    Youjun Tang
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

Maybe you are looking for

  • Best Practice for PDF print forms based on SAP standard

    Hi, I have copied the SAP standard PDF form F_D_INT_SCALE_00 to a Z form, and am using it in conjunction with the standard print program RFDZIS01_PDF.  However I need to output some additional fields that are not supplied by the print program / inter

  • WIRELESS PROBLEM

    Hey, I am currently on the internet through a cable modem. I was wondering if there is a way to use my MAC as a wireless router so that my pc can pick up a wireless internet signal from it. I started a network and my PC can pick up the Mac's signal j

  • Not synching some purchased music to mini

    I installed the latest iTunes 7.0 version and then bought some songs. The new songs are synching but some of our older purchased music won't synch on my daughter's mini ipod. I get the message that it is not an authorized computer and so these certai

  • Why I don't have standart android browser on my Z1?

    Please tell me why Z1 don't have standart android browser and where I can get it?

  • Swap space utilization is increasing after Oracle11gr2 upgrade

    Hi we are using oracle11.5.10.2 on AIX 5.3 and recently upgraded database from oracle9.2.0.8 to Oracle 11gr2 (11.2.0.2) After upgrade Database i have observed gradually swap space is increasing and it is reaching upto 100% what could be the reason ?