Java String Class

From Wikiversity
(Redirected from Java lang String)
Jump to navigation Jump to search

This topic will guide through the most used functions of the String class. You need to know basic Java to understand this

Functions[edit | edit source]

One very useful function is the substring(int, int) method (or substring(int)). This method will return a string starting at the first integer, inclusive and ending at the second position (within that String), exclusive. Same as array elements, characters in the String count from 0. For Example:
String test="something";
String test2=test.substring(5, 9);

In this case, test2 would be 'hing'.


Another is equals(String). If you want to check if a string is "Hello", then:
boolean b=test.equals("Hello");
if(b==true)//equal to if(b)
System.out.println(Equal);

Do not compare strings directly, with the == sign. It is a different operation, an identity comparison. It may succeed in some cases, but in others will return for you incorrect false.


Another is replaceAll(String, String). It replaces all instances of the string you enter in the entire string with the second string. You want to replace all instances of to with ot:

String s="i want to go to school too fast, to study"<br>
s.replaceAll("to", "ot")<br>



Another is charAt(int index).It will returns the character at the specified index

 String str="Welcome";
 for (i=0;i<str.length();i++)
   {
         System.out.println(str.charAt(i))
   }

Another is length().It will returns the length of the string

 String str="Welcome";
 String str1=str.length();
 System.out.println(str1);

Another is compareTo().It will Compare two strings

 String str="Welcome";
 String str1="Goodbye";
  if (str.compareTo(str1)>0)
   {
        System.out.println("First string is ordered after the second string");
   }

equals() and hashCode()[edit | edit source]

The method equals(String other) returns true if the string passed as a parameter is equal by content (this is the correct operation to test strings for equality). The similar method equalsIgnoreCase(String other) performs case insensitive comparison. The method hashCode() computes the numeric value that depends on the string content. The different strings most often have different hashcodes but in some corner cases may happen that they have the same. However two strings with the same content never have different hashcodes. Hashcode is used when implementing various advanced algorithms on strings.

As String implements hashCode() and equals() properly, it is possible to have structures like HashMap or HashSet of strings. The set will not store duplicate entries and the map will always find a key that matches the passed key string by content.


Add more useful functions...