Why the output is -1 in this java code? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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)); } }

19th Sep 2021, 11:49 AM
Coding San
Coding San - avatar
2 Answers
+ 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.
19th Sep 2021, 12:30 PM
Ipang
+ 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 ").
19th Sep 2021, 12:27 PM
Abhay
Abhay - avatar