(Translated by https://www.hiragana.jp/)
String class in Java - GeeksforGeeks
Open In App

String class in Java

Last Updated : 03 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The string is a sequence of characters. In Java, objects of String are immutable which means a constant and cannot be changed once created.

Creating a String

There are two ways to create string in Java:

1. String literal

String s = “GeeksforGeeks”;

2. Using new keyword

String s = new String (“GeeksforGeeks”);

String Constructors in Java

1. String(byte[] byte_arr)

Construct a new String by decoding the byte array. It uses the platform’s default character set for decoding.

Example:

byte[] b_arr = {71, 101, 101, 107, 115};
String s_byte =new String(b_arr); //Geeks

2. String(byte[] byte_arr, Charset char_set)

Construct a new String by decoding the byte array. It uses the char_set for decoding.

Example:

byte[] b_arr = {71, 101, 101, 107, 115};
Charset cs = Charset.defaultCharset();
String s_byte_char = new String(b_arr, cs); //Geeks

3. String(byte[] byte_arr, String char_set_name)

Construct a new String by decoding the byte array. It uses the char_set_name for decoding. It looks similar to the above constructs and they appear before similar functions but it takes the String(which contains char_set_name) as parameter while the above constructor takes CharSet.

Example:

byte[] b_arr = {71, 101, 101, 107, 115};
String s = new String(b_arr, "US-ASCII"); //Geeks

4. String(byte[] byte_arr, int start_index, int length)

Construct a new string from the bytes array depending on the start_index(Starting location) and length(number of characters from starting location).

Example:

byte[] b_arr = {71, 101, 101, 107, 115};
String s = new String(b_arr, 1, 3); // eek

5. String(byte[] byte_arr, int start_index, int length, Charset char_set)

Construct a new string from the bytes array depending on the start_index(Starting location) and length(number of characters from starting location).Uses char_set for decoding.

Example:

byte[] b_arr = {71, 101, 101, 107, 115};
Charset cs = Charset.defaultCharset();
String s = new String(b_arr, 1, 3, cs); // eek

6. String(byte[] byte_arr, int start_index, int length, String char_set_name)

Construct a new string from the bytes array depending on the start_index(Starting location) and length(number of characters from starting location).Uses char_set_name for decoding.

Example:

byte[] b_arr = {71, 101, 101, 107, 115};
String s = new String(b_arr, 1, 4, "US-ASCII"); // eeks

7. String(char[] char_arr)

Allocates a new String from the given Character array

Example:

char char_arr[] = {'G', 'e', 'e', 'k', 's'};
String s = new String(char_arr); //Geeks

8. String(char[] char_array, int start_index, int count)

Allocates a String from a given character array but choose count characters from the start_index.

Example:

char char_arr[] = {'G', 'e', 'e', 'k', 's'};
String s = new String(char_arr , 1, 3); //eek

9. String(int[] uni_code_points, int offset, int count)

Allocates a String from a uni_code_array but choose count characters from the start_index.

Example:

int[] uni_code = {71, 101, 101, 107, 115};
String s = new String(uni_code, 1, 3); //eek

10. String(StringBuffer s_buffer)

Allocates a new string from the string in s_buffer

Example:

StringBuffer s_buffer = new StringBuffer("Geeks");
String s = new String(s_buffer); //Geeks

11. String(StringBuilder s_builder)

Allocates a new string from the string in s_builder

Example:

StringBuilder s_builder = new StringBuilder("Geeks");
String s = new String(s_builder); //Geeks


String Methods in Java

1. int length()

Returns the number of characters in the String.

"GeeksforGeeks".length();  // returns 13

2. Char charAt(int i)

Returns the character at ith index.

"GeeksforGeeks".charAt(3); // returns  ‘k’

3. String substring (int i)

Return the substring from the ith  index character to end.

"GeeksforGeeks".substring(3); // returns “ksforGeeks”

4. String substring (int i, int j)

Returns the substring from i to j-1 index.

 "GeeksforGeeks".substring(2, 5); // returns “eks”

5. String concat( String str)

Concatenates specified string to the end of this string.

 String s1 = ”Geeks”;
String s2 = ”forGeeks”;
String output = s1.concat(s2); // returns “GeeksforGeeks”

6. int indexOf (String s)

Returns the index within the string of the first occurrence of the specified string.

If String s is not present in input string then -1 is returned as the default value.

1.   String s = ”Learn Share Learn”;
int output = s.indexOf(“Share”); // returns 6
2. String s = "Learn Share Learn"
int output = s.indexOf(“Play”); // return -1

7. int indexOf (String s, int i)

Returns the index within the string of the first occurrence of the specified string, starting at the specified index.

 String s = ”Learn Share Learn”;
int output = s.indexOf("ea",3);// returns 13

8. Int lastIndexOf( String s)

Returns the index within the string of the last occurrence of the specified string.

If String s is not present in input string then -1 is returned as the default value.

 1. String s = ”Learn Share Learn”;
int output = s.lastIndexOf("a"); // returns 14
2. String s = "Learn Share Learn"
int output = s.indexOf(“Play”); // return -1

9. boolean equals( Object otherObj)

Compares this string to the specified object.

 Boolean out = “Geeks”.equals(“Geeks”); // returns true
Boolean out = “Geeks”.equals(“geeks”); // returns false

10. boolean  equalsIgnoreCase (String anotherString)

Compares string to another string, ignoring case considerations.

 Boolean out= “Geeks”.equalsIgnoreCase(“Geeks”); // returns true
Boolean out = “Geeks”.equalsIgnoreCase(“geeks”); // returns true

11. int compareTo( String anotherString) 

Compares two string lexicographically.

 int out = s1.compareTo(s2);  
// where s1 and s2 are
// strings to be compared
This returns difference s1-s2. If :
out < 0 // s1 comes before s2
out = 0 // s1 and s2 are equal.
out > 0 // s1 comes after s2.

12. int compareToIgnoreCase( String anotherString) 

Compares two string lexicographically, ignoring case considerations.

 int out = s1.compareToIgnoreCase(s2);  
// where s1 and s2 are
// strings to be compared
This returns difference s1-s2. If :
out < 0 // s1 comes before s2
out = 0 // s1 and s2 are equal.
out > 0 // s1 comes after s2.

Note: In this case, it will not consider case of a letter (it will ignore whether it is uppercase or lowercase).

13. String toLowerCase()

Converts all the characters in the String to lower case.

String word1 = “HeLLo”;
String word3 = word1.toLowerCase(); // returns “hello"

14. String toUpperCase()

Converts all the characters in the String to upper case.

String word1 = “HeLLo”;
String word2 = word1.toUpperCase(); // returns “HELLO”

15. String trim()

Returns the copy of the String, by removing whitespaces at both ends. It does not affect whitespaces in the middle.

String word1 = “ Learn Share Learn “;
String word2 = word1.trim(); // returns “Learn Share Learn”

16. String replace (char oldChar, char newChar)

Returns new string by replacing all occurrences of oldChar with newChar.

String s1 = “feeksforfeeks“;
String s2 = “feeksforfeeks”.replace(‘f’ ,’g’); // return “geeksforgeeks”

Note: s1 is still feeksforfeeks and s2 is geeksgorgeeks

17. boolean contains(CharSequence sequence)

Returns true if string contains contains the given string

String s1="geeksforgeeks";
String s2="geeks";
s1.contains(s2) // return true

18. Char[] toCharArray():

Converts this String to a new character array.

String s1="geeksforgeeks";
char []ch=s1.toCharArray(); // returns [ 'g', 'e' , 'e' , 'k' , 's' , 'f', 'o', 'r' , 'g' , 'e' , 'e' , 'k' ,'s' ]

19. boolean startsWith(String prefix)

Return true if string starts with this prefix.

String s1="geeksforgeeks";
String s2="geeks";
s1.startsWith(s2) // return true

Example of String Constructor and String Methods

Below is the implementation of the above mentioned topic:

Java
// Java code to illustrate different constructors and methods
// String class.
import java.io.*;
import java.util.*;

// Driver Class
class Test
{
      // main function
    public static void main (String[] args)
    {
        String s= "GeeksforGeeks";
        // or String s= new String ("GeeksforGeeks");

        // Returns the number of characters in the String.
        System.out.println("String length = " + s.length());

        // Returns the character at ith index.
        System.out.println("Character at 3rd position = "
                           + s.charAt(3));

        // Return the substring from the ith  index character
        // to end of string
        System.out.println("Substring " + s.substring(3));

        // Returns the substring from i to j-1 index.
        System.out.println("Substring  = " + s.substring(2,5));

        // Concatenates string2 to the end of string1.
        String s1 = "Geeks";
        String s2 = "forGeeks";
        System.out.println("Concatenated string  = " +
                            s1.concat(s2));

        // Returns the index within the string
        // of the first occurrence of the specified string.
        String s4 = "Learn Share Learn";
        System.out.println("Index of Share " +
                           s4.indexOf("Share"));

        // Returns the index within the string of the
        // first occurrence of the specified string,
        // starting at the specified index.
        System.out.println("Index of a  = " +
                           s4.indexOf('a',3));

        // Checking equality of Strings
        Boolean out = "Geeks".equals("geeks");
        System.out.println("Checking Equality  " + out);
        out = "Geeks".equals("Geeks");
        System.out.println("Checking Equality  " + out);

        out = "Geeks".equalsIgnoreCase("gEeks ");
        System.out.println("Checking Equality " + out);

        //If ASCII difference is zero then the two strings are similar
        int out1 = s1.compareTo(s2);
        System.out.println("the difference between ASCII value is="+out1);
        // Converting cases
        String word1 = "GeeKyMe";
        System.out.println("Changing to lower Case " +
                            word1.toLowerCase());

        // Converting cases
        String word2 = "GeekyME";
        System.out.println("Changing to UPPER Case " +
                            word2.toUpperCase());

        // Trimming the word
        String word4 = " Learn Share Learn ";
        System.out.println("Trim the word " + word4.trim());

        // Replacing characters
        String str1 = "feeksforfeeks";
        System.out.println("Original String " + str1);
        String str2 = "feeksforfeeks".replace('f' ,'g') ;
        System.out.println("Replaced f with g -> " + str2);
    }
}

Output
String length = 13
Character at 3rd position = k
Substring ksforGeeks
Substring  = eks
Concatenated string  = GeeksforGeeks
Index of Share 6
Index of a  = 8
Checking Equality  false
Checking Equality ...

For Set – 2 you can refer: Java.lang.String class in Java | Set 2

 This article is contributed by Rahul Agrawal and our helpfull users. 



Previous Article
Next Article

Similar Reads

Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Java.lang.Class class in Java | Set 2
Java.lang.Class class in Java | Set 1 More methods: 1. int getModifiers() : This method returns the Java language modifiers for this class or interface, encoded in an integer. The modifiers consist of the Java Virtual Machine's constants for public, protected, private, final, static, abstract and interface. These modifiers are already decoded in Mo
15+ min read
StringJoiner Class vs String.join() Method to Join String in Java with Examples
Prior to Java 8 when we need to concatenate a group of strings we need to write that code manually in addition to this we needed to repeatedly use delimiter and sometimes it leads to several mistakes but after Java 8 we can concatenate the strings using StringJoiner class and String.join() method then we can easily achieve our goal. Example: Withou
6 min read
Java.lang.String class in Java | Set 2
Java.lang.String class in Java | Set 1 In this article we would be discussing different constructor and methods provided by java.lang.String. Strings in java are immutable. Now lets discuss some of the methods provided by String class. Methods: public int codePointAt(int index) - It takes as parameter a index which must be from 0 to length() - 1. a
5 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java.util.TimeZone Class (Set-2) | Example On TimeZone Class
TimeZone class (the methods of this class was discussed in this article Java.util.TimeZone Class | Set 1) can be used in many cases like using TimeZone class we can get the time difference in term of hour and minute between two places.Problem : How we can get time difference of time in terms of hours and minutes between two places of Earth?Solution
5 min read
Implement Pair Class with Unit Class in Java using JavaTuples
To implement a Pair class with a Unit class in Java using JavaTuples, you can use the Pair class provided by the library and create a new Unit class that extends the Unit class provided by the library. Here is an example implementation: Here is an example Java code that uses the MyPair class with MyUnit and displays the output: Java Code import org
4 min read
Implement Triplet Class with Pair Class in Java using JavaTuples
Following are the ways to implement Triplet Class with Pair Class Using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // create Pair Pair<Integer, String> pair = new Pair<Integer, String>( Integer.valueOf(1), "GeeksforGeeks"); // Print the Pair System.out.printl
2 min read
Implement Quintet Class with Quartet Class in Java using JavaTuples
Following are the ways to implement Quintet Class with Quartet Class Using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // create Quartet Quartet<String, String, String, String> quartet = new Quartet<String, String, String, String>( "Quartet", "Triplet
4 min read
Implement Quartet Class with Triplet Class in Java using JavaTuples
Following are the ways to implement Quartet Class with Triplet Class Using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // create Triplet Triplet<String, String, String> triplet = new Triplet<String, String, String>( "Triplet 1", "1", "GeeksforGe
3 min read
Implement Octet Class from Septet Class in Java using JavaTuples
Prerequisite: Octet Class, Septet Class Below are the methods to implement a Octet Class using Septet Class in Java: Using direct values // Java program to illustrate // implementing Octet Class // from Septet Class // using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // Create Sep
6 min read
Implement Ennead Class from Octet Class in Java using JavaTuples
Prerequisite: Ennead Class, Octet Class Below are the methods to implement a Ennead Class using Octet Class in Java: Using direct values // Java program to illustrate // implementing Ennead Class // from Octet Class // using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // Create Oct
7 min read
Implement Sextet Class from Quintet Class in Java using JavaTuples
Prerequisite: Sextet Class, Quintet Class Below are the methods to implement a Sextet Class using Quintet Class in Java: Using direct values // Java program to illustrate // implementing Sextet Class // from Quintet Class using // direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // crea
5 min read
Implement Septet Class from Sextet Class in Java using JavaTuples
Prerequisite: Septet Class, Sextet Class Below are the methods to implement a Septet Class using Sextet Class in Java: Using direct values // Java program to illustrate // implementing Septet Class // from Sextet Class // using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // Create
6 min read
Implement Decade Class from Ennead Class in Java using JavaTuples
Prerequisite: Decade Class, Ennead Class Below are the methods to implement a Decade Class using Ennead Class in Java: Using direct values // Java program to illustrate // implementing Decade Class // from Ennead Class // using direct values import java.util.*; import org.javatuples.*; class GfG { public static void main(String[] args) { // Create
8 min read
Difference between Abstract Class and Concrete Class in Java
Abstract Class: An abstract class is a type of class in Java that is declared by the abstract keyword. An abstract class cannot be instantiated directly, i.e. the object of such class cannot be created directly using the new keyword. An abstract class can be instantiated either by a concrete subclass or by defining all the abstract method along wit
5 min read
Java - Inner Class vs Sub Class
Inner Class In Java, one can define a new class inside any other class. Such classes are known as Inner class. It is a non-static class, hence, it cannot define any static members in itself. Every instance has access to instance members of containing class. It is of three types: Nested Inner ClassMethod Local Inner ClassAnonymous Inner Class Genera
3 min read
Java I/O Operation - Wrapper Class vs Primitive Class Variables
It is better to use the Primitive Class variable for the I/O operation unless there is a necessity of using the Wrapper Class. In this article, we can discuss briefly both wrapper class and primitive data type. A primitive data type focuses on variable values, without any additional methods.The Default value of Primitive class variables are given b
3 min read
Using predefined class name as Class or Variable name in Java
In Java, you can use any valid identifier as a class or variable name. However, it is not recommended to use a predefined class name as a class or variable name in Java. The reason is that when you use a predefined class name as a class or variable name, you can potentially create confusion and make your code harder to read and understand. It may a
5 min read
Why BufferedReader class takes less time for I/O operation than Scanner class in java
In Java, both BufferReader and Scanner classes can be used for the reading inputs, but they differ in the performance due to their underlying implementations. The BufferReader class can be generally faster than the Scanner class because of the way it handles the input and parsing. This article will guide these difference, provide the detailed expla
3 min read
Class forName(String, boolean, ClassLoader) method in Java with Examples
The forName(String, boolean, ClassLoader) method of java.lang.Class class is used to get the instance of this Class with the specified class name, using the specified class loader. The class is initialized only if the initialize parameter is true and if it has not been initialized earlier.Syntax: public static Class<T> forName(String classNam
2 min read
Java String Class indent() Method With Examples
JDK 12 introduced indent() method in Java.lang.String class. This method is useful to add or remove white spaces from the beginning of the line to adjust indentation for each string line. Syntax: public String indent(int n) Parameter: It takes integer n as input and does indentation accordingly. Also, each line is suffixed with “\n” (a newline char
3 min read
Java String Class lines() Method with Examples
lines() method is a static method which returns out stream of lines extracted from a given multi-line string, separated by line terminators which are as follows: Line terminators Command Line feed character\nA carriage return character\rA carriage return followed immediately by a line feed\r\n Syntax: public Stream<String> lines() Return Type
3 min read
String Handling with Apache Commons' StringUtils Class in Java
The Apache Commons Lang library is a popular third-party library for working with Strings in Java, and the StringUtils class is a key part of this library. StringUtils is a utility class that provides a wide range of String manipulation methods that are not available in the standard Java String class. Key Features of The StringUtils ClassNull-safe
9 min read
String Class stripTrailing() Method in Java with Examples
This method is used to strip trailing whitespaces from the string i.e. stripTrailing() method removes all the whitespaces only at the ending of the string. Example: Input: String name = " kapil "; System.out.println("#" + name + "#"); System.out.println("#" + name.stripTrailing() + "#"); Output: # kapil # # kapil# // trailing whitespaces are remove
2 min read
Java.io.ObjectInputStream Class in Java | Set 2
Java.io.ObjectInputStream Class in Java | Set 1 Note : Java codes mentioned in this article won't run on Online IDE as the file used in the code doesn't exists online. So, to verify the working of the codes, you can copy them to your System and can run it over there. More Methods of ObjectInputStream Class : defaultReadObject() : java.io.ObjectInpu
6 min read
Java.lang.StrictMath class in Java | Set 2
Java.lang.StrictMath Class in Java | Set 1More methods of java.lang.StrictMath class 13. exp() : java.lang.StrictMath.exp(double arg) method returns the Euler’s number raised to the power of double argument. Important cases: Result is NaN, if argument is NaN.Result is +ve infinity, if the argument is +ve infinity.Result is +ve zero, if argument is
6 min read
java.lang.instrument.ClassDefinition Class in Java
This class is used to bind together the supplied class and class file bytes in a single ClassDefinition object. These class provide methods to extract information about the type of class and class file bytes of an object. This class is a subclass of java.lang.Object class. Class declaration: public final class ClassDefinition extends ObjectConstruc
2 min read
java.net.URLConnection Class in Java
URLConnection Class in Java is an abstract class that represents a connection of a resource as specified by the corresponding URL. It is imported by the java.net package. The URLConnection class is utilized for serving two different yet related purposes, Firstly it provides control on interaction with a server(especially an HTTP server) than URL cl
5 min read
Java.util.GregorianCalendar Class in Java
Prerequisites : java.util.Locale, java.util.TimeZone, Calendar.get()GregorianCalendar is a concrete subclass(one which has implementation of all of its inherited members either from interface or abstract class) of a Calendar that implements the most widely used Gregorian Calendar with which we are familiar. java.util.GregorianCalendar vs java.util.
10 min read
Practice Tags :