String Class Tutorials

public String concat(String str)

In this tutorial I will talk about the concat method. The concat method returns a new String instance that is the concatenation of the value of the current string instance plus the string value of the parameter. There is a common misperception that the concat method and the + (concatenation operator) are the same thing. While they are similar in the way they work, the + operator actually uses the StringBuilder class .append() method to do its work. The concat method works like this:
String apples = "Apples ";
String oranges = "& Oranges";
String NewString = apples.concat(oranges);
// Apples & Oranges

Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>md StringConcat
C:\Java>cd StringConcat

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.

class StringConcat {
    public static void main(String args[]) {
        String apples = "Apples ";
        String oranges = new String("& Oranges");
        String NewString = apples.concat(oranges); // Apples & Oranges

        String multiple = "The quick brown fox ".concat("jumps over the ").concat("lazy dog."); 
        String enemies = "Cat ";
        enemies.concat("Mouse"); // common error - return value goes nowhere
        enemies = enemies.concat("Mouse"); // remember the return value;

Now switch back to the command prompt (CMD) and type in javac and press Enter.
Now type in java StringConcat and press Enter.

C:\Java\StringConcat>java StringConcat
Apples & Oranges
The quick brown fox jumps over the lazy dog.
Cat Mouse

Final thoughts

One strategy that I regularly use to solidify my knowledge of Java is to browse through the actual source code. Due to some language in their copyright file, I can't actually show the source code in my videos. The source code is contained inside of a file called located in the folder where your JDK is installed. I recommend using notepad++ to browse the class files.