Tutorial Playlist
The concept of string in Java is taught in any beginner Java programming class. It is an instrumental concept in different coding scenarios and a must-have in your Java knowledge arsenal. This tutorial provides an in-depth guide to the various concepts of strings in Java.
Java uses strings for various tasks, such as text data storage and manipulation, user input handling, file processing, network connection, and more. Java provides many inbuilt functions to work on strings.
Understanding the concept of strings is crucial for mastery of Java programming.
A string in Java is a data type used to store a sequence of characters. It acts the same way as an array does in Java.
There are two ways we can create strings in Java. Let us look at the Java string syntax:
Example syntax:
String myString = "Hello, World!";
myString = "Java Programming";
Example syntax:
String myString = new String("Hello, World!");
myString = new String("Java Programming");
A class in Java refers to a group of objects with similar properties. Different objects in a class may show different attributes and properties described by the class. A class is also called a blueprint for the creation of objects.
An interface in Java can be called the blueprint of a class and has fields like static, final, and public. The method body can not be defined in Java. An interface, unlike an abstract class, can not be instantiated.
Interfaces are used in Java for the following reasons:
Let us look at a Java string program with output.
Example:
import java.util.StringTokenizer;
public class StringInterfacesAndClassesExample {
public static void main(String[] args) {
// Using CharSequence interface
CharSequence charSequence = "Hello, World!";
int length = charSequence.length();
char firstChar = charSequence.charAt(0);
CharSequence subSequence = charSequence.subSequence(7, 12);
System.out.println("Length: " + length);
System.out.println("First Character: " + firstChar);
System.out.println("Subsequence: " + subSequence);
// Using StringBuilder class
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Hello");
stringBuilder.append(" ");
stringBuilder.append("World!");
String result = stringBuilder.toString();
System.out.println("StringBuilder result: " + result);
// Using StringTokenizer class
String sentence = "The quick brown fox jumps over the lazy dog";
StringTokenizer tokenizer = new StringTokenizer(sentence);
System.out.println("Tokenized sentence:");
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
System.out.println(token);
}
}
}
In this example, we create an instance of CharSequence and demonstrate its length(), charAt(), and subSequence() methods. Then, we use the StringBuilder class to efficiently concatenate strings. Finally, we tokenize a sentence using the StringTokenizer class to split it into individual words.
A sequence of characters is represented with the help of the CharSequence interface in Java. It is implemented with the help of
The string is immutable in Java, meaning it can not be modified. StringBuffer and StringBuilder classes are used for mutable strings.
String name = "John";
int age = 30;
// Format string using placeholders
String formattedString = String.format("My name is %s and I am %d years old.", name, age);
System.out.println(formattedString);
// Output: My name is John and I am 30 years old.
The StringBuilder and StringBuffer classes provide mutable sequences of characters. They are commonly used for efficient string concatenation or manipulation.
StringBuilder builder = new StringBuilder();
builder.append("Hello");
builder.append(" World!");
String result = builder.toString();
System.out.println(result);
The StringTokenizer class allows you to tokenize a string into individual tokens based on a specified delimiter.
String sentence = "The quick brown fox jumps over the lazy dog";
StringTokenizer tokenizer = new StringTokenizer(sentence);
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
System.out.println(token);
}
Strings in Java are stored in a heap storage area called the string pool. String Intern pool and String Constant pool are other names of String pool. Java String class maintains the string pool and is empty by default, just like any other object storage.
When you initialize a new string, JVM checks if the same string is already present in the string pool before allotting space to it. If yes, it just stores a reference to the previously stored string to save resources.
In Java 8, the String pool was transferred from the Permanent Generation (PermGen) area to the standard heap area. This modification was developed to address problems with PermGen space, a fixed-size memory space that holds class metadata, interned strings, and other JVM-specific information.
A string works the same way an array of characters do. The String class in Java provides a lot of default methods like concat(), compare(), replace(), compareTo(), substring(), and more. With the help of these predefined functions, it is very convenient to operate on strings in Java.
Strings in Java are an immutable data type that stores a sequence of characters. Here we will discuss an example.
Let us look at this piece of code
String s1 = “computer”;
Here, the name of the string is s1, and the value stored in it is “computer.” The compiler treats the string like an array and puts the characters of “computer” in different memory locations in a series. If we take this example, the character ‘c’ is stored at position 0, ‘o’ is stored at position 1, and so on.
Here is an example of using strings in Java:
public class String1 {
public static void main(String[] args) {
String message = "Hello, World!";
int length = message.length();
System.out.println("Length: " + length);
String name = "Alice";
String greeting = message + " My name is " + name;
System.out.println("Greeting: " + greeting);
String substring = message.substring(7, 12);
System.out.println("Substring: " + substring);
String uppercase = message.toUpperCase();
String lowercase = message.toLowerCase();
System.out.println("Uppercase: " + uppercase);
System.out.println("Lowercase: " + lowercase);
String str1 = "apple";
String str2 = "banana";
int result = str1.compareTo(str2);
System.out.println("Comparison result: " + result);
String sentence = "I love programming";
String[] words = sentence.split(" ");
System.out.println("Words: ");
for (String word : words) {
System.out.println(word);
}
String paddedString = " Hello ";
String trimmedString = paddedString.trim();
System.out.println("Trimmed string: " + trimmedString);
String replacedString = message.replace('o', 'a');
System.out.println("Replaced string: " + replacedString);
}
}
There are numerous string methods in Java which make Java programming a lot easier. Let us look at some string methods in Java with examples.
The int length() method is used to measure the size of the string or how many characters the string consists of. The method has an integer return type and always returns the output in a whole number.
String myString = "Hello, World!";
int length = myString.length();
System.out.println("Length of the string: " + length);
The char charAt(int index) method returns the character present at a specific point in an array. This method has a character return type and always returns characters. The position at which the method returns the character can be defined in the variable named index by the programmer.
String myString = "Hello, World!";
char character = myString.charAt(7);
System.out.println("Character at index 7: " + character);
The String concat(String string1) method adds a string at the end of another string. Here, it will add the string string1 at the end of another pre-existing desired string.
This method has a string return type and thus returns a string.
String string1 = "Hello";
String string2 = "World!";
String concatenatedString = string1.concat(string2);
System.out.println("Concatenated String: " + concatenatedString);
This method is used to extract a substring from an already declared string. We can derive the new string from a desired start point by mentioning it in the variable int beginIndex. If the endpoint is not specified at int endIndex, the method assumes the end to be till the end of the array. This method has a string return type.
String string1 = "Hello";
String string2 = "World!";
String concatenatedString = string1.concat(string2);
System.out.println("Concatenated String: " + concatenatedString);
The String equals(String anotherString) method is used to compare whether or not two strings have the same contents. If they are the same, the method returns true. Otherwise, it returns false. It is a boolean-type method and only returns true or false.
String str1 = "Hello";
String str2 = "Hello";
String str3 = "World";
boolean isEqual1 = str1.equals(str2);
boolean isEqual2 = str1.equals(str3);
System.out.println("isEqual1: " + isEqual1);
System.out.println("isEqual2: " + isEqual2);
The contains() method is used to check if the provided substring is present inside the parent string we are checking in. The user can put the value of what they want to search in the substring variable in Java. This method also has a boolean data type and only returns true or false.
String str = "Hello, world!";
boolean contains1 = str.contains("World");
boolean contains2 = str.contains("Java");
System.out.println("contains1: " + contains1);
System.out.println("contains2: " + contains2);
The String class, introduced in Java 8, contains a static method called String.join(). With a designated delimiter, you can concatenate multiple strings.
String joinedString = String.join(" ", "Hello", "World", "Java");
System.out.println("Joined String: " + joinedString);
A static method in Java's String class is int compareTo(String string1, String string2). It performs a lexical comparison between two strings and outputs an integer value representing the relative order of the strings.
String str1 = "apple";
String str2 = "banana";
int comparisonResult = str1.compareTo(str2);
System.out.println("Comparison Result: " + comparisonResult);
The String class in Java contains the method toUpperCase(). It creates a new string with the uppercase representation after changing every character in a string to uppercase. The return type of this method is a string.
String str = "Hello, World!";
String upperCaseString = str.toUpperCase();
System.out.println("Upper Case String: " + upperCaseString);
Similarly, The String class in Java includes a built-in method called toLowerCase(). It gives back a new string that has all the characters in lowercase. This method also has the return type string.
String str = "Hello, World!";
String lowerCaseString = str.toLowerCase();
System.out.println("Lower Case String: " + lowerCaseString);
The trim() method in Java removes any leading or trailing whitespaces in the string. This means the trim() method checks the beginning and end of the string. It stops scanning when it finds any white spaces from either end of the string. It does not hamper the orientation of spaces inside a string but only on the extremities.
String str = " Hello, World! ";
String trimmedString = str.trim();
System.out.println("Trimmed String: " + trimmedString);
The String class in Java includes a built-in method called replace(char oldChar, char newChar). Here, oldChar is a variable that pre-exists in the string and is replaced by newChar, which is user-defined. All instances of the oldChar are replaced with the newChar in the new string returned. This method also has a string return type.
String str = "Hello, World!";
String replacedString = str.replace(',', ';');
System.out.println("Replaced String: " + replacedString);
Concatenating means linking multiple things together. Similarly, when we concatenate multiple strings in Java, they make a new string with the combination of two or more previously defined strings.
We can concatenate strings in Java using two methods:
// Concatenating two strings using the '+' operator
std::string firstName = "John";
std::string lastName = "Doe";
std::string fullName = firstName + " " + lastName; // 'John Doe'
# Concatenating a string with other data types
name = "John Doe"
age = 25
string_info = "Name: " + name + ", Age: " + str(age)
# 'Name: John Doe, Age: 25'
Java format strings are created using the String.format() method. Java's String.format() function and the printf() method from the System.out or PrintStream class are used to create format strings. By mixing static text with placeholders for values that will be inserted during runtime, format strings enable you to build dynamic strings.
String name = "John";
int age = 30;
// Format string using placeholders
String formattedString = String.format("My name is %s and I am %d years old.", name, age);
System.out.println(formattedString);
// Output: My name is John and I am 30 years old.
A backslash (/) is used in Java to indicate the escape character. It is applied when a string literal has to contain special characters or escape sequences. Here are a few often utilized escape mechanisms:
A common question most beginner-level Java learners face is, “ Why string is immutable in Java?”
A string in Java, by default, is an immutable data type in Java. This means the contents in a string cannot be altered in the same instance of the string. A new string instance is created in the string pool whenever we alter or mutate a string. The state of a mutable class can also not be changed.
Objects in Java whose values can be changed after initialization in Java are called mutable objects. The field, state, and values can be changed; while doing so, no new object will be created. It will alter the value of the existing object. StringBuilder() and StringBuffer() in Java are examples of methods by which mutable strings can be created.
Strings are essential to Java programming since they are the primary data type for textual information representation. Throughout this tutorial, we have examined the main characteristics and capabilities of strings in Java, learning more about their adaptability and significance. This should serve as the foundation for you to master more advanced Java programming concepts.
1. What is string interning in Java?
String interning in Java refers to storing string literals in a string pool to save the system's resources.
2. How do you compare strings in Java?
You can compare strings in Java using the compareTo() and equals() methods.
3. What are some best practices for working with strings in Java?
Using StringBuilder and being mindful of memory usage is a good practice for using strings in Java.
PAVAN VADAPALLI
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...