String

Java Concatenate Strings Example

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

As we’ve mentioned 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 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 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 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

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button