Sunday, January 22, 2012

Delete a Substring From a String Using Java

Task:- Delete a substring from a String.
Solution: There are two approaches for the same. We might need to delete a specific substring from the String, or we might need to delete a substring using the index positions. Both the approaches are shown below:-

Delete a specific substring from a string. The below code deletes the word "substring" from the original String.
The code is given below:-

 package javaTest1;

 //Delete using the name of the substring to be deleted
 public class DeleteSubString1 {
    public static void main(String[] args) {
        String oldStr = "Hello, this is the string from which a substring will be deleted";
        String delStr = "substring";
        String newStr;

        newStr = oldStr.replace(delStr, "");

        System.out.println(oldStr);
        System.out.println(newStr);
    }
 }

When the above code is executed the output is:-
 Hello, this is the string from which a substring will be deleted
 Hello, this is the string from which a  will be deleted

Delete a substring from a string using index positions. The below code deletes the word "substring" from the original String based on the index positions provided.
The code is given below:-
 package javaTest1;

 //Delete using the index positions to be deleted
 public class DeleteSubString2 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        String oldStr = "Hello, this is the string from which a substring will be deleted";
        String delStr;
        String newStr;

        delStr = oldStr.substring(39, 48);
        newStr = oldStr.replace(delStr, "");

        System.out.println(oldStr);
        System.out.println(newStr);
    }
 }

When the above code is run, the output is:-
 Hello, this is the string from which a substring will be deleted
 Hello, this is the string from which a  will be deleted


Related Articles
Substring Index Out of Range Exception
Search and Replace a Substring in Java Example

Wednesday, August 17, 2011

Java Interview Notes Lesson 1

These notes below are aimed to be a quick reference to any one gearing for a Java Interview. I have broken the series in parts, and this is part one of the tutorial lesson.

Classes
  • A source code file can have only one public class.
  • If the source file contains a public class, the filename must match the public class name.
  • There can be more than one nonpublic class in a file.
  • Files with no public classes have no naming restrictions.
  • Classes can also be final or abstract, but not both at the same time.
  • Classes can have only public or default access.
    • A class with default access can be seen only by classes within the same package.
    • A class with public access can be seen by all classes from all packages

Local Variables
  •  Local variables can not have access modifiers, and final is the only modifier applicable for them.

Interface
  • Interface methods are by default public and abstract. Explicit declaration of these modifiers is optional. 
  • Interfaces can have variables declared which are by implicitly constants as they are always implicitly  public, static, and final.
Polymorphism
  • The reference variable's type (not the object's type), determines which methods can be called.
  • Object type (not the reference variable's type), determines which overridden method is used at runtime.

Some Pointer Notes:
  • Abstract class cannot be instantiated.
  • Final class cannot be subclassed.
  • Private instance variables and methods are not visible to subclass, so they cannot be inherited.
  • Final methods cannot be overridden in a subclass. 
  • Abstract classes have constructors that are called when a concrete subclass is instantiated.
  • Interfaces do not have constructors.

Thursday, August 11, 2011

Enabling Java in Ubuntu and Mozilla, Jar execution

Hi folks.

Today's Aim
  1. Enable Java in Ubuntu 11.
  2. Execute Applets in Mozilla in Ubuntu, adding the Java plug-in to Mozilla Firefox in Ubuntu.
  3. Execute Jar files directly in Ubuntu for which we do not have execute access.

I have been working on Java for a long time on Windows systems. Yesterday I was giving a try on Ubuntu and really felt the pain of getting Java up in Ubuntu. So I decided to dot my learning in this article.

Task 1: Enable Java in Ubuntu 11
Ubuntu comes with an open jdk for running Java. We need to install it, or else we may get it from Sun Microsystems (Now Oracle) also. I preferred the open-jdk as it was much easier to install and get running.

Steps:
  • Open Terminal
  • Type: java -version. This will give the list of packages containg java.I got the below listing on my machine.
                      $ java -version
                       The program 'java' can be found in the following packages:
                       * gcj-4.4-jre-headless
                       * gcj-4.5-jre-headless
                       * openjdk-6-jre-headless
                        Try: sudo apt-get install
  • Select the openjdk to be installed. My machine's screen text is below:
               $ sudo apt-get install openjdk-6-jre-headless
  • This will install Java in your Ubuntu machine.

Task 2: Execute Applets in Mozilla in Ubuntu, adding the Java plug-in to Mozilla Firefox in Ubuntu.
For enabling Java in Mozilla Firefox in Ubuntu so that it can run Java Applets, follow the below steps.
  • Open Terminal
  • Install icedtea6-plugin. The screen-text from my machine is:
                      $ sudo apt-get install icedtea6-plugin
  • This will install the icedtea6-plugin on your Ubuntu Mozilla Firefox and will enable you to run Java Applets.
 
Task 3: Execute Jar files directly in Ubuntu for which we do not have execute access.
This was the most tricky of all. I had a jar file which i made through my Windows login for which i do not have execute access on Ubuntu machine. I tried chmod, chown, manually changing the permissions, etc, but all failed. The trick that finally worked was with Terminal again.

Use the following command to execute jar files in Ubuntu from Terminal.
$ java -jar filename


The screentext from my machine is:-
$ java -jar HelloWorld.jar

the above jar is a Java Applet and it executed just perfectly fine on Ubuntu. I also heard about some software called Wine for the same purpose, but did not tried it, as my job got done with the Terminal.

I hope the article will be useful to my readers. Will keep posting on more updates from my-side on this Java blog.

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