Concat More than 2 Strings in Java

A simple logic to concat more than 2 (unlimited) no.of strings in Java. Here is the piece of code.

Concat Unlimited Strings - Example



class ConcatStrings
{
public static void main(String args[])
{
System.out.println(concat("gowtham","gutha","java","-","demos",".","blogspot",".com"));
}

public static String concat(String... st)
{
String tmp="";
for(String k:st)
{
tmp+=k;
}
return tmp;
}
}

Output



gowthamguthajava-demos.blogspot.com


Explanation


tmp=""; A temporary variable which is a single entity containing the chain of given strings.

String... st: It is a variable argument (vararg), a concept in Java used for unknown no.of parameters.

Advanced for loop: Used for var args.

tmp+=k; Attach the strings one by one. st contains the strings that user gives, every loop rotation represents an element of st in order, in order to perform operation the variable k is used.

return tmp: Returns the required string.

Why static? In the above example, method call to concat() is done in main() which is a static method. So in order to access the concat() method directly without need of creating an object, i've kept it static.

If you feel a still more smart logic can be written or didn't understand, drop a comment.

No comments: