aspose file tools*
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


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String - Char" Watch "String - Char" New topic
Author

String - Char

Tarun Oohri
Ranch Hand

Joined: Feb 20, 2013
Posts: 170
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 ?
Thanks!!!
E Armitage
Rancher

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

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


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: 31

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: 77
    
    1
To turn your char to a String you could use the primitive wrapper class.



SCJP 6 [ My stuff ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String - Char
 
Similar Threads
output is not coming please help
please help meeeee
string reverse O(N) or O(N/2)
Read a line of text and reverse each word do not use StringTokenizer
how to check whether a word is a palindrome