I assigned the name of the player to the string playername, which confirms the sysout. Why doesn't the if execute, even though the name in the string matches the default ("ThePlayer27")?
MFG Johannes
Here is the code:
public class join implements listener {
@EventHandler
public void onStart (PlayerJoinEvent e) {
Player p = e.getPlayer ();
e.setJoinMessage ("§bThe player §o§8" + p.getName () + "§has joined the server!");
GiveItemHubCompass.givePlayerItems (p);
p.sendMessage ("§7 / sinfo for more information!");
String playername = p.getName ();
p.setGameMode (GameMode.ADVENTURE);
System.out.println (playername);
if (playername == "ThePlayer27") {
System.out.println (1);
e.setJoinMessage ("§bThe §Owner§o§8" + playername + "§b has joined the server");
p.setGameMode (GameMode.CREATIVE);
That's because
if (playername == "ThePlayer27") {
Rather write it like this:
if (playername.equalsIgnoreCase ("ThePlayer27")) {
you only have to do the IgnoreCase if the case is not case sensitive. So you can too
if (playername.equals ("ThePlayer27")) {
Maybe as a quick test. Have you tried:
playername.equalsIgnoreCase ("ThePlayer27")
to rule out a capitalization error?
Perfect, worked, could you briefly explain to me why == not possible? Then I learn it for the future
A comparison with == tests whether the reference of the string object is identical.
A comparison with .equals () tests whether the content of the object is identical (even if the reference is different)
I hope this example makes it clearer:
String a = new string ("test");
String b = new string ("test");
String c = a;
if (a == b) {} // FALSE (because it's a different reference)
if (a.equals (b)) {} // TRUE
if (b.equals (a)) {} // TRUE
if (a == c) {} // TRUE (because the reference is the same)
if (a.equals (c)) {} // TRUE
if (c.equals (a)) {} // TRUE
Perfect thanks, I got it
You could add something like that
String s = "test";
String s1 = "test";
if (s == s1) {} // TRUE
works. But only because java internally makes it the same object reference (same object). If new objects are explicitly created, you can only compare the hash value if (a.hashCode () == b.hashCode ()).
In short, always take equals with String for safety.
I agree.