String

In Java, String is basically an object that represents a sequence of characters values. With the help of java.lang.String class we can create string object in Java.

We can create String object using below two ways:

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

For Example:

String str1=“Huge Learning”;
2. Using new keyword: Java String is also created by “new” keyword.

For Example:

String str2=new String(“Welcome in Huge Learning”);

Note

When we create object using “new” keyword, It creates two objects (one in String pool and other in heap) and one reference variable where the variable “str2” will refer to the object in the heap.

Java String Pool:

Java String pool represent a collection of Strings which are stored in heap memory. Whenever we create a new object, String pool first checks whether this object is already present in the pool or not. If it is available there, then same reference is returned to the variable else new object will be created in the String pool and the respective reference will be returned.

String Methods

1. public int length()- Java String length() method gets the length of the string. It returns total number of characters present in the String.
Let us see an example:

package hugelearningpackage;

public class StringTest {

  public static void main(String[] args) {
    String str1 = "Huge Learning";
    String str2 = new String("Welcome in Huge Learning world");

    System.out.println("Length of str1 : "+ str1.length());
    System.out.println("Length of str2 : "+ str2.length());
  }
}

Output:

Length of str1 : 13
Length of str2 : 30

2. public int compareTo(java.lang.String) – Java String compareTo() method compares the given string with current string. It is a method of Comparable interface which is implemented by String class. If ascii value of first string is greater than ascii value of second string then it returns positive number and negative for reverse and if ascii values are same or both strings are equal than it returns 0 value.

CompareTo function return following number :

if str1 > str2, it returns positive number
if str1 < str2, it returns negative number
if str1 == str2, it returns 0

Let us see an example:

public class StringTest {

	public static void main(String[] args) {
		String str1 = "ABC";
		String str2 = "ABC";
		String str3 = "BCA";
                String str4 = "abc";
		String str5 = "ABCDE";
		String str6 = "DCA";
		
		System.out.println(str1.compareTo(str2));
		System.out.println(str1.compareTo(str3));
		System.out.println(str1.compareTo(str4));
		System.out.println(str6.compareTo(str2));

	}
}

Output:

0
-1
-32
3

3. public java.lang.String concat(java.lang.String) – Java String concat() method combines first string at the end of another string and returns a combined string.

Let us see an example:

public class StringTest {

  public static void main(String[] args) {
    String str1 = "Huge";
    String str2 = "Learning";
      
    System.out.println(str1.concat(str2));

  }
}

Output:

HugeLearning

4. public boolean isEmpty() –   Java String isEmpty() method checks either the String contains anything or not. If the java String is Empty, it returns true else false.

Let us see an example:

public class StringTest {

  public static void main(String[] args) {
    String str1 = "HugeLearning";
    String str2 = "";
    String str3 = "  ";
    System.out.println(str1.isEmpty()); // Return false as string str1 is not empty
    System.out.println(str2.isEmpty()); // Return true as string str2 is not empty
    System.out.println(str3.isEmpty()); // Return false as string str3 is not empty because its contain spaces

  }
}

Output:

false
true
false

5. public char charAt(int) – Java String charAt() method returns a char value at the given index number.

Let us see an example:

public class StringTest {

	public static void main(String[] args) {
		String str1 = "HugeLearning";
		System.out.println(str1.charAt(3)); // Return 'e' as this character is present at 3rd index.
		System.out.println(str1.charAt(0));
	}
}

Output:

e
H

6. public boolean equals(java.lang.Object) – Java String equals() method compares two strings on the basis of their contents. If all the characters are similar, it returns true else it return false.

Let us see an example:

public class StringTest {

	public static void main(String[] args) {
		String str1 = "abc";
		String str2 = "ABC";
		String str3 = "abc";
		System.out.println(str1.equals(str2)); // Return 'false' as both Strings contents are not equals to each other.
		System.out.println(str1.equals(str3)); // Return 'true' as both Strings contents are equals to each other.
	}
}

Output:

false
true

7. public boolean equalsIgnoreCase(java.lang.String) – Java string equalsIgnoreCase method compares two string on the basis of content but it does not check the case.

In equalsIgnoreCase() methods:

if the characters match then it returns true.
otherwise it returns false

Let us see an example:


public class StringTest {

	public static void main(String[] args) {
		String str1 = "abc";
		String str2 = "ABC";
		String str3 = "BCS";
		System.out.println(str1.equalsIgnoreCase(str2)); // Return 'true' as both Strings contents are equals and ignore their case.
		System.out.println(str1.equalsIgnoreCase(str3)); // Return 'false' as both Strings contents are not equals to each other.
	}
}

Output:

true
false

8. public boolean startsWith(java.lang.String) –java string startsWith() method checks if this string start with given second string. It returns true if this string start with given second string else returns false.
Let us see an example:

public class StringTest {

	public static void main(String[] args) {
		String str1 = "Welcome to Huge Learning";
		System.out.println(str1.startsWith("Huge")); // Return 'false' as string str1 is not start with huge content.
		System.out.println(str1.startsWith("Welcome")); // Return 'true' as string str1 is not start with 'welcome' content. 
	}
}

Output:

false
true

9. public boolean endsWith(java.lang.String) –java string endsWith() method checks if this string ends with given second string. It returns true if this string ends with given second string else returns false.

Let us see an example:

public class StringTest {

	public static void main(String[] args) {
		String str1 = "Welcome to Huge Learning";
		System.out.println(str1.endsWith("Huge")); // Return 'false' as string str1 is not end with 'huge' content.
		System.out.println(str1.endsWith("Learning")); // Return 'true' as string str1 is not end with 'Learning' content. 
	}
}

Output:

false
true

10. public java.lang.String replace(char, char) – Java replace method returns a new string replacing old char or char serquence to new char or char sequence.
Let us see an example:

public class StringTest {

	public static void main(String[] args) {
		String str1 = "Welcome to Huge Learning";
		System.out.println(str1.replace('e', 'z')); 
		System.out.println(str1.replace("Huge", "Big")); 

	}
}

Output:

Wzlcomz to Hugz Lzarning
Welcome to Big Learning

11. public boolean matches(java.lang.String) – Java matches method says whether or not the string matches the given regular expression.
Let us see an example:

package hugelearningpackage;

public class StringTest {

	public static void main(String[] args) {
		String str1 = "Welcome to Huge Learning";
		System.out.println(str1.matches("(.*)Huge(.*)")); // Return true as string present before and after word "Huge"
		System.out.println(str1.matches("(.*)huge(.*)")); // Return false as we are taking "huge" in place of "Huge". 
		System.out.println(str1.matches("Huge")); //Return false as given string("Huge") does not matches the actual string("Welcome to Huge Learning").
		System.out.println(str1.matches("Welcome to Huge Learning")); // Return true as both string matches

	}
}

Output:

true
false
false
true

12. public boolean contains(java.lang.CharSequence) – Java contains method check if the string contains another substring or not. It return true if the string present else return false.
Let us see an example:

package hugelearningpackage;

public class StringTest {

	public static void main(String[] args) {
		String str1 = "Welcome to Huge Learning";
		System.out.println(str1.contains("Learning")); // Return true as string "Learning" present in the given string.
		System.out.println(str1.contains("World"));    // Return false as string "World" is not present in the given string.
	}
}

Output:

true
false

13. public java.lang.String toLowerCase() – Java toLowerCase method convert the entire string into lower case.
Let us see an example:

public class StringTest {

	public static void main(String[] args) {
		String str1 = "Welcome to Huge Learning";
		System.out.println(str1.toLowerCase()); // Convert the entire string into lower case.
	}
}

Output:

welcome to huge learning

14. public java.lang.String toUpperCase() – Java string toUpperCase method convert the entire string into upper case.
Let us see an example:

public class StringTest {

	public static void main(String[] args) {
		String str1 = "Welcome to Huge Learning";
		System.out.println(str1.toUpperCase()); // Convert the entire string into upper case.
	}
}

Output:

WELCOME TO HUGE LEARNING

15. public java.lang.String toString() – Java string toString method return or represent any object as a string. In Java, compiler internally check the toString method of Object class, so we need to override this toString method in our java class to return the desired output.
Let us see an example:

public class StringTest {

	int rollNo;
	String studentName;
	int age;

	public StringTest(int rollNo, String studentName, int age) {
		this.rollNo = rollNo;
		this.studentName = studentName;
		this.age = age;
	}
	public String toString() { // Override the toString method so that compiler execute this toString() method
		return "Roll No-" + rollNo + " Student Name " + studentName + " Age " + age;
	}
	public static void main(String[] args) {
		StringTest stu1 = new StringTest(1,"Ankit",29);
		StringTest stu2 = new StringTest(2, "Ajay", 28);
		
		System.out.println(stu1); // Internally Java compiler invoke toString() method of Object class.
		System.out.println(stu2);

	}
}

Output:

Roll No-1 Student Name Ankit Age 29
Roll No-2 Student Name Ajay Age 28

16. public char[] toCharArray() – Java string toCharArray method convert the string to character array.
Let us see an example:

public class StringTest {
	public static void main(String[] args) {

		String str1 = "Welcome to Huge Learning";
		int strLength =  0; 
		for(char ch:str1.toCharArray()) {
			System.out.print(ch+" ");
			strLength++;
		}
		System.out.println();
		System.out.println("Length of the string " + strLength);
	}
}

Output:

W e l c o m e t o H u g e L e a r n i n g
Length of the string 24

17. public static java.lang.String valueOf(java.lang.Object) –
Let us see an example:


Output: