• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

String - Char

 
Ranch Hand
Posts: 189
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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!!!
 
Rancher
Posts: 989
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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.
 
Ranch Hand
Posts: 52
Hibernate Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 80
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
To turn your char to a String you could use the primitive wrapper class.

 
There is no beard big enough to make me comfortable enough with my masculinity to wear pink. Tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic