Question
What is the syntax and usage of the '+' operator in Java?
int sum = 5 + 10; // Addition of integers
String result = "Hello, " + "World!"; // String concatenation
Answer
In Java, the '+' operator serves two distinct purposes: performing arithmetic addition and concatenating strings. This dual functionality can lead to a combination of numeric and string operations in one expression.
// Example of addition and string concatenation
int a = 5;
int b = 10;
int total = a + b; // total = 15
String greeting = "Hello, ";
String name = "Alice";
String message = greeting + name; // message = "Hello, Alice"
Causes
- The '+' operator is overloaded to work specifically for both integers (or numeric values) and String objects in Java.
Solutions
- To add two numbers, use the '+' operator directly between them, e.g., 'a + b'.
- For string concatenation, ensure at least one operand is a String. Java will convert other operands to string and concatenate them.
Common Mistakes
Mistake: Confusing between addition and string concatenation.
Solution: Ensure that one operand is a String when concatenating; otherwise, Java will perform addition.
Mistake: Using '+' in a context expecting only one type (e.g. only Numbers).
Solution: Always verify the types of both operands to avoid unexpected results.
Helpers
- Java '+' operator
- Java string concatenation
- Java arithmetic addition
- Java syntax for addition
- Java programming basics