java - Different null comparison? -


what it's difference between 2 codes?:

code 1

in first code have variable in put directly null.

string prove = null;  toast.maketext(getapplicationcontext(), prove, toast.length_long).show();   if(prove == null) {   toast.maketext(getapplicationcontext(), "correct", toast.length_long).show(); } else {   toast.maketext(getapplicationcontext(), "incorrect", toast.length_long).show(); } 

result 1

null correct 

code 2

in second code have class named car get , set methods method have return string return null.

public class car {      private int idcar;     private string name;      public car(){};      public car(int idcar, string name)     {         this.idcar = idcar;         this.name = name;     }      //here rest of , set methods      public string getname()     {         return name;     } } 

and in mainactivity.java have arraylist of cars:

arraylist<car> cars = new arraylist<car>(); 

that use on customadapter, follows:

toast.maketext(getapplicationcontext(), cars.get(position).getname(), toast.length_long).show();  if(cars.get(position).getname() == null) {    toast.maketext(getapplicationcontext(), "correct", toast.length_long).show(); } else {    toast.maketext(getapplicationcontext(), "incorrect", toast.length_long).show(); } 

result 2

null incorrect 

what difference between both codes? apparently similar because in both of them compare string it's null vs null behaviour it's different.

thanks in advance!

these 2 codes worlds apart in they're doing.

in first example, explicitly set variable null , comparing against null. can reasoned with; code path exercise doesn't directly change value that's non-null, make perfect sense see toast "correct".

in second example, 2 different things:

  • you create toast right off bat text cars(position).getname()
  • you check if cars(position).getname() null or not. scenario isn't , shows other path.

if wanted make them @ least similar, move cars(position).getname() variable...

string prove = cars(position).getname();  if(prove == null) {    toast.maketext(getapplicationcontext(), "correct", toast.length_long).show(); } else {    toast.maketext(getapplicationcontext(), "incorrect", toast.length_long).show(); } 

i did quick dive source code toast, , if string provide null supply empty string instead (or toast that's blank). haven't indicated you're not seeing text in second toast provided, presume value you're getting cars(position).getname() not null.


Comments