You are on page 1of 6

String Class

What is String?
- String is basically an object that represents a sequence of char values.
- We can create strings in java by using three classes which are String, StringBuffer,
StringBuilder.
- The java.lang.String class is used to create a string object.
- There are two ways to create a String object:
- By string literal
- By new keyword

1. String Literal: Java String literal is created by using double quotes:


String str = “Java”; -> creates “java” object by string literal
- Each time you create a string literal, the JVM checks the “string pool” first. If the string
already exists in the pool, a reference to the pooled instance is returned. If the string does
not exist in the pool, a new string instance is created and placed in the pool.

String Pool: A storage area in Java heap memory where string literals are stored.
- The JVM performs some steps during the initialization of string literals that
increase the performance and decrease the memory load. To decrease the number
of String objects created in the JVM the String class keeps a pool of strings.
- When we create a string literal, the JVM first checks that literal in the String pool.
If the literal is already present in the pool, the same reference is returned. So, new
memory is not allocated for the same string, existing memory is used instead. If the
literal is not present in the pool, the new String object takes place in the String
pool.

2. By new keyword: the new() keyword always creates a new String object.
- Using the new keyword guarantees that a new String object will be created and a new
memory location will be allocated in the Heap memory. This string will not be added to the
String constant/literal pool.

- Java String class is immutable which means once a String object is created it cannot be
changed (You cannot reassign it). When you use a String modification method like
concatenation or substring, what actually happens is that a new String is created and
returned that contains the result of the operation.
- And the old one becomes unreferenced and eligible for garbage collection.

- String is a special class in Java and also one of the most used too. That is why the concept
of constant String pool is used to minimize memory usage.
- String being immutable results in reduced memory usage.
String Class Methods:

1. length()
- length() method returns the count of the total number of characters in the string
including spaces.
- For an empty string, length is 0.
- Accepts no parameter
- Syntax: public int length()
String str = "Java"; //str.length() = 4
- Returns: An int value, representing the length of the string.

2. charAt(indexNumber)
- charAt() method returns a char value at the given index number.
- String indexes are zero-based: The first character is in position 0, the second in 1 ,
and so on.
- Accepts one parameter
- Last character of index: str.length()-1
- Syntax: public char charAt(int index)
String name = "Mike Smith"; //name.charAt(2) = k

Parameter Description

index An int value representing the index of the character to return

- Returns: A char value at the specified index of this string.


- The first char value is at index 0
- Throws: IndexOutOfBoundsException - if index is negative or not less than the length of
the specified string

3. concat()
- The concat() method joins two or more strings.
- concat() does not change the existing strings, but returns a new string.
- Syntax: string.concat(string1, string2, ..., stringX)

Parameter Description

string1, string2, ..., Required. The strings to be joined


stringX

- Returns: A new String, containing the text of the combined strings.

4. contains()
- The contains() method checks whether a string contains a sequence of characters.
- Syntax: public boolean contains(CharSequence chars)
Parameter Description

CharSequence chars The characters to be searched for

- Returns: A boolean, indicating whether a sequence of characters exist in the specified


string:
- true - sequence of characters exists
- false - sequence of characters does not exist
Throws: NullPointerException - if the returned value is null

5. indexOf()
- indexOf() method returns the position of the first occurrence of specified
character(s) in a string.
- Returns -1 if the value is not found
- There are 4 indexOf() methods (overloaded methods):
- public int indexOf(String str)
- public int indexOf(String str, int fromIndex)
- public int indexOf(int char)
- public int indexOf(int char, int fromIndex)
- lastIndexOf() method returns the position of the last occurrence of specified
character(s) in a string.

Parameter Description

str A String value, representing the string to search for

fromIndex An int value, representing the index position to start the search from

char An int value, representing a single character, e.g 'A', or a Unicode value

- Returns: An int value, representing the index of the first occurrence of the
character in the string, or -1 if it never occurs.
6. replace()
- The replace() method searches a string for a specified value, or a regular
expression, and returns a new string where the specified values are replaced.
- The replace method in Java replaces all occurrences of the specified substring
within the original string, not just the one at a specific index.
- replace() does not change the original string.
- string.replace(searchvalue, newvalue)

Parameter Description

searchvalue Required. The value, or regular expression, that will be replaced by


the new value

newvalue Required. The value to replace the search value with

- Returns: A new String, where the specified value(s) has been replaced by the new
value

7. equals()
- The equals() method compares two strings, and returns true if the strings are
equal, and false if not.
- Syntax: public boolean equals(Object anotherObject)

Parameter Description

Another object An Object, representing the other string to be compared

- Returns: A boolean value:


- true - if the strings are equal
- false - if the strings are not equal
- == operator checks only whether two strings refer to the same object. It does not tell you
whether they have the same contents.

String s1 = "Welcome to Java";


String s2 = new String("Welcome to Java");
System.out.println(s1==s2); //false
System.out.println(s1.equals(s2)); //true

8. equalsIgnoreCase()
- equalsIgnoreCase() compares the two given strings on the basis of the content of
the string irrespective of the case (lower and upper) of the string. It is just like the
equals() method but doesn't check the case sensitivity. If any character is not
matched, it returns false, else returns true.

9. substring()
- Syntax: public String substring(int beginIndex)
public String substring(int beginIndex, int endIndex)
- substring(int beginIndex) method returns a part of the string. The substring
begins with the character at the specified index and extends to the end of this
string.
- The substring(int beginIndex, int endIndex) begins at the specified beginIndex
and extends to the character at index endIndex - 1.
- beginIndex is inclusive, and endIndex is exclusive. In other words, the beginIndex
starts from 0, whereas the endIndex starts from 1.

10. toUpperCase()
- toUpperCase() method converts a string to upper case letters.
11. toLowerCase()
- toLowerCase()method converts a string to lower case letters.

12. trim()
- trim() method removes whitespace from both ends of a string.
- This method does not change the original string.
- Accepts no parameter

13. isEmpty()
- isEmpty() method checks whether a string is empty or not.
- This method returns true if the string is empty (length() is 0), and false if not.
- Syntax: public boolean isEmpty()
- Accepts no parameters.

14. isBlank()
- The new instance method java.lang.String.isBlank() returns true if the string is
empty or contains only white space.
- Syntax: boolean blank = string.isBlank();
- isBlank() method is equal to str.trim().isEmpty() in earlier to java 11 versions
String str = "\n\r ";
System.out.println(str.length()); // 3
System.out.println(str.isBlank()); //returns true
System.out.println(str.isEmpty()); //returns false

15. startsWith()
- The startsWith() method checks whether a string starts with the specified
character(s).
- Syntax: public boolean startsWith(String chars)
- Returns: A boolean value:
true - if the string starts with the specified character(s)
false - if the string does not start with the specified character(s)

16. endsWith()
- endsWith() method checks whether a string ends with the specified character(s).
- Syntax: public boolean endsWith(String chars)
- Returns: A boolean value:
true - if the string endswith the specified character(s)
false - if the string does not end with the specified character(s)

You might also like