0
Why the output is -1 in this java code?
Code in Online java compiler: https://www.w3schools.com/java/tryjava.asp?filename=demo_ref_string_lastindexof2 Code: public class Main { public static void main(String[] args) { String myStr = "Hello planet earth, you are a great planet."; System.out.println(myStr.lastIndexOf("g", 5)); } }
2 ответов
+ 3
lastIndexOf() scans the String value from index of last character down to index of first character when the second optional argument (index) was omitted.
When the optional argument (index) is provided, the method scans the String value from the given index argument down to the index of first character.
You had given the method a value of 5 for the optional (index) argument. But there is no substring "g" between index 5 and 0.
+ 2
2nd parameter is "fromIndex" value from which "lastIndexof" method will start the search in backward. So it starts the searching from the space after "hello" ( "Hello ").