Search code examples
javastringmethodsstatic-methods

Java String function can not be called because it's not static


Let me explain further. I have a String function (called stringReversal) that returns a reversed string, it has no errors in the function. But, when I try to print using System.out.println() from the main function, it gives me the error "Can not make a static reference to the non static method stringReversal (string s) from the type StringReverse".

I tried giving my stringReversal a static modifier, but after doing so, it gave me run time errors.

Here's what my code looks like:

public class StringReverse {

    public String stringReversal(String s){

        if(s == null){
            return null;
        }

        else if(s.length()% 2 == 0){
            int size = s.length();

            for(int i =0; i<s.length(); i++){
                s.replace(s.charAt(i), s.charAt(size));
                size--;
                if(i == (s.length()/2) || size==0)
                    break;
            }
        }

        else{
            for(int i =0; i<s.length(); i++){
                int size = s.length();

                s.replace(s.charAt(i), s.charAt(size));
                size--;

                if(i == ((s.length()/2) +1) || size==0 )
                    break;
            }
        }

        return s;
    }

    public static void main(String[] args) {
        String str = "Hello";
        String rev = stringReversal(str);

        System.out.println();
    }

}

Solution

  • You have to instantiate your class to call object members, or you need to make your function static, indicating it's not part of object oriented paradigm

    In your case you can do

    StringReverse sr = new StringReverse();
    String rev = sr.stringReversal("hello");
    

    or declare your method differently

    public static String stringReversal(String s)
    

    In fact the class name StringReverse itself does not sound like some kind of object, so the second way is preferred impo

    The deeper problem you have is the confusion on how Java handle OO and entrance function in general. Java is primarily an OO language so most of the time everything shall be an object or a member of a object. But when you telling the VM to run some java code, there got to be a place to start, which is the main method. There has to be one main method and it must be under some class, but it really has nothing to do with the class that contains it. Within the main method, you either start your OO life by instantiating objects and invoking their members (method 1) or stay in the spaghetti world for a bit longer, by calling other static members as procedures (method 2).