-2

I am trying to check if a playlist is simple or master by an index value. My problem is when I put the (True) URL it still returns a false statement "This is a simple Playlist".

Any tips on how I can fix this ?

String output = getPlaylistUrl(input);
String mediaRecord = output.substring(399);
String lastRecord = "gear4/prog_index.m3u8";
if (mediaRecord == lastRecord) {
    System.out.println("This is a master playlist");
} else {
    System.out.println("This is a simple playlist");
}
Modus Tollens
  • 5,083
  • 3
  • 38
  • 46
Dash
  • 11
  • 7

2 Answers2

3

In Java, strings can not be compared for equality using ==, because == compares two instances, not the content. So unless s1 and s2 are actually the same instance, s1 == s2 will never return true.

You need to use equals(...) to compare two strings for equality.

if (mediaRecord.equals(lastRecord) { ... }
Thorsten Dittmar
  • 55,956
  • 8
  • 91
  • 139
  • How can a perfectly correct answer be downvoted? – Thorsten Dittmar Apr 11 '18 at 14:02
  • 1
    'string comparisons using == always fail' well that's unecessarily broad... – daniu Apr 11 '18 at 14:02
  • @daniu What do you mean? You can not compare two strings for equality using == in Java. – Thorsten Dittmar Apr 11 '18 at 14:02
  • == will still check that the Strings are the same object. Not the same as checking that they have the same contents, but it won't necessary always fail (as daniu said). – the_pwner224 Apr 11 '18 at 14:04
  • 1
    `if ("a" == "a") System.out.println("true")` prints `true` for me, so the comparison doesn't _always_ fail. Same for `String a = "a"; System.out.println(a == "a")`, but that's becoming dangerous terrain. – daniu Apr 11 '18 at 14:04
  • I updated the answer anyways, but I still do not see why this should be a proper reason for a downvote. – Thorsten Dittmar Apr 11 '18 at 14:04
  • 1
    @daniu come on... that may not be completely accurate, but did not warrant a downvote... – jingx Apr 11 '18 at 14:06
  • Thanks for the feedback. I am still getting the Simple Playlist as a return value. I literally checked the index of the value I am comparing before this so I am confused why this may be happening. – Dash Apr 11 '18 at 14:09
  • Did you also debug to make sure that `mediaRecord` and `lastRecord` actually do contain the same text (including all whitespace, etc.)? – Thorsten Dittmar Apr 11 '18 at 14:15
  • Just checked thank you. MediaRecord is returning every record for some reason. – Dash Apr 11 '18 at 14:31
  • Thanks a ton I got it to work :) – Dash Apr 11 '18 at 14:46
0

In order to compare Strings you need to use .equals and not ==. Using == compares references and not values

Veselin Davidov
  • 7,031
  • 1
  • 15
  • 23