Sunday, June 22, 2014

String in Java

string java | new string java | string in java | java string example | string class methods in java

As most other programming languages, in java string is a sequence of characters. Java implements string as objects of type String. String class is to create string object.

How to create String in Java: -

  1. Implicitly (By string literal) created string in java
  2. Explicitly (By new keyword) created string in java
Implicitly (By string Literal) created string in Java: - When we use double quote, java automatically create a string object. For example:
String s="Hello world";

Explicitly (By new keyword) created string in java: - String create in java, when we use the new operator to instantiate a String object. For example:
String s= new String("Hello world");

Example of String in Java: -
  • Example of Implicitly Creating String in Java

  • Example of Explicitly Creating String in Java

String Class Methods in Java

  1. charAt( ): -It returns the character at the specified index.
  2. compareTo( ): -It compares this String to another Object.
  3. concat( ): -Concatenates the specified string to the end of this string.
  4. equals( ): -It compares this string to the specified object.
  5. endsWith( ): -Tests if this string ends with the specified suffix.
  6. getBytes( ): -Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
  7. getChars( ): -It copies characters from this string into the destination character array.
  8. length( ): -It returns the length of this string.
  9. indexOf( ): -It returns the index within this string of the first occurrence of the specified character.
  10. lastIndexOf( ): -It returns the index within this string of the last occurrence of the specified character.
  11. replace( ): -It returns a new string resulting from replacing all occurrences of old-Character in this string with new-Character.
  12. split( ): -Splits this string around matches of the given regular expression.
  13. substring( ): -It returns a new string that is a substring of this string.
  14. toCharArray( ): -It converts this string to a new character array.
  15. startsWith( ): -Tests if this string starts with the specified prefix.
  16. toLowerCase( ): -It converts all of the characters in this String to lower case using the rules of the default locale.
  17. toUpperCase( ): -It converts all of the characters in this String to upper case using the rules of the default locale.
  18. trim( ): -It returns a copy of the string, with leading and trailing whitespace omitted.
  19. toString( ): -This object (which is already a string!) is returned itself.
  20. replaceAll( ): -It replaces each substring of this string that matches the given regular expression with the given replacement.