24
JanWhat is String in Java - Java String Methods & Type (Examples)
String in Java
A String in Java is used to store and work with text, like names, messages, or any written information. Unlike a simple group of characters, a String in Java is an object with built-in tools to help combine, compare, and modify text easily. Whether it's displaying messages or taking user input, Strings in Java make handling text simple and efficient for programmers.
In this Java tutorial, let's explore the concept of String in Java, including What are Strings in Java?, How to Create a String Object in Java?, Interfaces and Classes in Strings in Java, Methods of Java Strings, Memory allotment in Java String, and a lot more.If you're interested in gaining expertise in working with Java, consider enrolling in our Java Online Course Free With Certificate.
What are Strings in Java?
String in Java does not identify as a datatype. It identifies as a class, a fundamental data type in Java. Any programmer can create a String in Java by instantiating the String class situated in Java. lang package. The string in Java methods assists in generating some methods and construction for creating, manipulating, and searching a String. The objects of string functions in Java are immutable.
Example:
String name = "ScholarHat";
Read More - Top 50 Java Interview Questions For Freshers
How to Create a String Object in Java?
There are a few steps to create a String Object in Java, those are:
Java String 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
Explanation
- Creating an Empty String: String ob1 = new String(); creates an empty String object with no content, and it's printed as "Empty String: ".
- Creating a String from a Character Array: String ob2 = new String(arr); creates a String from the given character array and prints its content as "Contents of Array String: jkaqe".
- Creating a String from a Subsequence: String ob3 = new String(arr, 1, 2); creates a String using a part of the character array (from index 1 to 2) and prints it as "Contents of subsequence of Array String: ka".
2 Ways to Create a String in Java
String objects can be created in two ways:
- Using String Literal
- Using new keyword
1. Using String Literal
In computer science, a literal is a term 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.
Syntax
<string_type> <string_variable> = "<sequence_of_string>";
Example
Let's look at the illustration of creating a string using a string literal in our Java Online Editor.
public class Main {
public static void main(String args[]) {
// A string object
String demoString = "Scholarhat";
System.out.println(demoString);
}
}
Output
Scholarhat
Explanation
- The code defines a String variable demoString and assigns it the value "Scholarhat".
- The System.out.println(demoString); line prints the value of demoString to the console, which is Scholarhat.
2. Using new keyword
The Java new keyword can be used to construct string in java. 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 place on the heap, regardless of whether or not another object with an identical value is already present there.
Syntax
String stringName = new String("string_value");
Example
public class Main {
public static void main(String[] args) {
String str = new String("ScholarHat");
System.out.println(str);
}
}
Output
Scholarhat
Explanation
- The code creates a new String object str with the value "ScholarHat" using the new keyword.
- The System.out.println(str); statement prints the value of str to the console, which is ScholarHat.
Read More - Java Programmer Salary In India
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 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:
- String
- StringBuffer
- StringBuilder
1. String
A string is an immutable class i.e. it cannot be changed. We need to create a new object and functions like toupper, tolower, etc return a new object.
Example
String str= "Scholarhat";
or
String str= new String("Scholarhat")
2. 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.
Example
StringBuffer demoString = new StringBuffer("Scholarhat");
3. 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.
Example
StringBuilder demoString = new StringBuilder();
demoString.append("Scholarhat");
StringTokenizer
A string can be divided into tokens using Java's StringTokenizer class. A StringTokenizer object internally maintains a current position within the string to be tokenized. A token is returned by taking a substring of the string used to create the StringTokenizer object.
Example
Java Strings: Mutable or Immutable
- Strings in Java are immutable, i.e. 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 string's value, it might impact other references and cause problems.
- To avoid these conflicts, Java ensures that string objects are immutable, meaning that their values cannot be changed.
Immutable String in Java
Definition: In Java, strings are immutable, meaning that once a string object is created, its value cannot be changed. Any operation that modifies a string creates a new string object in memory rather than altering the original one.
Characteristics:
- String immutability ensures security, simplicity, and efficiency in Java.
- It is thread-safe, meaning multiple threads can use a string without synchronization issues.
- Strings are stored in the String Pool for better memory optimization.
Advantages:
- Makes strings secure, especially when used in sensitive areas like database connections.
- Optimizes memory usage through the String Constant Pool.
Example:
public class ImmutableStringExample {
public static void main(String[] args) {
String str = "Hello";
str.concat(" World");
System.out.println(str); // Output: Hello
String newStr = str.concat(" World");
System.out.println(newStr); // Output: Hello World
}
}
Output
Hello
Hello World
Explanation
The concat method does not change the original string str but creates a new string newStr.
Memory Allotment of String
Definition: In Java, memory for strings is managed through two main areas:
- Heap Memory: Used for strings created using the new keyword.
- String Constant Pool: A special area in the heap for storing string literals.
Characteristics:
- The String Pool allows the reusability of string objects to optimize memory usage.
- Strings created using literals are stored in the String Constant Pool.
- Strings created with the new keyword are stored in the Heap Memory but can still reference the pool if intern() is used.
Advantages:
- Reduces memory consumption for commonly used strings.
- Improves performance in applications where string manipulation is frequent.
Example
public class StringMemoryExample {
public static void main(String[] args) {
String s1 = "Hello"; // Stored in String Pool
String s2 = "Hello"; // References the same object in String Pool
String s3 = new String("Hello"); // Stored in Heap Memory
String s4 = s3.intern(); // References String Pool object
System.out.println(s1 == s2); // true
System.out.println(s1 == s3); // false
System.out.println(s1 == s4); // true
}
}
Output
true
false
true
Explanation
- s1 and s2 point to the same object in the String Pool.
- s3 is a new object in the heap.
- s4 uses intern() to refer to the String Pool object.
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:
String Manipulation Example in Java in our Java Compiler
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()));
}
}
When you execute the above program in the Java Playground to see the output.
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
Some important methods are used to make the string comparison, such as:
String ComparisonExample
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:
Searching in a StringExample
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
Explanation
- String Initialization: String ob1 = "Scholar-Hat"; creates a string "Scholar-Hat".
- indexOf Method: ob1.indexOf('a') finds the first occurrence of 'a' (index 3) and prints it.
- lastIndexOf Method: ob1.lastIndexOf('a') finds the last occurrence of 'a' (index 9) and prints it.
Read More: Top 30+ String in Java Interview Questions with Answers 2025 |
Summary
In this comprehensive Java tutorial, we covered the Java strings methods, string in Java, and string operations in Java, which are essential topics to explore during a Free Java Certification Course. As you can see, there are a variety of operations and methods that can be performed on Java Strings. Do some experimenting and see which methods work best for your purposes.
To consider problems and help you clear your concepts, we provide you with complete Free Technology Courses. I hope this will help you surely and you will do great in your career
Practice with the Following MCQs
Q 1: Which method is used to compare two strings in Java?
Explanation: The equals() method is used to compare two strings in Java to check for their equality.
Q 2: Which of the following is the correct way to create a string in Java?
Explanation: Both ways are correct for creating a string in Java. The first method uses string literals, while the second uses the String constructor.
Q 3: What is the result of the following code snippet in Java? String str = "Hello World"; str = str.substring(0, 5);
Explanation: The substring() method extracts a part of the string. It returns the substring from index 0 to 5, i.e., "Hello".
Q 4: Which method is used to convert all characters of a string to lowercase?
Explanation: The toLowerCase() method in Java is used to convert all the characters in the string to lowercase.
Q 5: What does the length() method of a string return in Java?
Explanation: The length() method returns the total number of characters in the string, including spaces.