Working with Strings in Java

Sanskruti's Avatar author of Working with Strings in Java
This is an article on Working with Strings in Java in Java.

Comparing Strings



To compare strings function equals() is used.

Code: Java
String str1 = "XYZ";
String str2 = "xyz";

boolean result = str1.equals(str2);
boolean result2 = str1.equalsIgnoreCase(str2);
Output

Code: Java
result = false;
result2= true;
String comparison is a common source of bugs for novice Java programmers. A novice programmer will often attempt to compare strings using the comparison operator ==. When used with Strings, the comparison operator == compares object references, not the contents of the object. Because of this, two string objects that contain the same string data, but are physically distinct string object instances, will not compare as equal when using the comparison operator.

Code: Java
String name1 = new String("Timmy");
String name2 = new String("Timmy");

if (name1 == name2)
{
     System.out.println("The strings are equal.");
}
else
{
     System.out.println("The strings are not equal.");
}
The output from executing these statements will be

Code:
The strings are not equal.
Now use the equals() method and see the results:

Code: Java
String name1 = new String("Timmy");
String name2 = new String("Timmy");

if (name1.equals(name2))
{
     System.out.println("The strings are equal.");
}
else
{
     System.out.println("The strings are not equal.");
}
The output from executing these statements will be

Code:
The strings are equal.

Searching For and Retrieving Substrings



Code: Java
int result = string1.indexOf(string2);
int result = string1.indexOf(string2, 5);
In the first method shown, the value of result will contain the index of the first occurrence of string2 within string1. If string2 is not contained within string1, -1 will be returned.

In the second method shown, the value of result will contain the index of the first occurrence of string2 within string1 that occurs after the fifth character within string1. The second parameter can be any valid integer greater than 0. If the value is greater than the length of string1, a result of -1 will be returned.

Code: Java
String string1 = "My address is 555 Big Tree Lane";
String address = string1.substring(14);
System.out.println(address);
This code will print out

Code:
555 Big Tree Lane

Processing a String One Character at a Time



Code: Java
for (int index = 0; index < string1.length();index++)
{
     char aChar = string1.charAt(index);
}
The charAt() method allows you to obtain a single character from the string at the specified index. The characters are indexed 0 based, from 0 to the length of the string-1. The phrase shown previously loops through each character contained in string1.

An alternative method would be to use the StringReader class, as follows:

Code: Java
StringReader reader = new StringReader(string1);
int singleChar = reader.read();
Using this mechanism, the read() method of the StringReader class returns one character at a time, as an integer. Each time the read() method is called, the next character of the string will be returned.

Making a String All Uppercase or All Lowercase


Code: Java
String string = "Contains some Upper and some Lower.";

String string2 = string.toUpperCase();
String string3 = string.toLowerCase();

System.out.println(string2);
System.out.println(string3);
Output
Code:
CONTAINS SOME UPPER AND SOME LOWER.
contains some upper and some lower.
oleber's Avatar, Join Date: Apr 2007
Go4Expert Member
One more point:

The strings are a normal point of memory problems. Many times in a system exist allot of object instances representing an equal String. The String has the method String.intern() that gives the some Object instance (99% true) for equal String.

Code: JAVA
String name1 = new String("Timmy");
 String name2 = new String("Timmy");
 
 if (name1 == name2) {
     System.out.println("The strings are equal.");
 } else {
     System.out.println("The strings are not equal.");
 }
 
 if (name1.intern() == name2.intern()) {
     System.out.println("The strings are equal.");
 } else {
     System.out.println("The strings are not equal.");
 }

Output

Code:
 The strings are not equal.
 The strings are equal.
So, if you have allot of equal Strings, you can consider to have:

Code: JAVA
str = str.intern();

Last edited by oleber; 9May2007 at 21:53..
Khaos's Avatar, Join Date: May 2007
Newbie Member
Nice codes there. I kidna forgot some hack codes enabling Admin features in Java chat sites. OH WELL...
LauDauns's Avatar, Join Date: Oct 2007
Newbie Member
heheheh!~~!I have to say looks very good ...

Last edited by shabbir; 12Oct2007 at 14:11.. Reason: Confine links to signatures
devunion's Avatar, Join Date: Sep 2008
Go4Expert Member
It will be good to mention in your article memory leaks problems that can be caused by using substring() method.
JVposter's Avatar, Join Date: Feb 2009
Light Poster
hello!

you must use ".equals()" not "==" for string comparing like in above example

regards,
bapsbps's Avatar, Join Date: Mar 2009
Newbie Member
Code:
public class StringDemo {
    public static void main(String[] args) {
        String palindrome = "Dot saw I was Tod";
        int len = palindrome.length();
        char[] tempCharArray = new char[len];
        char[] charArray = new char[len];
        
        // put original string in an array of chars
        for (int i = 0; i < len; i++) {
            tempCharArray[i] = palindrome.charAt(i);
        } 
        
        // reverse array of chars
        for (int j = 0; j < len; j++) {
            charArray[j] = tempCharArray[len - 1 - j];
        }
        
        String reversePalindrome =  new String(charArray);
        System.out.println(reversePalindrome);
    }
}
Running the program produces this output:
doT saw I was toD