wood burning stoves
The moose likes Beginning Java and the fly likes ++ with String.indexOf() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "++ with String.indexOf()" Watch "++ with String.indexOf()" New topic

++ with String.indexOf()

George Dee-Brown
Ranch Hand

Joined: Mar 15, 2001
Posts: 35
Any ideas why theses do NOT compile:
1. ++(stringVar.indexOf("."))
2. (stringVar.indexOf(".")++)
but this does compile:

I got the above compilation error while writting the following class to print out all the ".class" files from a directory:
File dir = new File("c:\\javasoln");
String[] st = dir.list(new FilenameFilter()
{public boolean accept(File f1, String entry)
{if ((entry.substring((int)(entry.indexOf(".")+1),entry.length()).equals("class")))
return true;
return false;

Manfred Leonhardt
Ranch Hand

Joined: Jan 09, 2001
Posts: 1492
Hi George,
Think operator precedence. The post and pre fix operators have the highest precedence.
In your first examples the compiler would need to increment a string using the post fix or pre fix notation both of which are not overloaded for use with a String!
"string"++; // Illegal!
++"string"; // Illegal!
In the one that does work the method is called first and then the addition happens. This functionality is supported by Strings
"string" + 1; // Legal.
George Dee-Brown
Ranch Hand

Joined: Mar 15, 2001
Posts: 35
can post and pre fix operators only be used with a variable and not the returned result from a method? (even though the stringVar.indexOf() method returns an int which is compatiable with ++).
P.S. the one that does work is adding the integer value 1 to the returned result of the method, which is also an integer. It is not executing - "string" + 1; // Legal.
Dave Vick
Ranch Hand

Joined: May 10, 2001
Posts: 3244
Operator precendence doesn't enter the picture here, at least not in your first example because you the parenthesis around the method. The actual, reason it doesn't work in your first two examples is because you are not using a variable. The increment and decrement operators add one to the original value of the variable and then store the result back into the variable. So, yes, your assumption was correct - it must be a variable in the expression. In a sense you were trying to do this:
stringVar.indexOf(".") = stringVar.indexOf(".") + 1
(this isn't exactly what hapens but it does show the thought process).
The line of code you had that did work doesn't need the cast
because both the method and then literal 1 are ints so the result is an int.
Hope that helps
[This message has been edited by Dave Vick (edited July 03, 2001).]

I agree. Here's the link: http://aspose.com/file-tools
subject: ++ with String.indexOf()
It's not a secret anymore!