-3
public class Tester{
  public static void main (String args[]){

  String word="sandwich";
  char newWord[]=word.toCharArray();

  System.out.println(word.equals(transform(newWord)));
  if (word.equals(transform(newWord))){
      System.out.println("same");}
      else{
        System.out.println("not");
      }

  }
  public static String transform(char [] newWord){
    for(int i=0; i<newWord.length;i++)
    {
      System.out.print(String.valueOf(newWord[i]));
      //System.out.print(""+newWord[i]);

    }
   return "";
  }
    }

RESULT>> sandwich false sandwich not

Is there a way to convert a concatenated 'string' of characters to a string literal?

Richard
  • 7
  • 4
  • Use `System.out.println(word.equals(newWord));` – cpx Feb 03 '17 at 08:57
  • Thank you, but this is an example where it will not work. The altered string is not equivalent to the string literal so .equals() does not recognize them as equal. – Richard Feb 03 '17 at 10:10
  • Can you provide an example what you are trying to do? Try [ideone](http://ideone.com/). – cpx Feb 03 '17 at 10:14
  • @cpx. Just put up sample code. Thank you. – Richard Feb 03 '17 at 10:24
  • You don't need `transform` method. Just use `String s = String.valueOf(newWord);` to convert `char[]` to `String`. – cpx Feb 03 '17 at 10:35
  • @cpx. Dang, so close. I thought this would solve my problem, but the transform method is requred to do the grunt of the transformation work. So, the value from the method is what needs to be converted to a string literal. – Richard Feb 03 '17 at 11:24
  • If the goal is to convert `char[]` to `String` then what is the issue with `String.valueOf(newWord)`? – cpx Feb 03 '17 at 11:36
  • A method is used to convert and reform a string literal using some conditions. So, the original literal is taken apart and put together by some specific means. The result is then passed to be used to compare with the original literal. In my case, whether the reconstituted 'string' result is IDENTICAL to the original string literal. My example code indicates, even with the use of the valueOf(), for example, that they are not equivalent. The resulting mash-up of chars from the method is not recognized as a string literal equivalent. I hope that helps. – Richard Feb 03 '17 at 12:00
  • Here's the [correct way](http://pastebin.com/wQm5p744) to transform it into String if you're using a loop. – cpx Feb 03 '17 at 12:24

1 Answers1

0

You should never compare Strings with == (unless you know exactly what you are doing).

Use .equals() instead.

Boris Schegolev
  • 3,601
  • 5
  • 21
  • 34
  • The newly formed 'string' of characters is NOT equivalent to a string literal, so .equals is false. How can I convert the newly formed characters to a string literal? – Richard Feb 03 '17 at 10:12