A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/javaexamples/string_concatenation.htm below:

String Concatenation in Java

String Concatenation in Java

String concatenation is an operation to concatenate two or more strings. In Java, we can concatenate strings using the different approaches. The following are some of the approaches to concatenate the strings:

String concatenation using + operator

The + operator is a simple way to concatenate two strings It performs the concatenation operation directly between two operands (strings). This is a common method used due to its simplicity.

Example

Following example shows string concatenation by using "+" operator method

public class ConncatSample {
	public static void main(String []args) {
		String s1 = "Hello";
		String s2 = "world";
		String res = s1 + s2;
		System.out.print("Concatenation result:: ");
		System.out.println(res);
	}
}
output
Concatenation result:: Helloworld
String concatenation using concat() method

The string concat() method joins one string to the end of another string. It combines the two strings and returns the result. If any of the strings is null, it throws a NullPointerException.

Example

Following example shows concatenation string using concat() method

public class HelloWorld { 
   public static void main(String []args) {
      String s = "Hello"; 
      s = s.concat("world");
      System.out.print(s);
   }
}
output
Helloword
Using stringBuilder or stringBuffer class

The class StringBuilder provides append() method for performing concatenation operation, It takes various types of input arguments, that is Objects, StringBuilder, int, char, CharSequence, boolean, float, double. stringbuilder is the fastest and most popular way of concatenating strings in java.

Example

Following example shows concatenation of strings using stringBuilder or stringBuffer class

public class StringBuilderExample {  
    public static void main(String[] args) {  
        String firstName = "Mark";  
        String lastName = "Smith";  
        // Using StringBuilder for efficient string concatenation  
        StringBuilder sb = new StringBuilder();  
        sb.append("Hello, ");  
        sb.append(firstName);  
        sb.append(" ");  
        sb.append(lastName);  
        String result = sb.toString();  
        System.out.println(result);    
    }  
}  
output
Hello, Mark Smith

java_strings.htm


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4