Thursday, July 18, 2024
HomeEducationString Methods Java: A Guide To Java Strings With Examples

String Methods Java: A Guide To Java Strings With Examples

string methods java

A string is a sequence of characters. In Java Programming, strings are widely used and treated as objects, and string in Java can not be changed once it has been created. There are several methods in Java that assist in performing operations in a string called String functions. In this article, we will explore various string methods along with detailed examples. So, let’s get started.

Java Strings 

Strings in Java can be created using a character, object, or literal. There are numerous Java string methods such as equals(), split(), replace(), length(), and so on. An array of values represents a string. Serializable, Comparable, and CharSequence implement the class. You can create a string object using the java.lang.String class. It allows users to manipulate strings.

char[] ch={'j','a','v','a','t','p','o','i','n','t'}; String s=new String(ch); 

Example of Java String

public class StringExample{ public static void main(String args[]){ String s1="java";//creating string by Java string literal char ch[]={'s','t','r','i','n','g','s'}; String s2=new String(ch);//converting char array to string String s3=new String("example");//creating Java string by new keyword System.out.println(s1); System.out.println(s2); System.out.println(s3); }}

When you run it, it will give the following output:

java
strings
example

Creating a Java String 

A Java string can be created in two ways:

  • Using string literal
  • Using a new keyword 

String Literal- In Java, a string literal is created using double-quotes. For example:

String str1="welcome"; String str2 = "welcome"; (It does not create new instance)

The string literal in the above-given example is ‘welcome,’ and the compiler creates a String object. If an object already exists, it would simply assign the old object to the new instance. There are two string instances – str1 and str2 and the compiler assigned the value ‘welcome’ to both the instances. But if we want to create two different objects using the exact string. For that, we need to create a string using a new keyword. 

New keyword- Using literal, the compiler only created one object when we assigned the same object using two literals. To overcome this, we can create strings in this way:

String str1 = new String("Welcome");
String str2 = new String("Welcome");

In this example, the compiler will create two objects with one reference variable in this example. The value ‘welcome’ will be placed in the constant pool. 

Java String Methods

We have enlisted a few Java string methods that can be further explained individually. Here are they –

  • char charAt(int index)- It returns the character value at the particular index. The index value lie between 0 to length () – 1. 
  • String substring(int beginIndex)- It returns a substring from a specified index.
  • int length()- It returns string length.
  • String substring(int beginIndex, int endIndex)- It returns substring for begin and end index.
  • static String format(Locale l, String format, Object… args)- It returns a formatted string corresponding to the given locale. 
  • boolean equals(Object obj)- It returns a true value if the string matches the specified, or else it gives a false if it doesn’t.
  • boolean equalsIgnoreCase(String string)- It returns a value based on a case-sensitive comparison of the strings.
  • boolean startsWith(String prefix)- It returns a true or false value depending on the string’s specified prefix.
  • boolean endsWith(String suffix)- It checks if the particular string ends with the specified suffix.
  • int hashCode()- It returns the hash code of the string.
  • String substring(int beginIndex, int endIndex)- It returns the substring that begins with the character at beginIndex and ends with endIndex.
  • String intern()- It returns the canonical form of the given String.
  • String toLowerCase()- It returns a string with characters in lowercase.
  • String toUpperCase()- It returns a string with characters in uppercase.
  • String toLowerCase(Locale l)- It returns a string with a character in lowercase with a specified locale.
  • String toUpperCase(Locale l)- It returns a string with a character in uppercase with a specified locale.
  • subSequence()- It returns a sub sequence from the string. 
  • toCharArray()- It converts the string to a character array.
  • isEmpty()- It checks if a given string is empty or not. 
  • String Concat(String str)- It returns the value by linking together the strings.
  • String replace(char old, char new)- It replaces the specified char value at all instances with the new one.
  • String replace(CharSequence old, CharSequence new)- It replaces the value of a given CharSequence with a new one across all instances. 
  • String trim()- It eliminates the starting and ending tails of the string.
  • String matches()- It checks if the specified string matches the regex.
  • static String valueOf(int value)- It is an overloaded method to convert the given type into a string.  

Examples of String Functions

Let us check some examples of string functions in Java. 

  • How to convert a string to lowercase?
public class StringLowerExercise{
public static void main(String args[]){
String s1="HELLO HOW Are You TODAY?”;
String s1lower=s1.toLowerCase();
System.out.println(s1lower);}
}

Output:

  • How to check if two strings are equal?
public class EqualsExercise{
public static void main(String args[]){
String s1="Hi";
String s2="Hey";
String s3="Hello";
System.out.println(s1.equalsIgnoreCase(s2)); // returns true
System.out.println(s1.equalsIgnoreCase(s3)); // returns false
}
}

Output:

  • How to check if a string is empty?
public class IsEmptyExercise{
public static void main(String args[]){
String s1="";
String s2="Hello";
System.out.println(s1.isEmpty()); // true
System.out.println(s2.isEmpty()); // false
}}

Output:

  • How to replace a part of a string?
public class ReplaceExercise{
public static void main(String args[]){
String s1="hello how are you today";
String replaceString=s1.replace('h','t');
System.out.println(replaceString); }}

Output:

  • How to join two Java strings?
class Main { public static void main(String[] args) { // create first string String first = "Java "; System.out.println("First String: " + first); // create second String second = "Programming"; System.out.println("Second String: " + second); // join two strings String joinedString = first.concat(second); System.out.println("Joined String: " + joinedString); }
}

Output:

Conclusion 

Java strings are backed by a char array internally, giving them the immutable characteristic. Strings are stored in a heap along with all objects in Java. There are facts associated with string class and the functions and methods we explained above. A good developer should be adept at string manipulation, a crucial aspect of any programming language. Learn all about Java and other such popular programming languages for free at Great Learning Academy.

Recommended Articles

Source: GreatLearning Blog

RELATED ARTICLES
- Advertisment -

Most Popular

Recent Comments