Confused regarding static methods

Hello guys,
I like to know the only purpose of static method is to call a method with out creating
instance of that class.
I am totaly confused why and where to use static methods.
Thanks in advance
aneesh

Look at the API docs for some of the static methods in classes like java.lang.String, java.lang.Integer, java.lang.Thread, etc.
An object--an instance of a class--has state and behavior. The state is captured in the instance variables--the array that holds the characters of a String, the name, SS#, and hireDate fields of an Employee object, etc.
Static methods are used when the operation you're performing isn't associated with any particular instance of that class--it doesn't use or modify the state of a particular object. The operation is associated with the class as a whole.
For instance, Integer.parseInt(String). You're not operating on an existing Integer object. Rather you're creating a new Integer from a String. It's a utility or "helper" method of the Integer class.
And yes, do read the tutorial.

Similar Messages

  • Need some explanations regarding static Method

    Hello,
    I have a code where a class has a static method access by other classes. This not working as I thought and I would like to understand why.
    Here below is the code.
    Here is a class having the static method "test"
    package test;
    public class StaticTest {
        public StaticTest() {
        public static void test (int i){
        while (i < 1000){
            System.out.println("i = " + i );
            i++;
    }Here is the code of another class (Thread) using this static method. This Thread can be initialized with an integrer value that will be passed to the static Method.
    package test;
    public class ThreadTester extends Thread {
        int x;
        public ThreadTester(int i) {
            x=i;
        public void run(){
            StaticTest.test(x);
    }Here is the code starting 2 Thread running in parallel and both are then calling the static method.
    //start 2 thread accessing the static method.
          ThreadTester test1 = new ThreadTester(0);
          ThreadTester test2 = new ThreadTester(200);
          test1.start();
          test2.start();
    ...As the second thread is started with a bigger value I thought that we would only have seen few printouts from the first thread starting by 0 and then printouts starting by 200.
    Here is what I thought regarding the result:
    i = 0
    i = 1
    i = 2
    i = 3
    i = 200 --> startup of the second thread, x in static method is overriden (at least this is what I thought!)
    i = 201
    i = 202
    i = 203
    i = 204
    i = 205
    i = 206
    i = 207
    i = 208
    i = 209
    But the real result is:
    i = 0
    i = 1
    i = 2
    i = 3
    i = 4
    i = 5
    i = 200
    i = 6
    i = 201
    i = 202
    i = 203
    i = 204
    i = 205
    i = 206
    i = 7
    i = 207
    i = 208
    i = 209
    i = 8
    It seems that there is 2 instances running in parallel. I thought that it would'nt be the case with the word "Static".
    Also I don't understand the result because if I use JBuilder in Optimizer mode I can see that there is only one instance of StaticTest object.
    Can anyone here explain me how is that possible?
    Thanks in advance for your help.
    Regards,
    Alain.

    >
    thread test1 creates its own stack and starts incrementing �i� starting at values 0. However, in the middle of incrementing, it gets kicked out by the OS (or JVM) into a �blocked� state to allow other threads to run. BUT before leaving the running state, test1 saves the stack state including the value of �i�.
    >
    Ok, now I understand, but then I have another question.
    What is the difference between the code shown in my first post and the following where we create 2 instances of StaticTest class (which is not static in this case for sure).
    How to decide (while coding) if it is better to use difference instances of class or not?
    package test;
    public class StaticTest {
        public StaticTest() {
        public void test (int i){ //Not static anymore
        while (i < 1000){
            System.out.println("i = " + i );
            i++;
    }We create new instance in the Thread.
    package test;
    public class ThreadTester extends Thread {
        int x;
        public ThreadTester(int i) {
            x=i;
        public void run(){
    StaticTest newInstance = new StaticTest(); //Create a new instance
            newInstance .test(x);
    }Alain

  • I currently having problems when dialling with my 4S either from the contacts list, or when using the phone through bluetooth to my in-car system. The phone becomes confused regarding what method / route of connection handsfree, normal use or speaker.

    Hi each time i use my 4S phone a dial from the contact list, the phone will not select a communication mode, either normal speaker or handsfree (car), I have to force the phone into speaker mode and the back to normal mode before I can speak to or listen to anyone. The annoying aspect is the recipient of my call can answer but cannot hear me nor I them.
    What am I doing wrong, or is there an issue with the phone. The same situation occurs when the phone is used with bluetooth in my car, the previous iphone worked perfectly can you please advise.

    Just to recap, this is a collection of ports I have collected over time for people who needed this information when setting up the HP ePrint app so that they could view their email from within the app.  I am certain other applications also need this information.  Although lengthy, I could not find a more comprehensive place to retrieve this information.  Feel free to post additional information, faulty information, or other related topics below as this is simply a collection of data and it would be practically impossible to test all of them. Thank you!
    Don't forgot to say thanks by giving "Kudos" if I helped solve your problem.
    When a solution is found please mark the post that solves your issue.
    Every problem has a solution!

  • Can we override Static methods?

    Hi all, I m in little bit confusion abt static methods overriding.
    Could you help me on this issue.,
    Can we override Static methods?

    You can provide static methods with same name in both super class and subclass. But it is not overriding in this scenario. Both will act as independent methods.
    Example:
    have a super class:
    public class Test1 {
    public static void mthdA()
    System.out.println("in super");
    have a sub class:
    public class Test2 extends Test1{
    public static void mthdA()
    System.out.println("inside sub");
    public static void main(String[] args){
    Test1 objTest = new Test2();
    objTest.mthdA();
    Try to run the sub class Test2. The output would be "in super".
    Remove static modifier in mthdA() in both the classes and then run. The output would be "in sub". Meaning, methdA is overriden in sub class.

  • Regarding Returning Parameter and Static method

    Hi frnds,
    I am learning oops ABAP. I want to use returning parameters in method and also STATIC METHOD.
    If any example it will be more helpful
    regards,
    satya

    Hi satya,
                 Check this out ,Its helpful.
    To get some values from a method , one can use the exporting, changing or returning parameters.If one uses RETURNING parameters, the following restrictions apply:-(1) No EXPORTING/CHANGING parameters can be used for the method.(2) Only one RETURNING parameter can be used.(3) RETURNING parameters are only passed by value.This program demonstrates the use of RETURNING parameters and the various ways   to call a method with RETURNING parameter to get the value into some variable.
    Sample Program
    </code>
    report ysubdel1 message-id 00.
    data : w_num type i.
    class c1 definition .
    public section. 
    methods : m1 importing input1 type i
                            input2 type i
                            returning value(result) type i .
    endclass.
    class c1 implementation.
    method  : m1.
    result = input1 * 2 + input2.
    endmethod.
    endclass.
    start-of-selection.
    data : obj1 type ref to c1 . 
    create object obj1.
    Syntax 1     
    call method obj1->m1 EXPORTING input1 = 5                                                        input2 = 4  
                                   RECEIVING result = w_num.  
      write:/5 w_num .
    Syntax 2
         w_num = obj1->m1( input1 = 10 input2 = 20 ).
      write:/5 w_num .
    Syntax 3     
    move obj1->m1( input1 = 2 input2 = 3 ) to w_num .  
    write:/5 w_num .
    </code>
    Static method example
    <code>
    REPORT  zstatic.                              .
    data : num type i.
    class testclass definition.
    public section.
      class-methods : testmethod.
    endclass.
    class testclass implementation.
    method : testmethod.
      num = 5.
      write:/5 num.
    endmethod.
    endclass.
    start-of-selection.
    call method testclass=>testmethod.
    </code>
    Reward Points if u find helpful.
    Thnks & Regards,
    Rajesh

  • Querry regarding overriding static methods

    Hi ,
    I m overriding a static method defined in superclass ThreadLocal1 as:
    public static void mm()
         System.out.println("bye");
    class Thread1 extends ThreadLocal1{
    tt(){}
    public static void mm()
         System.out.println("hi");
    public static void main(String args[])
         Thread1 t1= new Thread1();
         ThreadLocal1 th1;
         th1=t1;          // t1 is assigned      th1.mm();
         t1.mm();
    }output is : bye
    hi
    I am not getting why ref var th1 is not calling overridden method mm() when th1 is assigned t1 that is subclass instance.
    when i m removing static modifier from mm(0 in superclass then output is : hi hi
    plz clarify why is it so.....
    Edited by: jawatch on Oct 29, 2007 7:01 AM

    jawatch wrote:
    @kajbj :
    but i have overridden static method mm()No, you haven't. You've hidden it. Overriding only applies to non-private, non-final, non-static methods, and they are the only case where you can see the kind of polymorphism you're talking about.

  • Regarding static or instance

    Hi all,
               I am in confusion that which is called first static (method / attribute ) or Instance (method/attribute).
    Becoz what i know is whenever an object is created, first static is called then instance.
    please correct me if i am wrong.
    regards,
    satish

    Hi Sathis,
    Instance & Static Method :
    if u declare one method as a static then we can call that method using class name, that method is independent of that object.You declare them using the CLASS-DATA statement.
    if u declare one method as a instance then we can call that method using object name, that method is dependent of that object.You declare them using the DATA statement.
    Instance & Static Attribute :
    if u declare one attribute as a static then we can use that attribute through class name, that attribute is independent of that object.You declare static methods using the CLASS-METHODS statement.
    if u declare one attribute as a instance then we can use that attribute through object name, that attribute is dependent of that object.You declare instance methods using the METHODS statement.
    if u have any doubt ask me,
    Regards,
    Vijay
    Edited by: Vijay.V on Dec 26, 2007 3:33 PM
    Edited by: Vijay.V on Dec 26, 2007 3:36 PM

  • Using static methods to instantiate an object

    Hi,
    I have a class A which has a static method which instantiates it. If I were to instantiate the class A twice with it's static method within class B then you would think class B would have two instances of class A, right?
    Example:
    class A
       static int i = 0;
       public A(int _i)
           i = _i;
       public static A newA(int _i)
            return new A(_i);
    class B
        public B()
            A.newA(5);
            A.newA(3);
            System.out.println(A.i);
        public static void main(String[] args)
            B b = new B();
    }Is there really two instances of class A or just one? I think it would be the same one because if you check the int i it would be 3 and not 5. Maybe static instantiated objects have the same reference within the JVM as long as you don't reference them yourself?
    -Bruce

    It
    seems like you are the only one having trouble
    understanding the question.Well I was only trying to help. If you don't want any help, its up to you, but if that's the case then I fail to see why you bothered posting in the first place...?
    Allow me to point out the confusing points in your posts:
    you would think class B would have two
    instances of class A, right?The above makes no sense. What do you mean by one class "having" instances of another class? Perhaps you mean that class B holds two static references to instances of Class A, but in your code that is not the case. Can you explain what you mean by this?
    Is there really two instances of class
    A or just one?You have created two instances.
    >I think it would be the same one because if you
    check the int i it would be 3 and not 5.
    I fail to see what that has to do with the number of instances that have been created...?
    Maybe static instantiated objects have the
    same reference within the JVM as long as you
    don't reference them yourself????? What is a "static instantiated object"? If you mean that it was created via some call to a static method, then how is it different to creating an object inside the main method, or any other method that was called by main? (i.e. any method)
    What do you mean by "the same reference within the JVM"? The same as what?
    What happened to the first call "A.newA(5)"?
    I think it was overidden by the second call
    "A.newA(3)".As i already asked, what do you mean by this?
    If you change the line for the constructor
    in A to i = i * i you will get "9" as the
    output, if you delete the call "A.newA(3)"
    you will get "25" as the output. Yes. What part of this is cauing a problem?

  • Redefine Static Methods in ABAP OO

    Hello,
    I want to redefine an public static method and returns always an error.
    Okay, I already solved the problem with an workaround, but I still don't understand, why it is not possible to redefine static methods in ABAP OO.
    If someone can give me an plausible reason, so I don't have do die stupid. G
    Thanks for help!
    Matthias

    It is built into the language that way.  HEre is a link that may or may not give you an answer.
    redefine static method?
    Regards,
    Rich Heilman

  • How to get the class name  static method which exists in the parent class

    Hi,
    How to know the name of the class or reference to instance of the class with in the main/static method
    in the below example
    class AbstA
    public static void main(String[] args)
    System.out.println(getXXClass().getName());
    public class A extends AbstA
    public class B extends AbstA
    on compile all the class and run of
    java A
    should print A as the name
    java B
    should print B as the name
    Are there any suggestions to know the class name in the static method, which is in the parent class.
    Regards,
    Raja Nagendra Kumar

    Well, there's a hack you can use, but if you think you need it,Could you let me the hack solution for this..
    you probably have a design flaw and/or a misunderstanding about how to use Java.)May be, but my needs seems to be very genuine..of not repeat the main method contents in every inherited class..
    The need we have is this
    I have the test cases inheriting from common base class.
    When the main method of the test class is run, it is supposed to find all other test cases, which belong to same package and subpackages and create a entire suite and run the entire suite.
    In the above need of the logic we wrote in the main method could handle any class provided it knows what is the child class from which this main is called.
    I applicate your inputs on a better way to design without replicating the code..
    In my view getClass() should have been static as the instance it returns is one for all its instances of that class.
    I know there are complications the way compiler handles static vars and methods.. May be there is a need for OO principals to advance..
    Regards,
    Raja Nagendra Kumar
    Edited by: rajanag on Jul 26, 2009 6:03 PM

  • Dynamic call of a static method of an static attribute

    Hi all,
    is it possible to call dynamically a static method of a static attribute of a class.
    The statement without dynamic call would look like this:
    cl_test_class=>static_attribute=>static_method( ).
    I would like to do it like this:
    ('CL_TEST_CLASS')=>static_attribute=>static_method( ).
    Netiher the one nor the other way works for me - I'm getting the error "The notation used is reserved for business object classes".
    Regards, Stefan

    I guess, it is not possible to call method using the short form (parameters in brackets) is not possible in Dynamic Access. You may need to get the attribute first and then call the method.
    CLASS lcl_main DEFINITION.
      PUBLIC SECTION.
        CLASS-DATA: o_same TYPE REF TO lcl_main.
        METHODS: run.
    ENDCLASS.                    "lcl_main DEFINITION
    CLASS lcl_main IMPLEMENTATION.
      METHOD run.
        WRITE: 'success'.
      ENDMETHOD.                    "run
    ENDCLASS.                    "lcl_main IMPLEMENTATION
    START-OF-SELECTION.
      DATA: lo_same TYPE REF TO lcl_main.
      CREATE OBJECT lcl_main=>o_same.
    *  lcl_main=>o_same=>run( ).
      TRY.
          FIELD-SYMBOLS: <fs> TYPE REF TO lcl_main.
          ASSIGN ('LCL_MAIN')=>('O_SAME') TO <fs>.
          CALL METHOD <fs>->('RUN').
        CATCH cx_root.
      ENDTRY.
    Regards,
    Naimesh Patel

  • Can't get ClassLoader from static method.

    I'm trying to get the ClassLoader within a static method getInstance().
    public class PropertyManager {
    public static PropertyManager getInstance(String fileName) {
    //The following line returns null
    ClassLoader cl = (new Object()).getClass().getClassLoader();
    URL url = cl.getResource(fileName);
    etc...
    However if getInstance gets called from e.g. a statless session bean, a null
    is returned instead of a valid ClassLoader.
    The same code executed from a standalone java program (e.g. from
    main(String[] args)) returns a valid ClassLoader
    Why does getClassLoader behave differently in WebLogic than in a standalone
    java program?
    Thanks for you help.
    Bernie

    Sorry for the confusion. I wrote a couple of more test programs and was able
    to confirm that WL behaves exacltly the same as java does. For some reason
    my intial tests were messed up...
    getClassLoader() executed from a static method always returns null (in WL as
    well as in a java standalone program).
    In this case ClassLoader.getSystemClassLoader() will return a valid class
    loader.
    Thanks for your help.
    Bernie
    "Rob Woollen" <[email protected]> wrote in message
    news:[email protected]..
    Bernhard Lenz wrote:
    I tried that as well, but getClassLoader() still returns null when
    executed
    in WL.
    I'm still not clear how getClassLoader() gets affected by running withinWL.
    >>
    >
    Very odd. Where is this class located? in the server's classpath, in ajar or
    war file? Does getClass().getClassLoader work from a non-static method inthis
    class?
    -- Rob
    "Rob Woollen" <[email protected]> wrote in message
    news:[email protected]..
    You want PropertyManager.class.getClassLoader()
    -- Rob
    Bernhard Lenz wrote:
    I'm trying to get the ClassLoader within a static method
    getInstance().
    >>>>
    public class PropertyManager {
    public static PropertyManager getInstance(String fileName) {
    //The following line returns null
    ClassLoader cl = (new Object()).getClass().getClassLoader();
    URL url = cl.getResource(fileName);
    etc...
    However if getInstance gets called from e.g. a statless sessionbean, a
    null
    is returned instead of a valid ClassLoader.
    The same code executed from a standalone java program (e.g. from
    main(String[] args)) returns a valid ClassLoader
    Why does getClassLoader behave differently in WebLogic than in astandalone
    java program?
    Thanks for you help.
    Bernie

  • OOPs Concept ! - Why Static Methods can't be redefined in its subclass ?

    Dear Experts ,
    I had searched the SDN , but unable to find out the satisfactorily answers ..
    Can anybody let me know the reason for the following Confusion in Oops Concept
    Question 1: As we know , We can Inherit the Static Methods in the Sub Class , But we can't redefine it in the base class  or       Sub Class  ?
    Question 2 : Why can't Static Method be Abstract ?
    Question 3 : Can a Class be Abstract or Final Both, If yes, then why ?
    Thanks in Advance
    Saurabh Goel

    As per the above discussion two of your doubts have already been clarified  so I am taking only third one.
    A class cannot never be Abstract and final both coz Abstract signifies that the implementation of the class has not been defined completelyi.e. may be some methods have been defined but few methods are still missing implementation. 'Final' is used for those classes/methods which cannot be redefined  means the complete implementation of the method has been defined no one can implement further logic under the same method.
    If you are saying your method is Final then it cannot be overridden and Abstract implies that method implementation is yet to be defined which can only be implemented if that class/method is not 'Final'. So both the terms are contradictory.
    Hope it clarifies!!!
    Thanks,
    Vishesh

  • Static methods vs instant methods

    hi to all abap gurus
    thanks in advance
    all of the objects in the class can acess its its static attributes . and if u change the static attribute in an  object the change is visible in all other objects in the calsssss.
    can u pls expain this and tell the diffrence bewteen static and instance metod s?

    Hi,
    <b>Instance Method</b>
    You can declare instance methods by using the METHODS statement. They play a very important role as they can access all of the attributes of a class and can trigger all of the events of the class.
    <b>Static Methods</b>
    You can declare static methods by using the CLASS-METHODS statement. They are important and can only access static attributes and trigger static events.
    <b>STATIC METHODS</b>
    CAN ONLY USE STATIC COMPONENTS IN THEIR IMPLEMENTATION PART
    CAN BE CALLED USING THE CLASS
    Static methods (also referred to as class methods) are called using CALL METHOD <classname>=><class_method>.
    If you are calling a static method from within the class, you can omit the class name.
    You access static attributes using <classname>=><class_attribute>
    Regards,
    Padmam.

  • Nested Classes and Static Methods

    I was perusing the Java Tutorials on Nested Classes and I came across this...
    [http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html|http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html]
    I was reading the documentation and I read a slightly confusing statement. I was hoping some further discussion could clarify the matter. The documentation on "Nested Classes" says (I highlighted the two statements, in bold, I am having trouble piecing together.)
    Static Nested Classes
    As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class ? it can use them only through an object reference.
    Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.
    So this means a nested static inner class CANNOT refer to its own instanced variables, like a normal static method, but CAN refer to its outer class instanced variables?

    So this means a nested static inner class CANNOT refer to its own instanced variables, like a normal static method, but CAN refer to its outer class instanced variables?No, it means that a static nested class cannot refer to instance variables of its enclosing class. Example:public class Foo {
        int i;
        static class Bar {
            int j = i; // WRONG! Bar class is static context
    }~

Maybe you are looking for

  • S2240L, faulty audio output

    Hi, i am connecting a speaker to my Dell S2240L monitor audio out jack port. However, only can hear sound from right speaker it was fine last few days. I had tried to plug in other speaker then output still the same. i also changed another HDMI cable

  • Error when including hierarchical column in repot

    Hi All, I am getting following error [nQSError: 42039] Columns in BY clause of REPORT totalling function must be in select list. (HY000) when i include the Hierarchical column, Is it something i should set for it. Thanks, Sreekanth

  • May be getting hacked by someone...

    I'm getting Dos attacked off xbox live and I know exactly who it is and his IP address.. I would just like to know if anyone has an email address where I can shoot these pictures over to show them who it is and what he's doing.. He is just a stupid k

  • How can I format the harddisk?

    I upgraded from snowleopard to OS lion and made a partition to still have Snow Leopard for some applicatins that would not run on Lion. Lion collapsed completely. I cannot reinstall the OS because the partition was made under Lion and I have only the

  • 5.1 audio / extra frame?

    I have a project of HDV 1440x1080 30fps of which I have imported several HDV clips with simple stereo audio and dragged them to the timeline. The video and audio tracks are linked together by default and flow right after eachother with no empty frame