Home  >  Blog  >   Java

String Handling in Java

Rating: 5
  
 
14413
  1. Share:
Java Articles

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


 

Are you interested in taking up Core Java Certification Training? Enroll Now for Core Java Training!

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 the 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 the number of characters in it. The 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

 MindMajix YouTube Channel

String Modification

String Concatenation

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

As we can see in the below example, we can join a 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 a concatenation operation, it will be a new object but the older object’s value won’t be changed.

Extraction

Java can extract substrings 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

Check Out Core Java Tutorials

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

------        Related Article: Types of Operators in Java ------

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 the 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 the 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 the 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 the 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

Join our newsletter
inbox

Stay updated with our newsletter, packed with Tutorials, Interview Questions, How-to's, Tips & Tricks, Latest Trends & Updates, and more ➤ Straight to your inbox!

Course Schedule
NameDates
Core Java TrainingApr 27 to May 12View Details
Core Java TrainingApr 30 to May 15View Details
Core Java TrainingMay 04 to May 19View Details
Core Java TrainingMay 07 to May 22View Details
Last updated: 03 Apr 2023
About Author

I am Ruchitha, working as a content writer for MindMajix technologies. My writings focus on the latest technical software, tutorials, and innovations. I am also into research about AI and Neuromarketing. I am a media post-graduate from BCU – Birmingham, UK. Before, my writings focused on business articles on digital marketing and social media. You can connect with me on LinkedIn.

read more
Recommended Courses

1 / 15