String class in Java
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 will learn about the String class in Java.
Example of String Class in Java:
// Java Program to Create a String
import java.io.*;
class GFG {
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
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 Program to Create a String
import java.io.*;
class GFG {
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);
}
}
Output
String1 String2
String Constructors in Java
String Constructor | Description |
---|---|
1. String(byte[] byte_arr) | Construct a new String by decoding the byte array. It uses the platform’s default character set for decoding. |
2. String(byte[] byte_arr, Charset char_set) | Construct a new String by decoding the byte array. It uses the char_set for decoding. |
3. 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). |
4. 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. |
5. String(char[] char_arr) | Allocates a new String from the given Character array. |
6. 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. |
7. 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. |
8. String(StringBuffer s_buffer) | Allocates a new string from the string in s_buffer. |
9. 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 Program to implement String Constructor
import java.nio.charset.Charset;
class Main {
// 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 Method | Description |
---|---|
1. int length() | Returns the number of characters in the String. |
2. Char charAt(int i) | Returns the character at ith index. |
3. String substring (int i) | Return the substring from the ith index character to end. |
4. String substring (int i, int j) | Returns the substring from i to j-1 index. |
5. String concat( String str) | Concatenates specified string to the end of this string. |
6. int indexOf (String s) | Returns the index within the string of the first occurrence of the specified string. |
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. |
8. Int lastIndexOf( String s) | Returns the index within the string of the last occurrence of the specified string. |
9. boolean equals( Object otherObj) | Compares this string to the specified object. |
10. boolean equalsIgnoreCase (String anotherString) | Compares string to another string, ignoring case considerations. |
11. int compareTo( String anotherString) | Compares two string lexicographically. |
12. 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). |
13. String toLowerCase() | Converts all the characters in the String to lower case. |
14. String toUpperCase() | Converts all the characters in the String to upper case. |
15. String trim() | Returns the copy of the String, by removing whitespaces at both ends. It does not affect whitespaces in the middle. |
16. 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 |
17. boolean contains(CharSequence sequence) | Returns true if string contains contains the given string. |
18. Char[] toCharArray(): | Converts this String to a new character array. |
19. 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 code to illustrate different constructors and methods in String class
import java.io.*;
import java.util.*;
class Test
{
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
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 true Checking Equality false the difference between ASCII value is=-31 Changing to lower Case geekyme Changing to UPPER Case GEEKYME Trim the word Learn Share Learn Original String feeksforfeeks Replaced f with g -> geeksgorgeeks
For Set – 2 you can refer: Java.lang.String class in Java | Set 2