Java Strings
Strings in Java are objects that can hold a sequence of characters contained within a pair of double quotes (""). Strings are immutable, meaning once a string is created, it cannot be changed. This provides benefits such as better performance, security, and thread safety.
Creating Strings
In Java, there are two ways to create a string:
- Using string literals
- Using the
newkeyword
Creating Strings Using String Literals
This example uses string literals (“…”) to create a string in Java:
class Main {public static void main(String[] args) {String s1 = "Hello";System.out.println(s1);}}
Here is the output:
Hello
Creating Strings Using new
This example uses the new keyword to create a string in Java:
class Main {public static void main(String[] args) {String s1 = new String("Hello");System.out.println(s1);}}
Here is the output:
Hello
Accessing String Characters
In Java, an index refers to the numerical position of an element within a data structure like an array or a string.
The charAt() method is used to access string characters.
Here is an example that uses this method to access the first character (index 0) of a Java string:
class Main {public static void main(String[] args) {String str = "Java";// Indexing starts at '0'char ch = str.charAt(0);System.out.println(ch);}}
Here is the output:
J
Get the Length of a String
The length() method can be used to get the length or the number of characters in a string:
String str = "Java Programming";int len = str.length();System.out.println("Length: " + len);
Here is the output:
Length: 16
Join Two Strings
The concat() method is used to join two strings in Java:
class Main {public static void main(String[] args) {String first = "Hello ";String second = "World";String result = first.concat(second);System.out.println(result);}}
Here is the output:
Hello World
Frequently Asked Questions
1. Are strings in Java mutable?
No, strings in Java are immutable. To create mutable strings, use StringBuilder or StringBuffer.
2. What is the difference between String, StringBuilder, and StringBuffer in Java?
Stringis immutable.StringBuilderis mutable and not thread-safe.StringBufferis mutable and thread-safe.
3. Can we override methods of the String class in Java?
No. the String class in Java is final, which means it cannot be subclassed.
Strings
- .charAt()
- Returns the character at a particular index in a string.
- .codePointAt()
- Returns the Unicode value at the given index in the string.
- .codePointBefore()
- Returns the Unicode value before the given index in the string.
- .codePointCount()
- Returns the number of Unicode values in specified range of a string.
- .compareTo()
- Compares two strings lexicographically using their Unicode values.
- .compareToIgnoreCase()
- Returns 0 if two strings are equal in Unicode value, regardless of character case. Otherwise, the lexicographical difference is returned.
- .concat()
- Returns a string that is the concatenation of the given strings.
- .contains()
- Returns true if a sequence of characters exists in a given string, otherwise false.
- .contentEquals()
- Returns true if the sequence of characters in the string is equal to the content of the specified string. If not, returns false.
- .copyValueOf()
- Returns a string with characters copied from an array.
- .endsWith()
- Returns true if a string ends with a given suffix, otherwise false.
- .equals()
- Returns true if two strings are equal in value and false otherwise.
- .equalsIgnoreCase()
- Compares two strings in a case-insensitive manner.
- .format()
- Returns a formatted string using the specified format string and arguments.
- .getBytes()
- Encodes the string into an array of bytes that represent the characters in the string.
- .getChars()
- Copies characters from the given string into the destination character array.
- .hashCode()
- Returns an integer hash code value for the object on which it is invoked.
- .indexOf()
- Returns the zero-indexed position of the first occurrence of the given character(s) in a string.
- .intern()
- Creates an exact copy of a string located in the heap memory and stores it in the string constant pool.
- .isEmpty()
- Returns true if a string has no content, otherwise false.
- .join()
- Returns a new string composed of the elements joined together with the specified delimiter.
- .lastIndexOf()
- Searches a string for a specified value and returns the position of the match.
- .length()
- Returns the length or number of characters in a string.
- .matches()
- Checks whether a string matches a given regular expression.
- .offsetByCodePoints()
- Returns the new index of a character in a string after applying the specified code point offset.
- .regionMatches()
- Tests if two string regions are equal.
- .replace()
- Returns a new string where all instances of a given value are switched with a new value.
- .replaceAll()
- Searches a string with a regex pattern and replaces each match with a replacement string.
- .replaceFirst()
- Replaces the first matching substring in a string with the specified replacement string.
- .split()
- Splits a string into an array of substrings based on a delimiter pattern.
- .startsWith()
- Returns true if a string starts with a given character sequence and false otherwise.
- .subSequence()
- Returns a character sequence from a string.
- .substring()
- Returns a part of the string specified through a starting index and an optional ending index.
- .toCharArray()
- Returns an new character array from a given string.
- .toLowerCase()
- Converts a string to lowercase characters.
- .toUpperCase()
- Returns a given string in all uppercase letters
- .trim()
- Removes leading and trailing whitespace from a string.
- .valueOf()
- Converts various data types to their string representations in Java
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
- Beginner Friendly.17 hours