Java Strings – Concatenation, Numbers & Special Characters
Strings are essential in Java, and often we need to combine strings, work with numbers in strings, or use special characters. This tutorial covers all these aspects with examples.
Java String Concatenation
String concatenation means joining two or more strings together.
Using + Operator
String firstName = "John";
String lastName = "Doe";
String fullName = firstName + " " + lastName;
System.out.println(fullName); // John Doe
Using concat() Method
String str1 = "Java";
String str2 = " Programming";
String result = str1.concat(str2);
System.out.println(result); // Java Programming
Concatenation with Numbers
When you combine strings and numbers using +, numbers are converted to strings automatically.
int age = 25;
String message = "Age: " + age;
System.out.println(message); // Age: 25
Tip: Use parentheses to control operations with numbers.
int a = 10, b = 20;
System.out.println("Sum: " + a + b); // Sum: 1020
System.out.println("Sum: " + (a + b)); // Sum: 30
Java Numbers and Strings
Java allows converting numbers to strings and vice versa.
Number to String
int num = 100;
String str = String.valueOf(num); // "100"
String str2 = Integer.toString(num); // "100"
String to Number
String str = "200";
int number = Integer.parseInt(str); // 200
double value = Double.parseDouble("99.99"); // 99.99
Example: Concatenate Numbers with Strings
int x = 50;
int y = 30;
String result = "Total: " + (x + y);
System.out.println(result); // Total: 80
Java Special Characters
Special characters in Java allow you to include characters that are not easily typed or control text formatting.
Common Escape Sequences
| Escape Sequence | Description | Example |
|---|---|---|
\\n | New line | "Hello\\nWorld" → |
| Hello | ||
| World | ||
\\t | Tab | "Hello\\tWorld" → Hello World |
\\\\ | Backslash | "C:\\\\Java\\\\Files" → C:\Java\Files |
\\" | Double quote | "He said, \\"Hello\\"" → He said, "Hello" |
\\' | Single quote | "It\\'s Java" → It's Java |
\\r | Carriage return | "Hello\\rWorld" |
\\b | Backspace | "Java\\bScript" → JaaScript |
Example: Using Special Characters
public class SpecialChars {
public static void main(String[] args) {
System.out.println("Line1\\nLine2");
System.out.println("Column1\\tColumn2");
System.out.println("Path: C:\\\\Java\\\\Files");
System.out.println("Quote: \\"Java is fun\\"");
}
}
Output:
Line1
Line2
Column1 Column2
Path: C:\\Java\\Files
Quote: "Java is fun"
Points to Know :
- Use
+orconcat()for string concatenation. - Numbers can be converted to strings using
String.valueOf()ortoString(). - Strings with numbers can be concatenated; use parentheses to avoid errors.
- Escape sequences allow special characters in strings and formatting.
- Strings are immutable; concatenation always creates new objects.
