Write a Java program to practice using String class and its methods.

Program Code:
import java.lang.String;
class stringdemo
{
public static void main(String arg[])
{
String s1=new String("gpt gulbarga");
String s2="GPT GULBARGA";
System.out.println(" The string s1 is : " +s1);
System.out.println(" The string s1 is : " +s2);
System.out.println(" Length of the string s1 is : " +s1.length());

System.out.println(" The first accurence of r is at the position : " +s1.indexOf('r'));
System.out.println(" The String in Upper Case : " +s1.toUpperCase());
System.out.println(" The String in Lower Case : " +s1.toLowerCase());
System.out.println(" s1 equals to s2 : " +s1.equals(s2));
System.out.println(" s1 equals ignore case to s2 : " +s1.equalsIgnoreCase(s2));
int result=s1.compareTo(s2);
System.out.println("After compareTo()");
if(result==0)
System.out.println( s1 + " is equal to "+s2);
else if(result>0)
System.out.println( s1 + " is greather than to "+s2);
else
System.out.println( s1 + " is smaller than to "+s2);
System.out.println(" Character at an index of 6 is :" +s1.charAt(6));
String s3=s1.substring(4,12);
System.out.println(" Extracted substring is :"+s3);
System.out.println(" After Replacing g with a in s1 : " + s1.replace('g','a'));
String s4=" This is a book ";
System.out.println(" The string s4 is :"+s4);
System.out.println(" After trim() :"+s4.trim());
}
}

Output:
The string s1 is : gpt gulbarga
The string s1 is : GPT GULBARGA
Length of the string s1 is : 12
The first accurence of r is at the position : 9
The String in Upper Case : GPT GULBARGA
The String in Lower Case : gpt gulbarga
s1 equals to s2 : false
s1 equals ignore case to s2 : true
After compareTo()
gpt gulbarga is greather than to GPT GULBARGA
Character at an index of 6 is :l
Extracted substring is :gulbarga
After Replacing g with a in s1 : apt aulbaraa
The string s4 is : This is a book
After trim() :This is a book
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: