• Articles
  • Tutorials
  • Interview Questions

Java Strings - A Beginner's Guide with Syntax and Examples

Introduction to Java Strings

In Java, strings are a fundamental data type used to represent sequences of characters. Strings are instances of the String class, which is part of the java.lang package and is automatically imported into every Java program.

Types of Java Strings

  1. Java String Literal: A string literal refers to a sequence of characters enclosed within double quotation marks. This type of string is created using the syntax for string literals. For instance:
String literalString = "Greetings, Java!";
  1. Java String Object: Strings in Java are treated as objects of the String class. To create a string object, you utilize the constructor of the class:
String objectString = new String("Java's Strings");
  1. Java Immutable Strings: In the Java programming language, strings are deemed immutable, signifying that their values remain unchanged after their instantiation. Any action that appears to alter a string actually leads to the formation of a new string. This immutability feature contributes to thread safety and memory management:
String immutable = "I am unchangeable";

immutable = immutable.concat(", yet I can be concatenated"); // A new string is generated
  1. Java String Pool: Java employs a dedicated memory section referred to as the “string pool” or “string constant pool.” This pool is used to store distinct string literals. When a novel string literal is generated, Java checks whether it already resides in the pool. If it does, the new string references the existing one, optimizing memory usage:
String str1 = "Hola";

String str2 = "Hola"; // Both str1 and str2 point to the same string in the pool
  1. Java String Concatenation: String concatenation encompasses the process of merging strings. In Java, the + operator can be employed for concatenation; however, it entails the creation of fresh strings:
String firstName = "Alice";

String lastName = "Smith";

String fullName = firstName + " " + lastName;
  1. Raw Strings (Java 13+): Java 13 introduced “raw strings” as an experimental feature. These strings permit the inclusion of line breaks and special characters devoid of escape sequences. They are enveloped within triple backticks (“`):
String rawString = ```

This is a raw string.

It can encompass line breaks and special characters without the need for escape sequences.

  1. Unicode Escapes:**

Java facilitates the utilization of Unicode escapes within strings, allowing you to denote characters via their corresponding Unicode code points. For example:

```java

String unicodeString = "\u00A9 All Rights Reserved";

These various types and characteristics of strings in Java serve specific purposes, contributing to the manipulation and portrayal of strings in diverse scenarios.

Java String Class Methods

1. Creating Strings in Java:

You can create strings in Java using either the String class constructor or string literals.

// Using constructor

String str1 = new String("Hello, World!");

// Using string literal

String str2 = "Java Strings";

String literals are more commonly used because they are concise and easier to read.

2. Java String Concatenation:

Java provides the + operator for string concatenation. When used with strings, it concatenates them together.

String firstName = "John";

String lastName = "Doe";

String fullName = firstName + " " + lastName; // Results in "John Doe"

3. Java String Methods:

Within the Java spectrum, the String class boasts an array of inherent methods tailored to manipulate strings. Some of these encompass:

  • toUpperCase() and toLowerCase(): These functions metamorphose the string to uppercase or lowercase, respectively.
  • substring(int beginIndex, int endIndex): Enabling the extraction of a designated segment from the string, confined by specified indices.
  • indexOf(String str): This utility serves to yield the index of the inaugural occurrence of a given substring.
  • replace(char oldChar, char newChar): Paving the way to supplant instances of a particular character with an alternative character.

4. Java String Comparison:

Java’s framework accommodates diverse methods to facilitate string comparison. The equals() method facilitates content-based comparison between two strings. Conversely, the compareTo() method undertakes lexicographical comparison.

String str1 = "apple";

String str2 = "banana";

boolean areEqual = str1.equals(str2); // Returns false

int comparisonResult = str1.compareTo(str2); // Returns a value < 0

5. Immutability:

In the realm of Java, strings are imbued with immutability, signifying that their values remain unalterable subsequent to their genesis. Any endeavor to manipulate a string effectively engenders the conception of a fresh string.

6. Java String Formatting:

Within the domain of Java, the String.format() method assumes the role of a facilitator for string formatting through the utilization of designated placeholders:

int age = 30;

String formatted = String.format("My age is %d", age); // "My age is 30"

7. Java String Splitting and Joining:

The potential to partition a string into an array of substrings is conferred by the split() method, while the capacity to unify an array of strings into a solitary string is made accessible through either the join() function or the StringJoiner class.

String sentence = "This is a sample sentence";

String[] words = sentence.split(" "); // Splits at spaces

String joined = String.join("-", words); // Joins with hyphens

8. Java String Formatting with printf Method:

Java provides the printf method (similar to C’s printf) that allows you to format strings more conveniently.

double price = 19.99;

System.out.printf("The price is %.2f dollars%n", price); // "The price is 19.99 dollars"

The %n is used for a platform-independent line separator.

9. Java String Trimming:

The trim() method removes leading and trailing white spaces from a string, but not spaces within the string.

String padded = "   Hello, Java   ";

String trimmed = padded.trim(); // "Hello, Java"

10. Java String Interning:

Java has a concept called “string interning,” where strings that are created using string literals are stored in a common pool. This can optimize memory usage and improve equality checks for these strings.

String s1 = "hello";

String s2 = "hello";

boolean areEqual = s1 == s2; // true, due to string interning

11. Java String Building with StringBuilder:

If you need to perform a lot of string manipulation, using the StringBuilder class is more efficient than concatenating strings directly.

StringBuilder builder = new StringBuilder();

builder.append("Java");

builder.append(" is");

builder.append(" great!");

String result = builder.toString(); // "Java is great!"

12. Java String Equality and equals() Method:

When comparing strings for equality, use the equals() method, not the == operator. equals() compares the content of the strings, while == compares references.

String str1 = "hello";

String str2 = new String("hello");

boolean areEqual = str1.equals(str2); // true, contents are equal

13. StringBuffer for Thread-Safety:

If you need a mutable string that can be safely accessed by multiple threads, use the StringBuffer class. It’s similar to StringBuilder but includes synchronization for thread safety.

StringBuffer buffer = new StringBuffer();

buffer.append("Thread-");

buffer.append("safe");

String result = buffer.toString(); // "Thread-safe"

14. Unicode and Characters:

Java uses Unicode to represent characters, allowing you to work with a wide range of languages and symbols. You can use escape sequences to represent special characters, such as \n for newline and \t for tab.

char euroSymbol = '\u20AC'; // Euro symbol

String message = "Hello, \nJava\tWorld!";

15. Java String Performance Considerations:

While using string concatenation with + is convenient, repeated concatenation in loops can lead to performance issues due to the creation of intermediate strings. In such cases, using StringBuilder is more efficient.

16. Java String Immutability and Memory Efficiency:

String immutability means that once a string is created, it cannot be changed. While this has benefits, it can also lead to memory wastage when performing many modifications. StringBuilder can be used to mitigate this in such scenarios.

17. Regular Expressions and String Manipulation:

Java’s Pattern and Matcher classes allow you to work with regular expressions, which are powerful tools for string manipulation and pattern matching.

import java.util.regex.*;

Pattern pattern = Pattern.compile("\\d{3}-\\d{2}-\\d{4}");

Matcher matcher = pattern.matcher("123-45-6789");

boolean isMatch = matcher.matches(); // true, matches SSN pattern

Course Schedule

Name Date Details
Python Course 14 Dec 2024(Sat-Sun) Weekend Batch View Details
21 Dec 2024(Sat-Sun) Weekend Batch
28 Dec 2024(Sat-Sun) Weekend Batch

About the Author

Senior Consultant Analytics & Data Science

Sahil Mattoo, a Senior Software Engineer at Eli Lilly and Company, is an accomplished professional with 14 years of experience in languages such as Java, Python, and JavaScript. Sahil has a strong foundation in system architecture, database management, and API integration.