Thursday, December 3, 2009

Java String


Creating Strings

Manipulating text is a common computer programming task. Several languages (perl, for instance) were purposely designed to include powerful text processing capabilities. Early Java versions were not designed with this in mind, so developers had to rely on third-party libraries to add decent string handling capabilities. But, with recent releases of the JDK, Java now has solid, built-in support for manipulating text through both regular expressions and enhanced string-related classes. In this tutorial, we'll take a look at Java's basic text processing class java.lang.String

Strings are Objects

Java uses primitives to represent basic data types, such as integers, floats, characters, and bytes, because primitives are very efficient for a computer to manipulate internally. For a programmer, though, primitives don't provide any benefit. Object-oriented programming emphasizes putting related data and behavior together into objects, but primitives can only hold data. In order to provide both an efficient and object-oriented string data type, the Java designers came up with a specially-handled class called java.lang.String.

Creating Strings

String enjoys a special shortcut syntax for instantiating new String objects from string literals:

String myName = "Arunkumar Subramaniam ";

The text between double quotes is a string literal. By assigning a string literal to myName, you can avoid using the new keyword. In fact, this special shortcut syntax was designed to improve String performance: Each JVM only keeps one copy of each string literal. The following code creates a single string literal that both String references point to:

String literalOne = "I am a literal.";

//points to the same object as literalOne

String literalTwo = "I am a literal.";

But, you can still use new to create a String object:

String myName = new String("Arunkumar Subramaniam");  
Note: You almost always want to initialize String references with literals to avoid creating unnecessary objects in the JVM. This can really add up if you are creating hundreds of identical Strings.

You can also instantiate an empty String object by passing in just a pair of empty double quotes:

   String myName = "";  
If you don't know what a String object's value should be, but you need to create a reference, you can indicate this by assigning the null value;
   String myName = null;  
Java has a char primitive for representing single characters, and Strings are simply one or more characters. Not surprisingly, the language designers have made it is easy to convert a char[] to a String and vice versa. In this example, firstName, myName, and name all end up holding the text "Kevin":
   char[] firstName = {'A', 'r', 'u', 'n' };    
String myName = new String(firstName);
char[] name = myName.toCharArray();
Now that you know what a String is and how to create one, in Part 2, we'll take a look at common String operations.

Joining Strings

The operators '+' and '+=' are overloaded to work with Strings; this makes it easier for programmers to treat Strings as if they were primitives (trust me, they are not).

  //Using the + operator
String firstName = "Arunkumar";
String lastName = "Subramaniam";
String fullName = firstName + " " + lastName;

//Using the += operator
String fullName = "";
fullName += "Arunkumar";
fullName += " ";
fullName += "Subramaniam";
Both of these code snippets produce the same output:
Arunkumar Subramaniam
Note: One thing to keep in mind when joining Strings is that String objects are immutable: once a String object has been instantiated, its data cannot change. When you join (or concatenate) one String object to another using + or +=, you are not changing the original String object. You are actually creating a third String object that contains the data from the first two. This can cause performance issues when many String objects are being concatenated together. A better alternative is to use the java.lang.StringBuilder (or java.lang.StringBuffer in pre-5.0 JDKs) class, which is mutable.

Joining Strings to Primitives

The '+' and '+=' operators are also overloaded to join Strings to all the primitive data types:

  
String data = "";
char delimiter = ',';
data += 123;
data += delimiter;
data += 4L;
data += delimiter;
data += "Arunkumar";

This will produce: 123,4,Arunkumar

Comparing Strings

Remember that in Java there are two ways to test for equality. For primitives, the == operator is always used. For objects, including Strings, either the == operator or the equals() method (that all classes inherit from class Object) can be used. But, be careful: == tests the equality of the two String references. Do both String references point to the same object, i.e. the same location in memory? On the other hand, String.equals() tests whether the value of the two String objects are the same. In most cases, you want to use String.equals().

A few examples will clarify the difference between == and equals():

String a = new String("a");

String aVar = new String("a");

//Notice I need to wrap the == comparison
//in () because of operator precedence rules.
System.out.println("a == aVar:" + (a == aVar));
System.out.println("a.equals(aVar):" + a.equals(aVar));

This will produce:
 a == aVar:false
a.equals(aVar):true

So, the == operator compared object references. It said that, no, a does not point to the same memory space as aVar: they point to different objects. a.equals(aVar) returns true, on the other hand, because the value of the two Strings are equal: they both contain "a".

Okay, it is just a tad bit trickier than what I just stated. Remember that there are two ways to define a String. What I just said applies only when at least one of the Strings was instantiated with the new keyword. In these cases, a new object is created in memory. But, what about when both String references point to the same string literal? Then the == and equals() comparisons will both return the same result! Take a look:

   //We are not using the new operator
String a = "a";
String aVar = "a";

System.out.println("a == aVar:" + (a == aVar));
System.out.println("a.equals(aVar):" + a.equals(aVar));
This will produce:
a == aVar:true
a.equals(aVar):true

Finding a Substring

A common operation is determining if a String contains a smaller substring.
String address = "SSM College of Engg,Salem Main Road";
int location = address.indexOf("Street");
System.out.println("Street starts at index " + location);
substring() returns the zero-based index of the start of the substring. In this case: Street starts at index 9

Other String Methods

We have covered the essentials of how the String class works. But, there are dozens of useful String methods available and the best way to learn them is to read the API documentation and write some practice code (just as we did above). Here are some of the most useful String methods:
endsWith(String s) Does the String end with the String s.
contains(CharSequence s) Does the String contain the CharSequence s.
length() Return the number of characters in the String.
split(String regex) Use regular expression to split the String into a String[].
substring(int beginIndex, int endIndex) Return the substring between beginIndex and endIndex.
trim() Remove leading and trailing whitespace from the String.

0 comments:

Post a Comment

 

JAVA INTRODUCTION Blak Magik is Designed by productive dreams for smashing magazine Bloggerized by Ipiet © 2008