To compare strings, you should use (or rather what should be) using the equals method, but you may never have used an expression like this:
public static void main ( String [] args) {String
= "Hello";
if ("". Equals (a))
{System.out.println ("String is empty");
}}
Actually not very funny we're just calling the equals method of the String class, a String that is quoting but it has some advantages, such as creating an if to validate that user input is empty, but where is the advantage?.
Well if we have a String to and want to see it empty, the comparison would be very simple:
if (a.equals ("") {
System.out.println ("String is empty");}
But we must also validate that the String is not null, because if for example we are recovering in a Servlet, if the parameter was not sent, the String is null, then our comparison should look like:
This last amendment, we will assume that the compiler is able to recognize that if the first condition is met, will not run no more and not throw an exception, but since that would take something (in fact they do well), the comparison should be something like:
if (to! = null & & a.equals
("")) {System.out.println ("String is empty");}
With
public static void main (String [] args) {
String a = "Hello";
if (to! = null) {
if (a.equals ( ")
{System.out.println (" String is empty ");
}}}
However this problem can be solved easily as follows: public static void main (String [] args)
{String a = null;
if ("". equals (a))
{System.out.println ("String is empty");
}}
0 comments:
Post a Comment