Adding Numbers and Strings
Important Note: Java uses the +
operator for both addition and concatenation.
- When you add numbers, the result is their sum.
- When you add strings, the result is their concatenation (joining).
Adding Numbers
If you add two numbers, you’ll get a numeric result:
Example
int a = 10; int b = 20; int result = a + b; // result will be 30 (an integer/number)
Adding Strings
If you add two strings, you’ll get a concatenated string:
Example
String num1 = "10"; String num2 = "20"; String concatenatedResult = num1 + num2; // concatenatedResult will be "1020" (a String)
Adding a Number and a String
If you add a number and a string, the result will still be a concatenated string:
Example
String numStr = "10"; int num = 20; String combinedResult = numStr + num; // combinedResult will be "1020" (a String)
Additional Information
String concatenation in Java can be performed using several methods. Besides using the +
operator, you can use methods such as StringBuilder
or StringBuffer
for more efficient concatenation in loops or large applications.
Example with StringBuilder
StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("The result is: "); stringBuilder.append(30); System.out.println(stringBuilder.toString()); // Outputs "The result is: 30"
Efficiency Note
Using StringBuilder
or StringBuffer
is recommended for better performance when concatenating strings in loops or when dealing with large strings.