Java String Handling Program Methods [Coding Examples Explained]

Java String Handling Program Methods [Coding Examples Explained]

In the previous tutorial, we learned the basic object-oriented programming concepts and built a base in Java. Now, moving ahead, we will be discussing a new section in Java, String Handling in Java.

We will cover the following topics related to String Handling in Java Programming.

What is a String?

In computer science, a string is a series of characters, which are either a literal or some variable, for example, “Happy” is a string of 5 characters.

But in Java, strings are observed as objects that represent a sequence of characters of String class type. The String class is a wrapper class in java.lang.String package.

A string once created cannot be modified, i.e., a string is immutable.

How to create a String in Java?

In Java, a string object can be created using two varied ways, namely –

  1. Using String literal
  2. Using ‘new’ keyword

1. Using String literal:

A String literal in Java is created using double quotes and assigning this literal to an instance.

For example (Syntax):

String example = “Happy Learning” ;

2. Using ‘new’ keyword:

Here, we use the new keyword to create a String instance.

For example (Syntax):

String example = new String (“Happy Learning”);

This way of creating a string in Java creates 2 objects- one in the String constant pool (if the example doesn’t exist in the constant pool) and one in the memory heap.

Where is the String object stored?

As a string object is created, it is stored in a pool of Strings called the String pool which is in turn stocked up in the heap memory of Java.

Java string object stored in string pool

Fig: Storing of String Objects in Java

Moving ahead, the Java String class implements 3 various interfaces, to be precise- CharSequence, Serializable, and Comparable.

The Object class is the superclass of the String class. As we have seen prior, Strings are immutable, thus whenever we mutate a string a new string gets created. To create a mutable string, Java makes us available with service classes, namely – StringBuilder and StringBuffer.

Java string class interfaces

As we have learned, String in Java is a class, and thereby it is obvious that it has wide-ranging methods associated with it.

Java String Handling Program Methods

Let’s sneak peek into some of the frequently used methods allied with the String class.

1. charAt(int index)

This method returns the character value at the specified index.

Example:

public class CharAtSample{
  public static void main(String args[]){
    String sample = "csestack.org";
    char ch1 = sample.charAt(4);
    System.out.println(ch1);
   }
}

Output :

t

2. compareTo(String certainString)

This is a method of Comparable interface and is implemented by the String class. It is used to compare a certain string to the current string. As a result, the method returns 0, a positive or negative value after comparison.

  • 0 when both strings are equal
  • positive if string s1 is greater than string s2
  • negative if string s1 is less than string s2.

Example:

public class CompareToSample { 
  public static void main(String args[]) { 
    String s1="string"; 
    String s2="string"; 
    String s3="ring"; 
    String s4="swing"; 
 
    System.out.println(s1.compareTo(s2));
    //0 because both are equal 

    System.out.println(s1.compareTo(s3));
    //1 because "s" is 1x greater than "r"

    System.out.println(s1.compareTo(s4)); 
    // -3 because "t" is 3x lower than "w"
  }
 }

Output:

0
1
-3

3. equals(Object obj)

This method returns a Boolean value, i.e. true if the comparing string is matching and false if it doesn’t.

Example:

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

    String s1="string"; 
    String s2="string"; 
    String s3="swing"; 

    System.out.println(s1.equals(s2));
    //true because both are equal 

    System.out.println(s1.equals(s3)); 
    //false because both are not equal
  }
}
 

Output:

True
False

4. length()

This method returns an integer value that specifies the complete length of the string.

Example:

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

    String s1="Happy "; 
    String s2="Learning";  

    System.out.println(s1.length()); 
    // 5 is the length of happy string

    System.out.println(s2.length()); 
    //8 is the length of learning string
  }
}

Output:

5
8

5. replace(char oldLetter, char newLetter)

This method returns a new string where all the occurrences of the old character are replaced by the new character in the string.

Example:

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

    String s1="string";
    String s2 = replace("t","w"); 

    System.out.println(s2);
  }
}

Output:

swing

6. toLowerCase()

This method converts all the characters in the string into lower case.

Example:

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

    String s1="HAPPY LEARNING"; 
    String s2 = s1.toLowerCase(s1);

    System.out.println(s2);
  }
}

Output:

happy learning

7. toUpperCase()

This method converts all the characters in the string into uppercase.

Example:

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

    String s1="happy learning"; 
    String s2 = s1.toUpperCase(s1);

    System.out.println(s2);
  }
 }

Output:

HAPPY LEARNING

8. trim()

This method returns a string that omits the leading and trailing whitespaces present in the actual string.

Example:

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

    String s1="      Happy Learning          ";  

    System.out.println(s1 +":csestack.org");
    System.out.println(s1.trim() +":csestack.org");
  }
}

Output:

      Happy Learning          :csestack.org
Happy Learning:csestack.org

9. concat(String newString)

This returns a new concatenated string which has a new string placed right at the end of the old string. The new string is tagged on a string.

Example:

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

    String s1="Welcome to"; 
    String s2 =" csestack.org !!";
    String s3 = s1.concat(s2);

    System.out.println(s3);
  }
}

Output:

Welcome to csestack.org !!

10. split()

This method returns a character array after splitting the given string against the specified regular expression.

Example:

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

    String s1="Maths:25 English:23 Science:22"; 
    String [] s2 = s1.split("\\s"); 
    //splits based on whitespace

    for(String word: s2){
      System.out.println(s2);
    }
  }
}

Output:

Maths:25
English:23
Science:22

11. valueOf()

This method is used to convert the varied types into String, like int to string, long to string, Boolean to string, float to string, etc.

Example:

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

    float value = 11.50;
    String s1 = String.valueOf(value);

    System.out.println(s1+"%"); 
    //concatenating the obtained string
  }
}

Output:

11.50%

These are thee different types of Java String handling program methods. The String class doesn’t limit itself to the above-mentioned methods, it has many more useful methods that could make programming easy. Try using a few of the String methods, and enjoy coding.

Happy Learning!

8 Comments

  1. Excellent. I was searching this all and I get your website. Overall Excellent work. Please Keep It Up.

Leave a Reply

Your email address will not be published. Required fields are marked *