Thursday, November 27, 2008

Java ques

There are three types of empty string, null, "" and " ". Here is how to check for each flavour:

if ( s == null ) echo ( "was null" );
else if ( s.length() == 0 ) echo ( "was empty" );
else if ( s.trim().length () == 0 ) echo ( "was blank or other whitespace" );

We cant use the following
String s="";
sop("string equal");

Java tricky ques

Q: How can I check a string has no numbers?

A: The simplest way to check that a String does not contain any numbers is to use the regular expression class Pattern in the java.util.regex package. The method below uses the regular expression [^0-9]+ to check that none of the characters in the input string is a number. The square brackets define a character class. The negation modifier, ^, followed by the number range 0-9 means "not a number". The + quantifier asks the regular expression to match the character class one or more times.

Wednesday, November 26, 2008

Java String tricky ques

String s1 = "hello world";
String s2 = "hello world";


// output of first is Yes
the reason being that in above code you are comparing two references

public static void point1()
String s = new String("Friday");
String s1 = new String("Friday");
if (s == s1)
System.out.println("Equal A");
if (s.equals("Friday"))
System.out.println("Equal B");
ANS : Equal B
Because they are two different objects on heap , refering diff memeory addresses
hence their reference is not same.

more explanation here.

Tuesday, November 4, 2008