How to concatenate strings in Java

Textbooks for Java programming

String concatenation can be defined as the process of concatenating two or more strings into a new string. Most programming languages ​​offer at least one way to concatenate strings. Java gives you several options to choose from, including:

  • the + operator
  • the String.concat() method
  • the StringBuilder class
  • the StringBuffer class

Today’s programming guide will cover how to use each of the above four ways to concatenate strings, as well as give some tips on how to choose which one is best for a particular situation.

Do you want to learn Java in online classes? We have a list of the best Java courses to help you get started.

Using the plus (+) operator.

This is the easiest and most commonly used way of concatenating strings in Java. Putting a plus (+) between two or more strings will combine them into an entirely new string. Therefore, Series the object produced by chaining will be stored in a new memory location on the Java heap. However, if a matching string already exists in the string set, a reference to found Series the object is returned. You can think of it as a form of caching. Here’s a quick code example for + operator at work in Java:

String firstName = "Rob";
String lastName  = "Gravelle";
// Outputs "Rob Gravelle"
System.out.println(firstName + " " + lastName);

Advantages of the Plus (+) operator: Automatic type conversion and zero handling

The + operator automatically converts all native types to their string representations, so it can process anything from int, floatsand double be single (char) signs. Moreover, it does not allow any exceptions for Null values, conversion Null into your own Series the national team as well. Here are some code examples to show how to use + operator in Java for string concatenation:

String fruits = "apples";
int howMany = 4;
String other = null;
// Outputs "I have 4 apples as well as null."
System.out.println("I have " + howMany + " " + fruits + " as well as " + other + ".");

behind the scenes, + the operator silently converts non-professional types of data ua Series using implicit type conversion for native types and toString() method for objects, thus avoiding NullPointerException. The only downside is that we end with the word “null and void” in the resulting string, which may not be what developers want.

String concatenation is implemented through to add() method StringBuilder class. The + the operator produces a new one Series by adding the second operand to the end of the first operand. In the case of our previous example, here’s what Java does:

String s = (new StringBuilder())
             .append("I have ")
             .append(howMany)
             .append(" ")
             .append(fruits)
             .append(" as well as ")
             .append(other)
             .append(".")
               .toString();  

Tips for concatenating Java strings

Always store the string returned after concatenation using + operator in a variable if you plan to reuse it. This will avoid developers going through the chaining process multiple times. Also, avoid using + operator to concatenate strings in a loop, as this will result in a large overhead.

Although practical, + operator is the slowest way to concatenate strings. The other three options are much more efficient, as we’ll see below.

Read: Java tools to increase productivity

Using the String.concat() method.

The Series concat method concatenates the specified string to the end of the current string. Its syntax is:

@Test
void concatTest() 
String str1 = "Hello";
String str2 = " World";
assertEquals("Hello World", str1.concat(str2));
assertNotEquals("Hello World", str1); // still contains "Hello"


We can concatenate multiple arrays by sequential concatenation concat invocations, like this:

void concatMultiple() 
String str1 = "Hello";
String str2 = " World";
String str3 = " from Java";
str1 = str1.concat(" ").concat(str2).concat(str3);
System.out.println(str1); //"Hello World from Java";



Note that neither electricity Series neither Series which is added may contain Null values. Otherwise, concat method throws a NullPointerException.

StringBuilder and StringBuffer classes

The StringBuilder and StringBuffer classes are the fastest way to chain Wires in Java. As such, they are an ideal choice for concatenating large numbers of strings – especially in a loop. Both of these classes behave in almost the same way, the main difference being that StringBuffer is thread-safe, while StringBuilder it is not. Both classes provide to add() method for performing chaining operations. The to add() method is overloaded to accept arguments of many different types such as Subjects, StringBuilder, int, char, CharSequence, Boolean, float, doubleand others.

Along with the performance benefits, StringBuffer and StringBuilder offer a changeable alternative to an unchangeable one Series class. Unlike Series class, which contains an immutable string of fixed-length characters, StringBuffer and StringBuilder have an expandable length and an exchangeable string of characters.

Here is an example that concatenates an array of ten integers using StringBuilder and StringBuffer:

import java.util.stream.IntStream;
import java.util.Arrays;

public class StringBufferAndStringBuilderExample 
  public static void main(String[] args) 
    // Create an array from 1 to 10
    int[] range = IntStream.rangeClosed(1, 10).toArray();
    
    // using StringBuilder
    StringBuilder sb = new StringBuilder();
    for (int num : range) 
      sb.append(String.valueOf(num));
    
    System.out.println(sb.toString()); // 12345678910
    
    // using StringBuffer
    StringBuffer sbuf = new StringBuffer();
    for (int num : range) 
      sbuf.append(String.valueOf(num));
    
    System.out.println(sbuf.toString()); // 12345678910
  


Final thoughts on Java string concatenation

In this programming guide, we have learned all about the four main ways of chaining in Java Wires along with advice on how to choose what is best for a given situation. In short, when you need to choose between + operator, concat method, i StringBuilder/StringBuffer class, consider whether you are dealing with Wires exclusively or a mix of data types. You should also consider the possibility NullPointerExceptions on Null values. Finally, there is the issue of performance and volatility. The + operator is the slowest of all options seen today, while StringBuilder and StringBuffer classes are fast and variable.

If you really want to look at all the chaining options in Java, version 8 introduced even more ways to chain Wiresincluding String.join() method i StringJoiner class. Version 8 also saw the introduction Collectors. The Collectors class has join() a method that works very similarly join() method Series class.

Read more Java programming tutorials and software development tips.

Source link

Leave a Reply

Your email address will not be published. Required fields are marked *