A Java String is made up of a sequence of characters and is used to store text. For example, “Codementor” is a String of 9 characters. A Java String is an immutable object, which means that once it has been created, it cannot be changed.
In this beginner-friendly tutorial, we’ll walk through some Java String basics and teach you how to convert Java int to String, Java char to String, and Java array to String.
If you’re interested in digging deeper into Java Strings & more Java related subjects, you can find an experienced Java mentor to teach you or find some tutorials online!
Java String Overview
Create a Java String object
To create a Java String, you must create the type, String
, before assigning a value to it:
public class Main {
public static void main(String[] args) {
String Company = "Codementor";
System.out.println(Company);
}
}
Output:
Codementor
The example above is done by assigning a String literal to a String instance. If you want to have two different objects with the same String, you would need to create Strings using a new keyword.The code would look like this:
public class Main {
public static void main(String[] args) {
String language = "Java";
String languageConversion = new String("Converting Java int, char, array to Java string");
System.out.println(lagnuage);
System.out.println(companyDescription);
}
}
Output:
Java
Converting Java int, char, array to Java string
Another way to work with Strings is to convert characters into a String. We will go into this in the last section of the tutorial.
Find the length of a Java String
If you want to find out how many characters are in a String, you can simply use the length()
method. Here’s an example:
public class JavaStringLength{
public static void main(String args[]){
String txt = "Need to learn how to apply Java String to your projects?";
System.out.println("The length of the txt String is: " + txt.length());
}}
Output:
The length of the txt String is: 56
⚠️ Note: The length of the Java String includes the white spaces as well.
Concatenate Java Strings
There are three ways to mix two Strings and generate a new String in Java. You can use the “+” operator, the concat() method, or the StringBuffer
and StringBuilder
classes.
Using the “+” operator
The + operator allows you to combine two Java String literals:
public class Main {
public static void main(String[] args) {
String str1 = "Java";
String str2 = "String";
String result = str1+str2;
System.out.println(result);
}
}
Output
JavaString
Using the concat()
method
The concat()
method accepts a Java String value and creates a new string object that combines str1 and str2.
public class Main {
public static void main(String[] args) {
String str1 = "Java";
String str2 = "String";
String result = str1.concat(str2);
System.out.println(result);
}
}
Output:
JavaString
Using StringBuilder
(or StringBuffer
) class
Java String concatenation can be done using the StringBuilder
class and the append method. StringBuilder
classes are similar to Java Strings, but they are mutable. In combination with the append()
method, we can add a String value to existing StringBuilder
objects.
public class Main {
public static void main(String[] args) {
String str1 = "Java";
String str2 = "Mentors";
StringBuilder sb = new StringBuilder (str1);
sb.append(str2);
System.out.println(sb);
}
}
Output:
JavaMentors
Java int to String Conversion
When you want to display numbers in textfields, you would have to convert integers into Strings. This is because everything is displayed as a String in Java. There are multiple ways to convert int to String in Java, we’ll cover four types in this section:
- Using
String.valueOf()
- Using
Integer.toString()
- Using
StringBuilder()
(orStringBuffer()
) - Using
String.format()
String.valueOf()
method
Int to String Java: Syntax:
public static String valueOf(int i
Here’s a simple and straightforward example to convert int to String in Java:
public class IntToStringJava
{
public static void main(String args[])
{
int a = 8888;
String str3 = String.valueOf(a);
System.out.println("String 1 = " + str3);
}
}
Output:
String 1 = 8888
The String.ValueOf()
method also allows you to add up integers or concatenate integer Strings:
public class IntToStringJava
{
public static void main(String args[])
{
int i = 300;
String str3 = String.valueOf(i);
System.out.println(i+100);
System.out.println(str3+100);
}
}
Output:
400
300100
In the example above, (i+100)
returns 400 because +
is a binary plus operator while (str3+100)
returns 300100 because +
is a String concatenation operator.
Integer.toString()
method
Int to String Java: Integer values are taken in as arguments and returned as String.valueOf()
Strings. The integer argument ~i~ can be both positive and negative integers. If the integer is negative, the -
sign will be preserved.
Syntax:
public static String toString(int i)
Example:
public class IntToStringJava
{
public static void main(String args[])
{
int a = 3011;
int b = -2948;
String str1 = Integer.toString(a);
String str2 = Integer.toString(b);
System.out.println("String 1 = " + str1);
System.out.println("String 2 = " + str2);
}
}
Output:
String 1 = 3011
String 2 = -2948
StringBuilder
(StringBuffer
) method
Int to String Java: StringBuilder
and StringBuffer
are two classes that can be used interchangeably to build Strings with the append()
method. To create an object, we can use either of the classes, and pass the integer by calling the append()
method.
Example 1:
public class IntToStringJava
{
public static void main(String args[])
{
int f = 2021;
StringBuffer sb = new StringBuffer();
sb.append(f);
String str1 = sb.toString();
System.out.println("String 1 = " + str1);
}
}
Output:
String 1 = 2021
Example 2:
public class IntToStringJava
{
public static void main(String args[])
{
String str1 = new StringBuffer().append(11).toString();
System.out.println("String 1 = " + str1);
}
}
Output:
String 1 = 11
String.format()
method
Int to String Java: The String.format()
is versatile and multipurpose. When converting int to Java String, the String.format()
method formats arguments into Strings. As String.format()
is quite complex, this method is not only used for conversion. But to convert int to Java String this method, you’d use %d
as the first argument and the integer as the second argument. The %d String will be replaced by the integer.
Example:
public class IntToStringJava
{
public static void main(String args[])
{
int num = 259;
String str1 = String.format("%d",num);
System.out.println("String 1 = " + str1);
}
}
Output:
String 1 = 259
Java Char to String Conversion
A char in Java refers to any single character. The character could be a letter, digit, punctuation mark, tab, or space. To convert char to String in Java, we can use the String.valueOf(char)
method in the String class or the Character.toString(char)
method in the Character class.
⚠️ Note: Converting Java char to String is different from converting Java char array to String! This tutorial will only cover char to String in Java.
String.valueOf(char)
method
Char to String Java: Example:
public class CharToStringJava
{
public static void main(String args[])
{
char ch = 'C';
String str = String.valueOf(ch);
System.out.println("String is = "+str);
}
}
Output:
String is = C
Character.toString(char)
method
Char to String Java: Example:
public class CharToStringJava
{
public static void main(String args[])
{
char ch = 'a';
String str = Character.toString(ch);
System.out.println("String is = "+str);
}
}
Output:
String is = a
⚠️ Note: If the letter for your character is capitalized, the output will remain capitalized. The letter case will remain the same.
Java Array to String Conversion
Converting an array to String in Java is often required when you want to perform certain actions. For instance, if you want to log array contents or convert values of the array to String in order to invoke other Java methods. To convert an array to String in Java, you can utilize the Array.toString()
method or the StringBuilder append(char[])
method.
Array.toString()
method
Array to String Java: By using the Arrays.toString()
method, we can turn the contents in the specified array into a String representation. A list of the array’s elements, enclosed in []
, is returned as a String representation. The different elements in an array are separated by ,
. There are different types of arrays and we’ll look at character, integer, double, object, and boolean arrays.
Example:
import java.io.*;
import java.util.*;
public class CharToStringJava {
public static void main(String[] args)
{
char[] charAr
= new char[] { 'C', 'o', 'd', 'e', 'm', 'e', 'n', 't', 'o', 'r'};
int[] intAr
= new int[] { 2, 4, 6, 8 };
double[] doubAr
= new double[] { 2, 4, 6, 8 };
Object[] objAr
= new Object[] { 1, 2, 3, 4 };
boolean[] boolAr
= new boolean[] { true, false, true, true };
System.out.println(
"Character Array: "
+ Arrays.toString(charAr));
System.out.println(
"Integer Array: "
+ Arrays.toString(intAr));
System.out.println(
"Double Array: "
+ Arrays.toString(doubAr));
System.out.println(
"Object Array: "
+ Arrays.toString(objAr));
System.out.println(
"Boolean Array: "
+ Arrays.toString(boolAr));
}
}
Output:
Character Array: [C, o, d, e, m, e, n, t, o, r]
Integer Array: [2, 4, 6, 8]
Double Array: [2.0, 4.0, 6.0, 8.0]
Object Array: [1, 2, 3, 4]
Boolean Array: [true, false, true, true]
StringBuilder append()
method
Array to String Java: We’ve already talked about the basics of the StringBuilder
class in Java String Overview. Here are the steps to convert an array to String in Java using StringBuilder
:
- Create an array
- Create a
StringBuilder
object - Iterate the array
- Use the
append()
method to append the elements of the array (from step 3) - Use the
toString()
method to return a String instance from the object (from step 2)
Example:
class Codementor {
public Codementor()
}
public static void main(String[] args) {
String[] data = {"Convert","Array", "to", "String", "Java"};
StringBuilder stringb = new StringBuilder();
for (int i = 0; i < data.length; i++) {
stringb.append(data[i]+" ");
}
String joinedstr = stringb.toString();
System.out.println(joinedstr);
}
}
Output:
Convert Array to String Java