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

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.