📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Introduction
Strings are immutable in Java, meaning once a String object is created, its value cannot be changed. Instead, every modification results in the creation of a new String object. The java.lang.String
class is used to create and manipulate strings, offering a wide array of methods to handle text.
Table of Contents
- String Overview
- String Constructors
- String Methods
- charAt()
- codePointAt()
- codePointBefore()
- codePointCount()
- compareTo()
- compareToIgnoreCase()
- concat()
- contains()
- contentEquals()
- endsWith()
- equals() and equalsIgnoreCase()
- getBytes()
- getChars()
- hashCode()
- indexOf()
- intern()
- lastIndexOf()
- length()
- regionMatches()
- replace()
- replaceAll()
- replaceFirst()
- split()
- startsWith()
- subSequence()
- substring()
- toCharArray()
- toLowerCase()
- toUpperCase()
- trim()
- valueOf()
- strip()
- stripLeading()
- stripTrailing()
- isBlank()
- lines()
- repeat()
- indent()
- transform()
- describeConstable()
- resolveConstantDesc()
- formatted()
- stripIndent()
- translateEscapes()
- Conclusion
String Overview
Creating Strings
There are two ways to create a String object: by string literal or by using the new
keyword.
Using String Literal
String s = "javaguides";
Using new Keyword
public class StringExample { public static void main(String[] args) { String str = new String("Java Guides"); int length = str.length(); System.out.println("Length of the string '" + str + "' is: " + length); } }
Output:
Length of the string 'Java Guides' is: 11
Using Character Array
char[] chars = {'a', 'b', 'c'}; String s = new String(chars);
String Constructors
The String
class supports several constructors. Here are a few important ones with examples:
Default Constructor
String s = new String();
From Character Array
char[] chars = {'a', 'b', 'c'}; String s = new String(chars);
Subrange of Character Array
char[] chars = {'a', 'b', 'c', 'd', 'e', 'f'}; String s = new String(chars, 2, 3);
From Another String
String s1 = new String("Hello"); String s2 = new String(s1); System.out.println(s1); // Output: Hello System.out.println(s2); // Output: Hello
String Methods
charAt()
Returns the char value at the specified index.
public class CharAtExample { public static void main(String[] args) { String str = "Welcome to string handling guide"; char ch1 = str.charAt(0); System.out.println("Character at 0 index is: " + ch1); } }
Output:
Character at 0 index is: W
codePointAt()
Returns the character (Unicode code point) at the specified index.
public class CodePointAtExample { public static void main(String[] args) { String str = "javaguides"; int unicode = str.codePointAt(0); System.out.println("Unicode code point at index 0 is: " + unicode); } }
Output:
Unicode code point at index 0 is: 106
codePointBefore()
Returns the character (Unicode code point) before the specified index.
public class CodePointBeforeExample { public static void main(String[] args) { String str = "javaguides"; int unicode = str.codePointBefore(1); System.out.println("Unicode code point before index 1 is: " + unicode); } }
Output:
Unicode code point before index 1 is: 106
codePointCount()
Returns the number of Unicode code points in the specified text range.
public class CodePointCountExample { public static void main(String[] args) { String str = "javaguides"; int unicodeCount = str.codePointCount(0, str.length()); System.out.println("Number of Unicode code points: " + unicodeCount); } }
Output:
Number of Unicode code points: 10
compareTo()
Compares two strings lexicographically.
public class CompareToExample { public static void main(String[] args) { String s1 = "Hello World"; String s2 = "Java"; System.out.println(s1.compareTo(s2)); // Output: 2 (because "H" is 2 characters after "J") } }
Output:
2
compareToIgnoreCase()
Compares two strings lexicographically, ignoring case differences.
public class CompareToIgnoreCaseExample { public static void main(String[] args) { String s1 = "Hello World"; String s2 = "hello world"; System.out.println(s1.compareToIgnoreCase(s2)); // Output: 0 } }
Output:
0
concat()
Concatenates the specified string to the end of this string.
public class ConcatExample { public static void main(String[] args) { String str = "javaguides"; str = str.concat(".net"); System.out.println(str); // Output: javaguides.net } }
Output:
javaguides.net
contains()
Returns true if and only if this string contains the specified sequence of char values.
public class ContainsExample { public static void main(String[] args) { String str = "javaguides"; boolean contains = str.contains("guides"); System.out.println("Contains 'guides': " + contains); // Output: true } }
Output:
Contains 'guides': true
contentEquals()
Compares this string to the specified CharSequence.
public class ContentEqualsExample { public static void main(String[] args) { String str = "javaguides"; boolean isContentEquals = str.contentEquals("javaguides"); System.out.println("Content equals: " + isContentEquals); // Output: true } }
Output:
Content equals: true
endsWith()
Tests if this string ends with the specified suffix.
public class EndsWithExample { public static void main(String[] args) { String str = "javaguides"; boolean endsWith = str.endsWith("guides"); System.out.println("Ends with 'guides': " + endsWith); // Output: true } }
Output:
Ends with 'guides': true
equals() and equalsIgnoreCase()
Compares two strings for equality.
public class EqualsExample { public static void main(String[] args) { String str1 = "javaguides"; String str2 = "JAVAguides"; System.out.println("Equals: " + str1.equals(str2)); // Output: false System.out.println("Equals ignore case: " + str1.equalsIgnoreCase(str2)); // Output: true } }
Output:
Equals: false Equals ignore case: true
getBytes()
Encodes this String into a sequence of bytes.
public class GetBytesExample { public static void main(String[] args) throws UnsupportedEncodingException { String str = "javaguides"; byte[] bytes = str.getBytes("UTF-8"); for (byte b : bytes) { System.out.print(b + " "); } } }
Output:
106 97 118 97 103 117 105 100 101 115
getChars()
Copies characters from this string into the destination character array.
public class GetCharsExample { public static void main(String[] args) { String str = "This is a demo of the getChars method."; char[] buf = new char[10]; str.getChars(10, 20, buf, 0); System.out.println(buf); } }
Output:
demo of th
hashCode()
Returns a hash code for this string.
public class HashCodeExample { public static void main(String[] args) { String str = "javaguides"; int hashCode = str.hashCode(); System.out.println("Hash code: " + hashCode); } }
Output:
Hash code: -138203751
indexOf()
Returns the index within this string of the first occurrence of the specified character or substring.
public class IndexOfExample { public static void main(String[] args) { String str = "javaguides"; System.out.println("Index of 'guides': " + str.indexOf("guides")); } }
Output:
Index of 'guides': 4
intern()
Returns a canonical representation for the string object.
public class InternExample { public static void main(String[] args) { String str = "javaguides"; String newStr = new String("javaguides"); System.out.println(newStr.intern() == str); // Output: true } }
Output:
true
lastIndexOf()
Returns the index within this string of the last occurrence of the specified character or substring.
public class LastIndexOfExample { public static void main(String[] args) { String str = "javaguides"; System.out.println("Last index of 'g': " + str.lastIndexOf('g')); } }
Output:
Last index of 'g': 4
length()
Returns the length of this string.
public class LengthExample { public static void main(String[] args) { String str = "Java Guides"; int length = str.length(); System.out.println("Length: " + length); } }
Output:
Length: 11
regionMatches()
Tests if two string regions are equal.
public class RegionMatchesExample { public static void main(String[] args) { String str = "javaguides"; boolean result = str.regionMatches(0, "java", 0, 4); System.out.println("Region matches: " + result); // Output: true } }
Output:
Region matches: true
replace()
Replaces each occurrence of the specified character or substring.
public class ReplaceExample { public static void main(String[] args) { String str = "javaguides"; String newStr = str.replace('a', 'b'); System.out.println("Replaced: " + newStr); // Output: jbvbguides } }
Output:
Replaced: jbvbguides
replaceAll()
Replaces each substring of this string that matches the given regular expression.
public class ReplaceAllExample { public static void main(String[] args) { String str = "javaguides"; String newStr = str.replaceAll("[a-z]", "java"); System.out.println("Replaced all: " + newStr); // Output: javajavajavajavajavajavajavajavajavajava } }
Output:
Replaced all: javajavajavajavajavajavajavajavajavajava
replaceFirst()
Replaces the first substring of this string that matches the given regular expression.
public class ReplaceFirstExample { public static void main(String[] args) { String str = "javaguides"; String newStr = str.replaceFirst("[a-z]", "java"); System.out.println("Replaced first: " + newStr); // Output: javaavaguides } }
Output:
Replaced first: javaavaguides
split()
Splits this string around matches of the given regular expression.
public class SplitExample { public static void main(String[] args) { String str = "java,guides.net"; String[] parts = str.split(","); for (String part : parts) { System.out.println(part); } } }
Output:
java guides.net
startsWith()
Tests if this string starts with the specified prefix.
public class StartsWithExample { public static void main(String[] args) { String str = "javaguides"; boolean startsWith = str.startsWith("java"); System.out.println("Starts with 'java': " + startsWith); // Output: true } }
Output:
Starts with 'java': true
subSequence()
Returns a character sequence that is a subsequence of this sequence.
public class SubSequenceExample { public static void main(String[] args) { String str = "javaguides"; CharSequence subSeq = str.subSequence(0, 4); System.out.println("Subsequence: " + subSeq); // Output: java } }
Output:
Subsequence: java
substring()
Returns a new string that is a substring of this string.
public class SubStringExample { public static void main(String[] args) { String str = "javaguides"; String subStr = str.substring(4); System.out.println("Substring from index 4: " + subStr); // Output: guides } }
Output:
Substring from index 4: guides
toCharArray()
Converts this string to a new character array.
public class ToCharArrayExample { public static void main(String[] args) { String str = "javaguides"; char[] charArray = str.toCharArray(); for (char c : charArray) { System.out.print(c + " "); } } }
Output:
j a v a g u i d e s
toLowerCase()
Converts all of the characters in this string to lowercase using the rules of the default locale.
public class ToLowerCaseExample { public static void main(String[] args) { String str = "JAVAGUIDES"; String lowerCaseStr = str.toLowerCase(); System.out.println("Lowercase: " + lowerCaseStr); // Output: javaguides } }
Output:
Lowercase: javaguides
toUpperCase()
Converts all of the characters in this string to uppercase using the rules of the default locale.
public class ToUpperCaseExample { public static void main(String[] args) { String str = "javaguides"; String upperCaseStr = str.toUpperCase(); System.out.println("Uppercase: " + upperCaseStr); // Output: JAVAGUIDES } }
Output:
Uppercase: JAVAGUIDES
trim()
Returns a string whose value is this string, with any leading and trailing whitespace removed.
public class TrimExample { public static void main(String[] args) { String str = " javaguides "; String trimmedStr = str.trim(); System.out.println("Trimmed: '" + trimmedStr + "'"); // Output: 'javaguides' } }
Output:
Trimmed: 'javaguides'
valueOf()
The valueOf()
method converts different types of values into a string. It has multiple overloaded forms.
public class ValueOfExample { public static void main(String[] args) { boolean b = true; char c = 'A'; int i = 123; long l = 12345L; float f = 1.23f; double d = 1.234567; System.out.println(String.valueOf(b)); // Output: true System.out.println(String.valueOf(c)); // Output: A System.out.println(String.valueOf(i)); // Output: 123 System.out.println(String.valueOf(l)); // Output: 12345 System.out.println(String.valueOf(f)); // Output: 1.23 System.out.println(String.valueOf(d)); // Output: 1.234567 } }
Output:
true A 123 12345 1.23 1.234567
strip()
Removes leading and trailing white space according to the Unicode definition of whitespace.
public class StripExample { public static void main(String[] args) { String str = " javaguides "; String strippedStr = str.strip(); System.out.println("Stripped: '" + strippedStr + "'"); // Output: 'javaguides' } }
Output:
Stripped: 'javaguides'
stripLeading()
Removes leading whitespace.
public class StripLeadingExample { public static void main(String[] args) { String str = " javaguides"; String strippedLeadingStr = str.stripLeading(); System.out.println("Leading stripped: '" + strippedLeadingStr + "'"); // Output: 'javaguides' } }
Output:
Leading stripped: 'javaguides'
stripTrailing()
Removes trailing whitespace.
public class StripTrailingExample { public static void main(String[] args) { String str = "javaguides "; String strippedTrailingStr = str.stripTrailing(); System.out.println("Trailing stripped: '" + strippedTrailingStr + "'"); // Output: 'javaguides' } }
Output:
Trailing stripped: 'javaguides'
isBlank()
Checks if the string is empty or contains only whitespace characters.
public class IsBlankExample { public static void main(String[] args) { String str = " "; boolean isBlank = str.isBlank(); System.out.println("Is blank: " + isBlank); // Output: true } }
Output:
Is blank: true
lines()
Returns a stream of lines extracted from the string, separated by line terminators.
public class LinesExample { public static void main(String[] args) { String str = "javaguides\nJava 11"; str.lines().forEach(System.out::println); } }
Output:
javaguides Java 11
repeat()
Repeats the string the specified number of times.
public class RepeatExample { public static void main(String[] args) { String str = "javaguides "; String repeatedStr = str.repeat(3); System.out.println("Repeated: " + repeatedStr); // Output: javaguides javaguides javaguides } }
Output:
Repeated: javaguides javaguides javaguides
indent()
Adjusts the indentation of each line of the string based on the value of n.
public class IndentExample { public static void main(String[] args) { String str = "Java\n12"; String indentedStr = str.indent(4); System.out.println("Indented:\n" + indentedStr); } }
Output:
Indented: Java 12
transform()
Applies the provided function to the string.
public class TransformExample { public static void main(String[] args) { String original = " java 12 "; String transformed = original .transform(String::strip) .transform(s -> s.concat(" is awesome")) .transform(String::toUpperCase); System.out.println("Transformed: " + transformed); // Output: JAVA 12 IS AWESOME } }
Output:
Transformed: JAVA 12 IS AWESOME
describeConstable()
Returns an Optional
describing the string, suitable for use in constant expression.
import java.util.Optional; public class DescribeConstableExample { public static void main(String[] args) { String str = "Java"; Optional<String> opt = str.describeConstable(); opt.ifPresent(System.out::println); // Output: Java } }
Output:
Java
resolveConstantDesc()
Part of the JVM's constant API, resolving a String constant description to a String.
import java.lang.invoke.MethodHandles; public class ResolveConstantDescExample { public static void main(String[] args) { String str = "Java"; String resolved = str.resolveConstantDesc(MethodHandles.lookup()); System.out.println("Resolved: " + resolved); // Output: Java } }
Output:
Resolved: Java
formatted()
Formats the string using the given arguments, similar to String.format()
.
public class FormattedExample { public static void main(String[] args) { String template = "Welcome to %s!"; String result = template.formatted("javaguides"); System.out.println("Formatted: " + result); // Output: Welcome to javaguides! } }
Output:
Formatted: Welcome to javaguides!
stripIndent()
Removes incidental white space from the beginning and end of every line in the string.
public class StripIndentExample { public static void main(String[] args) { String textBlock = """ javaguides Java 15 """; String result = textBlock.stripIndent(); System.out.println("Stripped Indent:\n" + result); } }
Output:
Stripped Indent: javaguides Java 15
translateEscapes()
Translates escape sequences like \n
, \t
, etc., in the string as if in a string literal.
public class TranslateEscapesExample { public static void main(String[] args) { String str = "javaguides\\nJava 15"; String result = str.translateEscapes(); System.out.println("Translated Escapes:\n" + result); } }
Output:
Translated Escapes: javaguides Java 15
Conclusion
The String
class in Java provides a comprehensive set of methods for creating, manipulating, and handling strings. By understanding and utilizing these methods, you can efficiently manage string operations in your Java applications. This guide covers a broad range of methods introduced up to Java 21, demonstrating how to use each with simple, beginner-friendly examples.
Comments
Post a Comment
Leave Comment