tags:

views:

1210

answers:

5

I need to know whether in Java does the indexOf() method return false or void for an unfound string? or does it return an index int of 0?

+8  A: 

It'll return -1 (hint: try it)

As in the JavaDoc

Brian Agnew
"Try it" isn't particularly definitive - but "read the docs" is :)
Jon Skeet
Assuming the docs are correct :-) I take your point, however.
Brian Agnew
+5  A: 

The Java API docs contain this answer. the indexOf methods on a String return -1 if the character is not found.

Thomas Owens
A: 

You mean Javascript? It returns -1.

Gustavo
No, he means Java, hence the phrase 'in Java', rather than 'in Javascript'
Visage
Well, with people who cannot read the JavaDoc, one can never be sure ...
Thilo
It is a very basic question, so his knowledge is very limited. I heard people refering to Javasctipt as Java when they are begginers. Now he knows the answer for two different questions ;)
Gustavo
+3  A: 

Look at the signature. It says int, so an integer is returned. To return another type (void or boolean) the signature would be different.

Brian Rasmussen
I'm guessing he is coming from the PHP world, where the "int" datatype is "only a guideline" ;-)
scunliffe
+2  A: 

Only PHP's str_pos is weird enough to return 0/false when the index isn't found. Most consider the PHP version to be a bad implementation.

int strpos  ( string $haystack  , mixed $needle  [, int $offset= 0  ] )

//Returns the position as an integer. If needle  is not found, strpos()
// will return boolean  FALSE.

/*
  Warning
  function may return Boolean FALSE, but may also return a non-Boolean value which
  evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more
  information. Use the === operator for testing the return value of this function.
*/
scunliffe
Oh my word that makes my brain hurt! Why??? Whhhhyyyyyy????
Software Monkey
What I don't get is the... ok so if the string starts with the keyword you are looking for, it will return 0, but if doesn't find what you are looking for, it might also return 0? WT?
scunliffe
@scunliffe: Although 0 == false, 0 !== false. But indeed, that's one of the worse design decisions in PHP's built-in functions (as in: bites me in the butt every so often).
Piskvor