0

I split String to String[] arr and want to compare element of arr with String but I don't know why System.out.println(arr[0] == "P"); return 'false'

Please check my code and answer to me. Thank you!

enter code here
String s = "pPooyy";
s = s.toUpperCase(); 
String[] arr; 
arr = s.split("");

System.out.println(arr[0]);
System.out.println(arr[0] == "P");

this is result. P false

System.out.println(arr[0]); -> the result of this println is P so I thought System.out.println(arr[0] == "P"); would return 'true' but it wasn't.

Why are these two types different?

  • *"I simply want to know why does this statement, `System.out.println(arr[0] == "P")` print false"* - Because `arr[0]` and `"P"` are not the same object. That is what `==` means for reference values. The correct way to test if two strings are equal (in the intuitive sense) is described in the dup-linked Q&A. – Stephen C Feb 16 '20 at 05:42
  • *"Why are these two types different?"* - The types are not different. It is the values that are different. Types and values are not the same thing. – Stephen C Feb 16 '20 at 05:43
  • @Stephen C Thank you so much for you answel! based on your answel, I could find the difference between '==' with .equals() and also I figure I need to learn about CBR, CBV! – Sungwon WI Feb 16 '20 at 06:00
  • I am glad I could help. – Stephen C Feb 16 '20 at 06:04

1 Answers1

0

Why not use charAt ?

Syso(s.charAt(0)=='P')

Let me know if this helps

  • Thank you for your answer! but I simply want to know why does this statement, System.out.println(arr[0] == "P"); return false.. – Sungwon WI Feb 16 '20 at 05:23