Hi, I just started in java and I'm working through Sams Teach Yourself Java 1.2 in 21 Days. There's an example that uses string methods like indexOf, charAt and others. Well there's one that I'm confused on and hoped someone could shed some light on for me. Here's the code.
String str = "In my next life, I will believe in reincarnation";
System.out.println("The index of the beginning of the " + "substring \"will\": + str.indexOf("will")); I understand it's using the indexOf method, but my question is why does it break up ...."of the" + "substring \"will\": into two strings there? I assume the quotes around will have something to do with it, but I'm not really clear on it all. Thanks for any insight you can give.
Hi Tyler, You seem to be missing some quotes there - I'm guessing that what you meant is:- System.out.println("The index of the beginning of the " + "substring \"will\": "+ str.indexOf("will")); I've added " before the final +. I don't think there is any good reason for splitting up the string. It's equivalent to:- System.out.println("The index of the beginning of the substring \"will\": "+ str.indexOf("will")); It may simply be to improve the format of the code. If the code makes the line too long, you can spread it over two lines if you use + to concatenate the strings. Hope this helps, Kathy
[This message has been edited by Kathy Rogers (edited December 01, 2000).]
posted 19 years ago
Thanks. I couldn't figure out why they would do that, so I'm glad to hear that there's really no reason and I don't have to worry about it.
Hi Tyler, The '\' is known as escape character which is used when you need to override the chars that have spceial meaning in java, int this case '"'. Here you are also missing a quote just before + str. In your example the output would be : The index of the beginning of the substring "will" : <some number>
This parrot is no more. It has ceased to be. Now it's a tiny ad: