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


let me explain further. have string function (called stringreversal) returns reversed string, has no errors in function. but, when try print using system.out.println() main function, gives me error "can not make static reference non static method stringreversal (string s) type stringreverse".

i tried giving stringreversal static modifier, after doing so, gave me run time errors.

here's 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 =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 =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();     }  } 

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

in case can do

stringreverse sr = new stringreverse(); string rev = sr.stringreversal("hello"); 

or declare method differently

public static string stringreversal(string s) 

in fact class name stringreverse not sound kind of object, second way preferred impo

the deeper problem have confusion on how java handle oo , entrance function in general. java oo language of time shall object or member of object. when telling vm run java code, there got place start, main method. there has 1 main method , must under class, has nothing class contains it. within main method, either start oo life instantiating objects , invoking members (method 1) or stay in spaghetti world bit longer, calling other static members procedures (method 2).


Comments

Popular posts from this blog

php - Magento - Deleted Base url key -

javascript - Tooltipster plugin not firing jquery function when button or any click even occur -

java - WrongTypeOfReturnValue exception thrown when unit testing using mockito -