- Java add string
- Java add strings with + operator
- Java add strings with String.concat
- Java add strings with String.join
- Java add strings with StringBuilder
- Java add strings with String.format
- Author
- Class StringBuilder
- How we can insert a string into another string in Java
- By Traversing the String
- Output
- Using substring() method
- Syntax
- Output
- Class StringBuilder
Java add string
Java add string tutorial shows how to concatenate strings in Java.
In Java, a string is a sequence of Unicode characters. Strings are objects. There are two basic classes for working with strings:
- + operator
- concat method
- String.join method
- StringBuilder append method
- String.format
Java add strings with + operator
The easiest way of concatenating strings is to use the + or the += operator. The + operator is used both for adding numbers and strings; in programming we say that the operator is overloaded.
package com.zetcode; public class AddStrings < public static void main(String[] args) < System.out.println("Return" + " of " + "the king."); String msg = "There are"; msg += " three"; msg += " falcons"; msg += " in the sky"; System.out.println(msg); >>
The example adds two strings using the + and += operators.
$ java com/zetcode/AddStrings.java Return of the king. There are three falcons in the sky
Java add strings with String.concat
The String.concat method concatenates the specified string to the end of this string.
package com.zetcode; public class AddStrings < public static void main(String[] args) < System.out.println("Return".concat(" of ").concat("the king.")); >>
In the example, we add strings with String.concat .
Java add strings with String.join
The String.join method returns a new atring composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.
package com.zetcode; public class AddStrings < public static void main(String[] args) < String[] words = < "There", "are", "two", "owls", "on", "the", "tree" >; String msg = String.join(" ", words); System.out.println(msg); > >
We have an array of words. We form a sentence from the words with the String.join method.
$ java com/zetcode/AddStrings.java There are two owls on the tree
Java add strings with StringBuilder
StringBuilder is a mutable sequence of characters. Its append method appends the specified string to the string instance.
package com.zetcode; public class AddStrings < public static void main(String[] args) < var sb = new StringBuilder(); sb.append("Return"); sb.append(" of "); sb.append("the king."); System.out.println(sb); >>
In the example, we form a new string with StringBuilder.
$ java com/zetcode/AddStrings.java Return of the king.
Java add strings with String.format
The String.format method returns a formatted string using the specified format string and arguments.
package com.zetcode; public class AddStrings < public static void main(String[] args) < var w1 = "three"; var w2 = "owls"; var msg = String.format("There are %s %s on the tree", w1, w2); System.out.println(msg); >>
In the example, we build a new string with String.format .
In this article we have showed how to add strings in Java.
Author
My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.
Class StringBuilder
A mutable sequence of characters. This class provides an API compatible with StringBuffer , but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.
The principal operations on a StringBuilder are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string builder. The append method always adds these characters at the end of the builder; the insert method adds the characters at a specified point.
For example, if z refers to a string builder object whose current contents are » start «, then the method call z.append(«le») would cause the string builder to contain » startle «, whereas z.insert(4, «le») would alter the string builder to contain » starlet «.
In general, if sb refers to an instance of a StringBuilder , then sb.append(x) has the same effect as sb.insert(sb.length(), x) .
Every string builder has a capacity. As long as the length of the character sequence contained in the string builder does not exceed the capacity, it is not necessary to allocate a new internal buffer. If the internal buffer overflows, it is automatically made larger.
Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used.
Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.
How we can insert a string into another string in Java
In this tutorial, we will see a program to insert a string into another string in Java. Consider the user enters two strings and an index value, we need to insert the second string at the given index of the first string.
Let us see the possible ways to solve the problem,
By Traversing the String
In this method, we will traverse through the string until we encounter the index given by the user. Once we reach the index value add the second string elements to the new string and continue with the original string.
Let us see the step by step procedure for this method,
- Input the original string from the user.
- Input the string that needs to be inserted (second string).
- Get the index value at which the second string needs to be inserted.
- Traverse the original string and add it’s elements one by one to a new string.
Use the charAt() method to access each character of the string. - Add the second string to the new string when you reach the index value.
- Continue by adding the original string elements and print the new string.
Let us see a Java program based on the following steps,
import java.lang.*; import java.util.*; class StrInsert < public static void main(String[] args) < Scanner input=new Scanner(System.in); // Input original string System.out.println("Enter the Original String: "); String firStr = input.nextLine(); //Input the second string to be inserted System.out.println("Enter the String to be Inserted: "); String secStr = input.nextLine(); //Input the index after which the string should be inserted System.out.println("Enter the Index: "); int index = input.nextInt(); String newStr = new String(); for (int i = 0; i < firStr.length(); i++) < //Add character by character to new string newStr += firStr.charAt(i); if (i == index) < //Insert the second string newStr += secStr; >> // Output System.out.println("New String After Insertion: "+ newStr); > >
Output
Enter the Original String: CODEY Enter the String to be Inserted: SPEED Enter the Index: 3 New String After Insertion: CODESPEEDY
Using substring() method
In this method, we will be using the substring() method in Java to insert a string. This method belongs to the String class in Java. The substring() method returns a part of the string without changing the original string.
Syntax
stringVariable.substring(startIndex, endIndex);
Let us see the step by step procedure for this method,
- Input the original string from the user.
- Input the string that needs to be inserted (second string).
- Get the index value at which the second string needs to be inserted.
- Using substring() add a substring of the original string to the new string.
The substring must be until the index value. - Add the second string and finally add the remaining elements of the original string.
Java program based on the substring() concept,
import java.lang.*; import java.util.*; class StrInsert < public static void main(String[] args) < Scanner input=new Scanner(System.in); // Input original string System.out.println("Enter the Original String: "); String firStr = input.nextLine(); //Input the second string to be inserted System.out.println("Enter the String to be Inserted: "); String secStr = input.nextLine(); //Input the index after which the string should be inserted System.out.println("Enter the Index: "); int index = input.nextInt(); //New string using substring() method String newStr = firStr.substring(0, index + 1) + secStr + firStr.substring(index + 1); // Output System.out.println("New String After Insertion: "+ newStr); >>
Output
Enter the Original String: CODEY Enter the String to be Inserted: SPEED Enter the Index: 3 New String After Insertion: CODESPEEDY
We can notice that both methods yield the same output. Hence we can conclude that in Java we can insert a string into another string using these two methods.
Class StringBuilder
A mutable sequence of characters. This class provides an API compatible with StringBuffer , but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.
The principal operations on a StringBuilder are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string builder. The append method always adds these characters at the end of the builder; the insert method adds the characters at a specified point.
For example, if z refers to a string builder object whose current contents are » start «, then the method call z.append(«le») would cause the string builder to contain » startle «, whereas z.insert(4, «le») would alter the string builder to contain » starlet «.
In general, if sb refers to an instance of a StringBuilder , then sb.append(x) has the same effect as sb.insert(sb.length(), x) .
Every string builder has a capacity. As long as the length of the character sequence contained in the string builder does not exceed the capacity, it is not necessary to allocate a new internal buffer. If the internal buffer overflows, it is automatically made larger.
Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used.
Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.