String

Java Concatenate Strings Example

Photo of Nikos MaravitsasNikos MaravitsasMarch 12th, 2014Last Updated: September 15th, 2020
0 279 4 minutes read

In this example, we are going to explain string concatenation in Java. We are going to showhow you can concatenate in Java two Strings, or in fact, anyObject with a String in Java.

As we’ve mentioned in an introductory article aboutJava String Class, String is one of the most used types in Java programs. So Java creators wanted to make the usage ofStrings as straightforward as possible. Admittedly, concatenation is one of the most frequent operations on Strings. Fortunately, you can use'+' operator to concatenate Strings.

Let’s see some examples.

1. Using the ‘+’ operator

This is how you can concatenate two String literals together:

StringConcatenationExample.java

package com.javacodegeeks.core.lang.string;public class StringConcatenationExample {    public static void main(String[]args){        String s4 = "Java" + "Code" + "Geeks";        System.out.println(s4);    }}

This will print out:

JavaCodeGeeks

And another example:

StringConcatenationExample.java

package com.javacodegeeks.core.lang.string;public class StringConcatenationExample {    public static void main(String[]args){        String s4 = "Java" + "Code" + "Geeks";        s4 = s4 + " " + "are awesome!";        System.out.println(s4);    }}

This will print out:

JavaCodeGeeks are awesome!

It’s worth reminding thatStrings are immutable objects. Which means that once aString object is instantiated, you cannot change its value. So what happens when you take an already existingString instance, likes4 in the above example, and append to it anotherString Object (remember that in Java, all literals are of typeString)? What really happens is that a brand newString object is created to accommodate the extended sequence of characters.

Let’s see an example that can prove that:

StringConcatenationExample.java

package com.javacodegeeks.core.lang.string;public class StringConcatenationExample {    public static void main(String[]args){        String s4 = "Java" + "Code" + "Geeks";        // hold the reference of s4        String s1 = s4;        s4 += " " + "are awesome!";        System.out.println(s4);        System.out.println(s1 == s4);    }}

This will print out:

JavaCodeGeeks are awesome!false

It is also worth mentioning that internally,String concatenation is implemented with the help of aStringBuilder (orStringBuffer) class with theirappend method.

2. Concatenate primitives with a String

Fortunately you can use the'+' operator to concatenate aString object with any primitive type variable. This is done like so : In an expression where the operator'+' is present, if one of the operands is of typeString, then aString conversion of the other operands is performed at run time, in order to form a new extended String contaning

Let’s see an example:

StringConcatenationExample.java

package com.javacodegeeks.core.lang.string;public class StringConcatenationExample {    public static void main(String[]args){       int a = 12345;       String out = "The value of integer is : "+ a;        System.out.print(out);    }}

This will print out:

The value of integer is : 12345

And some more examples with other primitive type variables:

StringConcatenationExample.java

package com.javacodegeeks.core.lang.string;public class StringConcatenationExample {    public static void main(String[]args){       int a = 12345;       String out = "The value of integer is : "+ a;        System.out.print(out);        out += " And the value of a floating point number is :"+ 45.01f;        boolean bl = false;        double d = 21.0129312312;        char s ='y';        byte bt = 10;        out += ", "+ bl + ", "+d + ", "+s+ ". And a byte is:"+bt;        System.out.println(out);    }}

This will print out:

The value of integer is : 12345The value of integer is : 12345 And the value of a floating point number is :45.01, false, 21.0129312312, y. And a byte is:10

It’s important to note that numeric values will be represented in their decimal format inside the newString.

3. Concatenate user defined types with a String

As we said earlier, when the operator ‘+’ is present in an expression and one of the operands is of typeString, then the other operands are converted to String at runtime. Java can handle the conversion of primitive types toString (without any loss of information, e.g forfloats ordoubles). But what if an operand is a user-defined class? In this case, Java will use thetoString method ofObject class, to retrieve a code>String “representation” of anObject. For this to work properly, you have to overridetoString (inherited form Object super class) in your class and provide your own implementation.

So here is a user defined class with the overridertoString method:

Employee .java

package com.javacodegeeks.core.lang.string;public class Employee {    private int id;    private String firstName;    private String lastName;    private int age;    private double salary;    private boolean externalPartner;    public Employee(){    }    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getFirstName() {        return firstName;    }    public void setFirstName(String firstName) {        this.firstName = firstName;    }    public String getLastName() {        return lastName;    }    public void setLastName(String lastName) {        this.lastName = lastName;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    public double getSalary() {        return salary;    }    public void setSalary(double salary) {        this.salary = salary;    }    public boolean isExternalPartner() {        return externalPartner;    }    public void setExternalPartner(boolean externalPartner) {        this.externalPartner = externalPartner;    }    @Override    public String toString() {        return "Employee{" +                "id=" + id +                ", firstName='" + firstName + '\'' +                ", lastName='" + lastName + '\'' +                ", age=" + age +                ", salary=" + salary +                ", externalPartner=" + externalPartner +                '}';    }}

Let’s see how you can concatenate aString with an instance of typeEmployee:

StringConcatenationExample.java

package com.javacodegeeks.core.lang.string;public class StringConcatenationExample {    public static void main(String[]args){        Employee emp = new Employee();        emp.setId(1);        emp.setFirstName("James");        emp.setLastName("Prady");        emp.setAge(22);        emp.setSalary(1200.50);        emp.setExternalPartner(true);        String out = "Employee information :" + emp;        System.out.print(out);    }}

This will print out:

Employee information :Employee{id=1, firstName='James', lastName='Prady', age=22, salary=1200.5, externalPartner=true}

That’s it. There is an additionalString class API method,concat, that can also be used to concatenate Strings together but you’ll rarely (or never) use it. So line 15 of the above snippet could also be written like this:

String out = "Employee information :".concat(emp.toString());

4. Download the Source Code

This was a Java String Concatenation Example.

Download
You can download the source code of this example here:Java Concatenate Strings Example

Last updated on May 5th, 2020

Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Nikos MaravitsasNikos MaravitsasMarch 12th, 2014Last Updated: September 15th, 2020
0 279 4 minutes read
Photo of Nikos Maravitsas

Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. During his studies he discovered his interests about software development and he has successfully completed numerous assignments in a variety of fields. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.
Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.