aspose file tools*
The moose likes Beginning Java and the fly likes Return a String at index with charAt. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Return a String at index with charAt." Watch "Return a String at index with charAt." New topic
Author

Return a String at index with charAt.

Lex van Rijswijk
Greenhorn

Joined: Jul 07, 2012
Posts: 10
I have two simple examples to support my question. I can't figure out why (1) is working while (2) isn't. In my opinion I use them the same way.

(1)

(2)

With the second one, I get an type mismatch error that says: Cannot convert from char to string. When I try to find an answer on internet I see the str declared as a var type in all examples. But it works with the first example. So what is the difference in the 'return line' of the code and why is the first working while the second isn't?

What am I missing? Thanks
John Jai
Bartender

Joined: May 31, 2011
Posts: 1776
Welcome to the Ranch, Lex.

The '+' operator is overloaded to do concatenation if one of the arguments to it is a String. Hence str.charAt(str.length()-1) + mid + str.charAt(0) forms a String which is the return type of frontBack() method but str.charAt(0) returns a char which is incompatible return type for the front22() method.

You can read that here
Lex van Rijswijk
Greenhorn

Joined: Jul 07, 2012
Posts: 10
John Jai,

Thank you for your fast and clear reply. I've asked this question at some other fora but... lets just say their answers weren't helpfull or friendly in any way.

If I want to return a String in the second example it's better to use str.substring()? Or are there other possibilities?

John Jai
Bartender

Joined: May 31, 2011
Posts: 1776
Yes, you can use the substring() method. Also you can use the valueOf(char) method to get the String representation of the character.
John Jai
Bartender

Joined: May 31, 2011
Posts: 1776
Lex van Rijswijk wrote:I've asked this question at some other fora but...

As you are new to ranch, please read this.
Lex van Rijswijk
Greenhorn

Joined: Jul 07, 2012
Posts: 10
Thank you, I'll give it a try!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Return a String at index with charAt.