Table of Contents
What is a String in Java?
A String in Java is an object that represents a sequence of characters. It belongs to the java. lang package which is automatically available in every Java program no import statement needed. Strings in Java are immutable, meaning once a String object is created its value can never be changed. Any operation that appears to modify a string actually creates a brand-new String object with the updated value while the original stays untouched. Strings can be created in two ways using a string literal which is the recommended approach, or using the new keyword which creates a separate object outside the String Pool.Syntax:
Example:// Using string literal (recommended)
String name = "Java";
// Using new keyword
String name = new String("Java");
// Java program to implement Strings
public class TutorialforGeeks
{
public static void main (String [] args)
{
String firstName = "James";
String lastName = "Gosling";
String fullName = firstName + " " + lastName;
System.out.println("First Nam: " + firstName);
System.out.println("Last Name: " + lastName);
System.out.println("Full Name: " + fullName);
System.out.println("Length: " + fullName.length());
System.out.println("Uppercase: " + fullName.toUpperCase());
System.out.println("Lowercase: " + fullName.toLowerCase());
}
}
Output:
Explanation:First Name: James
Last Name: Gosling
Full Name: James Gosling
Length: 13
Uppercase: JAMES GOSLING
Lowercase: james gosling
- firstName and lastName are two separate String objects created using string literals.
- The + operator joins them with a space in between to produce fullName.
- fullName.length() counts all characters, including the space, giving 13.
- toUpperCase () converts every character to uppercase and returns a new String object.
- toLowerCase () converts every character to lowercase and returns a new String object.
- The original fullName remains "James Gosling" throughout because strings are immutable.
Key Features of Strings in Java
- Immutable by Nature: Once a String object is created in Java, its content can never be modified. Every method that appears to change a string actually creates and returns a brand-new String object, leaving the original completely unchanged.
- Stored in the String Pool: When a string is created using a literal, Java stores it in a special memory area called the String Pool inside the heap. If the same literal is used again, Java simply reuses the existing object rather than creating a new one, which saves memory efficiently.
- Rich Set of Built-in Methods: The String class in Java provides a large collection of ready-to-use methods for finding length, comparing content, extracting substrings, replacing characters, searching for values, splitting text, and converting between types.
- Concatenation with + Operator: Java allows strings to be joined using the + operator. This works with other data types too. Java automatically converts integers, booleans, and other types into their string form before joining them together.
- Content vs Reference Comparison: Strings must be compared using the equals () method when checking content. Using == compares memory references, not actual values, which is one of the most common and costly mistakes beginners make in Java.
- Part of java. lang Package: The String class belongs to the java. lang package, which is automatically imported in every Java program. You never need to write any import statement to start working with strings.
String Creation and Concatenation
Creating String objects and joining them together using the + operator or the concat () method.Syntax:
Example:String s1 = "value1";
String s2 = "value2";
String result = s1 + s2; // using + operator
String result = s1.concat(s2); // using concat () method
// Java program to implement string
// creation and concatenation
public class TutorialforGeeks
{
public static void main (String [] args)
{
String s1 = "Hello";
String s2 = "World";
String s3 = "Java";
String result1 = s1 + ", " + s2 + "!";
String result2 = s1.concat(" ").concat(s3);
String result3 = "I am learning " + s3 + " programming.";
System.out.println(result1);
System.out.println(result2);
System.out.println(result3);
}
}
Output:
Explanation:Hello, World!
Hello Java
I am learning Java programming.
- s1 + ", " + s2 + "!" joins three strings and punctuation using the + operator.
- s1.concat(" ").concat(s3) chains two concat calls to join strings with a space.
- The third result uses + to embed the value of s3 inside a longer sentence naturally.
- result3.length() counts all 31 characters in the final sentence, including spaces.
String Comparison
Comparing two strings for equal content using equals() and for reference using ==.Syntax:
Example:s1.equals(s2); // compares content — recommended
s1.equalsIgnoreCase(s2); // compares content ignoring case
s1 == s2; // compares memory reference only
s1.compareTo(s2); // compares lexicographically
// Java program to implement string comparison
public class TutorialforGeeks
{
public static void main (String [] args)
{
String a = "Java";
String b = "Java";
String c = "java";
String d = new String("Java");
System.out.println("a.equals(b) : " + a.equals(b));
System.out.println("a.equals(c) : " + a.equals(c));
System.out.println("a.equalsIgnoreCase(c) : " + a.equalsIgnoreCase(c));
System.out.println("a == b : " + (a == b));
System.out.println("a == d : " + (a == d));
System.out.println("a.equals(d) : " + a.equals(d));
System.out.println("a.compareTo(b) : " + a.compareTo(b));
}
}
Output:
Explanation:a.equals(b) : true
a.equals(c) : false
a.equalsIgnoreCase(c) : true
a == b : true
a == d : false
a.equals(d) : true
a.compareTo(b) : 0
- a.equals(b) returns true because both strings contain exactly "Java".
- a.equals(c) returns false because "Java" and "java" differ in case and equals is case-sensitive.
- a.equalsIgnoreCase(c) returns true because it ignores the uppercase and lowercase difference.
- a == b returns true because both literals point to the same object inside the String Pool.
- a == d returns false because d was created using new, making it a separate object outside the pool.
- a.equals(d) returns true because equals checks actual content, not memory location.
- a.compareTo(b) returns 0 because both strings are lexicographically equal.
String Length and Character Access
Finding the total length of a string and accessing individual characters at specific index positions.Syntax:
Example:string.length(); // total number of characters
string.charAt(index); // character at given index
string.indexOf("value"); // first index of given value
string.lastIndexOf("value"); // last index of given value
// Java program to implement string
// length and character access
public class TutorialforGeeks
{
public static void main (String [] args)
{
String text = "Java Programming";
System.out.println("String : " + text);
System.out.println("Length : " + text.length());
System.out.println("charAt(0) : " + text.charAt(0));
System.out.println("charAt(5) : " + text.charAt(5));
System.out.println("indexOf('a') : " + text.indexOf('a'));
System.out.println("indexOf('P') : " + text.indexOf('P'));
System.out.println("lastIndexOf('a') : " + text.lastIndexOf('a'));
System.out.println("indexOf(\"Pro\") : " + text.indexOf("Pro"));
}
}
Output:
Explanation:String : Java Programming
Length : 16
charAt(0) : J
charAt(5) : P
indexOf('a') : 1
indexOf('P') : 5
lastIndexOf('a') : 10
indexOf("Pro") : 5
- length () returns 16, the total characters including the space between the two words.
- charAt (0) returns 'J' which is the very first character at index 0.
- charAt (5) returns 'P' which is the first character of "Programming" at index 5.
- indexOf('a') returns 1 because the first 'a' in "Java" appears at index 1.
- lastIndexOf('a') returns 14 because the last 'a' in "Programming" is at index 14.
- indexOf("Pro") returns 5, which is the starting index of the substring "Pro".
String Modification Methods
Producing modified versions of a string using methods like substring (), replace (), and trim ().Syntax:
Example:string.substring(startIndex); // from index to end
string.substring(startIndex, endIndex); // from start up to endIndex-1
string.replace("old", "new"); // replace all occurrences
string.trim(); // remove leading and trailing spaces
string.strip(); // modern version of trim()
// Java program to implement string modification methods
public class TutorialforGeeks
{
public static void main (String [] args)
{
String text = " Hello, Java World! ";
System.out.println("Original : '" + text + "'");
System.out.println("Trimmed : '" + text.trim() + "'");
System.out.println("Uppercase : " +
text.trim().toUpperCase());
System.out.println("Replace : " +
text.trim().replace("Java", "Python"));
System.out.println("Substring(7) : " +
text.trim().substring(7));
System.out.println("Substring(7,11) : " +
text.trim().substring(7, 11));
System.out.println("Strip : '" + text.strip() + "'");
}
}
Output:
Explanation:Original : ' Hello, Java World! '
Trimmed : 'Hello, Java World!'
Uppercase : HELLO, JAVA WORLD!
Replace : Hello, Python World!
Substring(7) : Java World!
Substring(7,11) : Java
Strip : 'Hello, Java World!'
- trim () removes all leading and trailing whitespace from both sides of the string.
- toUpperCase () converts the entire trimmed string to uppercase and returns a new object.
- replace ("Java", "Python") swaps every occurrence of "Java" with "Python" cleanly.
- substring (7) extracts everything from index 7 all the way to the end of the string.
- substring (7, 11) extracts characters from index 7 up to but not including index 11, thus printing "Java".
- strip () does the same job as trim () but also handles Unicode whitespace it is the modern recommended version.
String Searching Methods
Checking whether a string contains, starts with, ends with, or is empty using built-in search methods.Syntax:
Example:string.contains("value"); // true if value found anywhere
string.startsWith("value"); // true if string begins with value
string.endsWith("value"); // true if string ends with value
string.isEmpty(); // true if length is zero
string.isBlank(); // true if empty or only whitespace
// Java program to implement string searching methods
public class TutorialforGeeks
{
public static void main (String [] args)
{
String sentence = "Java is a powerful programming language.";
System.out.println("Contains 'powerful' : " +
sentence.contains("powerful"));
System.out.println("Contains 'Python' : " +
sentence.contains("Python"));
System.out.println("Starts with 'Java' : " +
sentence.startsWith("Java"));
System.out.println("Ends with 'language.' : " +
sentence.endsWith("language."));
System.out.println("Is empty : " + sentence.isEmpty());
System.out.println("Empty string isEmpty : " + "".isEmpty());
System.out.println("Blank string isBlank : " + " ".isBlank());
}
}
Output:
Explanation:Contains 'powerful' : true
Contains 'Python' : false
Starts with 'Java' : true
Ends with 'language.' : true
Is empty : false
Empty string isEmpty : true
Blank string isBlank : true
- contains("powerful") returns true because "powerful" exists somewhere inside the sentence.
- contains("Python") returns false because Python does not appear anywhere in the sentence.
- startsWith("Java") returns true because the sentence begins with the word "Java".
- endsWith("language.") returns true because those exact characters close the sentence.
- isEmpty() returns false on the full sentence and true on an empty string "".
- isBlank () returns true for " " because it contains only whitespace characters.
String Splitting and Type Conversion
Splitting a string into an array of parts and converting between strings and other data types.Syntax:
Example:string.split("delimiter"); // splits into String array
String.valueOf(value); // converts any type to String
Integer.parseInt(string); // converts String to int
Double.parseDouble(string); // converts String to double
string.toCharArray(); // converts String to char array
// Java program to implement string splitting
// and type conversion
public class TutorialforGeeks
{
public static void main (String [] args)
{
String csv = "Apple,Mango,Banana,Orange,Grapes";
String [] fruits = csv.split(",");
System.out.println("Total fruits : " + fruits.length);
for (String fruit : fruits)
{
System.out.println("→ " + fruit);
}
String numStr = "2025";
int year = Integer.parseInt(numStr);
System.out.println("\nString to int : " + (year + 1));
double pi = Double.parseDouble("3.14159");
System.out.println("String to double : " + pi);
int score = 98;
String scoreStr = String.valueOf(score);
System.out.println("Int to String : " + scoreStr);
char[] chars = "Java".toCharArray();
System.out.print("Char array : ");
for (char c : chars)
{
System.out.print(c + " ");
}
}
}
Output:
Explanation:Total fruits : 5
Apple
Mango
Banana
Orange
Grapes
String to int : 2026
String to double : 3.14159
Int to String : 98
Char array : J a v a
- split(",") breaks the CSV string at every comma and stores each part in a String array.
- The enhanced for loop prints each fruit from the array on its own line.
- Integer.parseInt("2025") converts the string to an integer so arithmetic can be performed on it.
- Double.parseDouble("3.14159") converts the string to a double value correctly.
- String.valueOf(98) converts the integer 98 into its String equivalent "98".
- toCharArray() breaks "Java" into individual characters stored in a char array.
How Strings Work in Java Step-by-Step?
- String Object is Created: When you write String name = "Java", Java checks the String Pool first. If "Java" already exists there, the same object is reused. If not, a new object is created and stored in the pool.
- Reference Variable Points to the Object: The variable name does not store the actual text it stores a reference that points to the String object in memory. This is why == compares references and not actual text content.
- Methods are Called on the Object: When you call a method like name.toUpperCase(), Java executes that method on the String object and returns a brand-new String object with the result. The original name object is never touched.
- Immutability is Enforced: Every time a string operation produces a new value, a fresh String object is created. If you want to keep the result, you must assign it to a variable. Simply calling name.toUpperCase() without assigning it does nothing to name.
- String is Ready to Use: The final String object, whether original or newly created, can be printed, compared, passed to methods, stored in arrays, or used anywhere text is needed throughout the program.
Conclusion
Strings are one of the most used and most important parts of Java programming. Almost every real-world application, whether it processes user names, reads file content, handles form data, or communicates over a network, relies heavily on strings at every level. Understanding that strings are immutable objects stored in the String Pool is the foundation of using them correctly and efficiently. The rich set of built-in methods that Java provides, from basic concatenation and comparison all the way to splitting, searching, and type conversion, gives you everything you need to work with text in any situation. The one rule that will save you the most bugs is to always use equals () when comparing string content and never rely on == for that purpose. Mastering strings thoroughly puts you in a strong position to handle real-world Java programming challenges with confidence.Frequently Asked Questions
1. Why are strings immutable in Java?2. What is the difference between String and StringBuilder in Java?Strings are immutable in Java to ensure security, memory efficiency, and thread safety across the entire application.
3. Why should we never use == to compare strings in Java?String creates a new object for every modification, while StringBuilder modifies the same object in place, making it faster for repeated changes.
4. What happens to the original string when we call toUpperCase() on it?Because == compares memory references, not actual content, always use equals () to compare string values correctly.
5. Can a String in Java be null, and how is it different from an empty string?The original string stays completely unchanged, and toUpperCase () simply returns a brand-new String object with the result.
Null means the variable points to no object at all, while an empty string "" is a real object that exists in memory with zero characters.
0 Comments