Object Oriented Programming: Unit IV: I/O, Generics, String Handling

String Methods

with Example Java Programs

We can find the length of a given string using the method length(). Following program shows the use of length() method for strings

String Methods

We can find the length of a given string using the method length(). Following program shows the use of length() method for strings

Java Program [Str_length Demo.Java]

class Str_lengthDemo

{

public static void main(String[] args).

{

char str[]={'P', 'R','O', 'G', 'R', 'A', 'M'};

String S=new String(str);

System.out.println("The string S is "+S);

System.out.println("The length of string is "+S.length());

System.out.print("The string in character array is ");

for(int i=0;i<S.length();i++)

System.out.print(str[i]);

}

}

Output

D:\>javac Str_length Demo.java

D:\>java Str_lengthDemo

The string S is PROGRAM

The length of string is 7

The string in character array is PROGRAM

String in reverse direction

There is no direct method for reversing the string but we can display it in reverse direction.

Following is the Java program for the same

Java Program[Str_reverse.java]

*********************

Printing the String in reverse order

*********************

class Str_reverse

{

public static void main(String[] args)

{

char str[] = {'S','T', 'R','I', 'N','G'};

String S=new String(str);

System.out.println("The string S is "+S);

System.out.print("The string written in Reverse order ");

for(int i=S.length()-1;i>=0;i--)

System.out.print(str[i]);

}

}

Output

The string S is STRING

The string written in Reverse order GNIRTS

Character Extraction

• As we know that the string is a collection of characters. String class provides the facility to extract the character from the String object. There is a method called charAt(index) with the help of which we can extract the character denoted by some index in the array.

For example:

String fruit=new String("mango");

char ch;

ch=fruit.charAt(2);

System.out.println(ch);

• The output of above code fragment will be n because at the index position 2 of string object fruit the character n is present.

String Comparison

Sometimes we need to know whether two strings are equal or not. We use method equals() for that purpose. This method is of Boolean type. That is, if two strings are equal then it returns true otherwise it returns false.

The syntax is

Boolean equals(String Str);

Let us see one illustrative program -

Java Program [StringCompare Demo.Java]

class StringCompareDemo

{

public static void main(String[] args)

{

String str1= new String("INDIA");

String str2= new String("india");

if(str1.equals(str2)== true)

System.out.println("\n The two strings are equal");

else

System.out.println("\n The two strings are not equal");

}

}

Output

D:\>javac StringCompare Demo.java

D:\>java StringCompareDemo

The two strings are not equal

The above program will generate the message "The two strings are not equal" if str1 and str2 are not equal but if we write same strl and str2 then naturally the output will be "The two strings are equal". This string comparison is case sensitive. But if we want to compare the two strings without caring for their case differences then we can use the method equalsIgnoreCase().

Searching for the Substring

We can look for the desired substring from the given string using a method substring(). The syntax of method substring() is as follows -

String substring(int start_index, int end_index)

Java Program [Substring Demo.Java]

class SubstringDemo

{

public static void main(String[] args)

{

String str1= new String("I love my country very much");

System.out.println("\n One substring from the given sentence is:"+str1.substring(2,6));

System.out.println("\n And another substring is:"+str1.substring(18));

}

}

Output

D:\>javac SubstringDemo.java

D:\>java SubstringDemo

One substring from the given sentence is:love And another substring is:very much

Replacing the Character from String

We can replace the character by some desired character. For example

Java Program [replace Demo.java]

class replaceDemo

{

public static void main(String[] args)

{

String str=new String("Nisha is Indian ");

String s= str.replace('i','a');

System.out.println(s);

}

}

Output

D:\>javac replace Demo.java

D:\>java replace Demo

Nasha as Indaan

Upper and Lower Case

We can convert the given string to either upper case or lower case using the methods toUpperCase() and toLowerCase(). Following program demonstrates the handling of the case of the string -

Java Program [CaseDemo.Java]

class caseDemo

{

public static void main(String[] args)

{

String str=new String("Nisha is Indian ");

System.out.println("\n The original string is: "+str);

String str_upper= str.toUpperCase();

System.out.println("\n The Upper case string is: "+str_upper);

String str_lower= str.toLowerCase();

System.out.println("\n The Lower case string is: "+str_lower);

}

}

Output

D:\>javac caseDemo.java

D:\>java caseDemo

The original string is: Nisha is Indian

The Upper case string is: NISHA IS INDIAN

The Lower case string is: nisha is Indian

Concatenating Strings

We can concatenate two strings using + operator which is illustrated by following code -

Java Program [Test.Java]

class Test

public static void main(String[] args)

{

String fruit new String("mango");

System.out.println("I like "+fruit +" very much");

}

}

Output

I like mango very much

We can make use of a method concat() for concatenating two strings. The above program is slightly modified for the use of concat()-ne

Java Program

class Test

{

public static void main(String[] args)

{

String str=new String("I like ");

String fruit=new String("mango very much");

System.out.println(str.concat(fruit));

}

}

Output

I like mango very much

Ex. 4.10.1: Write a Java Program that collects the input as a decimal number of integer type and converts it into a String of equivalent hexadecimal number.

Sol. :

import java.io.*;

class DecToHex

{

public static void main(String[] args) throws IOException

{

//Following 3 statements is required to read the input through keyboard BufferedReader br=new BufferedReader (new InputStreamReader(System.in));

System.out.print("Enter a decimal number: ");

int num= Integer.parseInt(br.readLine());

int rem;

String str=""";

//array storing the digits (as characters) in a hexadecimal number system char digits[] = {'0', '1', '2', '3', '4','5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

while(num>0)//divide until num is 0

{

rem=num%16; //finding remainder by dividing the number by 16

str=digits[rem] + str; //adding the remainder to the result

num=num/16;

}

System.out.println("Output "+str);

}

}

Output

Enter a decimal number: 10

Output = A

Ex. 4.10.2: Write a Java Program that arranges the given set of strings in alphabetical order. Supply the strings through the command line.

Sol.:

class String Demo

{

public static void main(String[] args)

{

String temp;

int n = args.length;

int i,j,c;

for (i=0; i<n-1; i++)

{

for (j=i+1; j<n; j++)

{

c= args[i].compareTo(args[j]);

if (c >0)

{

temp = args[i];

args[i] = args[j];

args[j] = temp;

}

}

}

for (i=0; i<n;i++)

{

System.out.println(args[i]);

}

}

}

Output


Object Oriented Programming: Unit IV: I/O, Generics, String Handling : Tag: : with Example Java Programs - String Methods