Java (programming language)

Strings In Java


Strings are fundamental data types in Java, representing sequences of characters used for storing and manipulating text. They are essential for various tasks, including user interaction, data storage, file handling, and more.

Creating Strings

  • String literals: Enclose a sequence of characters within double quotes:


String greeting = "Hello, world!";
  • Using the new keyword: Explicitly create a String object:


String name = new String("Alice");

String Immutability

  • Strings in Java are immutable, meaning their contents cannot be changed after creation.
  • Any modification operation creates a new String object:


String message = "Welcome";
message = message + " to Java!";  // Creates a new String object

Common String Operations

  • Concatenation: Combine Strings using the + operator:


String fullName = firstName + " " + lastName;
  • Accessing characters: Use the charAt() method:


char firstLetter = name.charAt(0);
  • Finding substrings: Use indexOf(), lastIndexOf(), and substring():


int position = text.indexOf("Java");
String subString = text.substring(5, 10);
  • Getting length: Use the length() method:


int length = message.length();
  • Converting to uppercase/lowercase: Use toUpperCase() and toLowerCase():


String uppercase = name.toUpperCase();
String lowercase = title.toLowerCase();
  • Trimming whitespace: Use trim():


String trimmed = input.trim();

Comparing Strings

  • Use the == operator to compare references (not content):


if (str1 == str2) { ... }  // Compares object references
  • Use the equals() method to compare content:


if (str1.equals(str2)) { ... }  // Compares string values

String Methods

Java’s String class offers a rich set of methods for various operations:

  • Searching: contains(), startsWith(), endsWith()
  • Replacement: replace(), replaceFirst(), replaceAll()
  • Splitting: split()
  • Formatting: format()
  • Parsing: parseInt(), parseFloat()
  • And many more!

StringBuilder and StringBuffer

  • For frequent string modifications, use StringBuilder or StringBuffer (thread-safe) to avoid creating multiple String objects:


StringBuilder builder = new StringBuilder();
builder.append("Hello").append(" ").append("world!");
String finalString = builder.toString();


Mastering strings in Java is crucial for effective text manipulation and application development. Understanding their immutability, versatility, and available methods empowers you to work with text data efficiently and create robust solutions.


Learn coding the easy way. Find programming guides, examples and solutions with explanations.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button