dimanche 19 avril 2020

null check if statement isn't working in java

i want to check a instanciate object is null in java when i press enter, i have a class with a constructor and i pass a parameter

private String codigo;
    private String nombre;
    private String descripcion;
    private String foto;
    private String stock;

public Producto(String codigo) {
   this.codigo = codigo;
        this.nombre = nombre;
        this.descripcion = descripcion;
}
/*then getters and setters


*/


//this is in a java form 
private void txtCodigoProductoActionPerformed(java.awt.event.ActionEvent evt) { 
Producto producto = new Producto(txtCodigoProducto.getText());
System.out.println(producto);


if (producto==null) {
            JOptionPane.showMessageDialog(this, "No existe este producto");

        }else{
            lbl1.setText(producto.getNombre());
            lbl2.setText(producto.getDescripcion());
         }

}

System.out.println(producto) shows null when i press enter since i wrote an incorrect number so all the attributes of producto are null but then why it doesn't check if is null and doesn't show me the the message dialog? I change the condition to one of the attributes since all of them are null:

if (producto.getStock()==null) {
            JOptionPane.showMessageDialog(this, "No existe este producto");

        }else{
            lbl1.setText(producto.getNombre());
            lbl2.setText(producto.getDescripcion());
         }
}

and it worked and showed me the messageDialog, so why producto == null doesn't work?

Aucun commentaire:

Enregistrer un commentaire