String Methods


🙋 Need help? Ask an expert now!

The concat() method performs String concatenation, meaning it takes two strings and forms a new String by putting the original two strings together. For example, the program below concatenates the first String "Hello " with the second String "World!" and makes a new String that refers to "Hello World!".
package exlcode;

public class ConcatenationExample {

  public static String exampleVariableOne = "Hello ";
  public static String exampleVariableTwo = "World!";
  // returns a String that concatenates exampleVariableTwo to
  // exampleVariableOne and assigns it to String variables
  public static String exampleVariableThree = exampleVariableOne + exampleVariableTwo;
  public static String exampleVariableFour = exampleVariableOne.concat(exampleVariableTwo);

  public static void main(String[] args) {

Keep in mind the concept of immutability when it comes to strings. The first two strings, exampleVariableOne and exampleVariableTwo, are not altered by the action of concat(). A brand new String is created that is made up of the characters "Hello World!".

Do you remember the '+' operator? It may also be used instead of the concat() method, as you see above. Both the operator and the method do the exact same thing, so you as the programmer may choose whichever one you are more comfortable with and fits your coding style.

This is your friendly reminder that if the first operand in front of the '+' operator is a String and the ones that come after are not, everything that comes after the String will be changed to be a String, and the '+' operator will behave as concatenation, not addition.

Edit Me on GitHub!

Application Question