Clean • Professional
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.
String concatenation means joining two or more strings together.
+ OperatorString firstName = "John";
String lastName = "Doe";
String fullName = firstName + " " + lastName;
System.out.println(fullName); // John Doe
concat() MethodString str1 = "Java";
String str2 = " Programming";
String result = str1.concat(str2);
System.out.println(result); // Java Programming
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 allows converting numbers to strings and vice versa.
int num = 100;
String str = String.valueOf(num); // "100"
String str2 = Integer.toString(num); // "100"
String str = "200";
int number = Integer.parseInt(str); // 200
double value = Double.parseDouble("99.99"); // 99.99
int x = 50;
int y = 30;
String result = "Total: " + (x + y);
System.out.println(result); // Total: 80
Special characters in Java allow you to include characters that are not easily typed or control text formatting.
| 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 |
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"
+ or concat() for string concatenation.String.valueOf() or toString().