Using +
to Join Text and Numbers
- In Java, the
+
symbol is used to join (combine) text and numbers when displaying output. - This process is called string concatenation (which simply means “joining text together”).
- Example:
public class joinTextnNum{
public static void main(String[] args) {
int age = 20;
System.out.println("I am " + age + " years old.");
}
}
Output: I am 20 years old.
- Java automatically converts the number
20
into text and joins it with"I am "
and" years old."
.
- Example 2: Performing Calculations Before Joining
If we want to perform a calculation before displaying the result, we must use parentheses ()
.
public class joinTextnNum{
public static void main(String[] args) {
int num = 10;
System.out.println("Double of " + num + " is " + (num * 2));
}
}
Output: Double of 10 is 20
- Java calculates
num * 2
first (because of the parentheses), then joins it with the text.
⚠️ Common Mistake
If you forget the parentheses, Java will join the text first, then add the number as text instead of doing the math:
public class joinTextnNum{
public static void main(String[] args) {
System.out.println("10 + 5 = " + 10 + 5);
}
}
Output: 10 + 5 = 105
✅ Fix: Use parentheses ()
to ensure the calculation happens first:
public class joinTextnNum{
public static void main(String[] args) {
System.out.println("10 + 5 = " + (10 + 5));
}
}
Output: 10 + 5 = 15
What is the output of the following Java code?
int num = 10;
System.out.println("Double of " + num + " is " + (num * 2));