In this tutorial we will discuss Java String trim()
and hashCode()
methods with the help of examples.
Java String trim() method signature
It returns a String after removing leading and trailing white spaces from the input String. For e.g. " Hello".trim()
would return the String "Hello"
.
public String trim()
Java String trim() method example
In the following example we have a string with leading and trailing white spaces, we are using trim() method to get rid of these leading and trailing white spaces but we want to retain the white spaces that are in between the words of the given string str
. The trim() method only removes the leading and trailing white spaces and leaves the in between spaces as it is.
public class JavaExample{ public static void main(String args[]){ String str = new String(" How are you?? "); System.out.println("String before trim: "+str); System.out.println("String after trim: "+str.trim()); } }
Output:
Java String hashCode() method signature
This method returns the hash code for the String. The computation is done like this:
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
public int hashCode()
Java hashCode() method Example
In the following example we have a string str
with the value “Welcome!!”, we are displaying the hash code of this value using the hashCode() method.
public class JavaExample{ public static void main(String args[]){ String str = new String("Welcome!!"); System.out.println("Hash Code of the String str: "+str.hashCode()); } }
Output:
Leave a Reply