• Post Reply Bookmark Topic Watch Topic
  • New Topic

Reversing a String  RSS feed

 
Shubham Semwal
Ranch Hand
Posts: 176
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I'm trying to reverse a string to find if it's a palindrome or not.



Sample -
ABC -> nullCBA (it's adding the reversed code after null).

Only later I found that for reversing I need to initialize revPhrase=" ".
Why is null getting appended as a character ?
 
Tushar Goel
Ranch Hand
Posts: 934
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
default value of an object is null so when you dont initialize String with empty string or some other value then it consists null.
 
Shubham Semwal
Ranch Hand
Posts: 176
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was under the impression that if anything is assigned to string NULL ceases to exist.
 
Ramya R Subramanian
Ranch Hand
Posts: 182
18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I guess the variables phrase and revPhrase are instance variables. If they are not initialized then they will be given default value of null. Now the reversed value is concatenated with default value null so you get " nullCBA". But when you initialize with "", its like an empty String and works fine.

 
Shubham Semwal
Ranch Hand
Posts: 176
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes. That's exactly what's happening.
 
Ramya R Subramanian
Ranch Hand
Posts: 182
18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you can check out the default values for data types here

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

If you are not providing any initial value for an instance variable, a default initial value is provided automatically. An instance variable can also be a variable of object type. For such variables, the default initial value is null. In particular, since Strings are objects, the default initial value for String variables is null.


from - Introduction to Programming Using Java by David J Eck
 
Shubham Semwal
Ranch Hand
Posts: 176
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks all
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!