Issue
I returned a String through a function and tried to compare using "if" block and I can clearly see those are same strings still is returns false Source code :
import java.util.HashMap;
public class solution {
public static void main(String[] args) {
String s="paper";
String t="title";
String ans = pivotIndex(s,t);
System.out.println(ans);
System.out.println(t);[output](https://i.stack.imgur.com/09NQj.png)
if(ans == t)
{
System.out.println("yes");
}
else {
System.out.println("no");
}
}
public static String pivotIndex(String s, String t) {
HashMap<Character, Character> map=new HashMap<>();
String compare = t;
for(int i=0;i<s.length();i++){
map.put(s.charAt(i),t.charAt(i));
}
String ans = "";
for(int i=0;i<s.length();i++){
ans+= map.get(s.charAt(i));
}
return ans;
}
}
Just wanted to return true when both string are the same!
Solution
String
is a class in Java, so you should compare it with other String
with equals()
method. When comparing via ==
, you compare links of objects, but not the objects itself.
But you may be confused with this code:
public class Main {
public static void main(String[] args) {
String a="hello";
String b="hello";
if(a == b)
{
System.out.println("yes");//prints 'yes'
}
else {
System.out.println("no");
}
}
}
When initializing with constant, constant String
puts in the memory, and subsequent initializations with that constant points to that memory.
Answered By - Barsikspit
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)