1 of 27

String Methods

UNIT - 1

2 of 27

public char charAt(int index) – �It returns char value for the particular index

  • The method accepts index as a parameter (0 as starting index) and returns a character at a specific index position in a string.
  • ThrowsStringIndexOutOfBoundsException if the index is a negative value or greater than this string length.

public class StringMethods {

public static void main(String[] args) {

// TODO Auto-generated method stub

String name="Java Prograaming";

//returns the char value at the 4th index

char ch=name.charAt(5);

System.out.println(ch);

}

}

3 of 27

public int length() – �Length of characters. In other words, the total number of characters present in the string.

  • internally uses a char[] array to store the characters. The length variable of the array is used to find the total number of elements present in the array. Since the Java String class uses this char[] array internally; therefore, the length variable can not be exposed to the outside world.

public class StringMethods {

public static void main(String[] args) {

String str = "Javatpoint";

if(str.length()>0) {

System.out.println("String is not empty and length is: "+str.length());

}

str = "";

if(str.length()==0) {

System.out.println("String is empty now: "+str.length());

}

}

}

4 of 27

public static String format(String format, Object... args)

  • locale : specifies the locale to be applied on the format() method.
  • format : format of the string.
  • args : arguments for the format string. It may be zero or more.
  • returns the formatted string by given locale, format and arguments.
  • like sprintf() function in c language and printf() method of java language

Throws

  • NullPointerException : if format is null.
  • IllegalFormatException : if format is illegal or incompatible.

5 of 27

public static String format(String format, Object... args) �public static String format(Locale locale, String format, Object... args)

public class StringMethods {

public static void main(String[] args) {

String name="sonoo";

String sf1=String.format("name is %s",name);

String sf2=String.format("value is %f",32.33434);

//returns 12 char fractional part filling with 0

String sf3=String.format("value is %32.12f",32.33434);

System.out.println(sf1);

System.out.println(sf2);

System.out.println(sf3);

}�

}

6 of 27

7 of 27

public String substring(int startIndex) �public String substring(int startIndex, int endIndex)

Exception Throws

  • StringIndexOutOfBoundsException is thrown when any one of the following conditions is met.
    • if the start index is negative value
    • end index is lower than starting index.
    • Either starting or ending index is greater than the total number of characters present in the string.

8 of 27

public boolean contains(CharSequence sequence)

Returns

true if the sequence of char value exists, otherwise false.

Exception

NullPointerException : if the sequence is null.

public class StringMethods {

public static void main(String[] args) {

String name="what do you know about me";

System.out.println(name.contains("do you know"));

System.out.println(name.contains("about"));

System.out.println(name.contains("hello"));

}

}

9 of 27

public static String join(CharSequence delimiter, CharSequence... elements) �public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)

Parameters

delimiter : char value to be added with each element

elements : char value to be attached with delimiter

Returns

joined string with delimiter

Exception Throws

NullPointerException if element or delimiter is null.

10 of 27

Example of join methods

public static void main(String[] args) {

String words[] = new String[] {"Hello", "All"};

List<String> colors = Arrays.asList("red", "green");

//using characterSequence elements

System.out.println(String.join("/", "31","07","2024"));

//using iterable object

System.out.println(String.join(" ", colors));

System.out.println(String.join(" ", words));

}

11 of 27

Public boolean equals(Object anotherObject) 

  • The Java String class equals() method compares the two given strings based on the content of the string. If any character is not matched, it returns false. If all characters are matched, it returns true.
  • The String equals() method overrides the equals() method of the Object class.

12 of 27

int compareTo(String anotherString)�int compareToIgnoreCase(String str)�

Parameters

  • str – takes another string to compare

Returns

  • A negative integer if this string is lexicographically less than the specified string.
  • Zero if this string is equal to the specified string.
  • A positive integer if this string is lexicographically greater than the specified string.

String s1="javatpoint is a very good website";

System.out.println(s1.replace('a','e'));//replaces all occurrences of 'a' to 'e'

System.out.println(s1.replace("good", "best"));

13 of 27

public boolean isEmpty()

  • It checks if the input string is empty or not. Note that here empty means the number of characters contained in a string is zero.

String str1 = null;

String str2 = "";

System.out.println(new String().isEmpty()); //true

System.out.println(str2.isEmpty()); //true

//raise NullPointerException

System.out.println(str1.isEmpty());

14 of 27

public String concat(String anotherString)

  • Parameter - anotherString : another string i.e., to be combined at the end of this string.
  • Returns - combined string

String str1 = "Hello";

String str2 = "All";

String str3 = "Reader";

// Concatenating one string

String str4 = str1.concat(str2);

System.out.println(str4);

// Concatenating multiple strings

String str5 = str1.concat(str2).concat(str3);

System.out.println(str5);

15 of 27

public String replace(char oldChar, char newChar) �public String replace(CharSequence target, CharSequence replacement)

Parameters

  • oldChar : old character
  • newChar : new character
  • target : target sequence of characters
  • replacement : replacement sequence of characters

Returns - replaced string

Exception Throws - NullPointerException: if the replacement or target is equal to null.

String s1="javatpoint is a very good website";

System.out.println(s1.replace('a','e'));//replaces all occurrences of 'a' to 'e'

System.out.println(s1.replace("good", "best"));

16 of 27

public boolean equalsIgnoreCase(String str)

Parameters

  • str : another string i.e., compared with this string.

Returns - It returns true if characters of both strings are equal, ignoring case otherwise false.

String s1="javatpoint";

String s2="javatpoint";

String s3="JAVATPOINT";

String s4="python";

System.out.println(s1.equalsIgnoreCase(s2));//true content is same

System.out.println(s1.equalsIgnoreCase(s3));//true because case is ignored

System.out.println(s1.equalsIgnoreCase(s4));//false because content is not same

17 of 27

public String split(String regex) �and, �public String split(String regex, int limit)

Parameters

  • regex : regular expression to be applied on string.
  • limit : This argument specifies the maximum number of substrings to be returned. If it is zero, it will returns all the strings matching regex.

Returns - array of strings

Throws - PatternSyntaxException if pattern for regular expression is invalid

s1="welcome to split world";

System.out.println("returning words:");

//no. of substring is greater than possible words

String[] words2 = s1.split("\\s",10);

System.out.println(words2.length); //4

for(String w: words2){

System.out.println(w);

}

18 of 27

public String intern()

Why?

  • It returns the canonical representation of string. It can be used to return string from memory if it is created by a new keyword.
  • It creates an exact copy of the heap string object in the String Constant Pool.
  • We know that creating an object is a costly operation in Java. Therefore, to save time, Java developers came up with the concept of String Constant Pool (SCP).
  • The SCP is an area inside the heap memory. It contains the unique strings.
  • In order to put the strings in the string pool, one needs to call the intern() method.
  • Before creating an object in the string pool, the JVM checks whether the string is already present in the pool or not.
  • If the string is present, its reference is returned.

19 of 27

public String intern()

What will be the output?

String s1 = new String("Hello");

String s2 = new String("Hello");

String s3 = s2;

System.out.println(s1==s2);

System.out.println(s1==s3);

System.out.println(s2==s3);

System.out.println(System.identityHashCode(s2)+" "+System.identityHashCode(s1));

20 of 27

public String intern()

What will be the output?

String s1 = new String("Hello");

String s2 = new String("Hello");

String s3 = s2;

System.out.println(s1==s2);\\false

System.out.println(s1==s3);\\false

System.out.println(s2==s3);\\true

System.out.println(System.identityHashCode(s2)+" "+System.identityHashCode(s1)); \\will print different memory

21 of 27

public String intern()

What will be the output?

String s1 = new String("Hello").intern();

String s2 = new String("Hello");

String s3 = s2;

System.out.println(s1==s2);

System.out.println(s1==s3);

System.out.println(s2==s3);

System.out.println(System.identityHashCode(s2)+" "+System.identityHashCode(s3));

false

false

true

1867750575 2046562095

22 of 27

public String intern()

What will be the output?

String s1 = new String("Hello").intern();

String s2 = new String("Hello").intern();

String s3 = s2;

System.out.println(s1==s2);

System.out.println(s1==s3);

System.out.println(s2==s3);

System.out.println(System.identityHashCode(s1)+" "+System.identityHashCode(s2)

+" "+System.identityHashCode(s3));

true

true

true

1867750575 1867750575 1867750575

23 of 27

public int indexOf()

Parameters

  • ch: It is a character value, e.g. 'a'
  • fromIndex: The index position from where the index of the char value or substring is returned.
  • substring: A substring to be searched in this string.

Returns - Index of the searched string or character.

24 of 27

public int indexOf()

Example of indexOf()

String s1="this is index of example";

//passing substring

int index1=s1.indexOf("is");//returns the index of is substring

int index2=s1.indexOf("index");//returns the index of index substring

System.out.println(index1+" "+index2);//2 8

//passing substring with from index

int index3=s1.indexOf("is",4);//returns the index of is substring after 4th index

System.out.println(index3);//5 i.e. the index of another is

//passing char value

int index4=s1.indexOf('s');//returns the index of s char value

System.out.println(index4);//3

25 of 27

public String toLowerCase() - coverts to lowercase �public String toLowerCase(Locale locale) - converts based on the specified locale.

Parameters

  • locale: A Locale object representing the desired locale for case conversion

The second method is essential for handling text in different languages and cultures, as lowercase conversion rules can vary significantly.

String text = "TURKISH i CHARACTER";

// Convert to lowercase using the default locale (might not be correct)

String defaultLowercase = text.toLowerCase();

System.out.println(defaultLowercase); // Output: turkish i character

// Convert to lowercase using Turkish locale

String turkishLowercase = text.toLowerCase(Locale.forLanguageTag("tr"));

System.out.println(turkishLowercase); // Output: türkış ı character

26 of 27

public String toUpperCase() �public String toUpperCase(Locale locale)

Parameters

  • locale: A Locale object representing the desired locale for case conversion

The second method variant of toUpperCase(), converts all the characters into uppercase using the rules of given Locale.

String s = "hello string";

String turkish = s.toUpperCase(Locale.forLanguageTag("tr"));

String english = s.toUpperCase(Locale.forLanguageTag("en"));

System.out.println(turkish);//will print I with dot on upper side

System.out.println(english);

27 of 27

public String trim() - string with omitted leading and trailing spaces

String str = " abc ";

String str1 = str.trim();

System.out.println(str.hashCode());

System.out.println(str1.hashCode() + "\n");

String s = "xyz";

String s1 = s.trim();

System.out.println(s.hashCode());

System.out.println(s1.hashCode());

Returns the same reference of the string if string didn’t contain any leading and trailing spaces. Otherwise returns a new string

32539678

96354

119193

119193