String Concatenation In Java

String Concatenation Java

Now let’s talk about String concatenation. Remember about the + operator? Well, this is something that we have used whenever we need to add numbers right? But if you use this operator with strings, it is then used to concatenate the string. You can understand concatenation as gluing the two strings, one after the other. This is like –

“Hello” + “Java” is HelloJava. Isn’t it interesting? If we want to have some space, we can have it right after the word Hello, or just before the word Java, or even we can concatenate a space along with Hello and Java. So, now I hope you have an idea of what we mean by concatenation right?

String Concatenation In Java

Let’s have a look at the program below, which demonstrates the concept of concatenation –

public class Main {
public static void main(String[] args) {
String concatenatedString = “This is one String ” + “This is another String.”;
System.out.println(concatenatedString);
}
}

If we try running the above program, we find that the two strings are now concatenated. The space between them came from just after the word String in the first String as we observe.

So, this is string concatenation, and it is pretty much simple. Now, let’s make it even more interesting. We now know that we can concatenate a string with another string. But what if I try to concatenate the string with an integer? Or a boolean value, or a floating-point number? What do you think will happen? Let’s have a look at the below program, which demonstrates the same.

public class Main {
public static void main(String[] args) {
int value = 1000;
String valueString = “The value in the variable value is: ” + value;
System.out.println(valueString);
}
}

If we carefully observe, we are trying to simply concatenate a string and a number. If you are thinking hey- this should throw an error because this is a string and that is a number, and both are different things. But this is not the case. Here, if we are trying to concatenate anything with the string, then it first gets converted to a string and then is concatenated.

So, in this case, the value, in order to be concatenated, is converted to a string for concatenation to be possible. So, keeping this in mind, let’s now move on to the next concept.

Note: The strings start with a zero index. The index is something that helps us access the individual characters. Also, when we talk about the length of a string, it refers to the number of characters. So, if the string is ”hello” for example, then the length of the string is straightaway 5. The index starts from 0, so the character ‘h’ is at zero indexes, ‘e’ is at 1, and so on, and the final character ‘o’ is at index 4.

So, it is like if the string has a length n, the last character is at position n – 1. Keep this in mind, since we will be using indexes ahead, so you must know that the string has indexed from 0, and the last character is present at n – 1 for a string of length n.