Supernovah
Supernovah

Reputation: 2044

Java indexOf returns false for unfound string?

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?

Upvotes: 7

Views: 46106

Answers (5)

scunliffe
scunliffe

Reputation: 63606

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.
*/

Upvotes: 3

Brian Rasmussen
Brian Rasmussen

Reputation: 116421

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

Upvotes: 5

Gustavo
Gustavo

Reputation: 359

You mean Javascript? It returns -1.

Upvotes: 0

Thomas Owens
Thomas Owens

Reputation: 116187

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

Upvotes: 13

Brian Agnew
Brian Agnew

Reputation: 272337

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

As in the JavaDoc

Upvotes: 30

Related Questions