String Special Operations with Examples


As we know strings are a common and important part of programming, Java has added special support for several string operations within the syntax of the language. These operations include the automatic creation of new String instances from string literals, concatenation of multiple String objects by use of the + operator, and the conversion of other data types to a string representation. There are explicit methods available to perform all of these functions, but Java does them automatically as a convenience for the programmer and to add clarity.
Let's discuss below Special String Operations with examples.
  • String Literals
  • String Concatenation
  • String Concatenation with Other Data Types
  • String Conversion and toString( )
Learn complete Java programming language at Java Tutorial | Learn Java Programming with Examples

String Literals

Java String literal is created by using double quotes. For Example:
String s="javaguides";  
Each time you create a string literal, the JVM checks the string constant pool first. If the string already exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in the pool, a new string instance is created and placed in the pool. For example:
String s1="Welcome";  
String s2="Welcome";//will not create new instance  
In the above example only one object will be created. Firstly JVM will not find any string object with the value "Welcome" in string constant pool, so it will create a new object. After that it will find the string with the value "Welcome" in the pool, it will not create new object but will return the reference to the same instance.
String objects are stored in a special memory area known as string constant pool.

String Concatenation

In general, Java does not allow operators to be applied to String objects. The one exception to this rule is the + operator, which concatenates two strings, producing a String object as the result. This allows you to chain together a series of + operations. For example, the following fragment concatenates three strings:
String age = "9";
String s = "He is " + age + " years old.";
System.out.println(s);
This displays the string "He is 9 years old."
One practical use of string concatenation is found when you are creating very long strings. Instead of letting long strings wrap around within your source code, you can break them into smaller pieces, using the + to concatenate them. Here is an example:
// Using concatenation to prevent long lines.
class ConCat {
    public static void main(String args[]) {
         String longStr = "This could have been " + "a very long line that would have "
         + "wrapped around. But string concatenation " + "prevents this.";
         System.out.println(longStr);
    }
}
String provides String java.lang.String.concat(String str) method to concatenates the specified string to the end of this string.

String java.lang.String.concat(String str)

This method returns a string that represents the concatenation of this object's characters followed by the string argument's characters.
Example:
public class ConcatExmaple {
    public static void main(String[] args) {
         String str = "javaguides";
         str = str.concat(".net");
         System.out.println("Concatenates the specified string to the end of this string : " + str);

         System.out.println("cares".concat("s"));
         System.out.println("to".concat("get"));
    }
}
Output:
Concatenates the specified string to the end of this string : javaguides.net
caress
toget

String Concatenation with Other Data Types

You can concatenate strings with other types of data. For example, consider this slightly different version of the earlier example:
int age = 9;
String s = "He is " + age + " years old.";
System.out.println(s);
In this case, age is an int rather than another String, but the output produced is the same as before. This is because the int value in age is automatically converted into its string representation within a String object. This string is then concatenated as before. The compiler will convert an operand to its string equivalent whenever the other operand of the + is an instance of String.
Be careful when you mix other types of operations with string concatenation expressions, however. You might get surprising results. Consider the following:
String s = "four: " + 2 + 2;
System.out.println(s);
This fragment displays
four: 22
rather than the
four: 4
that you probably expected. Here’s why. Operator precedence causes the concatenation of "four" with the string equivalent of 2 to take place first. This result is then concatenated with the string equivalent of 2 a second time. To complete the integer addition first, you must use parentheses, like this:
String s = "four: " + (2 + 2);
Now s variable contains the string "four: 4".

String Conversion and toString( )

When Java converts data into its string representation during concatenation, it does so by calling one of the overloaded versions of the string conversion method valueOf( ) defined by String.
valueOf( ) is overloaded for all the primitive types and for type Object. For the primitive types, valueOf( ) returns a string that contains the human-readable equivalent of the value with which it is called. For objects, valueOf( ) calls the toString( ) method on the object.
Let's understand the usage of valueOf() and toString() methods with examples.

valueOf( )

The valueOf( ) method converts data from its internal format into a human-readable form.
The Java string valueOf() method converts different types of values into a string. By the help of string valueOf() method, you can convert int to string, long to string, boolean to string, character to string, float to a string, double to string, object to string and char array to string.
Here are a few of its forms and the signature or syntax of string valueOf() method is given below:
public static String valueOf(boolean b)  
public static String valueOf(char c)  
public static String valueOf(char[] c)  
public static String valueOf(int i)  
public static String valueOf(long l)  
public static String valueOf(float f)  
public static String valueOf(double d)  
public static String valueOf(Object o)  
Example: Let's see an example where we are converting all primitives and objects into strings.
public class StringValueOfExample5 {  
    public static void main(String[] args) {  
        boolean b1=true;  
        byte b2=11;    
        short sh = 12;  
        int i = 13;  
        long l = 14L;  
        float f = 15.5f;  
        double d = 16.5d;  
        char chr[]={'j','a','v','a'};  
        StringValueOfExample5 obj=new StringValueOfExample5();  
        String s1 = String.valueOf(b1);    
        String s2 = String.valueOf(b2);    
        String s3 = String.valueOf(sh);    
        String s4 = String.valueOf(i);    
        String s5 = String.valueOf(l);    
        String s6 = String.valueOf(f);    
        String s7 = String.valueOf(d);    
        String s8 = String.valueOf(chr);    
        String s9 = String.valueOf(obj);    
        System.out.println(s1);  
        System.out.println(s2);  
        System.out.println(s3);  
        System.out.println(s4);  
        System.out.println(s5);  
        System.out.println(s6);  
        System.out.println(s7);  
        System.out.println(s8);  
        System.out.println(s9);  
    }  
}
Output:
true
11
12
13
14
15.5
16.5
java
StringValueOfExample5@2a139a55

toString()

let’s examine the toString( ) method, because it is the means by which you can determine the string representation for objects of classes that you create.
Every class implements toString( ) because it is defined by Object. However, the default implementation of toString( ) is seldom sufficient. For most important classes that you create, you will want to override toString( ) and provide your own string representations.
Fortunately, this is easy to do. The toString( ) method has this general form:
String toString( )
To implement toString( ), simply return a String object that contains the human-readable string that appropriately describes an object of your class.
For example, they can be used in print( ) and println( ) statements and in concatenation expressions.
The following program demonstrates this by overriding toString( ) for the Box class:
class Box {
    double width;
    double height;
    double depth;

    Box(double w, double h, double d) {
         width = w;
         height = h;
         depth = d;
    }

    public String toString() {
         return "Dimensions are " + width + " by " + depth + " by " + height + ".";
    }
}

class toStringDemo {
    public static void main(String args[]) {
         Box b = new Box(10, 12, 14);
         String s = "Box b: " + b; // concatenate Box object
         System.out.println(b); // convert Box to string
         System.out.println(s);
    }
}
The output of this program is shown here:
Dimensions are 10.0 by 14.0 by 12.0
Box b: Dimensions are 10.0 by 14.0 by 12.0

Comments