0

I could not find any threads containing information about why the indexOf method allows for different parameters other than an integer.

I tried to check in the javados to see if there was a method with the same name but different parameters but I couldn't find any that allowed an input of characters here: https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#indexOf-int-

However, reading the indexOf method with the int as a parameter I get that:

If a character with value ch occurs in the character sequence represented by this String object, then the index (in Unicode code units) of the first such occurrence is returned.

How is this possible though, I thought that you could only return a type that is the same as the method?

3
  • 1
    Unicode code units as a count of characters offset for the match (or -1 if there is no match). The result is an int (the count). Commented Dec 13, 2016 at 3:37
  • Oh okay, so the gist is you can pass characters to the parameter because they are unicode units right? Commented Dec 13, 2016 at 11:54
  • Possible duplication of this question. Commented Jun 7, 2017 at 10:01

1 Answer 1

1

One of the indexOf() methods(when we pass a character) is of type int and the parameter is also an int:

int indexOf(int ch)

When we pass a character thru the function, it will be typecasted automatically to the unicode value of the character, which is indeed an integer. The method will return an integer which is the index where the corresponding character first appears in the string.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh okay, I'll have to create a method and try that out myself, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.