Important String methods in Java

Java » Important String methods in Java

A string is a sequence of characters and considered as a constant because it cannot be changed once it’s created, making it immutable. “xyz” , “ijk” are the examples. In Java, all strings are an instance of String class. However, string buffers support mutable strings( strings that can be changed).

For example

Some useful methods in String Class

String Class provides a set of methods for searching, comparing, extracting and concatenating strings.These are some method that provides Java String Class

1. Char charAt(int position)

It returns character from the mentioned position.

Program:

Output:

2. Int compareTo(String str) 

It tells which one of them comes first alphabetically.It returns an integer value,

  • It returns 0, when two strings are identical
  • It returns negative or lesser than 0, when a string which triggered the compareTo() method would alphabetically come first.
  • It returns positive or greater than 0, when a string which is in the argument would come first alphabetically.

Program

Output:

3.String concat(String str)

It appends one string to another. It returns a newly created string.

Program:

Output:

4. Boolean IsEmpty()

It returns true if length() is 0. In other words, It checks whether a string consists of a character or not.

Program:

Note: Whitespaces are also characters.

Output:

5. String replace ( char old , new char)

It replaces all the old characters with a new one.  It returns a new altered string.

Program:

Output:

Note:  ‘T’ and ‘t’ are not the same

6.Char[] toCharArray()

It breaks down a particular string into an array of characters.

Program:

Output:

7. String toLowerCase() and toUpperCase()

toLowerCase() turns all the characters in strings to lower case

toUpperCase() converts a string to uppercase.

Program:

Output:

8. String ToString()

It represents a string as an object. Each Object that we create is a part of Object class which consists of toString() method and when we try to print the object using System.out.Println method, the compiler uses this predefined toString method and produces hashcode which is not desirable. To make it correct, we have to override this toString method.

Program:

 

Output:

9. String substring(int strartingpoint) &  String substring(int begin,int end)

It extracts a substring from this string which  takes a single argument that is the starting point.

It extracts a substring from the string as per specified range which takes two arguments that are starting points and end points.

Program:

Output:

10. Trim()

It removes all the whitespaces that come before and after the string.


You must be logged in to take the quiz.

error: Content is protected !!