What is String in Java - Java String Types and Methods (With Examples)

Java Programming Course
Start Learning View All CoursesStrings in Java: An Overview
What Is a Java String?
In Java, String does not identify as a Datatype. It identifies as a class, which is a fundamental data type and variable in Java. Any programmer can create a String by instantiating the String class that is situated in the package of java.lang. The Java string methods assist in generating some Methods and construction for creating, manipulating, and searching a String. The objects of string functions in Java are immutable, that's why they cannot be overwritten. If there are any alterations needed in string operations in Java, it creates a new object.
How to Create a String Object?
There are a few steps to create a String Object in Java, those are:
Example
class String_Creation_Demo
{
public static void main(String[] args)
{
String ob1 = new String(); //creates an empty string
//new keyword helps to create an object of class String
System.out.println("Empty String: " +ob1);
char arr[] = {'j','k','a','q','e' };
String ob2 = new String(arr); //String from an array
System.out.println("Contents of Array String: " +ob2);
String ob3 = new String(arr,1,2); //String from subsequence of an array
System.out.println("Contents of subsequence of Array String: " +ob3);
String ob4 = new String(ob3); //String from another string object
System.out.println("Contents of Array String ob4: " +ob4);
}
}
Output
Empty String:
Contents of Array String: jkaqe
Contents of subsequent of Array String: ka
Contents of Array String ob4: ka
String objects can be created using two ways:
- Using String Literal.
- Using new keyword.
1. Using String Literal
In computer science, a literal is a term that is used to represent a value. Double quotes can be used to produce and represent Java String literals. You can insert any text or character between double quotes.
Example
String demoString = “Scholarhat”;
2. Using new keyword
The Java new keyword can be used to construct strings. A new object of the String class is produced in the heap memory, outside the string constant pool, when a string is created with the new command. These objects, as opposed to string literals, are given their own place on the heap, regardless of whether or not another object with an identical value is already present there.
Example
String demoString = new String (“Scholarhat”);
Interfaces and Classes in Strings in Java
The CharSequence interface is implemented by the class known as CharBuffer. By using character buffers instead of CharSequences, this class enables their use. Java.util.regex's regular-expression package serves as an illustration of this usage. A string is a collection of characters. String objects in Java are immutable, which simply means they can never be modified after they have been created.
CharSequence Interface
In Java, the CharSequence Interface is used to represent the order of characters. The following list includes classes that implement the CharSequence interface:
- StringBuffer
- StringBuilder
- StringTokenizer
1. StringBuffer
The majority of the functionality of strings is provided by the peer class of StringBuffer. StringBuffer represents expandable and writable character sequences, whereas the string represents fixed-length, immutable character sequences.
2. StringBuilder
A mutable string of characters is represented by the Java class StringBuilder. The StringBuilder class offers a substitute for the String Class in Java since it constructs a mutable sequence of characters instead of an immutable one as the String Class does.
3. StringTokenizer
A string can be divided into tokens using Java's StringTokenizer class.
Java Strings: Mutable or Immutable
- Strings in Java are immutable, which means that once they are formed, their values cannot be altered.
- To avoid conflicts that can result from numerous references to the same string object, immutability is required.
- Multiple references may point to a single string object in the String constant pool in Java.
- If one reference was permitted to change the value of the string, it might have an impact on other references and cause problems.
- Java makes sure that string objects are immutable, meaning that their values cannot be changed, to avoid these conflicts.
Methods of Java Strings
Name | Description |
length() | Returns the length (number of characters) of the string. |
charAt(int index) | Returns the character at the specified index within the string (indexing starts at 0). |
substring(int beginIndex) | Returns a new string that is a substring of the original string starting from the specified beginIndex. |
substring(int beginIndex, int endIndex) | Returns a substring of the original string starting from beginIndex and ending just before endIndex. |
concat(String str) | Concatenates the specified string str to the end of the current string. |
equals(Object obj) | Check if the current string is equal to the specified object. Returns true if equal, false otherwise. |
equalsIgnoreCase(String anotherString) | Compares the current string to another string, ignoring case differences. |
indexOf(String str) | Returns the index of the first occurrence of the specified substring str within the string, or -1 if not found. |
replace(char oldChar, char newChar) | Replace all occurrences of oldChar with newChar in the string. |
split(String regex) | Splits the string into an array of substrings based on the regular expression regex. |
String Manipulation
String manipulation mainly works for changing the case, fetching a character from a string, and trimming the content. There are other various important methods in string manipulation such as:
Example
class String_Manipulation_Demo
{
public static void main(String[] args)
{
String ob1 = "Scholar-Hat"; //creates a string object
//string length
System.out.println("Length of the String: " +ob1);
char arr[] = {'j','k','a','q','e' };
String ob2 = new String(arr); //String from an array
//string concatenation
System.out.println("Concatenate String and String Array: " +ob1.concat(ob2));
//to upper case
System.out.println("Contents of String in uppercase: " +ob1.toUpperCase());
//to lower case
System.out.println("Contents of String in lowercase: " +ob1.toLowerCase());
//split function
for(String res: ob1.split("-",2))
System.out.println("Splitting the String: " +res);
//contains function
System.out.println("Contains() function in String: " +(ob1.contains("Scholar")));
//Replace function
System.out.println("Replace function in String: " +(ob1.replace('o','a')));
//ReplaceAll function
System.out.println("ReplaceAll function in String: " +(ob1.replaceAll("lar","o")));
//substring function
System.out.println("Substring in String: " +(ob1.substring(3,6)));
//trim function
String str = " Scholar-Hat! ";
System.out.println("Without Trim function in String: " +str);
System.out.println("Trim function in String: " +(str.trim()));
}
}
Output
Length of the String: Scholar-Hat
Concatenate String and String Array: Scholar-Hatjkaqe
Contents of the String in uppercase: SCHOLAR-HAT
Contents of the String in lowercase: scholar-hat
Splitting the String: Scholar
Splitting the String: Hat
Contains() function in String: true
Replace function in String: Schalar-Hat
ReplaceAll function in String: Schoo-Hat
Substring in String: ola
Without Trim function in String: Scholar Hat!
Trim function in String: Scholar Hat!
String Comparison
There are some important methods that are used to make the string comparison, such as:
Example
class String_Comparison_Demo
{
public static void main(String[] args)
{
String ob1 = "Scholar-Hat"; //creates a string object
String ob2 = "scholar-hat";
//equals function
System.out.println("Using equals function: " +(ob1.equals(ob2)));
System.out.println("Using equalsIgnoreCase function: " +(ob1.equalsIgnoreCase(ob2)));
//compareTo function
System.out.println("Using compareTo function: " +(ob1.compareTo(ob2)));
System.out.println("Using compareToIgnoreCase function: " +(ob1.compareToIgnoreCase(ob2)));
//startsWith function
System.out.println("Using startsWith function: " +(ob1.startsWith("Sc")));
//endsWith function
System.out.println("Using endsWith function: " +(ob1.endsWith("at")));
}
}
Output
Using equals functions: false
Using equalsIgnoreCase functions: true
Using compareTo functions: 4
Using compareToIgnoreCase functions: 0
Using startsWith functions: true
Using endsWith functions: true
Searching in a String
There are some specific methods to search characters in a String Object, those are:
Example
class String_Searching_Demo
{
public static void main(String[] args)
{
String ob1 = "Scholar-Hat"; //creates a string object
System.out.println("Using indexOf function: " +ob1.indexOf('a'));
System.out.println("Using lastIndexOf function: " +ob1.lastIndexOf('a'));
}
}
Output
Using indexOf function: 5
Using lastIndexOf function: 9
FAQs
1. Why string objects are immutable in Java?
Because string objects cannot be changed after being created, Java makes them immutable to protect the security and integrity of data.
2. What is a string in Java with an example?
A string is a group of characters in Java. Example: String myString = "Hello, Java!";
3. What are Java 8 strings?
The java.util.StringJoiner class was added in Java 8 to allow for more effective string concatenation.
4. What is Java string data type?
A series of characters are represented by the string data type in Java. It's defined by the class java.lang.String.
5. Why string is used in Java?
Java uses strings to manipulate text, store text data, and carry out various actions on text.
6. What is string format?
In Java, the term "string format" describes setting a template with placeholders that will later be filled in with data. Example: "Hello,%s!" can be formatted as "Hello, Java!" by adding the word "Java".
Summary
In this comprehensive Java tutorial article, we covered the Java strings methods, string functions in java, and string operations in java., which are essential topics to explore during a Java online course with a certificate. As you can see, there are a variety of operations and methods that can be performed on Java Strings. This is just a small sampling of what you can do with strings in Java. With so many options available, you should have no problem finding the right tool for the job. Do some experimenting and see which methods work best for your purposes.