Working with Strings in Java

Discussion in 'Java' started by Sanskruti, May 7, 2007.

  1. Sanskruti

    Sanskruti New Member

    Joined:
    Jan 7, 2007
    Messages:
    108
    Likes Received:
    18
    Trophy Points:
    0
    Occupation:
    Software Consultant
    Location:
    Mumbai, India

    Comparing Strings



    To compare strings function equals() is used.

    Code:
    String str1 = "XYZ";
    String str2 = "xyz";
    
    boolean result = str1.equals(str2);
    boolean result2 = str1.equalsIgnoreCase(str2);
    Output

    Code:
    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:
    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:
    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:
    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:
    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:
    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:
    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:
    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.
     
  2. oleber

    oleber New Member

    Joined:
    Apr 23, 2007
    Messages:
    37
    Likes Received:
    2
    Trophy Points:
    0
    Occupation:
    Software Developer (Perl, C/C++ and Java)
    Location:
    Hamburg, Germany
    Home Page:
    http://oleber.freehostia.com/
    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:
     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:
     str = str.intern();
     
     
    Last edited: May 9, 2007
  3. Khaos

    Khaos New Member

    Joined:
    May 12, 2007
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    Nice codes there. I kidna forgot some hack codes enabling Admin features in Java chat sites. OH WELL...
     
  4. LauDauns

    LauDauns New Member

    Joined:
    Oct 11, 2007
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    heheheh!~~!I have to say looks very good ...
     
    Last edited by a moderator: Oct 12, 2007
  5. devunion

    devunion New Member

    Joined:
    Sep 26, 2008
    Messages:
    19
    Likes Received:
    2
    Trophy Points:
    0
    It will be good to mention in your article memory leaks problems that can be caused by using substring() method.
     
  6. JVposter

    JVposter New Member

    Joined:
    Feb 26, 2009
    Messages:
    6
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    java programmer
    Location:
    Romania
    Home Page:
    http://www.marblehost.com
    hello!

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

    regards,
     
  7. bapsbps

    bapsbps New Member

    Joined:
    Mar 31, 2009
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    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
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice