Aug 142011
 

Java String is widely used in Java application development to store data. An integer, a float point number, a character, a date, an array…all can be represented by a String. So it’s really importance if you study all thing related to Java String and best practice when using it.

1. Java String is immutable.

This means the String object is read-only when the object has been created. You cannot change it anymore.

String string1 = "Hello World this is Java String, it cannot be changed after created";
2. Java String literal is a reference to a String object

This means you can call method of Java String class with a String literal like below:

int strLength = "Java String".length();
3. String concatenate

You can concat Java String like I do below:

String result = "Java" + "String" + "is" + "Immutable";

But the problem is that Java String is Immutable, that mean when you concatenate like above, new String object will be created for each + operator. “Java” is an object and “String” is another object, if “Java” + “String” then it generate another object equals to “Java String”…and this continues if there are more plus (+) operators.

So what is the best practice here? Use StringBuilder instead (you may hear of StringBuffer but I don’t recommend you to use it, maybe I will show why later). OK you should concatenate String as below:

StringBuilder sb = new StringBuilder();
		sb.append("Java").append("String").append("is");
		sb.append("Immutable");

		String result = sb.toString();
4. Compare Java String

The next thing to study is comparing Java Strings. OK let’s do it by the below example.

package net.searchdaily.java.string.bestpractice;

/**
 * This is an indepth-example of Java String to demonstrate all features of this
 * class. http://java.searchdaily.net. *
 * 
 * @author namnvhue
 * 
 */
public class AllAboutJavaString {

	public static void main(String[] args) {
		String javaString1 = "Java String";
		String javaString2 = "Java String";
		String javaString3 = new String("Java String");

		if (javaString1 == javaString2) {
			System.out.println("javaString1 = javaString2");
		} else {
			System.out.println("javaString1 != javaString2");
		}
		if (javaString1.equals(javaString2)) {
			System.out.println("javaString1 = javaString2");
		} else {
			System.out.println("javaString1 != javaString2");
		}

		if (javaString1 == javaString3) {
			System.out.println("javaString1 = javaString3");
		} else {
			System.out.println("javaString1 != javaString3");
		}

		if (javaString1.equals(javaString3)) {
			System.out.println("javaString1 = javaString3");
		} else {
			System.out.println("javaString1 != javaString3");
		}

	}
}

And here is the result:

image thumb40 Java String and best practice

Now you may ask me why javaString1 is not equal to javaString3? what is the difference between == and equals() method? (Hehe this question maybe ask in some Java interview too if you notice)

Well, the main difference is == is for object reference while equals() is for value check.

So javaString1 != javaString3 in the line 3 of the result is because javaString3 = new String(“Java String”); then javaString3 is referenced to another object rather than javaString1’s.

And in additional to the comparison, there are some other methods that may be useful to you:

  • boolean equalsIgnoreCase() (work as its name tells)
  • int compareTo(String string2): would return:

    - value 0, if this string is equal to the string argument

    - a value less than 0, if this string is less than the string argument

    - a value greater than 0, if this string is greater than the string argument

package net.searchdaily.java.string.bestpractice;

/**
 * This is an indepth-example of Java String to demonstrate all features of this
 * class. http://java.searchdaily.net. *
 * 
 * @author namnvhue
 * 
 */
public class CompareString {

	public static void main(String args[]) {

		String str = "Java String";
		String anotherString = "Java string";

		/* compare two strings, case sensitive */
		System.out.println(str.compareTo(anotherString)); // give -32: negative
															// mean not
															// str <
															// anotherString

		/* compare two strings, ignores character case */
		System.out.println(str.compareToIgnoreCase(anotherString)); // 0 means
																	// equals

		/* compare two strings, case sensitive */
		System.out.println(anotherString.compareTo(str)); // give 32: positive
															// mean
															// anotherString >
															// str
	}

}

Here is the result:

image thumb41 Java String and best practice

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>