"if" doesn't work while "switch" does

void setup(){
  
  String a = new String();
//a = "f*";
//a += "**";
  a+='f';
  a+='*';
  a+='*';
  a+='*';

  
  if(a == "f***"){
    println("hooray!");
  }else{
    println("f***");
  }
  
  switch(a){
    case "f***":
      println("why...");
      break;
  }
  
}

this problem occurs when i add string or char to String

maybe the problem is that I’m using win11
but if you have something that comes to your mind, let me know it

switch () / case: blocks invoke equals() internally when dealing w/ String types.

You should do the same everywhere else:

  • String is an immutable datatype.
  • Each time you append a character to it another String object is created.
  • When we use the equality == operator we’re comparing if both String operands are the same object, not if they have the same content.
  • Java caches String literals.
  • That’s why we can use the equality == operator on literals.
  • Try out println(P3D == OPENGL); on the PDE.
  • It outputs true b/c both constants hold the same String literal object.
  • Another example: println(platformNames[3] == "linux");
  • However avoid using == or != for comparing strings b/c they’ll fail outside literal comparing cases.
  • Just use method equals() for 100% success: println("windows".equals(platformNames[1])); // outputs true
1 Like

in short:
The == operator compares references not values.

1 Like

String doesn’t work with ==
better use equals() : if (myString.equals("Hello")) ....

switch() {.....} works with String

2 Likes

Hello,

Processing related references:

Above links to:

:)

1 Like