Concatenation – Conversion

We know earlier, the + operator is implicitly overloaded in Java – works for addition and concatenation. For concatenation, String class includes concat() method. That is, strings can be concatenated both with + operator an concat() method. Following program illustrates.

public class Concat
{
  public static void main(String args[])
  {			           
    String s1 = "to";
    String s2 = "get";
    String s3 = "her";
    String s4 = s1+s2+s3;
    String s5 = s1.concat(s2);
    String s6= (s1.concat(s2)).concat(s3);
    System.out.println(s4);   
    System.out.println(s5); 
    System.out.println(s6); 
  }
}
Concatenation - Conversion
Output screen of Concat.java

String s4 = s1+s2+s3;
String s5 = s1.concat(s2);
String s6= (s1.concat(s2)).concat(s3);

The strings s1, s2 and s3 are concatenated using + operator in the first statement and with concat() method in the second statement. Observe the third one where two concat() methods are used to concat all the three strings with a single step.

Continue to read "Concatenation – Conversion" to convert in between string to array and vice versa.

String to Array and Array to String

In realtime programming, it is very necessary to convert arrays to strings and vice versa. For example, in socket programming using UDP protocol, the strings to pass to the other systems must be converted into byte array. After receiving on the other side, the bytes are to be converted back to string to display to the user.

String to Array

To do this, the String class comes with three methods – getBytes(), toCharArray() and getChars(). Following are the methods details.

  1. byte[] getBytes(): Converts all the characters of the string into bytes and returns them in the form of a byte array.
  2. char[] toCharArray(): Converts all the characters of the string into character array and returns.
  3. void getChars(int srcStart, int srcEnd, char[] ch, int pos):
    Copies a few characters of the string starting from srcStart to srcEnd into the array ch starting from index number pos in the array.

A program on "Concatenation – Conversion" illustrating the style of using the above methods.

public class ConvertToArrays
{
  public static void main(String args[])
  {
                       			       // string to byte array
    String s1 = "universe"; 
    byte array1[] = s1.getBytes();
    System.out.println(array1[0]);             // prints 117, the byte value of u
    System.out.println(array1.length);         // prints 8
            				       // string to character array
    String s2 = "universe";
    char array2[] = s2.toCharArray();
    System.out.println(array2[0]);             // prints u
    System.out.println(array2.length);         // prints 8

    String s3 = "abcdefghi";
    char array3[] = { 'I','N','D','I','A','N','A','T','I','O', 'N' };
    s3.getChars(3,6,array3,4);
    System.out.println(array3);                // prints INDIdefTION
  }
}                 
Concatenation - Conversion
Output Screen of ConvertToArrays.java

byte array1[] = s1.getBytes();
char array2[] = s2.toCharArray();

getBytes() method of String class converts all the string s1 characters into bytes and returns as a byte array, array1. Similarly, toCharArray() method of String class converts all the string s2 into characters and returns as character array, array2.

s3.getChars(3,6,array3,4);

3 and 6 represent the starting and ending positions in the string s3. These three characters ' d', 'e' and 'f'. The three characters are copied into the array array3 at position 4. The original characters in the array3 are replaced.

Array to String & Hashing

Now let us convert arrays into strings, the other way you have done in the previous program. The easiest way is just to pass either a character array or byte array as parameter to String constructor. The other way is using copyValueOf() method.

Following are the method details.

  1. String copyValueOf(char[] ch): Converts all the characters of the array ch into a string and returns. It is a static method.
  2. String copyValueOf(char[] ch, int offset, int len): Converts len number of characters starting from position offset of the array ch and returns them as string. It is a static method.

Another program on "Concatenation – Conversion" illustrating the usage of the above methods.


class ConversionToStrings
{
   public static void main(String args[ ] )  
   {						        // conversion of character array
     char array1[] = {'w' , 'o' , 'r' , 'l'  , 'd'};
            				                // passing as parameter to constructor
     String s1 = new String(array1);       
     System.out.println(s1);  				// prints world
					                // other way using copyValueOf()
     String s2 = String.copyValueOf(array1);
     System.out.println(s2);  			        // prints world

				                  	// conversion of byte array
     byte array2[] = {'5', '6', '7', '8', '9', '0'};
     String s3 = new String(array2);       
     System.out.println(s3);				// prints 567890

     String s4 = "world";
     int hcode = s4.hashCode( );
     System.out.println(hcode);    		        // prints 113318802
  }
}

Concatenation - Conversion
Output screen of ConversionToStrings.java

The first style of passing array to the string constructor works both for character arrays and byte arrays. But copyValueOf() method works with character arrays only but not with byte arrays.

Hash code is an integer value Java converts a string to compare the strings. This is discussed more in Object class in java.lang package.

Leave a Comment

Your email address will not be published.