Java String Concatenation with Other Data Types



In Java, string concatenation is the operation of joining two or more strings together. However, string concatenation can be performed with various primitive data types, not just with other strings.

Two strings can be concatenated using concat() method of String class, but, to concatenate strings with other primitive data type you need to use the ?+' operator. The given data type will automatically converted to its string representation.

Example Scenario:

Input: String res = "Age: " + 45;
Output: result = Age: 45

String Concatenation with int

The int is a primitive datatype in Java which represents numeric data without any decimal points. In this Java program, we are concatenating a string with int data type using addition operator.

public class Test {
   public static void main(String args[]){
      String st1 = "Hello";
      int data = 230;
      String res = st1 + data;
      System.out.println(res);
   }
}

Output

Hello230

String Concatenation with double

In Java, double is a also a primitive datatype. It represents numeric value with decimal points. The following Java program illustrates how to concatenate a string with double data type using addition operator.

public class Test {
   public static void main(String args[]){
      String st1 = "Tutorialspoint";
      double data = 10.10;
      String res = st1 + data;
      System.out.println(res);
   }
}

Output

Tutorialspoint10.1

String Concatenation with byte

The byte data type represents integer value between -128 to 127. In the below Java program, we are concatenating a string with byte data type using addition operator.

public class Test {
   public static void main(String args[]){
      byte data = 10;
      String res = "Age: " + data;
      System.out.println(res);
   }
}

Output

Age: 10

String Concatenation with float

Similar to the double data type, float is also used to store floating point numbers. However, the size of double is larger than float. The following Java program demonstrates how to concatenate a string with float data type in Java.

public class Test {
   public static void main(String args[]){
      String st1 = "Tutorialspoint";
      float data = 90.09f;
      String res = data + st1;
      System.out.println(res);
   }
}

Output

90.09Tutorialspoint
Updated on: 2024-08-01T11:44:49+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements