What Is a String?
In Java, a String is used to store text data such as names, messages, or
sentences. A String is written inside double quotes ("") and can contain
letters, numbers, symbols, and spaces.
Example: Creating a String
String message = "Welcome to Java programming";
System.out.println(message);
String Length
In Java, a String is an object, not a primitive type. Because of this, it
comes with built-in methods that allow us to work with text easily. To find
the number of characters in a string, use the length() method.
Example: Finding String Length
String courseName = "Computer Science";
int totalCharacters = courseName.length();
System.out.println("Length of the string: " + totalCharacters);
Common String Methods
Java provides many useful methods to manipulate strings.
Converting Case
- toUpperCase() → Converts text to uppercase
- toLowerCase() → Converts text to lowercase
Example:
String city = "Chennai";
System.out.println(city.toUpperCase()); // CHENNAI
System.out.println(city.toLowerCase()); // chennai
Searching Inside a String
Finding Text Position
The indexOf() method returns the position of the first occurrence of a
word or character. Java starts counting from 0, not 1.
Example:
String sentence = "Learning Java is fun";
System.out.println(sentence.indexOf("Java")); // 9
Accessing Characters in a String
To get a character from a specific position, use the charAt()
method.
Example:
String language = "Java";
System.out.println(language.charAt(0)); // J
System.out.println(language.charAt(3)); // a
Comparing Strings
Strings should be compared using the equals() method, not
==.
Example:
String userInput = "admin";
String storedValue = "admin";
String role1 = "User";
String role2 = "Admin";
System.out.println(userInput.equals(storedValue)); // true
System.out.println(role1.equals(role2)); //
false
Removing Extra Spaces
The trim() method removes leading and trailing spaces from a
string.
Example:
String name = " Demo ";
System.out.println("Before trim: [" + name + "]");
System.out.println("After trim: [" + name.trim() +
"]");
Output:
Before trim: [ Demo ]
After trim: [Demo]
What Is String Concatenation?
String concatenation means joining two or more strings together to form
a single string. In Java, the most common way to combine strings is by
using the + operator.
Using the + Operator
String brand = "Tata";
String model = "Nexon";
String carName = brand + " " + model;
System.out.println(carName);
Output:
Tata Nexon
The " " adds a space between the two words.
Concatenating Text and Variables
String concatenation is often used to create dynamic sentences that
include variables.
String product = "Laptop";
double price = 59999.99;
System.out.println("The price of the " + product + " is Rs." +
price);
Output:
The price of the Laptop is Rs.59999.99
Combining Multiple Strings
You can join more than two strings in a single statement.
String day = "Monday";
String time = "10:00 AM";
String place = "Office";
String schedule = "Meeting on " + day + " at " + time + " in the " +
place;
System.out.println(schedule);
Using the concat() Method
Java also provides a concat() method to combine strings.
String part1 = "Data ";
String part2 = "Structures";
String course = part1.concat(part2);
System.out.println(course);
Chaining concat() Calls
Multiple strings can be joined by chaining concat()
methods.
String word1 = "Practice ";
String word2 = "makes ";
String word3 = "perfect.";
String sentence = word1.concat(word2).concat(word3);
System.out.println(sentence);
Important Note About Numbers
When using + with numbers:
int x = 10;
int y = 20;
System.out.println("Sum: " + x + y); // Sum:
1020
System.out.println("Sum: " + (x + y)); // Sum:
30
Parentheses are needed if you want addition before concatenation.
Java Numbers and Strings
In Java, the + operator has two different purposes:
- Addition → when used with numbers
- Concatenation → when used with strings
Java decides what to do based on the data types involved.
Adding Two Numbers
When both operands are numbers, Java performs mathematical
addition.
int a = 15;
int b = 25;
int total = a + b;
System.out.println("Total: " + total);
Output:
Total: 40
Since both variables are integers, Java adds them
numerically.
Joining Two Strings
When both operands are strings, Java joins them together instead of
adding.
String first = "30";
String second = "40";
String result = first + second;
System.out.println("Result: " + result);
Output:
Result: 3040
The values look like numbers, but they are text, so Java concatenates
them.
Mixing a String and a Number
When a string is combined with a number, Java converts the number into
text and performs concatenation.
String orderId = "ORD";
int number = 101;
String fullOrderId = orderId + number;
System.out.println("Order ID: " + fullOrderId);
Output:
Order ID: ORD101
The integer 101 is automatically converted to a string.
Order Matters in Mixed Expressions
Java evaluates expressions from left to right.
System.out.println(5 + 10 + " items"); // 15
items
System.out.println("Items: " + 5 + 10); // Items: 510
Explanation:
- 5 + 10 → number addition first
- "Items: " + 5 → string concatenation starts
Controlling Output with Parentheses
Use parentheses to force numeric addition before
concatenation.
System.out.println("Total = " + (5 + 10));
Output:
Total = 15
Parentheses ensure calculations happen first.
Real-Life Example: Bill Calculation
int price = 120;
int quantity = 3;
System.out.println("Final Amount: Rs." + (price *
quantity));
Output:
Final Amount: Rs.360
Java Special Characters in Strings
In Java, strings are enclosed in double quotes (" ). If you place
special characters like quotes or backslashes directly inside a
string, Java may get confused and throw a compile-time
error.
This will cause an error:
String message = "She said "Hello" to everyone.";
Java thinks the string ends at "She said ".
Escape Characters in Java
To safely include special characters inside strings, Java provides
escape characters. An escape character starts with a backslash (\),
telling Java to treat the next character as text.
Common Escape Characters
Table
Escape Sequence
\"
\'
\\
\n
\t
Output
"
'
\
New line
Tab
Meaning
Double quote
Single quote
Backslash
Line break
Horizontal spacing
Using Double Quotes Inside a String
String quote = "She said, \"Learning Java is fun!\"";
System.out.println(quote);
Output:
She said, "Learning Java is fun!"
The \" allows double quotes inside the string.
Using Single Quotes Inside a String
String sentence = "It\'s a beautiful day to code.";
System.out.println(sentence);
Output:
It's a beautiful day to code.
Useful for contractions like it's, don't, can't.
Using a Backslash Character
String path = "C:\\Java\\Programs\\Main.java";
System.out.println(path);
Output:
C:\Java\Programs\Main.java
Each backslash must be written as \\.
New Line Escape Sequence (\n)
String address = "Name: Rahul\nCity: Chennai\nCountry:
India";
System.out.println(address);
Output:
Name: Rahul
City: Chennai
Country: India
\n moves the cursor to a new line.
Tab Space (\t) Example
System.out.println("ID\tName\tScore");
System.out.println("1\tAnita\t95");
System.out.println("2\tRavi\t88");
Output:
ID Name Score
1 Anita 95
2 Ravi 88