When there is a need to concatenate two or more strings in java we generally use the concatenation operator ‘+’. But, for the same purpose we should prefer using concat() method from String class. After a closer look at the size of .class files which is generated after compiling the code, it is revealed that the size of the .class file containing ‘+’ operator exceeds by a greater margin than the .class file performing the same concatenation but by using concat() method.
ConcatFunDemo uses the concat() of String class:
class ConcatFunDemo { public static void main(String[] s) { String s1 = "www."; String s2 = "pcsalt."; String s3 = "com"; System.out.println(s1.concat(s2).concat(s3)); } }
ConcatOpDemo uses the concatenation operator (+):
class ConcatOpDemo { public static void main(String[] s) { String s1 = "www."; String s2 = "pcsalt."; String s3 = "com"; System.out.println(s1+s2+s3); } }
Compile it:
$ javac ConcatFunDemo.java $ javac ConcatOpDemo.java
The size of the .class file generated after compilation is:
ConcatFunDemo.class : 556 bytes ConcatOpDemo.class : 630 bytes
The above example contains only three strings which were concatenated in order to print the result. Just imagine the size of ByteCode of a project with hundred lines of code and multiple string concatenations. The revelation is that a concat() method is a lighter weight tool than the ‘+’ operator. Hence preferring concat() method over ‘+’ operator is a smart move.