File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes String - Char Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String - Char" Watch "String - Char" New topic

String - Char

Tarun Oohri
Ranch Hand

Joined: Feb 20, 2013
Posts: 189
Hi Everyone
I have a doubt on String. We all know String object are immutable, they can not be changed once created.
Above is the code which reverse the given string. My questions are as follows :
1. If String are immutable then how come we are able to append into the String using + operator ?
2. Why we can not cast (String)char ?
E Armitage

Joined: Mar 17, 2012
Posts: 989
Tarun Oohri wrote:Hi Everyone

1. If String are immutable then how come we are able to append into the String using + operator ?

We are not appending to the existing String. We are creating a new String whose value is a result of the concatenation of those two Strings. So the current String is not changed but a new String is created. That's why you don't just have
but to make sure that the old reference is now pointing to the new String.
Tarun Oohri wrote:Hi Everyone
2. Why we can not cast (String)char ?

Because String does not extend char or Character.
Pramod Kumar Pandey
Ranch Hand

Joined: Dec 05, 2013
Posts: 52

Tarun when you will try for this (String)char compile time error will occur. becauce if you are going to cast a char to a reference type then only possible options are Character, Object as a primitive is promoted to its own Wrapper or Object class , while String is a difference class.
Marc Cracco
Ranch Hand

Joined: Mar 09, 2010
Posts: 80
To turn your char to a String you could use the primitive wrapper class.

SCJP 6 [ My stuff ]
I agree. Here's the link:
subject: String - Char
It's not a secret anymore!