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:
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"); You can also instantiate an empty String object by passing in just a pair of empty double quotes:
String myName = "";
String myName = null;
char[] firstName = {'A', 'r', 'u', 'n' };
String myName = new String(firstName);
char[] name = myName.toCharArray(); 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";
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));
a == aVar:false
a.equals(aVar):true
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));
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);
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