Strings in Java - Learners Pool

Learners Pool

Knowledge that matters

Strings in Java

Share This

Strings in Java

Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects. The Java platform provides the String class to create and manipulate strings. String class is defined in java.lang package.
Strings in Java are represented internally using bytes, encoded as UTF-16. UTF-16 uses 2 bytes to represent a single character. UTF is a character encoding that can represent characters from a lot of different languages (alphabets).

Creating a String

We can create strings in two ways in Java
  •  By simply writing the text itself inside the double quote characters. This is called a String literal and assigning it to the String variable as 
String str=”Java Program”;

The java String is immutable i.e. it cannot be changed/modified but a new instance is created. For mutable class, you can use StringBuffer and StringBuilder class.

Each time you create a string literal, the JVM checks the string constant pool first. If the string already exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in the pool, a new string instance is created and placed in the pool. For example: 
1.    String s1="Welcome"; 
2.    String s2="Welcome";//will not create new instance 

In the above example only one object will be created. Firstly JVM will not find any string object with the value "Welcome" in string constant pool, so it will create a new object. After that it will find the string with the value "Welcome" in the pool, it will not create new object but will return the reference to the same instance.
String objects are stored in a special memory area known as string constant pool.
This is to make Java more memory efficient (because no new objects are created if it exists already in string constant pool).  

  • By new keyword We can also create Strings in java  by simply creating an instance for the String
String s=new String("Welcome");//creates two objects and one reference variable

In such case, JVM will create a new string object in normal(non pool) heap memory and the literal "Welcome" will be placed in the string constant pool. The variable s will refer to the object in heap(non pool).

Methods in String 

  1. char charAt(int index): It returns the character at the specified index. Specified index value should be between 0 to length() -1 both inclusive. It throws IndexOutOfBoundsException if index<0||>= length of String.
  2. int codePointAt(int index):It is similar to the charAt method however it returns the Unicode code point value of specified index rather than the character itself.
  3. void getChars(int srcBegin, int srcEnd, char[] dest, int destBegin): It copies the characters of src array to the dest array. Only the specified range is being copied(srcBegin to srcEnd) to the dest subarray(starting fromdestBegin).
  4. boolean equals(Object obj): Compares the string with the specified string and returns true if both matches else false.
  5. boolean contentEquals(StringBuffer sb): It compares the string to the specified string buffer.
  6. boolean equalsIgnoreCase(String string): It works same as equals method but it doesn’t consider the case while comparing strings. It does a case insensitive comparison.
  7. int compareTo(String string): This method compares the two strings based on the Unicode value of each character in the strings.
  8. int compareToIgnoreCase(String string): Same as CompareTo method however it ignores the case during comparison.
  9. boolean regionMatches(int srcoffset, String dest, int destoffset, int len): It compares the substring of input to the substring of specified string.
  10. boolean regionMatches(boolean ignoreCase, int srcoffset, String dest, int destoffset, int len): Another variation of regionMatches method with the extra boolean argument to specify whether the comparison is case sensitive or case insensitive.
  11. boolean startsWith(String prefix, int offset): It checks whether the substring (starting from the specified offset index) is having the specified prefix or not.
  12. boolean startsWith(String prefix): It tests whether the string is having specified prefix, if yes then it returns true else false.
  13. boolean endsWith(String suffix): Checks whether the string ends with the specified suffix.
  14. int hashCode(): It returns the hash code of the string.
  15. int indexOf(int ch): Returns the index of first occurrence of the specified character ch in the string.
  16. int indexOf(int ch, int fromIndex): Same as indexOf method however it starts searching in the string from the specified fromIndex.
  17. int lastIndexOf(int ch): It returns the last occurrence of the character ch in the string.
  18. int lastIndexOf(int ch, int fromIndex): Same as lastIndexOf(int ch) method, it starts search from fromIndex.
  19. int indexOf(String str): This method returns the index of first occurrence of specified substring str.
  20. int lastindexOf(String str): Returns the index of last occurrence of string str.
  21. String substring(int beginIndex): It returns the substring of the string. The substring starts with the character at the specified index.
  22. String substring(int beginIndex, int endIndex): Returns the substring. The substring starts with character at beginIndex and ends with the character at endIndex.
  23. String concat(String str): Concatenates the specified string “str” at the end of the string.
  24. String replace(char oldChar, char newChar): It returns the new updated string after changing all the occurrences of oldChar with the newChar.
  25. boolean contains(CharSequence s): It checks whether the string contains the specified sequence of char values. If yes then it returns true else false. It throws NullPointerException of ‘s’ is null.
  26. String replaceFirst(String regex, String replacement): It replaces the first occurrence of substring that fits the given regular expression “regex” with the specified replacement string.
  27. String replaceAll(String regex, String replacement): It replaces all the occurrences of substrings that fits the regular expression regex with the replacement string.
  28. String[] split(String regex, int limit): It splits the string and returns the array of substrings that matches the given regular expression. limit is a result threshold here.
  29. String[] split(String regex): Same as split(String regex, int limit) method however it does not have any threshold limit.
  30. String toLowerCase(Locale locale): It converts the string to lower case string using the rules defined by given locale.
  31. String toLowerCase(): Equivalent to toLowerCase(Locale. getDefault()).
  32. String toUpperCase(Locale locale): Converts the string to upper case string using the rules defined by specified locale.
  33. String toUpperCase(): Equivalent to toUpperCase(Locale.getDefault()).
  34. String trim(): Returns the substring after omitting leading and trailing white spaces from the original string.
  35. char[] toCharArray(): Converts the string to a character array.
  36. static String copyValueOf(char[] data): It returns a string that contains the characters of the specified character array.
  37. static String copyValueOf(char[] data, int offset, int count): Same as above method with two extra arguments – initial offset of subarray and length of subarray.
  38. static String valueOf(data type): This method returns a string representation of specified data type.
  39. byte[] getBytes(String charsetName): It converts the String into sequence of bytes using the specified charset encoding and returns the array of resulted bytes.
  40. byte[] getBytes(): This method is similar to the above method it just uses the default charset encoding for converting the string into sequence of bytes.
  41. int length(): It returns the length of a String.
  42. boolean matches(String regex): It checks whether the String is matching with the specified regular expression regex.

No comments:

Post a Comment