DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Generics in Java and Their Implementation
  • Mule 3 DataWeave(1.x) Script To Resolve Wildcard Dynamically
  • Immutability in JavaScript — When and Why Should You Use It
  • Writing DTOs With Java8, Lombok, and Java14+

Trending

  • DZone's Article Submission Guidelines
  • How to Submit a Post to DZone
  • Medallion Architecture: Why You Need It and How To Implement It With ClickHouse
  • Top Book Picks for Site Reliability Engineers
  1. DZone
  2. Coding
  3. Languages
  4. Java String: A Complete Guide With Examples

Java String: A Complete Guide With Examples

This blog delves into the importance of Java Strings, showcasing their role in text manipulation through examples and methods.

By 
Saba Qureshi user avatar
Saba Qureshi
·
Aug. 17, 23 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
6.8K Views

Join the DZone community and get the full member experience.

Join For Free

In Java, the String class is one of the most fundamental and widely used classes. It represents a sequence of characters and serves as the backbone of text manipulation in Java programs. Strings are immutable, meaning their values cannot be changed once they are created. In this blog, we'll explore the Java String class and its important methods and provide examples to illustrate its usage.

Creating Strings

In Java, you can create a String object using either a string literal or the new keyword. The string literal is enclosed in double quotes, while using new explicitly creates a new String object. Here are examples of both approaches:

Java
 
java// Using string literal
String greeting1 = "Hello, World!"; 
// Using the new keyword
String greeting2 = new String("Hello, World!");


String Concatenation

You can concatenate strings using the + operator or the concat() method. The + operator is a concise way to combine strings, while concat() provides a more explicit approach:

Java
 
java String firstName = "John";
String lastName = "Doe"; 
// Using the + operator
String fullName1 = firstName + " " + lastName; 
// Using the concat() method
String fullName2 = firstName.concat(" ").concat(lastName);


String Length

The length() method returns the number of characters in a String:

Java
 
java String message = "Hello, Java!";
int length = message.length(); // length will be 13


String Comparison

To compare strings, you should use the equals() method or equalsIgnoreCase() method (ignores case). Avoid using the == operator, as it checks for reference equality, not content equality:

Java
 
java String str1 = "hello";
String str2 = "HELLO"; 
boolean isEqual = str1.equals(str2); // false
boolean isEqualIgnoreCase = str1.equalsIgnoreCase(str2); // true


Substring

The substring() method extracts a portion of a string:

Java
 
java String original = "Java Programming";
String substring = original.substring(5, 12); // substring will be "Program"


Splitting Strings

You can split a string into an array of substrings using the split() method. It takes a regular expression as an argument to define the splitting pattern:

Java
 
javaString data = "apple,banana,orange"; String[] fruits = data.split(","); // fruits array will be ["apple", "banana", "orange"]


Converting Case

Java provides methods to convert the case of strings:

Java
 
java String text = "Hello, Java!";
String lowercase = text.toLowerCase(); // "hello, java!"
String uppercase = text.toUpperCase(); // "HELLO, JAVA!"


Searching in Strings

The indexOf() method finds the index of a specific substring in a string. It returns the index of the first occurrence or -1 if the substring is not found:

Java
 
java String text = "Java is fun!";
int index = text.indexOf("is"); // index will be 5


Replacing Substrings

The replace() method replaces occurrences of a specified substring with a new string:

Java
 
java String text = "I like cats. Cats are cute!";
String newText = text.replace("cats", "dogs"); // "I like dogs. Dogs are cute!"


String Formatting

Java offers several ways to format strings. One common approach is using String.format() or printf():

Java
 
java String name = "Alice";
int age = 30;
String formatted = String.format("My name is %s and I am %d years old.", name, age);
// formatted will be "My name is Alice and I am 30 years old."


StringBuilder and StringBuffer

If you need to perform intensive string manipulations, consider using StringBuilder or StringBuffer. They are mutable and provide better performance for frequent string modifications:

Java
 
java StringBuilder sb = new StringBuilder(); sb.append("Hello, "); sb.append("Java!");
String result = sb.toString(); // "Hello, Java!"


Conclusion

In Java, the String class is an essential component for handling text-based data. Its immutability ensures thread safety and consistency in applications. Understanding the various methods provided by the String class, as well as when to use StringBuilder or StringBuffer for more intensive manipulations, will enable you to efficiently work with text data in Java programs. The versatility and functionality of Java strings make them a fundamental tool for developers to master in their journey to create powerful and dynamic applications.

Data structure Thread safety Java (programming language) Object (computer science) Operator (extension) Strings

Opinions expressed by DZone contributors are their own.

Related

  • Generics in Java and Their Implementation
  • Mule 3 DataWeave(1.x) Script To Resolve Wildcard Dynamically
  • Immutability in JavaScript — When and Why Should You Use It
  • Writing DTOs With Java8, Lombok, and Java14+

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!