Rajinder Menu

Difference between concat() and + (String concatenation operator)


Both concat() and + are used to concatenate the strings but they have some differences which are described below:

1. Java.lang.NullPointerException :

concat() method if called on null String reference variable, will throw NullPointerException while this is not the case with + operator.

For example,

String s=null;
s.concat(“abc”);

will throw NullPointerException.

While

String s=null;

System.out.println(s+”abc”);

Will print nullabc. While concatenating strings with + operator, a null reference variable changes to “null” (i..e a String containing null as its contents.). That’s why s becomes “null” and output is nullabc.

2. Number of arguments:

concat() takes only one argument while + can take any number of arguments.

Example,

“I”+“ am”+” a”+” good”+” boy”

3. Type of Argument:

Signature of concat() method is:  public String concat(String str)

concat() only takes String type as argument. If any other type argument is passed to concat() it will give compile time error. Example,

s.concat(5);  // error as 5 is a non string value

s.concat(“5”);  // no error as here 5 is string (enclosed in “”)

While + can take any type of arguments. While doing concatenation non-string type argument is converted to String by using its toString() method

For example,

String s=”abc”;
int i=5;

System.out.println(s+i);  // no error, will print abc5.

Here int value 5 is a primitive value. It will be first converted to a string value as:


      int------>Integer.toString(5)-------> a String representation of int value 5.


Note that as explained in article String concatenation operator +, at least one argument of + must be of string type otherwise + will behave like mathematical addition operator instead of string concatenation operator.

4. Creation of new String Object:

You may have read that in Java Strings are immutable. Whenever you try to change its contents, a new String object with changed contents is created instead of modifying the original String object.

But concat() returns new String object only when the length of argument string is > 0.

String s=”Blue”;
String s1=”Sky!”
String s2=s.concat(s1);

Here concat() returns a new String object whose reference is stored in s2.

But if the length of argument string is 0, then concat() returns same original string instead of returning a new String object. Example,

String s=”abc”;
String s1=s.concat(“”);

Here “” (an empty String with length 0) is a passed as an argument to concat(). So no new String object created but reference to original string s is returned and strored in s1.

Therefore, s==s1  will give true here i.e both s and s1 are pointing to same objects.

While,

+ creates a new String object every time it concatenates something, except when the concatenation is done at compile time.

For example,

String s=”Hello”;

String s1=s+”World!”;

Here a new String object s1 is created with concatenated result (Hello World!).

Similarly,

String s=”Hello”;

String s1=”World!”;

String s2=s+s1;

Will create a new String object s2.

In both above example concatenation happen at run time.

But,

String s=”Hello”+”World!”;

Will not create a not create a new String object because here concatenation will happen at compile time.

There will be only one String object with contents “Hello World!”. Both String literals “Hello” and “World!” will be discarded.

5. Performance

Performance wise concat() is consider better than + operator. One of the reasons for this is that concat() returns a new String object only when length of its arguments is > 0 as stated in point 4.



I would like to know your comments and if you liked the article then please share it on social networking buttons.


3. Using append() method of StringBuilder or StringBuffer class



The append()method of StringBuilder and StringBuffer classes can also be used to concatenate strings.

Example:

StringBuilder sb= new StringBuilder(“Hello”);
sb.append(“World!”);
System.out.println(sb);

Output: HelloWorld!

You can also chain append() together like this:

StringBuilder sb= new StringBuilder("The police ");
sb.append(" called off ").append(“ the search”).append(" for the missing boy.");
System.out.println(sb);

Output: The police called off the search for the missing boy.

The StringBuffer and StringBuilder classes have many overloaded append() methods - for all the built-in types, for objects etc. You can refer JavaDocs for their details.

Note: StringBuilder class was introduced in java 5.

If the argument of append() is non string then it is converted to String first by String.valueOf() method.

For Example,

StringBuilder sb= new StringBuilder("There were ");
int i=5;
sb.append(i).append(" thieves.");
System.out.println(sb);

Output: There were 5 thieves.

In above example you have appended an int value 5. Before appending, 5 will be converted to its string representation by String.valueOf(5).

 « Using concat() method



I would like to know your comments and if you liked the article then please share it on social networking buttons.


2. Using concat() method of String class


« 1. String Concatenation operator +                                                   3. Using append() method »

concat() method of String class appends the argument string to the string object on which it is called. For example,

System.out.println(”Tom”.concat(“Cat”));  Will print TomCat.

"Go".concat(" to").concat(" hell !")          will print "Go to hell !"

Now consider,

   String str= "strike";
  str.concat("out");
  System.out.println(str);   // the output will be strike, NOT strike out. WHY?

This is because in Java strings are immutable. Due to which whenever you change the contents of a String object, a new String object is created instead of modifying the original string.

Therefore when you changed the String object str by appending “out “ using str.concat(), it returned a new String object with changed contents instead of modifying original str contents.

str is still pointing to original string with value strike.

That’s why System.out.println(str);  printed strike Not strike out.

The newly created String object with changed contents (strike out) will be garbage collected after some time as you have not stored its reference anywhere.

If your code will be:

 String str= "strike";
 str=str.concat("out");
 System.out.println(str);   // the output will be strike out, NOT strike.

Here you have stored the reference of newly created String object with changed contents in reference variable str, which was earlier pointing to original string.

Therefore System.out.println(str); printed strike out Not strike.

Now the reference to original string got lost and it will be garbage collected after some time.

Similarly,

String first= "strike";                
String sec=first.concat("out");    
System.out.println(first==sec);   // will be false.

first==sec will print false showing that they are different String objects.

Two cases are there:

1) If the length of argument String is 0 then concat() returns the same string instead of creating a new String object. For example,

String s="James ";
String s1=s.concat("");
System.out.println((s==s1);     // will print true.

Here argument of concat() is an empty string (length 0), Therefore instead of creating a new String object it returned reference to same original String object s.This can be confirmed by s==s1 giving true i.e both are pointing to same String object.

2) calling concat() on null reference variable:

Suppose your code is:

String s=null;
String s1=s.concat("Appending on null String variable");

It will give following error:
Exception in thread "main" java.lang.NullPointerException


« 1. String Concatenation operator +                                                   3. Using append() method »


I would like to know your comments and if you liked the article then please share it on social networking buttons.


1. String Concatenation operator +


« String Concatenation                                                        2. Using concat() method of String class »
 
In Java + operator has been overloaded so that it can also concatenate strings in addition to the normal plus operation (on integers etc.). Strings can be concatenated by using + operator as:

Example1:

String s= “Charlie” +”Chaplin”;
System.out.println(s);   // will print Charlie Chaplin.

Example 2:

String s=”Ranga”;
String s1=”nathan”;

String s3=s+s1;
System.out.println(s3);  // will print Ranganathan.


Example3:

System.out.println(“abc”+”def”);  // will print abcdef.

System.out.println(s+s1);    // will print Ranganathan.

Example 4:

String s=null;
String s1=”hello”

System.out.println(s+s1);  // will print nullhello

Note the above example. Here s is a null reference variable pointing to null. Whenever you print a null reference variable, it converts to “null” (i.e a string having value null).

Therefore above statement prints nullhello.

Example 5:

Concatenating more than two strings at the same time:

String s=”Stop”+ “beating”+”around”+ “the”+ “bush.”;
System.out.println(s);     // will print Stop beating around the bush

String s= “Big”
Styring s1=”fish”
String s2=”in”
String s3=”a little sea”;
String s4= s+s1+s2+s3;
System.out.println(s4);  // will print Big fish in a little sea

Example 6:

You can also use compound additive operator (+=) to add Strings:


String s=”Old”;
s += ” man”;
System.out.println(s);  // will print Old man.

s += ” man” is equivalent to s = s+” man”.

Example 7:

String s=”12”;
String s1=”12”;

String s2=s+s1;

System.out.println(s2);  // will print 1212, NOT 24

Note that in above example 12 +12 has not get added to give 24 (normal plus operation) but instead it prints 1212. That’s why + is said to be overloaded for strings.

Similarly,

System.out.println(“24”+”3”);  //will print 243 Not 27.

Working of String concatenation operator:

Consider,

String s=”3”;
int i=10;

System.out.println( s+i );

What will be the output 13 or 310? Output is 310.

Why so? This is because if any one of the arguments of + is String then + behaves like string concatenation operator instead of doing mathematical addition. Therefore instead of adding 3 and 10 (i.e 3+10=13) it concatenates them (310).

Similarly,

String s=”3”;
int i=10;
int i=11;
System.out.println(s+i+i1); 

Above statement will NEITHER print 24 (i.e 3+10+11=24), NOR 321 (i.e “3” +10+11=321), it will print 31011.

String concatenation operator works from left to right. Here s+i (i.e “3”+10) is evaluated first giving “310”( a string). Then “310”+11 evaluated to give 31011(also a string.)

Now consider,

String s=”3”;
int i=10;
int i1=11;

System.out.println(s+(i+i1));

Above statement will 321. This is because you have enclosed i+i1 in (). So (i+i1) will be evaluated first. Since both operands are of int type, + will do mathematical addition instead of string concatenation.

After adding i and i1 it will then concatenate 3 (a string) and 21 (an int) as “3”+21. Now since one of the operands is string therefore + will do string concatenation and result will be 321.

Similarly,

String s=”3”;
int i=10;
int i1=11;

System.out.println(i+i1+s);

Will print 213.

In above example i+i1 evaluated first to give 21 because + operates from left to right. Here + has done numerical addition instead of string concatenation. This is because both arguments are of int type, neither of the arguments is of String type.

Therefore,
10+11=21   (integer addition)
21+”3”=213 (String concatenation)

More Examples:

Example 1:

String s=”3”;
int i=10;
int i1=11;

System.out.println(i+s+i1);

Will print 10311

Example 2:

System.out.println(2+someObj.getValue());

Here what will be the output depends on the return type of getValue(). If getValue() returns String, only then above statement will be a String concatenation.

Suppose getValue() returns a String “10”, then output will be 210.

If getValue() returns an int 10, then output will be 12 (i.e 2+10=12).


Example 3:

System.out.print("" +14 + 2 );

 will print 142 NOT  16  because first argument  “” is a string (an empty string). Therefore  it will be String concatenation instead of mathematical addition.

Example 4:

System.out.println("The square root of 3 is " + Math.sqrt(3));

Will print : The square root of 3 is 1.7320508075688772.

Here value returned by Math.sqrt(3) is concatenated with The square root of 3 is.

« String Concatenation                                                        2. Using concat() method of String class »



I would like to know your comments and if you liked the article then please share it on social networking buttons.


String Concatenation




I would like to know your comments and if you liked the article then please share it on social networking buttons.


What do you undesrtand by String interning?







I would like to know your comments and if you liked the article then please share it on social networking buttons.


Interned Strings and use of ==







I would like to know your comments and if you liked the article then please share it on social networking buttons.


Why Strings in Java are immutable?






I would like to know your comments and if you liked the article then please share it on social networking buttons.


Hashcode Caching by String







I would like to know your comments and if you liked the article then please share it on social networking buttons.


Difference between Comparable and Comparator Interfaces in java.


 Both Comparable and Comparator interfaces in java are used in sorting of objects. Some of the main differences between them are outlined below:

1. Comparable interface lies in  java.lang  package while Comparator interface lies in java.util package.

2. Comparable interface use compareTo() method to compare objects while Comparator interface use compare() method.

 Signature of compareTo() is:

 public int compareTo(T obj)

compareTo() takes only one argument and compare it with the object on which compareTo()is called i.e object referenced by 'this' keyword.

Signature of compare() is :

public int compare(T obj1, T obj2)

Unlike compareTo(), compare() takes two arguments. These arguments are the two objects which are being compared.

3. Comparable in Java is used to implement natural ordering of objects while Comparator can be used to implement any user defined ordering.

4.  If you have a List (or an array) with each of its elements implementing Comparable interface and you pass this List( or array) to Collection.sort() (or Arrays.sort()), then they will be automatically sorted out according to their natural order.

If their elements do not implement Comparable then you have to pass a Comparator object to
Collections.sort() (or Arrays.sort()) in order to sort the elements like:

Collections.sort (listObject, comparatorObject);

Or

Arrays.sort (array, comparatorObject);

5. In order to use Comparable you have to change the class whose instances you are going to compare. For example, if you are going to compare instances of Accounts class then you have to change it in order to implement Comparable interface.

public class Account implements Comparable{
    …

  @Override
  public int compareTo(Account a1){
   …
  }

}

But Comparator does not force you to change the class. You can create separate comparator class as:

public  class AccountComparator implements Comparator{
    …
    @Override
    public int compare(Account a1, Account a2){
    …
  } 
}

and then pass it to the funtions like Arrays.sort() or Collections.sort() as shown in point 4.
Here you do not need to change your Account class.

6. Comparable contract specifies that if null is passed as argument to compareTo(), then it should throw NullPointerException.

   Obj1.compareTo(null)    // should throw NullPointerException

While contract of Comparator, upto Java 6, does not say anything about null arguments passed to compare(). It also does not specify that compare() should throw NullPointerException.

Its upto you how to handle null arguments. Here you can throw NullPointerException or, unlike Comparable, allow the comparison.

Note that contract of Comparator in Java7 explicitly says that :

Unlike Comparable, a comparator may optionally permit comparison of null arguments, while maintaining the requirements for an equivalence relation.

And

compare() should throw:

NullPointerException - if an argument is null and this comparator does not permit null arguments


7. Comparable should be used to compare elements according to their natural order and Comparator can be used for any other user defined order.

8. Objects which implement Comparable can be used as keys in a SortedMap ( like TreeMap) and as elements in a SortedSet (like TreeSet) without explicitly passing Comparator to their constructors.

9. Comparable can be used when you have only one sorting criteria. For example If you want to sort instances of a PhoneNumber class  according to its owners last name only.

But If you have multiple sorting criteria you would need Comparator. For example If you want to sort phone numbers according to area or owners first name also in addition to last name.



I would like to know your comments and if you liked the article then please share it on social networking buttons.


Why String is declared final?


String class is made final to close one of the open doors which can make an immutable class mutable.

There are many chances by which an immutable class can be made mutable if it is allowed to be subclassed (i.e if it can be extended). Therefore often immutable classes are made final so that they cannot be extended, making them strongly immutbale as against to weakly immutable.

Thus String is made final to make it strongly immutable.

If String had not been made final, then one can create its subclass and :

1)Can add new fields in sublcass which are not declared final (mutable):

New fields can be added to subclass of String class without declaring them final. So object of this subclass would not be immutable.

Now object of subclass of String class would also be object of  String class. This would cause an object of String class to exist which is not immutable.

2) Can override existing methods:

A subclass can override existing methods of String class which can then return different values each time they are called, thus breaking immutabillty. Example,

one can override public charAt(int index) method of String class to return some random character each time it is called as:

@Override
public char charAt(int index){
//retruning some randomly selected character.
}

thus breaking the immutablilty and whole design of String class as many features of String class depends on its immutabilty.





I would like to know your comments and if you liked the article then please share it on social networking buttons.