What are Strings in Java?
In Java, a String is a sequence of characters that we can use to represent a text, and it’s written inside double quotes(” “).
Strings are the most important data types in Java because they are essential for handling text in applications, such as input messages, file content, or data from the web.
String greeting = "Hello, World!";
Here, “Hello, World!” is a string that stores a set of characters as text.
Remember one thing: strings are immutable, which means their content cannot be changed once created. If you try to modify a string, a new string object is created in memory instead of changing the original one.
For example:
String name = "Java";
name = name + " Programming";
System.out.println(name);
Output:
Java Programming
Here, “Java” is not modified. Instead, a new string “Java Programming” is created and assigned to the name. The original string remains unchanged.
How Strings Work in Java
Java provides the String class to handle strings, which is part of the java.lang package. Since java.lang is automatically imported, you don’t need to import it in your code manually.
The String class provides many built-in methods to make working with text easy and an efficient way, like finding length, converting to uppercase, replacing characters, and more.
How To Create a Strings in Java
There are two primary ways to create strings in Java:
- Using String Literal
- Using the new Keyword
1) Using String Literals:
String message = "Hello Java";
When you use double quotes, Java automatically creates a string object and stores it in the String pool for memory optimization.
2) Using the new Keyword:
String message = new String("Hello Java");
This creates a new string object in memory, even if an identical one already exists.
Important Characteristics of Strings
Strings are not just ordinary text containers, they have some powerful and special features that make them work differently from other data types.
wo of the most important characteristics are immutability and the String Pool. Let’s understand both with clear examples.
1) Immutability of Strings:
In Java, strings are immutable, which means once a string object is created, its value cannot be changed.
Simple example:
public class ImmutabilityExample {
public static void main(String[] args) {
String s = "Hello";
// This does NOT change the original string
s.concat(" World");
System.out.println(s); // Output: Hello
}
}
In this code:
- We used s.concat(” World”), the original string “Hello” remained unchanged.
- The concat() method created a new string “Hello World”, but we didn’t store it.
If you want to use new string, you must assign it to a variable:
public class ImmutabilityExample2 {
public static void main(String[] args) {
String s = "Hello";
s = s.concat(" World"); // Now the new string is assigned to s
System.out.println(s); // Output: Hello World
}
}
- It makes strings thread-safe, so multiple parts of a program can use the same string without affecting each other.
- It allows strings to be cached and reused to improve performance.
2) String Pool (Memory Optimization):
Java uses a special memory area that is called the String Pool, also known as the string intern pool, to save memory and improve performance.
How It Works:
- Whenever you create a string literal (like “Java”), Java first checks if that string already exists in the pool.
- If it exists, Java will reuse the same object instead of creating a new one.
- If it doesn’t exist, a new string is added to the pool.
For example:
public class StringPoolExample {
public static void main(String[] args) {
String a = "Java";
String b = "Java";
System.out.println(a == b); // true
}
}
- Both a and b point to the same object in the String Pool.
- That’s why a == b returns true (they share the same memory reference).
3) Creating Strings with new keyword:
If you create a string using the new keyword, it will not use the pool by default, it will create a new object in the heap memory even if an identical string already exists in the pool.
public class NewStringExample {
public static void main(String[] args) {
String a = "Hello";
String b = new String("Hello");
System.out.println(a == b); // false (different memory)
System.out.println(a.equals(b)); // true (same content)
}
}
Explanation:
- a is stored in the String Pool.
- b is a new object created on the heap.
- Their references are different (a == b is false), but their values are the same (a.equals(b) is true).
Common String Operations
The String class provides many helpful methods to perform everyday text operations. Below are some of the most useful string operations we need in real Java programs.
1. Getting String Length
We use the length() method to find out how many characters a string contains. It counts all letters, spaces, numbers, and symbols.
For example:
public class StringLength {
public static void main(String[] args) {
String text = "Java Programming";
System.out.println("Length of text: " + text.length()); // Output: 17
}
}
- length() returns an integer value showing the total number of characters present in the string.
2. Concatenation (Joining Strings)
Concatenation means joining two or more strings into one. You can do this using the concat() method or the + operator.
For example:
public class StringConcatenation {
public static void main(String[] args) {
String first = "Java";
String second = "Developer";
String result = first.concat(" ").concat(second); // Using concat()
System.out.println(result); // Output: Java Developer
String combined = first + " " + second; // Using + operator
System.out.println(combined); // Output: Java Developer
}
}
- Both methods work the same way, but + is more commonly used for simplicity.
3. Character Extraction
We can use the charAt(index) method to get a single character from a string. Remember, Java indexing starts at 0.
For example:
public class CharacterExtraction {
public static void main(String[] args) {
String word = "Coding";
char letter = word.charAt(2); // 0-C, 1-o, 2-d
System.out.println("Character at index 2: " + letter); // Output: d
}
}
- It is useful when you need to check or process individual characters from a string.
4. Extracting Substrings
A substring is a part of a string. You can extract it using substring(startIndex, endIndex).
For example:
public class SubstringExample {
public static void main(String[] args) {
String sentence = "Java Programming Language";
String part = sentence.substring(5, 16); // from index 5 to 15
System.out.println("Extracted substring: " + part); // Output: Programming
}
}
- Note: The start index is inclusive, but the end index is exclusive.
5. Changing Case (Uppercase / Lowercase)
To convert all letters to uppercase or lowercase, use toUpperCase() and toLowerCase().
Example:
public class CaseConversion {
public static void main(String[] args) {
String language = "java";
System.out.println("Uppercase: " + language.toUpperCase()); // JAVA
String tech = "PYTHON";
System.out.println("Lowercase: " + tech.toLowerCase()); // python
}
}
- It is helpful for case-insensitive comparisons or formatting user input.
6. Replacing Characters or Words
The replace(old, new) method replaces characters or parts of the string with something else.
For example:
public class ReplaceExample {
public static void main(String[] args) {
String message = "I love Java";
String updated = message.replace("Java", "Python");
System.out.println("After replacement: " + updated); // Output: I love Python
}
}
7. Checking Equality
We can use the equals() method to check if two strings have the same content.
For example:
public class EqualityCheck {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "hello";
System.out.println("Are they equal? " + s1.equals(s2)); // Output: false
System.out.println("Ignore case: " + s1.equalsIgnoreCase(s2)); // Output: true
}
}
- You can also use equalsIgnoreCase() if you want to compare strings without caring about letter case.
8. Checking if a String is Empty
The isEmpty() method checks if the string contains no characters (length = 0).
For example:
public class EmptyCheck {
public static void main(String[] args) {
String str1 = "";
String str2 = "Java";
System.out.println("Is str1 empty? " + str1.isEmpty()); // true
System.out.println("Is str2 empty? " + str2.isEmpty()); // false
}
}
9. Trimming Extra Spaces (Whitespaces)
The trim() method removes any spaces at the start and end of a string but keeps spaces in the middle.
For example:
public class TrimExample {
public static void main(String[] args) {
String raw = " Java Programming ";
String cleaned = raw.trim();
System.out.println("Before: '" + raw + "'");
System.out.println("After: '" + cleaned + "'");
// Output: 'Java Programming'
}
}
Java String Exercise: “User Info Formatter”
Write a Java program that asks the user to enter their first name, last name, and favorite word.
Then, the program should:
- Combine the first and last name into one full name.
- Convert the full name to uppercase.
- Show the number of characters in the favorite word.
- Display the favorite word in reverse order.
Example Output:
Enter your first name: John
Enter your last name: Doe
Enter your favorite word: Programming
Full Name (Uppercase): JOHN DOE
Length of your favorite word: 11
Favorite word reversed: gnimmargorP
- Write this code in your own logic and understand Java Strings concept.
Also Learn Important Topics of Java
- What are the operators in Java Programming?
- What are Data Types in Java?
- What are the Variables in Java?
- Learn Java syntax.

M.Sc. (Information Technology). I explain AI, AGI, Programming and future technologies in simple language. Founder of BoxOfLearn.com.