Thursday, December 11, 2008

How to empty a StringBuffer

We know that StringBuffer is reusable , We may want to empty a String Buffer ( lets say at end of a loop )
so how do you do it ?

The easiest way i came across use the method setLength()
public void setLength(int newLength)
You may have the case like
StringBuffer sb = new StringBuffer("HelloWorld")
// after many iterations and manipulations
sb.setlength(0);
// reuse sb

Please note you cant say
StringBuffer sb = "";
You will get a type mismatch error saying that "Cannot assign a value of type String to StringBuffer"
Makes sense as StringBuffer is not String , and they both inherit from java.lang.Object

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="";
if(s.equals(""))
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";

if(s1==s2)
System.out.println("Yes");
else
System.out.println("No");

// 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

Sunday, September 28, 2008

Netbeans 6.1 and Tomcat 5.5

I was trying add Tomcat5.5 , i had used windows installer for it , to netbeans6.1 on windows and I always get the error "cannot find catalina.bat you cannot start your server through netbeans"
After spending quite some time on why was i getting this error I figured out that i must "Download the .zip formated Tomcat, not the Windows executable. It will have the files netbeans6.1 needs."

A lesson learned :)

Installing Netbeans without glassfish

Hi
This is crazy but true , you can install netbeans 6.1 without glassfish .. how ?? simple if you have no space in C drive and install Netbeans in D drive , i tried it out today and saw it happened that way for me

:)