Nikos Maravitsas

About Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. 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.

Java String Concatenation Example

In this example we are going to see how you can concatenate two Strings, or in fact, any Object with a String.

As we’ve mention in an introductory article about Java String Class, String is one of the most used types in Java programs. So Java creators wanted to make the usage of Strings as straightforward as possible. Admittedly, concatenation is one of the most frequent operation 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 that Strings are immutable objects. Which means that once a String object is instantiated, you cannot change its value. So what happens when you take an already existing String instance, like s4 in the above example, and append to it another String Object (remember that in Java, all literals are of type String)? What really happens is that a brand new String 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 a StringBuilder (or StringBuffer) class with their append method.

2. Concatenate primitives with a String

Fortunately you can use the '+' operator to concatenate a String 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 type String, then a String 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 new String.

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 type String, then the other operands are converted to String at runtime. Java can handle the conversion of primitive types to String (without any loss of information, e.g for floats or doubles). But what if an operand is a user-defined class? In this case, Java will use the toString method of Object class, to retrieve a code>String “representation” of an Object. For this to work properly, you have to override toString (inherited form Object super class) in your class and provide your own implementation.

So here is a user defined class with the overrider toString 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 a String with an instance of type Employee:

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 additional String class API method, concat, that can also be used to concatenate Strings together but you’ll rarely (or never) use it. So line 16 of the above snippet could also be written like this :

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

Download the Source Code

This was a Java String Concatenation Example. You can download the source code of this example here : StringConcatenationExample.zip

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.
Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close