Pages

String Class

String is a sequence of characters (or) group of characters (or) collection of characters. String is a Final Class and String is a immutable class which means a constant and cannot be changed once created. String is available in java.lang package and Strings can declared as objects and variables. String Class extends Object Class and implements Serializable, CharSequence, Comparable<String>

String are two ways to create String object
1. Creating a String Using Literal.
String str1 = "Delhi";
String str2 = "Mumbai";
String str3 = "Chennai";
String str4 = "Bangalore";
String str5 = "Jaladhi Naga Vijay";
String str6 = "Jaladhi Soft Technology";
2. Creating a String Using Object
String str1 = new String("New York");
String str2 = new String("Los Angeles");
String str3 = new String("Chicago");
String str1 = new String("Pennsylvania");
String str2 = new String("California");
String str3 = new String("San Jose");

Fields in String Class

CASE_INSENSITIVE_ORDER A Comparator that orders String objects as by compareToIgnoreCase.

Methods in String Class

charAt(int index)
charAt(int index) method returns the char value at the specified index.
codePointAt(int index)
codePointAt(int index) method returns the character (Unicode code point) at the specified index.
codePointCount(int beginIndex, int endIndex)
codePointCount(int beginIndex, int endIndex) method returns the number of Unicode code points in the specified text range of this String.
compareTo(String anotherString)
compareTo(String anotherString) method compares two strings lexicographically.
compareToIgnoreCase(String str)
compareToIgnoreCase(String str) method compares two strings lexicographically, ignoring case differences.
concat(String str)
concat(String str) concatenates the specified string to the end of this string.
contains(CharSequence s)
contains(CharSequence s) method returns true if and only if this string contains the specified sequence of char values.
contentEquals(CharSequence cs)
contentEquals(CharSequence cs) method compares this string to the specified CharSequence.
contentEquals(StringBuffer sb)
contentEquals(StringBuffer sb) method compares this string to the specified StringBuffer.
copyValueOf(char[] data)
copyValueOf(char[] data) method returns a String that represents the character sequence in the array specified.
copyValueOf(char[] data, int offset, int count)
copyValueOf(char[] data, int offset, int count) method returns a String that represents the character sequence in the array specified.
endsWith(String suffix)
endsWith(String suffix) mthod tests if this string ends with the specified suffix.
equals(Object anObject)
equals(Object anObject) method compares this string to the specified object.
equalsIgnoreCase(String anotherString)
equalsIgnoreCase(String anotherString) method compares this String to another String, ignoring case considerations.
format(Locale l, String format, Object... args)
format(Locale l, String format, Object... args) method returns a formatted string using the specified locale, format string, and arguments.
format(String format, Object... args)
format(String format, Object... args) method returns a formatted string using the specified format string and arguments.
getBytes()
getBytes() method encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
getBytes(Charset charset)
getBytes(Charset charset) method encodes this String into a sequence of bytes using the given charset, storing the result into a new byte array.
getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin)
getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin) method does not properly convert characters into bytes. As of JDK 1.1, the preferred way to do this is via the getBytes() method, which uses the platform's default charset. The Method was Deprecated.
getBytes(String charsetName)
getBytes(String charsetName) encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.
getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) metdhod copies characters from this string into the destination character array.
hashCode()
hashCode() method returns a hash code for this string.
indexOf(int ch)
indexOf(int ch) method returns the index within this string of the first occurrence of the specified character.
indexOf(int ch, int fromIndex)
indexOf(int ch, int fromIndex) method returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
indexOf(String str)
indexOf(String str) method returns the index within this string of the first occurrence of the specified substring.
indexOf(String str, int fromIndex)
indexOf(String str, int fromIndex) method returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
intern()
intern() method returns a canonical representation for the string object.
isEmpty()
isEmpty() method returns true if, and only if, length() is 0.
lastIndexOf(int ch)
lastIndexOf(int ch) method returns the index within this string of the last occurrence of the specified character.
lastIndexOf(int ch, int fromIndex)
lastIndexOf(int ch, int fromIndex) method returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.
lastIndexOf(String str)
lastIndexOf(String str) method returns the index within this string of the last occurrence of the specified substring.
lastIndexOf(String str, int fromIndex)
lastIndexOf(String str, int fromIndex) method returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.
length()
length() method returns the length of this string.
matches(String regex)
matches(String regex) method tells whether or not this string matches the given regular expression.
offsetByCodePoints(int index, int codePointOffset)
offsetByCodePoints(int index, int codePointOffset) method returns the index within this String that is offset from the given index by codePointOffset code points.
regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) method tests if two string regions are equal.
regionMatches(int toffset, String other, int ooffset, int len)
regionMatches(int toffset, String other, int ooffset, int len) method tests if two string regions are equal.
replace(char oldChar, char newChar)
replace(char oldChar, char newChar) method returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
replace(CharSequence target, CharSequence replacement)
replace(CharSequence target, CharSequence replacement) method replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.
replaceAll(String regex, String replacement)
replaceAll(String regex, String replacement) method replaces each substring of this string that matches the given regular expression with the given replacement.
replaceFirst(String regex, String replacement)
replaceFirst(String regex, String replacement) method replaces the first substring of this string that matches the given regular expression with the given replacement.
split(String regex)
split(String regex) methods splits this string around matches of the given regular expression.
split(String regex, int limit)
split(String regex, int limit) method splits this string around matches of the given regular expression.
startsWith(String prefix)
startsWith(String prefix) method tests if this string starts with the specified prefix.
startsWith(String prefix, int toffset)
startsWith(String prefix, int toffset) method tests if the substring of this string beginning at the specified index starts with the specified prefix.
subSequence(int beginIndex, int endIndex)
subSequence(int beginIndex, int endIndex) method returns a new character sequence that is a subsequence of this sequence.
substring(int beginIndex)
substring(int beginIndex) method returns a new string that is a substring of this string.
substring(int beginIndex, int endIndex)
substring(int beginIndex, int endIndex) method returns a new string that is a substring of this string.
toCharArray()
toCharArray() method converts this string to a new character array.
toLowerCase()
toLowerCase() method converts all of the characters in this String to lower case using the rules of the default locale.
toLowerCase(Locale locale)
toLowerCase(Locale locale) method converts all of the characters in this String to lower case using the rules of the given Locale.
toString()
This object (which is already a string!) is itself returned.
toUpperCase()
toUpperCase() method converts all of the characters in this String to upper case using the rules of the default locale.
toUpperCase(Locale locale)
toUpperCase(Locale locale) method converts all of the characters in this String to upper case using the rules of the given Locale.
trim()
trim() method returns a copy of the string, with leading and trailing whitespace omitted.
valueOf(boolean b)
valueOf(boolean b) method returns the string representation of the boolean argument.
valueOf(char c)
valueOf(char c) method returns the string representation of the char argument.
valueOf(char[] data)
valueOf(char[] data) method returns the string representation of the char array argument.
valueOf(char[] data, int offset, int count)
valueOf(char[] data, int offset, int count) method returns the string representation of a specific subarray of the char array argument.
valueOf(double d)
valueOf(double d) method returns the string representation of the double argument.
valueOf(float f)
valueOf(float f) method returns the string representation of the float argument.
valueOf(int i)
valueOf(int i) met returns the string representation of the int argument.
valueOf(long l)
valueOf(long l) returns the string representation of the long argument.
valueOf(Object obj)
valueOf(Object obj) method returns the string representation of the Object argument.

1. Basic String Example

public Class StringOne {
      String a = "Hello"; // String Literal.
      String b = new String("Welcome") // String Object.
      public void display() {
            System.out.println(" String Literal : " + a);
            System.out.println(" String Object : " + b);
      }
      public static void main(String [] args) {
            StringOne so = new StringOne();
            so.display();
      }
}

String Literal : Hello
String Object : Welcome
String Methods :

String charAt() Method : String charAt() method returns the character located at the String's specified index. The string indexes start from zero.
String charAt( ) Method using String Literal
public class CharAtMethod {
      public static void main(String args[]) {
            String s = "Jaladhi Soft Technology";
            char result1 = s.charAt(1);
            char result2 = s.charAt(8);
            char result3 = s.charAt(10);
            System.out.println(result1);
            System.out.println(result2);
            System.out.println(result3);
      }
}

a
s
f

String charAt() Method using String Object
public class CharAtMethod {
      public static void main(String args[]) {
            String s = new String("Jaladhi Soft Technology");
            char result1 = s.charAt(1);
            char result2 = s.charAt(8);
            char result3 = s.charAt(10);
            System.out.println(result1);
            System.out.println(result2);
            System.out.println(result3);
      }
}

a
s
f

String length( ) Method : String length() method returns the number of characters contained in the string object.
String Length Method using Litarial
public class String Litarial {
      public static void main(String[] args) {
            String str = "Jaladhi Soft Technology";
            System.out.print("String Length Method : " + str.length());
      }
}

String Length Method : 23
String Length Method using Object
public class StringObject {
      public static void main(String[] args) {
            String str = new String("Jaladhi Naga Vijay");
            System.out.print("String Length Mehod : "str.length());
      }
}

String Length Method : 18
String Length Method using Litarial with For Loop
public class StringLength {
      public static void main(String[] args) {
            String str = "Jaladhi";
            for(int i = 0; i < str.length(); i++) {
                  char result = str.charAt(i);
                  System.out.print(i + " ");
            }
      }
}

0 1 2 3 4 5 6
String Length Method using Object with For Loop
public class StringLength {
      public static void main(String[] args) {
            String str = new String("New York");
            for(int i = 0; i < str.length(); i++) {
                  char result = str.charAt(i);
                  System.out.print(i + " ");
            }
      }
}

0 1 2 3 4 5 6
2. String Concatenation Method : Add a string to the end of another string (or) Combine a string to the end of another string. public Class StringTwo {
      String a = "Hello"; // String Literal.
      String b = new String("Welcome") // String Object.
      public void display() {
            a = a.conat(b);
            System.out.println(" String Literal : " + a);
      }
      public static void main(String [] args) {
            StringTwo so = new StringTwo();
            so.display();
      }
}

String Literal : Hello Welcome

String Length Method Example

public Class StringThree {
      String a = "Hello"; // String Literal.
      String b = new String("Welcome") // String Object.
      public void display() {
            int b = a.length();
            int c = b.length();
            System.out.println(" String Literal Length : " + b);
            System.out.println(" String Object Length : " + c);
      }
      public static void main(String [] args) {
            StringThree so = new StringThree();
            so.display();
      }
}

String Literal Length : 5
String Object Length : 7

String charAt Method using without for Example

public Class StringFour {
      String a = "Hello"; // String Literal.
      String b = new String("Welcome") // String Object.
      public void display() {
            String c = a.charAt(3);
            String d = b.charAt(4);
            System.out.println(" String Literal : " + c);
            System.out.println(" String Object : " + d);
      }
      public static void main(String [] args) {
            StringFour so = new StringFour();
            so.display();
      }
}

String Literal Length : 5
String Literal : l
String Object : o

String charAt Method using with for Example

public Class StringFive {
      String a = "Hello"; // String Literal.
      String b = new String("Welcome") // String Object.
      public void display() {
            // String Literal
            for(int i = 0; i < a.length(); i++) {
                  char c = a.charAt(i);
                  System.out.print(c);
            }
            // String Object
            for(int i = 0; i < b.length(); i++) {
                  char d = a.charAt(i);
                  System.out.print(d);
            }
      }
      public static void main(String [] args) {
            StringFive so = new StringFive();
            so.display();
      }
}

H e l l o
W e l c o m e

String comparTo Method Example

public Class StringSix {
      String a = "Hello";
      String b = "Welcome";
      String c = "One";
      String d = "hello";
      public void display () {
            System.out.println(a.compareTo(b));
            System.out.println(a.compareTo(c));
            System.out.println(a.compareTo(d));
            System.out.println(b.compareTo(b));
            System.out.println(c.compareTo(c));
            System.out.println(d.compareTo(a));
      }       public static void main(String [] args) {
            StringSix ss = new StringSix();
            ss.display();
      }
}

-15     -7     -32     0     0     32

String comparToIgnoreCase Method Example

public Class StringSeven {
      String a = "Hello";
      String b = "Welcome";
      String c = "One";
      String d = "hello";
      public void display () {
            System.out.println(a.compareToIgnoreCase(b));
            System.out.println(a.compareToIgnoreCase(c));
            System.out.println(a.compareToIgnoreCase(d));
            System.out.println(b.compareToIgnoreCase(b));
            System.out.println(c.compareToIgnoreCase(c));
            System.out.println(d.compareToIgnoreCase(a));
      }       public static void main(String [] args) {
            StringSeven ss = new StringSeven();
            ss.display();
      }
}

-15     -7     0     0     0     0

String equals Method Example

public Class StringEight {
      String a = "Hello";
      String b = "Welcome";
      String c = "One";
      String d = "hello";
      public void display () {
            System.out.println(a.equals(b));
            System.out.println(a.equals(c));
            System.out.println(a.equals(d));
            System.out.println(b.equals(b));
            System.out.println(c.equals(c));
            System.out.println(d.equals(a));
      }       public static void main(String [] args) {
            StringEight ss = new StringEight();
            ss.display();
      }
}

False     False     False    True     True     False

String equalsIgnoreCase Method Example

public Class StringNine {
      String a = "Hello";
      String b = "Welcome";
      String c = "One";
      String d = "hello";
      public void display () {
            System.out.println(a.equalsIgnoreCase(b));
            System.out.println(a.equalsIgnoreCase(c));
            System.out.println(a.equalsIgnoreCase(d));
            System.out.println(b.equalsIgnoreCase(b));
            System.out.println(c.equalsIgnoreCase(c));
            System.out.println(d.equalsIgnoreCase(a));
      }
      public static void main(String [] args) {
            StringNine ss = new StringNine();
            ss.display();
      }
}

False     False     True     True     True     True

String subString Method Example

public Class StringTen {
      String a = "Hello ! How are you? ";
      public void display () {
            // subString single parameter
            System.out.println(a.subString(6));
            System.out.println(a.subString(7));
            // subString two parameters
            System.out.println(a.subString(0,9));
            System.out.println(a.subString(10,19));
      }
      public static void main(String [] args) {
            StringTen ss = new StringTen();
            ss.display();
      }
}

How are you?
How are you?
Hello !
How are you?

String toLowerCase Method Example

public Class StringEleven {
      String a = "Hello ! How are you? ";
      String b = "I am Fine.";
      public void display () {
            System.out.println(a.toLowerCase());
            System.out.println(b.toLowerCase());
      }       public static void main(String [] args) {
            StringEleven ss = new StringEleven();
            ss.display();
      }
}

hello ! how are you?
i am fine.

String toUppCase Method Example

public Class StringTweleven {
      String a = "Hello ! How are you? ";
      String b = "I am Fine.";
      public void display () {
            System.out.println(a.toUppCase());
            System.out.println(b.toUppCase());
      }
      public static void main(String [] args) {
            StringTweleven ss = new StringTweleven();
            ss.display();
      }
}

HELLO ! HOW ARE YOU?
I AM FINE.

String trim Method Example

public Class StringThirteen {
      String a = "      Hello ! How are you?       ";
      String b = "      I am Fine.       ";
      public void display () {
            System.out.println(a.trim());
            System.out.println(b.trim());
      }
      public static void main(String [] args) {
            StringThirteen ss = new StringThirteen();
            ss.display();
      }
}

Hello ! How are you?
I am Fine.

String contentEquals Method Example

public class StringFourteen {
      public static void main(String args[]) {
            String str1 = "One";
            String str2 = "Two";
            StringBuffer str3 = new StringBuffer("One");
            boolean result = str1.contentEquals(str3);
            System.out.println(result);
            result = str2.contentEquals(str3);
            System.out.println(result);
      }
}

Returned Value = true
true       false

String copyValueOf Method Example

public class StringFifteen {
      public static void main(String args[]) {
            char[] a = {'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'};
            String b = "";
            b = b.copyValueOf(a);
            System.out.println("Returned String: " + b);
            b = b.copyValueOf( a, 2, 6 );
            System.out.println("Returned String: " + b);
      } }

Returned Value = true
Returned String: hello world
Returned String: llo wo

String endsWith Method Example

public class StringSixteen {
      public static void main(String args[]){
            String a = new String("Java String Programming ");
            boolean b;
            b = a.endsWith( "Programming" );
            System.out.println("Returned Value = " + b);
            b = a.endsWith( "Prog" );
            System.out.println("Returned Value = " + b);
      }
}

Returned Value = true
Returned Value = false

String getBytes Method Example

public class StringSeventeen {
      public static void main(String [ ] args) {
            String a = new String("String Programming are very important in Java.");
            try {
                  byte[] b = Str1.getBytes();
                  System.out.println("Returned Value " + b);
                  b = a.getBytes( "UTF-8" );
                  System.out.println("Returned Value " + b);
                  b = a.getBytes( "ISO-8859-1" );
                  System.out.println("Returned Value " + b);
            } catch(Exception e) {
                  System.out.println("Unsupported character set");
            }
      }
}

Returned Value [B@192d342
Returned Value [B@15ff48b
Returned Value [B@1b90b39

String hashCode Method Example

public class StringEighteen {
      public static void main(String [ ] args) {
            String Str = new String("String Programming are very important in Java.");
            System.out.println("Hashcode for Str :" + Str.hashCode() );
      }
}

Hashcode for Str :1186874997

String indexOf Method Example

public class StringNineteen {
      public static void main(String [ ] args) {
            String a = new String("Java String Programming.");
            String b = new String("Programming");
            String c = new String("Grogramming");
            System.out.print("Found Index :" );
            System.out.println(a.indexOf('o'));
            System.out.print("Found Index :" );
            System.out.println(a.indexOf('o', 5 ));
            System.out.print("Found Index :" );
            System.out.println(a.indexOf(b));
            System.out.print("Found Index :" );
            System.out.println(a.indexOf(b, 15 ));
            System.out.print("Found Index :" );
            System.out.println(a.indexOf(c));
      }
}

Found Index : 4
Found Index :9
Found Index :11
Found Index :-1
Found Index :-1

String intern Method Example

public class StringTwenty {
      public static void main(String [ ] args) {
            String a = new String("Java Language");
            String b = new String("JAVA LANGUAGE");
            System.out.print("Canonical representation:" );
            System.out.println(a.intern());
            System.out.print("Canonical representation:" );
            System.out.println(b.intern());
      }
}

Canonical representation: Java Language
Canonical representation: JAVA LANGUAGE