String Class in Java (original) (raw)
Last Updated : 01 May, 2025
A **string is a sequence of characters. In Java, objects of the **String class are immutable, which means they cannot be changed once created. In this article, we are going to learn about the **String class in Java.
**Example of String Class in Java:
Java `
// Java Program to Create a String import java.io.*;
class Geeks { public static void main (String[] args) {
// String literal
String s = "Geeks for Geeks String in Java";
System.out.println(s);
}
}
`
Output
Geeks for Geeks String in Java
**Explanation:
The above program **creates a string using a literal and prints it.
Table of Content
- Creating a String
- String Constructors in Java
- String Methods in Java
- Example of String Constructor and String Methods
Creating a String
There are **two ways to create string in Java:
1. Using String literal
String s = “GeeksforGeeks”;
2. Using new keyword
String s = new String (“GeeksforGeeks”);
Example of Creating String in Java
Java `
// Java Program to Create a String import java.io.*;
class Geeks { public static void main (String[] args) {
// String literal
String s1="String1";
System.out.println(s1);
// Using new Keyword
String s2= new String("String2");
System.out.println(s2);
}
}
`
String Constructors in Java
String Constructors | Description |
---|---|
String(byte[] byte_arr) | Construct a new String by decoding the byte array. It uses the platform’s default character set for decoding. |
String(byte[] byte_arr, Charset char_set) | Construct a new String by decoding the byte array. It uses the char_set for decoding. |
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). |
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. |
String(char[] char_arr) | Allocates a new String from the given Character array. |
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. |
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. |
String(StringBuffer s_buffer) | Allocates a new string from the string in s_buffer. |
String(StringBuilder s_builder) | Allocates a new string from the string in s_builder. |
Let us check these constructors using a example demonstrating the use of them.
Example String Constructor in Java
Java `
// Java Program to implement String Constructor import java.nio.charset.Charset;
class Geeks {
// Variables in Methods
static byte[] b_arr = {71, 101, 101, 107, 115};
static Charset cs = Charset.defaultCharset();
static char[] char_arr = {'G', 'e', 'e', 'k', 's'};
static int[] uni_code = {71, 101, 101, 107, 115};
static StringBuffer s_buffer = new StringBuffer("Geeks");
static StringBuilder s_builder = new StringBuilder("Geeks");
public static void main(String[] args) {
// Method 1
String s1 = new String(b_arr);
System.out.println("Method 1: " + s1);
System.out.println();
// Method 2
String s2 = new String(b_arr, cs);
System.out.println("Method 2: " + s2);
System.out.println();
// This is alternative way for Method 2
String s3 = new String(b_arr, Charset.forName("US-ASCII"));
System.out.println("Method 2 Alternative: " + s3);
System.out.println();
// Method 3
String s4 = new String(b_arr, 1, 3);
System.out.println("Method 3: " + s4);
System.out.println();
// Method 4
String s5 = new String(b_arr, 1, 3, cs);
System.out.println("Method 4: " + s5);
System.out.println();
// This is alternative way for Method 4
String s6 = new String(b_arr, 1, 4, Charset.forName("US-ASCII"));
System.out.println("Method 4 Alternative: " + s6);
System.out.println();
// Method 5
String s7 = new String(char_arr);
System.out.println("Method 5: " + s7);
System.out.println();
// Method 6
String s8 = new String(char_arr, 1, 3);
System.out.println("Method 6: " + s8);
System.out.println();
// Method 7
String s9 = new String(uni_code, 1, 3);
System.out.println("Method 7: " + s9);
System.out.println();
// Method 8
String s10 = new String(s_buffer);
System.out.println("Method 8: " + s10);
System.out.println();
// Method 9
String s11 = s_builder.toString();
System.out.println("Method 9: " + s11);
System.out.println();
}
}
`
Output
Method 1: Geeks
Method 2: Geeks
Method 2 Alternative: Geeks
Method 3: eek
Method 4: eek
Method 4 Alternative: eeks
Method 5: Geeks
Method 6: eek
Method 7: eek
Method 8: Geeks
Method 9: Geeks...
String Methods in Java
String Methods | Description |
---|---|
int length() | Returns the number of characters in the String. |
Char charAt(int i) | Returns the character at ith index. |
String substring (int i) | Return the substring from the ith index character to end. |
String substring (int i, int j) | Returns the substring from i to j-1 index. |
String concat( String str) | Concatenates specified string to the end of this string. |
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. |
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. |
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. |
boolean equals( Object otherObj) | Compares this string to the specified object. |
boolean equalsIgnoreCase (String anotherString) | Compares string to another string, ignoring case considerations. |
int compareTo( String anotherString) | Compares two string lexicographically. |
int compareToIgnoreCase( String anotherString) | Compares two string lexicographically, ignoring case considerations. Note: In this case, it will not consider case of a letter (it will ignore whether it is uppercase or lowercase). |
String toLowerCase() | Converts all the characters in the String to lower case. |
String toUpperCase() | Converts all the characters in the String to upper case. |
String trim() | Returns the copy of the String, by removing whitespaces at both ends. It does not affect whitespaces in the middle. |
String replace (char oldChar, char newChar) | Returns new string by replacing all occurrences of oldChar with newChar. Note: s1 is still feeksforfeeks and s2 is geeksgorgeeks |
boolean contains(CharSequence sequence) | Returns true if string contains contains the given string. |
Char[] toCharArray(): | Converts this String to a new character array. |
boolean startsWith(String prefix) | Return true if string starts with this prefix. |
Example of String Constructor and String Methods
Below is the **implementation of string constructors and methods in Java.
Java `
// Java program to illustrate different // constructors and methods in String class import java.io.; import java.util.;
class Geeks { 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 w1 = "GeeKyMe";
System.out.println("Changing to lower Case " +
w1.toLowerCase());
// Converting cases
String w2 = "GeekyME";
System.out.println("Changing to UPPER Case " +
w2.toUpperCase());
// Trimming the word
String w4 = " Learn Share Learn ";
System.out.println("Trim the word " + w4.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:
For Set -2, you can refer: Java.lang.String class in Java | Set 2