Blog

String Handling in Java

  • (4.0)
  • | 152 Ratings

String Handling is the basic concept of Object Oriented Programming which revolves around the real-life entities.

String Handling in Java

The string is a sequence of characters. We can call an array of characters a string. 

public class Main{
    
   public static void main(String args[]){
       char[] c={'j','a','v','a'};  
       String s1=new String(c);  
       
       String s2="java";
       
       System.out.println(s1);
       System.out.println(s2);
   }
}

Like the above example, character array c and string s2 are same only. As we have already seen, we can define string using literal or using the new operator. String objects are immutable objects. You can perform operations over it without storing those values.

Now, let us explore how Java handles string with different examples.

String Length

String length is a number of characters in it. String object has a predefined method available called length() to obtain no. of characters in it.

public class Main{
  
   public static void main(String args[]){
      
       String s1="java";
       System.out.println(s1.length());
      
   }
}

Output:

4

Subscribe to our youtube channel to get new updates..!

String Modification

String Concatenation

Java has “+” operator to attach more than one string or string with some other data type value. We can have multiple chain of operations by using the + operator.

As we can see in below example, we can join string with another string literal, another string variable or another data type variable here, in this case, an integer.

public class Main{
  
   public static void main(String args[]){
      
       String s1="Java";
       int i = 10;
       System.out.println("Learn " + s1);
       System.out.println(s1 + "Version :" + i);
      
   }
}

Output:

Learn Java
java version: 10

We can also use concat() method to join strings same as above example.

public class Main{
  
   public static void main(String args[]){
      
       String s1="Java";
       String s2 = "Learn";
       s2.concat(s1);
       System.out.println(s2);
       System.out.println(s2.concat(s1));
      
   }
}

Output:

Learn
LearnJava

Here you can see, even after concatenation operation, s2 object’s value is still the same. That is why we have termed that string objects are immutable. When we perform concatenation operation, it will be a new object but the older object’s value won’t be changed.

Extraction

Java can extract substring using the substring() method. Its general form is as below:

String substring(int startIndex, int endIndex)

Here, if we have omitted endIndex then, it will extract the substring from startIndex till the end of the string.

public class Main{
  
   public static void main(String args[]){
      
       String s1="Learn Java";
       System.out.println(s1.substring(1));
       System.out.println(s1.substring(1,5));
      
   }
}

Output:

earn Java
earn

Like 1st  statement, if we omit endIndex, it will fetch from startIndex to the end of the string.

Replace

Java has a method called replace() to replace one character with another. The general form of replace() method is shown below:

String replace(char original, char replace)

Here, instead of one character we can also pass a string and replace it with another string. Below is the

example for the same:

public class Main{
  
   public static void main(String args[]){
      
       String s1="Learn Java in 10 days";
       System.out.println(s1.replace('a','e'));
       System.out.println(s1.replace("in","within"));
      
   }
}

Output:

Leern Jeve in 10 deys
Learn Java within 10 days

Trim

Java has a trim() method to remove extra white spaces from strings. It is very useful while processing user inputs.

public class Main{
  
   public static void main(String args[]){
      
       String s1="   Learn Java in 10 days  ";
       System.out.println(s1);
       System.out.println(s1.trim());
      
   }
}

Output:

Learn Java in 10 days 
Learn Java in 10 days

Case Conversion

Java has methods to convert the case of the strings.

String toLowerCase( )
String toUpperCase( )

These methods will convert the case of the whole string. These are very useful for user inputs where there will not be any consistency in which case the user will input their values. Non Alphabetic characters are not getting affected by these methods.

public class Main{
  
   public static void main(String args[]){
      
       String s1="Learn Java in 10 days";
       System.out.println(s1);
       System.out.println(s1.toUpperCase());
       System.out.println(s1.toLowerCase());
      
   }
}

Output:

Learn Java in 10 days
LEARN JAVA IN 10 DAYS
learn java in 10 days

String Conversion

Java has a method called toString() to convert the object into a string object. So when we concat any objects, Java internally hit toString() method to perform the operation and return the string object. Now, if we want to show an object as a string object, we can override toString() object and return the information in whichever way we like.

Let us understand through the below example:

class employee
{
    int empid;  
    String ename;  
  
 employee(int empid, String ename){  
 this.empid=empid;  
 this.ename=ename;  
 }  
   
 public String toString(){//overriding the toString() method  
  return empid+" "+ename;  
 }  
}
public class Main{
  
   public static void main(String args[]){
      
    employee e1=new employee(10001,"ABC");  
    employee e2=new employee(10002,"XYZ");  
     
    System.out.println(e1);//compiler writes here s1.toString()  
    System.out.println(e2);//compiler writes here s2.toString()  
      
   }
}

Output:

10001 ABC
10002 XYZ

String Comparison

Java has below methods to compare two strings or substrings. Let us understand their usage with examples.

  • equals() and equalsIgnoreCase() 
These 2 methods returns true if both strings are same and false if not same.
public class Main{
 
     public static void main(String []args){
        String s1 = "Learn";
        String s2 = "Java";
        String s3 = "JAVASCRIPT";
        
        
        System.out.println(s1.equals(s2));
        System.out.println(s3.substring(0,4));
        System.out.println(s2.equals(s3.substring(0,4)));
        System.out.println(s2.equalsIgnoreCase(s3.substring(0,4)));
     }
}

Output:

false
JAVA
false
true

Here in this example, we can see the usage of equals() and equalsIgnoreCase() methods. It always returns a Boolean value.

  • == 

This works the same as equals() method and returns true in case of similar strings. The only difference here is that == compares references, not values.

public class Main{
 
     public static void main(String []args){
      
        String s1 = "Java";
        String s2 = "Java";
        String s3 = new String("Java");
        
        
        System.out.println(s1==s2);
        System.out.println(s2==s3);
    }
}

Output:

true
false

Here == operator compares 2 object references and see whether those two refer to the same instances. If the same instance then it will return true else it will return false even if both objects have the same values in it.

  • compareTo()

This method returns the integer value 

0 – if both strings are same
<0 – if invoking string is less than passed string
>0 – if invoking string is greater than passed string

public class Main{
 
     public static void main(String []args){
      
        String s1 = "Java";
        String s2 = "Java";
        String s3 = "Learn";
        
        
        System.out.println(s1.compareTo(s2));
        System.out.println(s2.compareTo(s3));
        System.out.println(s3.compareTo(s2));
    }
}

Output:

0
-2
2

  • startsWith() and endsWith()

startsWith() method is used in Java to check whether a string starts with some specific string.
endsWith() method is used in Java to check whether a string ends with some specific string.
Both these methods return a Boolean value and their general form is as below:

boolean startsWith(String s) 
boolean endsWith(String s)

If string matched the criteria, the statement returns true else it returns false.

public class Main{
 
     public static void main(String []args){
      
        String s1 = "Learn Java";
        
        System.out.println(s1.startsWith("Learn"));
        System.out.println(s1.endsWith("Java"));
    }
}

Output:

true
true

Subscribe For Free Demo

Free Demo for Corporate & Online Trainings.

Ravindra Savaram
About The Author

Ravindra Savaram is a Content Lead at Mindmajix.com. His passion lies in writing articles on the most popular IT platforms including Machine learning, DevOps, Data Science, Artificial Intelligence, RPA, Deep Learning, and so on. You can stay up to date on all these technologies by following him on LinkedIn and Twitter.


DMCA.com Protection Status