+ 1
IndexOf()
Why is the output -1 https://sololearn.com/compiler-playground/cS7qCZUEdNaC/?ref=app
3 Antworten
+ 3
Shivam Gupta ,
> the string method `indexOf()` returns the zero-based index of the first occurrence of a specified character or substring in a given string.
> we can also pass an `index value` as a second argument to define where the search should start from.
> the method returns `-1` if the passed value can not be found.
in your case the search is looking for an upper case "F". but this does not exist in the string. so `-1` will be returned.
if we search for "r", the result will be 5.
+ 1
Shivam Gupta
Alright so look — when you run lambo.indexOf("F"), what Java’s actually doing is scanning the "Lamborghini" string from left to right, hunting for the capital letter F.
But guess what?
There’s no F in "Lamborghini". Not even by accident 😂
So Java just hits you back with a -1, which literally means:
> “Didn’t find it, my guy.”
Also — Java is case-sensitive, so "F" ≠ "f" — and since there's no match, boom: -1.
That’s just how indexOf() rolls. Nothing wrong with your code — just asking for something that doesn’t exist 👨💻