Thursday 12 October 2023

String Handling in Java

String Handling

Java implements strings as objects of type String.

Java provides a full complement of features that make string handling convenient. For example, Java has methods to compare two strings, search for a substring, concatenate two strings, and change the case of letters within a string.

 

Strings are immutable. That is, once a String object has been created, the characters that comprise that string cannot be changed. The original string is left unchanged.

 

 To create mutable strings (ie strings whose content can be changed), Java provides two options: StringBuffer and StringBuilder. Both hold strings that can be modified after they are created.

 

String objects can be constructed in several ways, making it easy to obtain a string when needed.


String Constructors

String s = new String(); //default

 

char ch[] = { 'a', 'b', 'c' };

String s = new String(ch); //converting array of characters to string

 

char ch[] = { 'a', 'b', 'c', 'd', 'e', 'f' };

String s = new String(ch, 2, 3);  //s="cde"   from second position to 3 characters

 

String(String strObj)   //copy constructor

   

    char c[] = {'J', 'a', 'v', 'a'};

    String s1 = new String(c);

    String s2 = new String(s1);

 

byte ascii[] = {65, 66, 67, 68, 69, 70 };

String s1 = new String(ascii);       //s1=ABCDEF

 

byte ascii[] = {65, 66, 67, 68, 69, 70 };

String s1 = new String(ascii,3,2);       //s1=DE

 

String(StringBuffer strBufObj)    //StringBuffer is a pre-defined class in Java

 

// Construct one String from another.

class MakeString

{

  public static void main(String args[])

  {

char c[] = {'J', 'a', 'v', 'a'};

String s1 = new String(c);

String s2 = new String(s1);

System.out.println(s1);

System.out.println(s2);

 }

}

String Concatenation

In general, Java does not allow operators to be applied to String objects. The one exception to this rule is the + operator, which concatenates two strings, producing a String object as the result. This allows you to chain together a series of + operations. For example, the following fragment concatenates three strings:

 

   String age = 10;

   String s = “He is “ + age + ” years old”; 

Java String class methods

The java.lang.String class provides many useful methods to perform operations on a sequence of char values.

 

Character Extraction

The String class provides several ways in which characters can be extracted from a String object. Some of the methods defined in the String class for this purpose are:

  • ·        charAt()
  • ·        getChars()
  • ·        getBytes()
  • ·        toCharArray()

 

charAt()

The charAt() method returns a char value at the given index number.

The index number starts from 0 and goes to n-1, where n is the length of the string. It returns StringIndexOutOfBoundsException if the given index number is greater than or equal to this string length or a negative number.

public class CharAtExample{  

public static void main(String args[]){  

String name="Strings in Java";  

char ch=name.charAt(4);   //returns the char value at the 4th index  

System.out.println(ch);  

}}  

 

getChars()

To extract more than one character at a time, use the getChars() method. It has this general form:

void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)

 

Example

String s = "This is a demo of the getChars method.";

            int start = 10;

            int end = 14;

            char buf[] = new char[end - start];

 

            s.getChars(start, end, buf, 0);

            System.out.println(buf);  //will store demo in buf

 

getBytes()

There is an alternative to getChars( ) that stores the characters in an array of bytes. This method uses the default character-to-byte conversions provided by the platform. Here is its simplest form:

byte[ ] getBytes( )

 

toCharArray( )

To convert all the characters in a String object into a character array, the easiest way is to call toCharArray( ). It returns an array of characters for the entire string. It has this general form:

 

char[ ] toCharArray( )

 

Java String length()

The java string length() method length of the string. It returns the count of total number of characters. The length of the Java string is the same as the Unicode code units of the string.

public class LengthExample{  

public static void main(String args[]){  

String s1="java";  

String s2="python";  

System.out.println("string length is: "+s1.length());  //4 is the length of javatpoint string  

System.out.println("string length is: "+s2.length());  //6 is the length of python string  

}}  

Java String substring()

The java string substring() method returns a part of the string.

We pass the begin index and end index number position in the Java substring method where the start index is inclusive and the end index is exclusive. In other words, the start index starts from 0 whereas the end index starts from 1.

There are two types of substring methods in Java string.

1.    public String substring(int startIndex)  


2.    public String substring(int startIndex, int endIndex)  

 

Example

public class SubstringExample{  

public static void main(String args[]){  

String s1="java Program";  

System.out.println(s1.substring(2,4));//returns va  

System.out.println(s1.substring(2));//returns va Program  

}} 

Java String equals()

The java string equals() method compares the two given strings based on the content of the string. If any character is not matched, it returns false. If all characters are matched, it returns true.

The String equals() method overrides the equals() method of the Object class.

public class EqualsExample{  

public static void main(String args[]){  

String s1="hello";  

String s2="hello";  

String s3="HELLO";  

String s4="python";  

System.out.println(s1.equals(s2));//true because content and case is same  

System.out.println(s1.equals(s3));//false because case is not same  

System.out.println(s1.equals(s4));//false because content is not same  

System.out.println(s1.compareTo(s4));

}}  

 

Java String compareTo

   The String compareTo() method compares values lexicographically and returns an integer value that describes if the first string is less than, equal to, or greater than the second string.

Suppose s1 and s2 are two string variables. If:

s1 == s2 : 0

s1 > s2   : positive value (difference of character value)

s1 < s2   : negative value

 

Example

public static void main(String args[])

{  

String s1="hello";  

String s2="hello";  

String s3="meklo";  

String s4="hemlo";  

String s5="flag";  

System.out.println(s1.compareTo(s2));     //0 because both are equal  

System.out.println(s1.compareTo(s3));//because "h" is 5 times lower than "m"  

System.out.println(s1.compareTo(s4));//1 because "l" is 1 times lower than "m"  

System.out.println(s1.compareTo(s5)); //2 because "h" is 2 times greater than "f"  

}

Java String concat

The java string concat() method combines the specified string at the end of this string. It returns a combined string. It is like appending another string.

public class ConcatExample{  

public static void main(String args[]){  

String s1="java string";  

s1.concat("is immutable");  

System.out.println(s1);  

s1=s1.concat(" is immutable so assign it explicitly");  

System.out.println(s1);  

}}  

Java String isEmpty()

The java string isEmpty() method checks if this string is empty or not. It returns true if the length of the string is 0 otherwise false. In other words, true is returned if the string is empty otherwise it returns false.

The isEmpty() method of the String class has been included in the Java string since JDK 1.6.

public class IsEmptyExample{  

public static void main(String args[]){  

String s1="";  

String s2="java";  

  

System.out.println(s1.isEmpty());  

System.out.println(s2.isEmpty());  

}}