0

I recently wrote a program to convert a string from infix to post-fix in java! To do that i used two strings 's' and 'p'. I initialized both strings with 'NULL'. Then i got the value of s from user using Scanner class.

s=s1.nextLine();

so if user enter "a+b", then s has the value "a+b". Note that 'NULL' is no longer the part of the string!

Now I manipulate p using the concatenation operator '+' like:

p = p + '*';

I do get my post-fix string: i.e.

ab+.

Problem is that this time, NULL does not disappear! The value of p is:

"nullab+" instead of "ab+".

Now I know my concatenation operator is causing problems! It adds to the string!

But java [eclipse indigo] does not let me use an operator without initializing it first! What do I do? Please help!

Thank you

Anuj Kalra

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
user2839702
  • 15
  • 1
  • 1
  • 7
  • Imagine null.toString() will get "null". Is there any reason for not giving an init value? an empty string is a valid init value. – porfiriopartida Oct 02 '13 at 18:13

1 Answers1

3

You can initialize the string to empty string to start with:

String str = "";

The issue with null is that string concatenation with a null reference will convert it to "null" string and then perform the concatenation.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • WOW! I thought this wasn't allowed! I did as you said! Needless to say that it worked! Thanks a lot! Really liked your explanation!--Thanks once again! – user2839702 Oct 02 '13 at 18:14