Query from Strings chapter (Java Basics)

Hi Guys

In the Strings section of the Java basics course, indexof retrieves the position of the letter “L” from “Hello World” however given there are 3 instances of the letter L and 2 instances of the letter O how do we retrieve the location of letter L from “World”

Thank for you reading and your time


You can use the two-argument version of indexOf to get the index of a string after a particular index. For example, this is saying, get the index of "l", but start at the index of "World":

String helloWorld = "Hello World";
Integer indexOfWorld = helloWorld.indexOf("World");
Integer indexOfTheLInWorld = helloWorld.indexOf("l", indexOfWorld);

Or you could just do something like this

String helloWorld = "Hello World";
Integer indexOfTheLInWorld = helloWorld.indexOf("ld");

Thank you for responding.

Tried the resolution however cannot get the member indexof to populate against the Integer class
Thank you for your patience again as I understand this may be a very basic question.

Sorry about that! I should have used the primitive type int instead of the class Integer. Try this instead.

String helloWorld = "Hello World";
int indexOfWorld = helloWorld.indexOf("World");
int indexOfTheLInWorld = helloWorld.indexOf("l", 


String helloWorld = "Hello World";
int indexOfTheLInWorld = helloWorld.indexOf("ld");

Thank you, that works

FYI: thanks to autoboxing, Java does not really care about the difference between int and Integer.

That code did not work because you were assigning the output of System.out.println(…) to an Integer variable, but println returns void (so no return value).

What eelsholz wrote would have worked just fine with Integer.

1 Like