Strings in Java Explained

Strings in Java Explained

4 mins read804 Views Comment
clickHere
Updated on Mar 17, 2023 15:00 IST

The below article goes through explaining and implementing Strings in Java with appropriate examples.

2022_06_strings-in-java.jpg

Java strings are objects of the class java.lang representing a sequence of characters. Creating and manipulating strings is possible with the String class of the Java platform. Strings in Java are used to make Java more memory efficient (since no new objects are created if one already exists in the string constant pool).

Let’s find out strings concept in Java, how to create them, their methods, and other related concepts.

Contents

What are Strings in Java?

Java identifies String as a class and not as a datatype. One can even create Strings in Java by just instantiating the String Class present in java.lang package. 

The java string class provides a set of constructors and methods used to create, manipulate, and search strings.

String objects are immutable, which means they can’t be overwritten. Every time we try to alter the contents of a String object, a new object is created.

For more, Read: OOPs Concepts in Java.

How to Create a String Object?

Strings can be created by instantiating the String class. Following are a few Constructors in Java in the String class used for string creation.

Constructors Description
String() Creates an empty string
String(char[] arr) It creates a string object with the contents from the character array passed.
String(char[] arr, int offset, int num) It creates a string object with the contents as that of the subsequence of the array passed.
String(String obj) Creates a String object with contents of the String object passed.

Read: Implementing Array in Java

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);
}
}
Copy code

Output:

output1

Read: Access Modifiers in Java

Java String Class Methods

There are various string class methods used for the creation, manipulation, and searching of strings.

Also Read: Difference between JDK, JRE, and JVM

String Manipulation

The string class in Java has several methods for manipulating the contents of a string like changing the case, trimming the contents of a string, fetching characters from a string, etc.

Also, Read: Java Operators Explained

Following is the list of important string manipulation methods.

Methods Description
length() Returns a number of characters present in the string as an integer.
concat() Returns a new concatenated string object built from the given string objects.
charAt() It returns the character at a given index from the string object.
toUpperCase() Returns a string object with all its contents in uppercase
toLowerCase() Returns a string object with all its contents in lowercase
split() It returns a string array by splitting a source string based on some delimiter or a regular expression.
contains() It returns the boolean value, which tests whether the given string contains the specified character or not.
replace() Replaces all occurrences of the old character with a new character.
replaceAll() It replaces a substring based on the regular expression passed with a new replacement string.
substring() It extracts a substring out of the given string.
trim() It removes the leading and trailing white spaces around a string object.

Example:

 
class String_Manipulation_Demo {
public static void main(String[] args) {
String ob1 = "Naukri-Learning"; //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 uppercase: " +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("Learn")));
//Replace function
System.out.println("Replace function in String: " +(ob1.replace('a','e')));
//ReplaceAll function
System.out.println("ReplaceAll function in String: " +(ob1.replaceAll("ing","e")));
//substring function
System.out.println("Substring in String: " +(ob1.substring(3,6)));
//trim function
String str = " Naukri Learning! ";
System.out.println("Without Trim function in String: " +str);
System.out.println("Trim function in String: " +(str.trim()));
}
}
Copy code

Output:

output2

Read: Exception Handling in Java.

String Comparison

There are several methods in the String class that can be used for comparison between string objects.

Methods  Description
equals() Compares to checking if two string objects are equal or not.
equalsIgnoreCase() Works same as equals(). But ignores the case (upper or lower) during comparison.
compareTo() Checks two strings based on lexicographic order. It returns 0 if two strings are equal. Moreover, it returns a value less than 0 if the first string is less than the second else returns a value greater than 0. 
compareToIgnoreCase() Same as compareTo().but it ignores the case while comparing.
startsWith() Return boolean after checking if the given string starts with the given prefix or not.
endsWith() Return boolean after checking if the given string ends with the given suffix or not.

Read: Reverse a String in Java

Example:

 
class String_Comparison_Demo {
public static void main(String[] args) {
String ob1 = "Shiksha Online"; //creates a string object
String ob2 = "naukri learning";
//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("Na")));
//endsWith function
System.out.println("Using endsWith function: " +(ob1.endsWith("ing")));
}
}
Copy code

Output:

output3

Searching in a String

The string class incorporates methods for searching characters in a string object at specified indices.

Methods  Description 
indexOf() Returns the index representing the first occurrence of a string or a substring.
lastIndexOf() Returns the index representing the last occurrence of a string or a substring.

Example:

 
class String_Searching_Demo {
public static void main(String[] args) {
String ob1 = "Shiksha Online"; //creates a string object
System.out.println("Using indexOf function: " +ob1.indexOf('i'));
System.out.println("Using lastIndexOf function: " +ob1.lastIndexOf('i'));
}
}
Copy code

Output:

output4

For more, read: 8 Most Important Data Structures a Programmer Must Know 

Conclusion

Hope you enjoyed reading the article and learned something new about Strings in Java. If you have any queries, feel free to reach us on the link below.

To learn more, Go for Best Courses on Java Programming.

FAQs

What is a String in Java?

A string is an object that represents a sequence of char values. It's a class in Java that uses the objects to create and implement strings.

Is string a class or datatype in Java?

In Java, a string is a class that creates an object to implement string functions.

What is the maximum length of the string in Java?

Java strings are considered as char array or an array of characters. Hence, the maximum length of String in java is 2147483647. Moreover, we cannot index characters after the 2147483648th character members.

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio

Comments