String Functions in Java
A number of methods provided in Java to perform operations in Strings are called String functions. The methods are compare(), concat(), equals(), split(), length(), replace(), compareTo() and so on. Strings in Java are constant and created using a literal or keyword. String literal makes Java memory efficient, and the keyword creates a Java string in normal memory. The string represents an array of character values, and the class is implemented by three interfaces such as Serializable, Comparable, and CharSequence interfaces. It represents the sequence of characters in a serialized or comparable manner.
ADVERTISEMENT Popular Course in this category JAVA MASTERY - Specialization | 78 Course Series | 15 Mock TestsConcept of String Functions in Java
Below are the main concepts of String Functions in java:
1. Creating String
In Java, there are two primary ways to create a String object:
Using a string literal: Double quotes are used to produce a string literal in Java.
Example:
String s= "Hello World!";
Using the new keyword: Java String can be created using “new”.
Example:
String s=new String ("Hello World!");
2. String length
Methods that are used to get information about an object are called accessor methods in Java. One such accessor method related to strings is the length () method. This returns the number of characters in the string object.
public class Exercise { public static void main(String args[]){ String s1="Hello"; String s2="World"; System.out.println("string length is: "+s1.length()); System.out.println("string length is: "+s2.length()); }}
Output:
3. Concatenating string
This method returns a new string which is string1 with string2 combined at the end. Concat () method can be used with string literals to get this done. Strings are also commonly concatenated using the + operator.
public class ExerciseNew { public static void main(String args[]){ String s1="Hello"; s1=s1.concat("What is your good name?"); System.out.println(s1); }}
Output:
4. Creating a format string
The printf() and format() functions output formatted numbers. The string has a similar class method named format (). It yields a String object. In contrast to the one-time print command, the static format () method accessible in the String object permits the construction of a formatted string that may be reused.
Methods of String Functions in Java
The following are the different methods:
Method | Description |
char charAt(int index) | It returns the char value of the particular index as mentioned. |
int length() | It returns the length of the string |
static String format(String format, Object… args) | It returns a string that is duly formatted. |
static String format(Locale l, String format, Object… args) | It returns a formatted string along with the given locale. |
String substring(int beginIndex) | It returns the substring, which starts from begin index. |
String substring(int beginIndex, int endIndex) | It returns a substring for a given start index position and ends index. |
boolean contains(CharSequence s) | It returns true or false after doing a match between the sequence of char values. |
static String join(CharSequence delimiter, CharSequence… elements) | It returns a string that is joined |
static String join(CharSequence delimiter, Iterable extends CharSequence> elements) | It returns a joined string, the same as above. |
boolean equals(Object another) | It checks the equality of the string. It does so with the given object. |
boolean isEmpty() | It checks if a given string is empty or not. |
String concat(String str) | It concatenates the specified string like the above example. |
String replace(char old, char new) | It replaces all occurrences of the specified old char value. With new value. |
String replace(CharSequence old, CharSequence new) | It replaces all occurrences of the given specified CharSequence with the new one. |
static String equalsIgnoreCase(String another) | It compares with another string, but It is not case-sensitive. |
String[] split(String regex) | It returns a split string based on matching the regex. |
String[] split(String regex, int limit) | It returns a split string that matches regex and limit. |
String intern() | It returns a string that is interned. |
int indexOf(int ch) | It returns the selected char value index. |
int indexOf(int ch, int fromIndex) | It returns the specified char value index, which starts with a given index. |
int indexOf(String substring) | It returns the selected substring index. |
int indexOf(String substring, int fromIndex) | It returns the selected substring index, which starts with a given index. |
String toLowerCase() | It returns a string with all chars in lowercase. |
String toLowerCase(Locale l) | It returns a string in lowercase with a specified locale. |
String toUpperCase() | It returns a string with all chars in uppercase. |
String toUpperCase(Locale l) | Same as above but with a specified locale. |
String trim() | It removes the starting and ending whitespaces of this string. |
static String valueOf(int value) | It converts another data type into a string. It is called an overloaded method. |
Examples of String functions in Java
In this section, we have discussed some examples of string functions in Java.
Example #1: Check if a string is empty
Code:
public class IsEmptyExercise{ public static void main(String args[]){ String s1=""; String s2="Hello"; System.out.println(s1.isEmpty()); // true System.out.println(s2.isEmpty()); // false }}
Output:
Example #2: Trim whitespaces in a string
Code:
public class StringTrimExercise{ public static void main(String args[]){ String s1=" HelloWorld "; System.out.println(s1+"How are you doing today"); // without trim() System.out.println(s1.trim()+"How are you doing today"); // with trim() }}
Output:
Example #3: Convert a string to lowercase
Code:
public class StringLowerExercise{ public static void main(String args[]){ String s1="HELLO HOW Are You TODAY?"; String s1lower=s1.toLowerCase(); System.out.println(s1lower);} }
Output:
Example #4: Replace a part of a string
Code:
public class ReplaceExercise{ public static void main(String args[]){ String s1="hello how are you today"; String replaceString=s1.replace('h','t'); System.out.println(replaceString); }}
Output:
Example #5: Check if two strings are equal
Code:
public class EqualsExercise{ public static void main(String args[]){ String s1="Hi"; String s2="Hey"; String s3="Hello"; System.out.println(s1.equalsIgnoreCase(s2)); // returns true System.out.println(s1.equalsIgnoreCase(s3)); // returns false } }
Output:
Conclusion
Apart from the above-mentioned characteristics, functions, and methods, there are other facts with the String class. The string class is a final class, which is why String class objects are immutable in nature. JVM reserves a special memory area for string classes; this area is called the String constant pool.
In the String library, available with Java. Lang, overriding the String references are possible, but the content or literals cannot be copied. Any number closed in double quotes is also treated as a string.
Students should test these codes in an IDE and modify them to enhance their understanding further. String manipulation is very important to know in any programming language, and developers use it daily.
The above is the detailed content of String Functions in Java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.
