Tutorial
Menus

Java Beginners - Java For Beginners

Java String

Rating: 5.0/5 (1 vote cast)

Level   : Beginners
Author : Arunkumar S
Download Source : Not Avaliable

Java String -Working with Strings

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.


< Previous 1 | 2 | 

Discussion about this tutorial

  Start a new Discussion | Read All Discussion
Subject RepliesLast Post
Javaorigin.com contact@javaorigin.com