Monday, December 13, 2010

Java Substring Compare Example

Welcome back to Java Code Online. Today's tutorial discusses comparison of a substring with other strings which is often required in Java programs.

In my last project I used to receive a large String message from a JMS sender via MQ. I was supposed to extract substrings from that original String using already known starting and ending index values. If the substring found matches the substring required, then the comparison is successful.

Today's example is based on the above process of comparison and matching the substrings.

Compare a substring
Task:- Extract a substring from a string starting at index value 5 and ending at index value 9. Compare it with the word "test", if a match occurs then display success else display no match.

The code is given below:-

    package JavaTest1;

    class TestIntToString {

        public static void main(String[] args) {

            String subStr = null;

            // Suppose this is the initial String,
            // we may also get this String from
            // the user or another external source
            String str = "I am testing substring comparision";

            // This is the word we are looking for in the
            // above string
            String strCompare = "test";

            // The starting Index value is
            int startIndexVal = 5;

            // The ending index value is
            int endIndexVal = 9;

            // Extract the substring in subStr
            subStr = str.substring(startIndexVal, endIndexVal);

            // Compare the subStr with strCompare
            if (subStr.equals(strCompare)) {
                System.out.println("Match Found in comparison, Success");
            } else {
                System.out.println("No Match found in comparison, Faliure");
            }       
        }
    }

When the above code is executed, the output is:-
      Match Found in comparison, Success


Related Articles
Search and Replace a Substring in Java Example

Sunday, December 12, 2010

Substring Index Out of Range or StringIndexOutOfBoundsException Java

While working with Strings in Java, we may get StringIndexOutOfBoundsException for the substring() method of the String class. This is to signify that the Index specified is out of the range.

For substring() method, we need to provide the start and end index values or only the start index value. The index value of String in Java starts from 0 and goes till one less then the string length. Substring method uses this information to extract a part of the original String.

While extracting a part of the String, if the starting index value is negative, or the end index value is greater then the String length. If such a case occurs then we get an StringIndexOutOfBoundsException, it is a message from the JVM to tell us that the index is out of range.

The below examples clarify it better:-

Reasons for StringIndexOutOfBoundsException 

The below code explains the occurrence of the StringIndexOutOfBoundsException.

     package JavaTest1;

    public class IndexOutOfRangeExample {

        /**
         * @param args
         */
        public static void main(String[] args) {

            String str = "Testing a string for Index out of range";
            System.out.println("The original String is: " + str);
            System.out.println("The length of the String is: " + str.length());

            str = str.substring(-1);

            System.out.println("The modified String is: " + str);
        }
    }

The above code will result in a run time exception. The output is shown below:-
    The original String is: Testing a string for Index out of range
    The length of the String is: 39
    Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
        at java.lang.String.substring(Unknown Source)
        at java.lang.String.substring(Unknown Source)
        at JavaTest1.IndexOutOfRangeExample.main(IndexOutOfRangeExample.java:14)


 The line str = str.substring(-1); is the root cause of this error. We will get the same exception if the line is replaced with any of the below line examples:-
  •  str = str.substring(0, 40);   //The length of the string considered is 39, so anything greater will cause index out of range.
  • str = str.substring(40, 49);   //The start index value is larger then the length of the String, so again the exception will be thrown.
  • str = str.substring(40);
  • str = str.substring(-58); //  Negative value for start index is cause of exception.
 To avoid this exception, make sure that you stay within the bounds of the String length.

Related Articles

Search and Replace a Substring in Java Example

Welcome back to Java Code Online. Very often in programming we need to search and replace particular instances of substring in a String. There are multiple ways of doing it, and the Java String class provides many methods and ways to doing the same. I am presenting some of the most common ways to achieve the same.

Using substring() method
The substring() method could be used to search and replace a substring in the main String. The below example searches and replaces the first instance of a substring in the original String.

    package JavaTest1;

    //This class search and replace the first
    //instance of a String in the main String.
    public class SearchReplaceSubString {

        /**
         * @param args
         */
        public static void main(String[] args) {

            String str = "This is a search and replace of substring example";

            System.out.println("The original String is: " + str);

            // We want to look for the String "search" and replace it with "find"
            String searchQuery = "search";
            String replaceWord = "find";
            int startIndexVal = 0;
            int endIndexVal = 0;

            // look for the starting index of searchQuery
            startIndexVal = str.indexOf(searchQuery);

            // evaluate the ending Index of searchQuery
            endIndexVal = startIndexVal + searchQuery.length();

            // Form the string again using the substring() method
            str = str.substring(0, startIndexVal) + replaceWord
                    + str.substring(endIndexVal);

            System.out.println("The modified String is: " + str);

        }

    }

When the above code is executed the output is:-
    The original String is: This is a search and replace of substring example
    The modified String is: This is a find and replace of substring example

Using replace() method
The String Class provides a very effective way to replace all the occurrences of a substring in the main string
It uses the replace() method of the String class. The example below looks for a substring and replaces all the occurrences of that substring with a new substring.

    package JavaTest1;

    //This class search and replace all the
    //instances of a substring in the main String.
    public class SearchReplaceSubString {

        /**
         * @param args
         */
        public static void main(String[] args) {

            String str = "Using Replace method for the searching and searching and replacing of a substring in a String";

            System.out.println("The original String is: " + str);

            // We want to look for the String "search" and replace it with "find"
            String searchWord = "search";
            String replaceWord = "find";

            // Replace all the occurrences of the searchWord with the replaceWord
            str = str.replace(searchWord, replaceWord);

            System.out.println("The modified String is: " + str);
        }
    }

When the example code is run, then the output is:-
     The original String is: Using Replace method for the searching and searching and replacing of a substring in a String
    The modified String is: Using Replace method for the finding and finding and replacing of a substring in a String


Related Articles


Java Substring Index

Welcome back to Java Code Online. The index of java substring is used to retrieve the starting and ending value of the substring in the original String. Understanding how the concept of index works in substring is vital to get a hold of this Java string method.

Index Value of Java Substring
When we use a substring to extract a part of the String, then we we provide the starting index value. We may use both the starting and ending value of index also.

The index value of a String stats from 0 and goes till one less then the length of the String. The below diagram clears this.

Suppose that we have a string called:-
     String str = "index value of substring";


In memory the string is stored as:-


So the string is stored starting at an index value of 0 to one less then the string length. Now there are two substring() operation possible on this. They are explained below:-

substring(startIndex)
When we want to retrive a substring from the original string, such that it starts from some index vale of the string and goes till the end of the String, then we use this method.

Using the above example, suppose we say:-
     String subStr1 = str.substring(6);

Then the output is:-
     value of substring

The below diagram explains this:-



So the method substring(startIndex) includes the starting index value while extracting the substring.

substring(startIndex, endIndex)
This method is used to extract a part of the string starting from the startIndex value and ending at the endIndex value.

Using the same example, suppose we say:-
      String subStr1 = str.substring(6, 18); 

Then the output is:-
     value of sub

The below image explains this:-


So the method substring(startIndex, endIndex) includes the starting Index value but excludes the ending Index value.

Related Articles
Substring Index Out of Range Exception
Convert int to String in Java
Convert int to String using Wrapper in Java
Java String Length Program
Reverse a String in Java

Java Substring Examples

Welcome back to Java Code Online. Today we would be discussing examples of Java substring() method. Substring is a method of the String class in Java. It is used to extract a part of the original String. The examples for Java substring() function are shown below.

Get a character from a String using substring()
This example extracts a character from the specified index value using the substring method.

    package JavaTest1;

    //Get a character at a specified index using substring
    public class SubStringChar {

        public static void main(String[] args) {

            String str = "substring() method example";
            String singleStr;

            singleStr = str.substring(5, 6);

            System.out.println(singleStr);
        }
    }

When the above code is executed, the output is:-
      r

The above code is useful when we want to extract a single character from a string. There are other methods also in the String class which can perform the above operation like charAt().

Get a substring from a string using the substring() method
The above example could be modified to extract a substring from the original String. The code is show below:-

    package JavaTest1;

  
    public class SubStringPart {

        public static void main(String[] args) {

            String str = "substring() method example";
            String singleStr;

            singleStr = str.substring(5, 16);

            System.out.println(singleStr);
        }
    }

The output of the above code is:-
      ring() meth


A very useful example when we want to extract some part of a string.

Search for a file type using substring() method
Suppose that we want to search a directory for a particular file type. We have many files in the directory, but we want a single file that is of a particular type (for example "pdf"). There are other files also in the directory which are of other file types(for example html, ppt, xml, xls, etc.).

The code below searches the directory for a pdf file and returns the name of the first pdf file found. This name could be used for reading the file in java, or for checking that a particular file type is present or not.

    package JavaTest1;

    import java.io.File;

    public class SearchSubString {

        private static final String fileExtensionDesired = "pdf";

        public static void main(String[] args) {

            String fileName = null;
            String fileExtension = null;
            String fileFound = null;

            int indexVal = 0;

            // Note the "\\" used in the path of the directory instead of "\",
            // this is required to read the path in the String format.

            File f = new File("D:\\JavaCodeFile");

            // Check if the directory exists
            if (f.exists()) {
                /*
                 * Retrieve all the files in the directory in the form of a File
                 * Array
                 */
                File[] fileArray = f.listFiles();

                for (int i = 0; i < fileArray.length; i++) {

                    // Get the file name and in a String
                    fileName = fileArray[i].getName();

                    // Get the index value of extension of the file
                    indexVal = fileName.lastIndexOf(".");

                    // Extension of the file starts from indexVal + 1
                    fileExtension = fileName.substring(indexVal + 1);

                    if (fileExtension.equals(fileExtensionDesired)) {

                        fileFound = fileName;

                        // Since we have found the first file, we can exit the
                        // for loop
                        break;
                    } else {
                        fileFound = null;
                        continue;
                    }
                }

                // if the file is found
                if (null != fileFound) {
                    // Display the name of the pdf file we were looking
                    System.out.println("Got the desired file: " + fileFound);
                }
                else
                {
                    System.out.println("No file found with the extension: " + fileExtensionDesired);
                }
            } else {
                System.out.println("The directory does not exist");
            }
        }
    }

When the above code is run on my machine, then the output is:-
      Got the desired file: JavaString.pdf


That's all from my side for the day. I hope the substring examples were helpful. Keep buzzing Java Code Online.

Related Readings
Java Substring Index
Search and Replace a Substring in Java Example 
Java Substring Compare Example 
Delete a Substring From a String Using Java

Related Articles

Convert int to String in Java
Convert int to String using Wrapper in Java
Java String Length Program
Reverse a String in Java


Saturday, December 11, 2010

Substring in Java

Substring is one of the most commonly used methods of the String class. Is is used for extracting a portion of the original string. This method is very useful when we are dealing with file names and extensions and want to extract some part of the Staring value.

Understanding substring()
For a good understanding of substring(), it is essential that we first see how Java stores the String in memory. For example if we say that:-
String str = "substring() is a method";

then in the memory the above String is stored as:-


from the above diagram it is clear that the indexing of Strings always start from zero, and goes till one less then the String length.

Substring uses this information to retrieve a part of the original string by providing the (starting) or (starting,ending) index values. The numbers mentioned in the above diagram are the index values for the characters of that String.

Syntax of substring() in Java
Substring comes in two flavor in Java. The two syntax of the method are:-

public String substring(int beginIndex)
Used to extract a portion of the String. The substring returned by this method starts from the character specified by the beginIndex value, and it ends till the last character of the original String.

public String substring(int beginIndex, int endIndex)
This method extracts a portion of the String. The substring returned by this method starts from the character specified by the beginIndex value and ends at the character specified by the endIndex value.

Exceptions for substring()
In case the starting Index value or the end Index value in the substring() method is out of the range of the String length, then the Java Virtual Machine throws a IndexOutOfBoundsException.

This exception shows that the Index value provided for the substring() method is either negative or larger than the String length.

substring() Examples
Example 1


    package JavaTest1;

    public class StringTest {

        public static void main(String[] args) {

            String str = "substring() is a method";
            String subStr;

            subStr = str.substring(5);
            System.out.println(subStr);
        }
    }

When the above code is executed, the output is:-
    ring() is a method

The below diagram explains the output received after the substring() operation.


Example 2

    package JavaTest1;

    public class StringTest {

        public static void main(String[] args) {

            String str = "substring() is a method";
            String subStrBeginEnd;

            subStrBeginEnd = str.substring(5, 21);
            System.out.println(subStrBeginEnd);
        }
    }

On execution of the above code, the output is:-
    ring() is a meth

The substring example is further explained by the diagram below.



Note:-The above diagram clears that the substring() method includes the starting index, but excludes the end index.

Do raise any queries if you need explanation on any part.

Related Readings
Java Substring Examples
Java Substring Index 
Substring Index Out of Range Exception

Related Articles
Convert int to String in Java
Convert int to String using Wrapper in Java
Java String Length Program
Reverse a String in Java

Friday, December 10, 2010

String In Java


Strings are Immutable Objects in Java. They are very commonly used in programs. The point that they are immutable means that whenever we modify or concat the previous string, then a new String Object is created. Moreover Strings are not Garbage collected by the garbage collector.

When we create a String object then the Java Virtual Machine (JVM) puts that String in the String Pool. If there is some String already existing in the String pool with the same value, then the JVM don't create a duplicate of that previous String. It just simply refers our reference variable to that already existing entry.

In Java programming we avoid using too many strings. the reason is that they are not garbage collected, and so when our programs are large, then the JVM ends up consuming lots of memory. This also makes the program execution slower.

For example if we just go through the below Java code:-

 String str = "abc";
 for(int counter= 0; counter<10; counter++)
 {
      str = str + counter;
      System.out.println(str);
 }

What do you think will happen after the above code is executed. What we are doing is creating 11 different string objects. When the code is executed, the output is:-

 abc0
 abc01
 abc012
 abc0123
 abc01234
 abc012345
 abc0123456
 abc01234567
 abc012345678
 abc0123456789


So we created 11 strings including the first one "abc". And the main part is that all these strings are in existence in the String pool even after you used the "+" operator to modify them. In-fact we cannot modify Strings, we concat them and thereby create new Strings with the new value.

It's for this reason that we use classes like StringBuffer and StringBuilder to do the appending operation. I will discuss StringBiffer and StringBuilder later.

Creation of a String in Java
The Java builders provide many Constructors to create a String. We can create a Java string simply by using the "new" keyword, since Strings are Objects in Java, and we can instantiate objects by using the "new" keyword.

So the below code creates a Java String and assigns it a value:-
 String str = new String ();
 str = "I love Java";

also this can be done by using a shorter way:-
 String str = new String ("I love Java");

both the code snippets do the same job of creating a new Java string and assigning it a value. Java provides an even better way of creating Strings:-
 String str = "I love Java";

Yes the above code did not used the "new" keyword, but does the same job. there are minor difference in the last method for creating Strings as compared to the previous ones.

When we say
 String str = "I love Java";
here we create a reference variable called "str", we place a String Object called "I love Java" in the String pool  and link them. So this method resulted in generation of an Object in the String pool and a reference variable. But when we say:-
 String str = new String ("I love Java");
here we create a reference variable called "str", we create a new Object on the Java heap(since we used the "new" keyword), and link them, finally we place the value Object "I love Java" on the String pool. So this method resulted in generation of two objects (one on the heap and the second on the String pool) and a reference variable.

Clearly direct invocation is better since it resulted in creating lesser Objects.
  
Methods in the String Class
Java provides multiple methods in the String class. These methods take care of almost any requirement we have regarding programming. The most commonly used and important methods of the String class are:-

concat() 
This method creates a new String with the value of the previous String appended to the new one.The usage of this method is shown below:-
 String str = "Java is fun";
 System.out.println(str.concat(" when you work hard") );

The output is:-
 Java is fun when you work hard

length()
This method returns the number of characters in the String. though the String indexing start from zero, but still the length counting starts from one. So for the below code:-
 String str = "Strings are intresting";
 System.out.println( str.length());

The output is:-
 22
 You may count yourself and check, don't forget to count the blank spaces in between, they are also characters and are therefore counted.

substring()
One of the most used method of the Java String class. It returns a part of the original String. It has two variations, they are substring(int begin) and substring(int begin, int end). The first one gives a sub part of the original string from the begin number till the end of the String. The second one is used to get a part of the original String from the begin number to the end number.

For example consider the below code snippet:-
 String str = "Strings are Immutable objects in Java"; 
 System.out.println(str.substring(12));
 System.out.println(str.substring(12, 21));

the output of the above code snippet is:-
 Immutable objects in Java
 Immutable


trim()
This method removes blank (whitespaces) from starting and ending of the String. It does not interfere with any blank space in between the words of the String.

Consider the below code snippet:-
String str = "           trim          testing                 ";
System.out.println( str.trim());

the output of the above code snippet is:-
 trim          testing

Note that the blank spaces at the start and end of the String are removed.

equals()
The most commonly used method to check the equality of two String Objects. Strings are compared using the equals() method since they are Objects and not primitives, Primitives are compared using "= =". The usage of equals() method is shown below:-
        String str = "Hello Java";
        System.out.println(str.equals("HeLLO JAVA"));
        System.out.println( str.equals("Hello Java"));

When this code is executed, the output is:-
 false
 true

this shows that equals() is case sensitive.

equalsIgnoreCase()
When we want to compare two Strings irrespective of their being in uppercase or lowercase, then we use equalsIgnoreCase(). This method is not case sensitive. Consider the previous example with the equals() replaced with equalsIgnoreCase():-
        String str = "Hello Java";
        System.out.println(str.equalsIgnoreCase("HeLLO JAVA"));
        System.out.println( str.equalsIgnoreCase("Hello Java"));

the output for this code is:-
 true
 true

replace()
This method is used to replace any occurrence of a character with a new character. It is a handy method and is often used in String manipulation. The example is given below:-
        String str = "java sample source code example";
        System.out.println( str.replace('a', 'b') );

When executed the output is:-
 jbvb sbmple source code exbmple

charAt()
This method is used to retrieve a character at a particular index in the String. The method returns a single character which is at the specified index location in the original String. Consider the code below:-
        String str = "Java";
        System.out.println( str.charAt(2) );

The output for the above code is:-
 v

toLowerCase()
This is a useful method to convert all the characters in the string to lower case. All the charcacters which are in uppercase in the original string are converted to lowercase. The code explains it further:-
        String str = "Java Is An Interesting Language";
        System.out.println(str.toLowerCase());

When executed the output is:-
 java is an interesting language

toUpperCase()
This is a useful method to convert all the characters in the string to upper case. All the charcacters which are in lowercase in the original string are converted to uppercase. The code explains it further:-
        String str = "Java Is An Interesting Language";
        System.out.println(str.toUpperCase());

When executed the output is:-
 JAVA IS AN INTERESTING LANGUAGE

toString()
This method simply returns the value of the string. Why would we need this method when we already have String? The answer is that this method is very useful when converting from StringBuffer to String and StringBuilder to String. The usage is shown below:-
        String str = "Java sample code";
        System.out.println(str.toString());

When executed the output is:-
Java sample code

I will discuss the StringBuilder and StringBuffer in my later articles.

Java class has lots of other methods which are useful. You may get the entire listing at:-
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html

Java String Examples
I would discuss few Java String Examples to make the topic more clear.

Java String Example 1
Task:- Conversion from an array of Strings to a single string using "," as a separator.

The code is given below:-
public class StringTest {

    public static void main(String[] args) {

        String[] str = { "Java", "Example", "for", "conversion", "from", "array", "of", "Strings", "to", "String" };
        String filler = "-";
        String output = "";

        // Check if the string array is not empty
        if (str.length > 0) {
            output = str[0];

            for (int i = 1; i < str.length; i++) {
                output = output + filler + str[i];
            }
        }
        System.out.println(output);
    }
}


 The output of the above code is:-
 Java-Example-for-conversion-from-array-of-Strings-to-String
 



Java String Example Links
Convert Java String to int
Convert int to String in Java
Convert int to String using Wrapper in Java
Java String Length Program
Reverse a String in Java

Other Java Examples you might be interested in
Java Program for Prime Numbers
Java Program for Fibonacci Series
Factorial Program in Java
Palindrome example in Java
Conversion from Decimal to Binary in Java
Conversion from Binary to Decimal in Java

Related readings
Substring in Java

External Readings
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html